diff --git a/activation.cpp b/activation.cpp index ad6d9a463..fd67c552b 100644 --- a/activation.cpp +++ b/activation.cpp @@ -224,54 +224,53 @@ namespace KWin activeClient(). And of course, to propagate the active client to the world. */ -void Workspace::setActiveClient( Client* c, allowed_t ) - { - if ( active_client == c ) +void Workspace::setActiveClient(Client* c, allowed_t) +{ + if (active_client == c) return; - - if(c != 0) { - emit clientActivated(c); - c->sl_activated(); + + if (c != 0) { + emit clientActivated(c); + c->sl_activated(); } - - if( active_popup && active_popup_client != c && set_active_client_recursion == 0 ) + + if (active_popup && active_popup_client != c && set_active_client_recursion == 0) closeActivePopup(); - StackingUpdatesBlocker blocker( this ); + StackingUpdatesBlocker blocker(this); ++set_active_client_recursion; - updateFocusMousePosition( cursorPos()); - if( active_client != NULL ) - { // note that this may call setActiveClient( NULL ), therefore the recursion counter - active_client->setActive( false ); - } + updateFocusMousePosition(cursorPos()); + if (active_client != NULL) { + // note that this may call setActiveClient( NULL ), therefore the recursion counter + active_client->setActive(false); + } active_client = c; - Q_ASSERT( c == NULL || c->isActive()); - if( active_client != NULL ) + Q_ASSERT(c == NULL || c->isActive()); + if (active_client != NULL) last_active_client = active_client; - if ( active_client ) - { - updateFocusChains( active_client, FocusChainMakeFirst ); - active_client->demandAttention( false ); - } + if (active_client) { + updateFocusChains(active_client, FocusChainMakeFirst); + active_client->demandAttention(false); + } pending_take_activity = NULL; updateCurrentTopMenu(); - updateToolWindows( false ); - if( c ) - disableGlobalShortcutsForClient( c->rules()->checkDisableGlobalShortcuts( false )); + updateToolWindows(false); + if (c) + disableGlobalShortcutsForClient(c->rules()->checkDisableGlobalShortcuts(false)); else - disableGlobalShortcutsForClient( false ); + disableGlobalShortcutsForClient(false); updateStackingOrder(); // e.g. fullscreens have different layer when active/not-active - rootInfo->setActiveWindow( active_client? active_client->window() : 0 ); + rootInfo->setActiveWindow(active_client ? active_client->window() : 0); updateColormap(); - if( effects ) - static_cast(effects)->windowActivated( active_client ? active_client->effectWindow() : NULL ); + if (effects) + static_cast(effects)->windowActivated(active_client ? active_client->effectWindow() : NULL); - if( tilingEnabled() ) - notifyTilingWindowActivated( active_client ); + if (tilingEnabled()) + notifyTilingWindowActivated(active_client); --set_active_client_recursion; - } +} /*! Tries to activate the client \a c. This function performs what you @@ -284,34 +283,31 @@ void Workspace::setActiveClient( Client* c, allowed_t ) \sa stActiveClient(), requestFocus() */ -void Workspace::activateClient( Client* c, bool force ) - { - if( c == NULL ) - { +void Workspace::activateClient(Client* c, bool force) +{ + if (c == NULL) { focusToNull(); - setActiveClient( NULL, Allowed ); + setActiveClient(NULL, Allowed); return; - } - raiseClient( c ); - if (!c->isOnCurrentDesktop() ) - { + } + raiseClient(c); + if (!c->isOnCurrentDesktop()) { ++block_focus; - setCurrentDesktop( c->desktop() ); + setCurrentDesktop(c->desktop()); --block_focus; - } - if (!c->isOnCurrentActivity() ) - { + } + if (!c->isOnCurrentActivity()) { ++block_focus; //DBUS! - activityController_.setCurrentActivity( c->activities().first() ); //first isn't necessarily best, but it's easiest + activityController_.setCurrentActivity(c->activities().first()); //first isn't necessarily best, but it's easiest --block_focus; - } - if( c->isMinimized()) + } + if (c->isMinimized()) c->unminimize(); // TODO force should perhaps allow this only if the window already contains the mouse - if( options->focusPolicyIsReasonable() || force ) - requestFocus( c, force ); + if (options->focusPolicyIsReasonable() || force) + requestFocus(c, force); // Don't update user time for clients that have focus stealing workaround. // As they usually belong to the current active window but fail to provide @@ -320,9 +316,9 @@ void Workspace::activateClient( Client* c, bool force ) // E.g. typing URL in minicli which will show kio_uiserver dialog (with workaround), // and then kdesktop shows dialog about SSL certificate. // This needs also avoiding user creation time in Client::readUserTimeMapTimestamp(). - if( !c->ignoreFocusStealing()) + if (!c->ignoreFocusStealing()) c->updateUserTime(); - } +} /*! Tries to activate the client by asking X for the input focus. This @@ -331,80 +327,73 @@ void Workspace::activateClient( Client* c, bool force ) \sa Workspace::activateClient() */ -void Workspace::requestFocus( Client* c, bool force ) - { - takeActivity( c, ActivityFocus | ( force ? ActivityFocusForce : 0 ), false); - } - -void Workspace::takeActivity( Client* c, int flags, bool handled ) - { - // the 'if( c == active_client ) return;' optimization mustn't be done here - if (!focusChangeEnabled() && ( c != active_client) ) +void Workspace::requestFocus(Client* c, bool force) +{ + takeActivity(c, ActivityFocus | (force ? ActivityFocusForce : 0), false); +} + +void Workspace::takeActivity(Client* c, int flags, bool handled) +{ + // the 'if ( c == active_client ) return;' optimization mustn't be done here + if (!focusChangeEnabled() && (c != active_client)) flags &= ~ActivityFocus; - if ( !c ) - { + if (!c) { focusToNull(); return; - } + } - if( flags & ActivityFocus ) - { + if (flags & ActivityFocus) { Client* modal = c->findModal(); - if( modal != NULL && modal != c ) - { - if( !modal->isOnDesktop( c->desktop())) - { - modal->setDesktop( c->desktop()); - if( modal->desktop() != c->desktop()) // forced desktop - activateClient( modal ); - } + if (modal != NULL && modal != c) { + if (!modal->isOnDesktop(c->desktop())) { + modal->setDesktop(c->desktop()); + if (modal->desktop() != c->desktop()) // forced desktop + activateClient(modal); + } // if the click was inside the window (i.e. handled is set), // but it has a modal, there's no need to use handled mode, because // the modal doesn't get the click anyway // raising of the original window needs to be still done - if( flags & ActivityRaise ) - raiseClient( c ); + if (flags & ActivityRaise) + raiseClient(c); c = modal; handled = false; - } - cancelDelayFocus(); } - if ( !( flags & ActivityFocusForce ) && ( c->isTopMenu() || c->isDock() || c->isSplash()) ) + cancelDelayFocus(); + } + if (!(flags & ActivityFocusForce) && (c->isTopMenu() || c->isDock() || c->isSplash())) flags &= ~ActivityFocus; // toplevel menus and dock windows don't take focus if not forced - if( c->isShade()) - { - if( c->wantsInput() && ( flags & ActivityFocus )) - { - // client cannot accept focus, but at least the window should be active (window menu, et. al. ) - c->setActive( true ); + if (c->isShade()) { + if (c->wantsInput() && (flags & ActivityFocus)) { + // client cannot accept focus, but at least the window should be active (window menu, et. al. ) + c->setActive(true); focusToNull(); - } + } flags &= ~ActivityFocus; handled = false; // no point, can't get clicks - } - if( c->clientGroup() && c->clientGroup()->visible() != c ) - c->clientGroup()->setVisible( c ); - if( !c->isShown( true )) // shouldn't happen, call activateClient() if needed - { - kWarning( 1212 ) << "takeActivity: not shown" ; + } + if (c->clientGroup() && c->clientGroup()->visible() != c) + c->clientGroup()->setVisible(c); + if (!c->isShown(true)) { // shouldn't happen, call activateClient() if needed + kWarning(1212) << "takeActivity: not shown" ; return; - } - c->takeActivity( flags, handled, Allowed ); - if( !c->isOnScreen( active_screen )) + } + c->takeActivity(flags, handled, Allowed); + if (!c->isOnScreen(active_screen)) active_screen = c->screen(); - } +} -void Workspace::handleTakeActivity( Client* c, Time /*timestamp*/, int flags ) - { - if( pending_take_activity != c ) // pending_take_activity is reset when doing restack or activation +void Workspace::handleTakeActivity(Client* c, Time /*timestamp*/, int flags) +{ + if (pending_take_activity != c) // pending_take_activity is reset when doing restack or activation return; - if(( flags & ActivityRaise ) != 0 ) - raiseClient( c ); - if(( flags & ActivityFocus ) != 0 && c->isShown( false )) - c->takeFocus( Allowed ); + if ((flags & ActivityRaise) != 0) + raiseClient(c); + if ((flags & ActivityFocus) != 0 && c->isShown(false)) + c->takeFocus(Allowed); pending_take_activity = NULL; - } +} /*! Informs the workspace that the client \a c has been hidden. If it @@ -413,126 +402,116 @@ void Workspace::handleTakeActivity( Client* c, Time /*timestamp*/, int flags ) \a c may already be destroyed */ -void Workspace::clientHidden( Client* c ) - { - assert( !c->isShown( true ) || !c->isOnCurrentDesktop() || !c->isOnCurrentActivity()); - activateNextClient( c ); - } +void Workspace::clientHidden(Client* c) +{ + assert(!c->isShown(true) || !c->isOnCurrentDesktop() || !c->isOnCurrentActivity()); + activateNextClient(c); +} -static inline bool isUsableFocusCandidate( Client *c, Client *prev, bool respectScreen ) - { +static inline bool isUsableFocusCandidate(Client *c, Client *prev, bool respectScreen) +{ return c != prev && - c->isShown( false ) && c->isOnCurrentDesktop() && c->isOnCurrentActivity() && - ( !respectScreen || c->isOnScreen( prev ? prev->screen() : Workspace::self()->activeScreen() ) ); - } + c->isShown(false) && c->isOnCurrentDesktop() && c->isOnCurrentActivity() && + (!respectScreen || c->isOnScreen(prev ? prev->screen() : Workspace::self()->activeScreen())); +} // deactivates 'c' and activates next client -bool Workspace::activateNextClient( Client* c ) - { +bool Workspace::activateNextClient(Client* c) +{ // if 'c' is not the active or the to-become active one, do nothing - if( !( c == active_client - || ( should_get_focus.count() > 0 && c == should_get_focus.last()))) + if (!(c == active_client + || (should_get_focus.count() > 0 && c == should_get_focus.last()))) return false; closeActivePopup(); - if( c != NULL ) - { - if( c == active_client ) - setActiveClient( NULL, Allowed ); - should_get_focus.removeAll( c ); - } - if( focusChangeEnabled()) - { - if ( options->focusPolicyIsReasonable()) - { // search the focus_chain for a client to transfer focus to, + if (c != NULL) { + if (c == active_client) + setActiveClient(NULL, Allowed); + should_get_focus.removeAll(c); + } + if (focusChangeEnabled()) { + if (options->focusPolicyIsReasonable()) { + // search the focus_chain for a client to transfer focus to, Client* get_focus = NULL; // first try to pass the focus to the (former) active clients leader - if ( c && ( get_focus = c->transientFor() ) && - isUsableFocusCandidate( get_focus, c, options->separateScreenFocus )) - { - raiseClient( get_focus ); // also raise - we don't know where it came from - } - else // nope, ask the focus chain for the next candidate - { + if (c && (get_focus = c->transientFor()) && + isUsableFocusCandidate(get_focus, c, options->separateScreenFocus)) { + raiseClient(get_focus); // also raise - we don't know where it came from + } else { // nope, ask the focus chain for the next candidate get_focus = NULL; // reset - for ( int i = focus_chain[ currentDesktop() ].size() - 1; i >= 0; --i ) - { - Client* ci = focus_chain[ currentDesktop() ].at( i ); - if ( isUsableFocusCandidate( ci, c, options->separateScreenFocus )) - { + for (int i = focus_chain[ currentDesktop()].size() - 1; i >= 0; --i) { + Client* ci = focus_chain[ currentDesktop()].at(i); + if (isUsableFocusCandidate(ci, c, options->separateScreenFocus)) { get_focus = ci; break; // we're done - } } } + } - if( get_focus == NULL ) // last chance: focus the desktop - get_focus = findDesktop( true, currentDesktop()); + if (get_focus == NULL) // last chance: focus the desktop + get_focus = findDesktop(true, currentDesktop()); - if( get_focus != NULL ) - requestFocus( get_focus ); + if (get_focus != NULL) + requestFocus(get_focus); else focusToNull(); - } - else - return false; - } - else + } else + return false; + } else // if blocking focus, move focus to the desktop later if needed // in order to avoid flickering focusToNull(); return true; - } +} -void Workspace::setCurrentScreen( int new_screen ) - { +void Workspace::setCurrentScreen(int new_screen) +{ if (new_screen < 0 || new_screen > numScreens()) return; - if ( !options->focusPolicyIsReasonable()) + if (!options->focusPolicyIsReasonable()) return; closeActivePopup(); Client* get_focus = NULL; - for( int i = focus_chain[ currentDesktop() ].count() - 1; - i >= 0; - --i ) - { - Client* ci = focus_chain[ currentDesktop() ].at( i ); - if( !ci->isShown( false ) || !ci->isOnCurrentDesktop() || !ci->isOnCurrentActivity()) + for (int i = focus_chain[ currentDesktop()].count() - 1; + i >= 0; + --i) { + Client* ci = focus_chain[ currentDesktop()].at(i); + if (!ci->isShown(false) || !ci->isOnCurrentDesktop() || !ci->isOnCurrentActivity()) continue; - if( !ci->screen() == new_screen ) + if (!ci->screen() == new_screen) continue; get_focus = ci; break; - } - if( get_focus == NULL ) - get_focus = findDesktop( true, currentDesktop()); - if( get_focus != NULL && get_focus != mostRecentlyActivatedClient()) - requestFocus( get_focus ); - active_screen = new_screen; } + if (get_focus == NULL) + get_focus = findDesktop(true, currentDesktop()); + if (get_focus != NULL && get_focus != mostRecentlyActivatedClient()) + requestFocus(get_focus); + active_screen = new_screen; +} -void Workspace::gotFocusIn( const Client* c ) - { - if( should_get_focus.contains( const_cast< Client* >( c ))) - { // remove also all sooner elements that should have got FocusIn, - // but didn't for some reason (and also won't anymore, because they were sooner) - while( should_get_focus.first() != c ) +void Workspace::gotFocusIn(const Client* c) +{ + if (should_get_focus.contains(const_cast< Client* >(c))) { + // remove also all sooner elements that should have got FocusIn, + // but didn't for some reason (and also won't anymore, because they were sooner) + while (should_get_focus.first() != c) should_get_focus.pop_front(); should_get_focus.pop_front(); // remove 'c' - } } +} -void Workspace::setShouldGetFocus( Client* c ) - { - should_get_focus.append( c ); +void Workspace::setShouldGetFocus(Client* c) +{ + should_get_focus.append(c); updateStackingOrder(); // e.g. fullscreens have different layer when active/not-active - } +} // focus_in -> the window got FocusIn event // ignore_desktop - call comes from _NET_ACTIVE_WINDOW message, don't refuse just because of window // is on a different desktop -bool Workspace::allowClientActivation( const Client* c, Time time, bool focus_in, bool ignore_desktop ) - { +bool Workspace::allowClientActivation(const Client* c, Time time, bool focus_in, bool ignore_desktop) +{ // options->focusStealingPreventionLevel : // 0 - none - old KWin behaviour, new windows always get focus // 1 - low - focus stealing prevention is applied normally, when unsure, activation is allowed @@ -541,150 +520,139 @@ bool Workspace::allowClientActivation( const Client* c, Time time, bool focus_in // 3 - high - new window gets focus only if it belongs to the active application, // or when no window is currently active // 4 - extreme - no window gets focus without user intervention - if( time == -1U ) + if (time == -1U) time = c->userTime(); - int level = c->rules()->checkFSP( options->focusStealingPreventionLevel ); - if( session_saving && level <= 2 ) // <= normal - { + int level = c->rules()->checkFSP(options->focusStealingPreventionLevel); + if (session_saving && level <= 2) { // <= normal return true; - } + } Client* ac = mostRecentlyActivatedClient(); - if( focus_in ) - { - if( should_get_focus.contains( const_cast< Client* >( c ))) + if (focus_in) { + if (should_get_focus.contains(const_cast< Client* >(c))) return true; // FocusIn was result of KWin's action // Before getting FocusIn, the active Client already // got FocusOut, and therefore got deactivated. ac = last_active_client; - } - if( time == 0 ) // explicitly asked not to get focus + } + if (time == 0) // explicitly asked not to get focus return false; - if( level == 0 ) // none + if (level == 0) // none return true; - if( level == 4 ) // extreme + if (level == 4) // extreme return false; - if( !ignore_desktop && !c->isOnCurrentDesktop()) + if (!ignore_desktop && !c->isOnCurrentDesktop()) return false; // allow only with level == 0 - if( c->ignoreFocusStealing()) + if (c->ignoreFocusStealing()) return true; - if( ac == NULL || ac->isDesktop()) - { - kDebug( 1212 ) << "Activation: No client active, allowing"; + if (ac == NULL || ac->isDesktop()) { + kDebug(1212) << "Activation: No client active, allowing"; return true; // no active client -> always allow - } + } // TODO window urgency -> return true? - if( Client::belongToSameApplication( c, ac, true )) - { - kDebug( 1212 ) << "Activation: Belongs to active application"; + if (Client::belongToSameApplication(c, ac, true)) { + kDebug(1212) << "Activation: Belongs to active application"; return true; - } - if( level == 3 ) // high + } + if (level == 3) // high return false; - if( time == -1U ) // no time known - { - kDebug( 1212 ) << "Activation: No timestamp at all"; - if( level == 1 ) // low + if (time == -1U) { // no time known + kDebug(1212) << "Activation: No timestamp at all"; + if (level == 1) // low return true; // no timestamp at all, don't activate - because there's also creation timestamp // done on CreateNotify, this case should happen only in case application // maps again already used window, i.e. this won't happen after app startup - return false; - } + return false; + } // level == 2 // normal Time user_time = ac->userTime(); - kDebug( 1212 ) << "Activation, compared:" << c << ":" << time << ":" << user_time - << ":" << ( timestampCompare( time, user_time ) >= 0 ) << endl; - return timestampCompare( time, user_time ) >= 0; // time >= user_time - } + kDebug(1212) << "Activation, compared:" << c << ":" << time << ":" << user_time + << ":" << (timestampCompare(time, user_time) >= 0) << endl; + return timestampCompare(time, user_time) >= 0; // time >= user_time +} // basically the same like allowClientActivation(), this time allowing // a window to be fully raised upon its own request (XRaiseWindow), // if refused, it will be raised only on top of windows belonging // to the same application -bool Workspace::allowFullClientRaising( const Client* c, Time time ) - { - int level = c->rules()->checkFSP( options->focusStealingPreventionLevel ); - if( session_saving && level <= 2 ) // <= normal - { +bool Workspace::allowFullClientRaising(const Client* c, Time time) +{ + int level = c->rules()->checkFSP(options->focusStealingPreventionLevel); + if (session_saving && level <= 2) { // <= normal return true; - } + } Client* ac = mostRecentlyActivatedClient(); - if( level == 0 ) // none + if (level == 0) // none return true; - if( level == 4 ) // extreme + if (level == 4) // extreme return false; - if( ac == NULL || ac->isDesktop()) - { - kDebug( 1212 ) << "Raising: No client active, allowing"; + if (ac == NULL || ac->isDesktop()) { + kDebug(1212) << "Raising: No client active, allowing"; return true; // no active client -> always allow - } - if( c->ignoreFocusStealing()) + } + if (c->ignoreFocusStealing()) return true; // TODO window urgency -> return true? - if( Client::belongToSameApplication( c, ac, true )) - { - kDebug( 1212 ) << "Raising: Belongs to active application"; + if (Client::belongToSameApplication(c, ac, true)) { + kDebug(1212) << "Raising: Belongs to active application"; return true; - } - if( level == 3 ) // high + } + if (level == 3) // high return false; Time user_time = ac->userTime(); - kDebug( 1212 ) << "Raising, compared:" << time << ":" << user_time - << ":" << ( timestampCompare( time, user_time ) >= 0 ) << endl; - return timestampCompare( time, user_time ) >= 0; // time >= user_time - } + kDebug(1212) << "Raising, compared:" << time << ":" << user_time + << ":" << (timestampCompare(time, user_time) >= 0) << endl; + return timestampCompare(time, user_time) >= 0; // time >= user_time +} // called from Client after FocusIn that wasn't initiated by KWin and the client // wasn't allowed to activate void Workspace::restoreFocus() - { +{ // this updateXTime() is necessary - as FocusIn events don't have // a timestamp *sigh*, kwin's timestamp would be older than the timestamp // that was used by whoever caused the focus change, and therefore // the attempt to restore the focus would fail due to old timestamp updateXTime(); - if( should_get_focus.count() > 0 ) - requestFocus( should_get_focus.last()); - else if( last_active_client ) - requestFocus( last_active_client ); - } + if (should_get_focus.count() > 0) + requestFocus(should_get_focus.last()); + else if (last_active_client) + requestFocus(last_active_client); +} -void Workspace::clientAttentionChanged( Client* c, bool set ) - { - if( set ) - { - attention_chain.removeAll( c ); - attention_chain.prepend( c ); - } - else - attention_chain.removeAll( c ); - } +void Workspace::clientAttentionChanged(Client* c, bool set) +{ + if (set) { + attention_chain.removeAll(c); + attention_chain.prepend(c); + } else + attention_chain.removeAll(c); +} // This is used when a client should be shown active immediately after requestFocus(), // without waiting for the matching FocusIn that will really make the window the active one. // Used only in special cases, e.g. for MouseActivateRaiseandMove with transparent windows, -bool Workspace::fakeRequestedActivity( Client* c ) - { - if( should_get_focus.count() > 0 && should_get_focus.last() == c ) - { - if( c->isActive()) +bool Workspace::fakeRequestedActivity(Client* c) +{ + if (should_get_focus.count() > 0 && should_get_focus.last() == c) { + if (c->isActive()) return false; - c->setActive( true ); + c->setActive(true); return true; - } + } return false; - } +} -void Workspace::unfakeActivity( Client* c ) - { - if( should_get_focus.count() > 0 && should_get_focus.last() == c ) - { // TODO this will cause flicker, and probably is not needed - if( last_active_client != NULL ) - last_active_client->setActive( true ); +void Workspace::unfakeActivity(Client* c) +{ + if (should_get_focus.count() > 0 && should_get_focus.last() == c) { + // TODO this will cause flicker, and probably is not needed + if (last_active_client != NULL) + last_active_client->setActive(true); else - c->setActive( false ); - } + c->setActive(false); } +} //******************************************** @@ -697,19 +665,20 @@ void Workspace::unfakeActivity( Client* c ) that qualifies for user interaction (clicking on it, activate it externally, etc.). */ -void Client::updateUserTime( Time time ) - { // copied in Group::updateUserTime - if( time == CurrentTime ) +void Client::updateUserTime(Time time) +{ + // copied in Group::updateUserTime + if (time == CurrentTime) time = xTime(); - if( time != -1U - && ( user_time == CurrentTime - || timestampCompare( time, user_time ) > 0 )) // time > user_time + if (time != -1U + && (user_time == CurrentTime + || timestampCompare(time, user_time) > 0)) // time > user_time user_time = time; - group()->updateUserTime( user_time ); - } + group()->updateUserTime(user_time); +} Time Client::readUserCreationTime() const - { +{ long result = -1; // Time == -1 means none Atom type; int format, status; @@ -717,27 +686,25 @@ Time Client::readUserCreationTime() const unsigned long extra = 0; unsigned char *data = 0; KXErrorHandler handler; // ignore errors? - status = XGetWindowProperty( display(), window(), - atoms->kde_net_wm_user_creation_time, 0, 10000, false, XA_CARDINAL, - &type, &format, &nitems, &extra, &data ); - if (status == Success ) - { + status = XGetWindowProperty(display(), window(), + atoms->kde_net_wm_user_creation_time, 0, 10000, false, XA_CARDINAL, + &type, &format, &nitems, &extra, &data); + if (status == Success) { if (data && nitems > 0) result = *((long*) data); XFree(data); - } - return result; } + return result; +} -void Client::demandAttention( bool set ) - { - if( isActive()) +void Client::demandAttention(bool set) +{ + if (isActive()) set = false; - if( demands_attention == set ) + if (demands_attention == set) return; demands_attention = set; - if( demands_attention ) - { + if (demands_attention) { // Demand attention flag is often set right from manage(), when focus stealing prevention // steps in. At that time the window has no taskbar entry yet, so KNotify cannot place // e.g. the passive popup next to it. So wait up to 1 second for the icon geometry @@ -748,96 +715,85 @@ void Client::demandAttention( bool set ) // Setting the demands attention state needs to be done directly in KWin, because // KNotify would try to set it, resulting in a call to KNotify again, etc. - info->setState( set ? NET::DemandsAttention : 0, NET::DemandsAttention ); + info->setState(set ? NET::DemandsAttention : 0, NET::DemandsAttention); - if( demandAttentionKNotifyTimer == NULL ) - { - demandAttentionKNotifyTimer = new QTimer( this ); - demandAttentionKNotifyTimer->setSingleShot( true ); - connect( demandAttentionKNotifyTimer, SIGNAL( timeout()), SLOT( demandAttentionKNotify())); - } - demandAttentionKNotifyTimer->start( 1000 ); + if (demandAttentionKNotifyTimer == NULL) { + demandAttentionKNotifyTimer = new QTimer(this); + demandAttentionKNotifyTimer->setSingleShot(true); + connect(demandAttentionKNotifyTimer, SIGNAL(timeout()), SLOT(demandAttentionKNotify())); } - else - info->setState( set ? NET::DemandsAttention : 0, NET::DemandsAttention ); - workspace()->clientAttentionChanged( this, set ); - } + demandAttentionKNotifyTimer->start(1000); + } else + info->setState(set ? NET::DemandsAttention : 0, NET::DemandsAttention); + workspace()->clientAttentionChanged(this, set); +} void Client::demandAttentionKNotify() - { +{ Notify::Event e = isOnCurrentDesktop() ? Notify::DemandAttentionCurrent : Notify::DemandAttentionOther; - Notify::raise( e, i18n( "Window '%1' demands attention.", KStringHandler::csqueeze(caption())), this ); + Notify::raise(e, i18n("Window '%1' demands attention.", KStringHandler::csqueeze(caption())), this); demandAttentionKNotifyTimer->stop(); demandAttentionKNotifyTimer->deleteLater(); demandAttentionKNotifyTimer = NULL; - } +} // TODO I probably shouldn't be lazy here and do it without the macro, so that people can read it -KWIN_COMPARE_PREDICATE( SameApplicationActiveHackPredicate, Client, const Client*, - // ignore already existing splashes, toolbars, utilities, menus and topmenus, - // as the app may show those before the main window - !cl->isSplash() && !cl->isToolbar() && !cl->isTopMenu() && !cl->isUtility() && !cl->isMenu() - && Client::belongToSameApplication( cl, value, true ) && cl != value); +KWIN_COMPARE_PREDICATE(SameApplicationActiveHackPredicate, Client, const Client*, + // ignore already existing splashes, toolbars, utilities, menus and topmenus, + // as the app may show those before the main window + !cl->isSplash() && !cl->isToolbar() && !cl->isTopMenu() && !cl->isUtility() && !cl->isMenu() + && Client::belongToSameApplication(cl, value, true) && cl != value); -Time Client::readUserTimeMapTimestamp( const KStartupInfoId* asn_id, const KStartupInfoData* asn_data, - bool session ) const - { +Time Client::readUserTimeMapTimestamp(const KStartupInfoId* asn_id, const KStartupInfoData* asn_data, + bool session) const +{ Time time = info->userTime(); - //kDebug( 1212 ) << "User timestamp, initial:" << time; + //kDebug( 1212 ) << "User timestamp, initial:" << time; //^^ this deadlocks kwin --replace sometimes. // newer ASN timestamp always replaces user timestamp, unless user timestamp is 0 // helps e.g. with konqy reusing - if( asn_data != NULL && time != 0 ) - { + if (asn_data != NULL && time != 0) { // prefer timestamp from ASN id (timestamp from data is obsolete way) - if( asn_id->timestamp() != 0 - && ( time == -1U || timestampCompare( asn_id->timestamp(), time ) > 0 )) - { + if (asn_id->timestamp() != 0 + && (time == -1U || timestampCompare(asn_id->timestamp(), time) > 0)) { time = asn_id->timestamp(); - } - else if( asn_data->timestamp() != -1U - && ( time == -1U || timestampCompare( asn_data->timestamp(), time ) > 0 )) - { + } else if (asn_data->timestamp() != -1U + && (time == -1U || timestampCompare(asn_data->timestamp(), time) > 0)) { time = asn_data->timestamp(); - } } - kDebug( 1212 ) << "User timestamp, ASN:" << time; - if( time == -1U ) - { // The window doesn't have any timestamp. - // If it's the first window for its application - // (i.e. there's no other window from the same app), - // use the _KDE_NET_WM_USER_CREATION_TIME trick. - // Otherwise, refuse activation of a window - // from already running application if this application - // is not the active one (unless focus stealing prevention is turned off). + } + kDebug(1212) << "User timestamp, ASN:" << time; + if (time == -1U) { + // The window doesn't have any timestamp. + // If it's the first window for its application + // (i.e. there's no other window from the same app), + // use the _KDE_NET_WM_USER_CREATION_TIME trick. + // Otherwise, refuse activation of a window + // from already running application if this application + // is not the active one (unless focus stealing prevention is turned off). Client* act = workspace()->mostRecentlyActivatedClient(); - if( act != NULL && !belongToSameApplication( act, this, true )) - { + if (act != NULL && !belongToSameApplication(act, this, true)) { bool first_window = true; - if( isTransient()) - { - if( act->hasTransient( this, true )) + if (isTransient()) { + if (act->hasTransient(this, true)) ; // is transient for currently active window, even though it's not - // the same app (e.g. kcookiejar dialog) -> allow activation - else if( groupTransient() && - findClientInList( mainClients(), SameApplicationActiveHackPredicate( this )) == NULL ) + // the same app (e.g. kcookiejar dialog) -> allow activation + else if (groupTransient() && + findClientInList(mainClients(), SameApplicationActiveHackPredicate(this)) == NULL) ; // standalone transient else first_window = false; - } - else - { - if( workspace()->findClient( SameApplicationActiveHackPredicate( this ))) + } else { + if (workspace()->findClient(SameApplicationActiveHackPredicate(this))) first_window = false; - } - // don't refuse if focus stealing prevention is turned off - if( !first_window && rules()->checkFSP( options->focusStealingPreventionLevel ) > 0 ) - { - kDebug( 1212 ) << "User timestamp, already exists:" << 0; - return 0; // refuse activation - } } + // don't refuse if focus stealing prevention is turned off + if (!first_window && rules()->checkFSP(options->focusStealingPreventionLevel) > 0) { + kDebug(1212) << "User timestamp, already exists:" << 0; + return 0; // refuse activation + } + } // Creation time would just mess things up during session startup, // as possibly many apps are started up at the same time. // If there's no active window yet, no timestamp will be needed, @@ -847,29 +803,29 @@ Time Client::readUserTimeMapTimestamp( const KStartupInfoId* asn_id, const KStar // Unless it was the active window at the time // of session saving and there was no user interaction yet, // this check will be done in manage(). - if( session ) + if (session) return -1U; - if( ignoreFocusStealing() && act != NULL ) + if (ignoreFocusStealing() && act != NULL) time = act->userTime(); else time = readUserCreationTime(); - } - kDebug( 1212 ) << "User timestamp, final:" << this << ":" << time; - return time; } + kDebug(1212) << "User timestamp, final:" << this << ":" << time; + return time; +} Time Client::userTime() const - { +{ Time time = user_time; - if( time == 0 ) // doesn't want focus after showing + if (time == 0) // doesn't want focus after showing return 0; - assert( group() != NULL ); - if( time == -1U - || ( group()->userTime() != -1U - && timestampCompare( group()->userTime(), time ) > 0 )) + assert(group() != NULL); + if (time == -1U + || (group()->userTime() != -1U + && timestampCompare(group()->userTime(), time) > 0)) time = group()->userTime(); return time; - } +} /*! Sets the client's active state to \a act. @@ -882,115 +838,112 @@ Time Client::userTime() const its own. */ -void Client::setActive( bool act ) - { - if ( active == act ) +void Client::setActive(bool act) +{ + if (active == act) return; active = act; const int ruledOpacity = active - ? rules()->checkOpacityActive( qRound( opacity() * 100.0 )) - : rules()->checkOpacityInactive( qRound( opacity() * 100.0 )); - setOpacity( ruledOpacity/100.0 ); - workspace()->setActiveClient( act ? this : NULL, Allowed ); - - if ( active ) - Notify::raise( Notify::Activate ); + ? rules()->checkOpacityActive(qRound(opacity() * 100.0)) + : rules()->checkOpacityInactive(qRound(opacity() * 100.0)); + setOpacity(ruledOpacity / 100.0); + workspace()->setActiveClient(act ? this : NULL, Allowed); - if( !active ) + if (active) + Notify::raise(Notify::Activate); + + if (!active) cancelAutoRaise(); - if( !active && shade_mode == ShadeActivated ) - setShade( ShadeNormal ); - - StackingUpdatesBlocker blocker( workspace()); - workspace()->updateClientLayer( this ); // active windows may get different layer + if (!active && shade_mode == ShadeActivated) + setShade(ShadeNormal); + + StackingUpdatesBlocker blocker(workspace()); + workspace()->updateClientLayer(this); // active windows may get different layer ClientList mainclients = mainClients(); - for( ClientList::ConstIterator it = mainclients.constBegin(); - it != mainclients.constEnd(); - ++it ) - if( (*it)->isFullScreen()) // fullscreens go high even if their transient is active - workspace()->updateClientLayer( *it ); - if( decoration != NULL ) + for (ClientList::ConstIterator it = mainclients.constBegin(); + it != mainclients.constEnd(); + ++it) + if ((*it)->isFullScreen()) // fullscreens go high even if their transient is active + workspace()->updateClientLayer(*it); + if (decoration != NULL) decoration->activeChange(); updateMouseGrab(); updateUrgency(); // demand attention again if it's still urgent workspace()->checkUnredirect(); - } +} void Client::startupIdChanged() - { +{ KStartupInfoId asn_id; KStartupInfoData asn_data; - bool asn_valid = workspace()->checkStartupNotification( window(), asn_id, asn_data ); - if( !asn_valid ) + bool asn_valid = workspace()->checkStartupNotification(window(), asn_id, asn_data); + if (!asn_valid) return; // If the ASN contains desktop, move it to the desktop, otherwise move it to the current // desktop (since the new ASN should make the window act like if it's a new application // launched). However don't affect the window's desktop if it's set to be on all desktops. int desktop = workspace()->currentDesktop(); - if( asn_data.desktop() != 0 ) + if (asn_data.desktop() != 0) desktop = asn_data.desktop(); - if( !isOnAllDesktops()) - workspace()->sendClientToDesktop( this, desktop, true ); - if( asn_data.xinerama() != -1 ) - workspace()->sendClientToScreen( this, asn_data.xinerama()); + if (!isOnAllDesktops()) + workspace()->sendClientToDesktop(this, desktop, true); + if (asn_data.xinerama() != -1) + workspace()->sendClientToScreen(this, asn_data.xinerama()); Time timestamp = asn_id.timestamp(); - if( timestamp == 0 && asn_data.timestamp() != -1U ) + if (timestamp == 0 && asn_data.timestamp() != -1U) timestamp = asn_data.timestamp(); - if( timestamp != 0 ) - { - bool activate = workspace()->allowClientActivation( this, timestamp ); - if( asn_data.desktop() != 0 && !isOnCurrentDesktop()) + if (timestamp != 0) { + bool activate = workspace()->allowClientActivation(this, timestamp); + if (asn_data.desktop() != 0 && !isOnCurrentDesktop()) activate = false; // it was started on different desktop than current one - if( activate ) - workspace()->activateClient( this ); + if (activate) + workspace()->activateClient(this); else demandAttention(); - } } +} void Client::updateUrgency() - { - if( urgency ) +{ + if (urgency) demandAttention(); - } +} void Client::shortcutActivated() - { - workspace()->activateClient( this, true ); // force - } +{ + workspace()->activateClient(this, true); // force +} //**************************************** // Group //**************************************** - + void Group::startupIdChanged() - { +{ KStartupInfoId asn_id; KStartupInfoData asn_data; - bool asn_valid = workspace()->checkStartupNotification( leader_wid, asn_id, asn_data ); - if( !asn_valid ) + bool asn_valid = workspace()->checkStartupNotification(leader_wid, asn_id, asn_data); + if (!asn_valid) return; - if( asn_id.timestamp() != 0 && user_time != -1U - && timestampCompare( asn_id.timestamp(), user_time ) > 0 ) - { + if (asn_id.timestamp() != 0 && user_time != -1U + && timestampCompare(asn_id.timestamp(), user_time) > 0) { user_time = asn_id.timestamp(); - } - else if( asn_data.timestamp() != -1U && user_time != -1U - && timestampCompare( asn_data.timestamp(), user_time ) > 0 ) - { + } else if (asn_data.timestamp() != -1U && user_time != -1U + && timestampCompare(asn_data.timestamp(), user_time) > 0) { user_time = asn_data.timestamp(); - } } +} -void Group::updateUserTime( Time time ) - { // copy of Client::updateUserTime - if( time == CurrentTime ) +void Group::updateUserTime(Time time) +{ + // copy of Client::updateUserTime + if (time == CurrentTime) time = xTime(); - if( time != -1U - && ( user_time == CurrentTime - || timestampCompare( time, user_time ) > 0 )) // time > user_time + if (time != -1U + && (user_time == CurrentTime + || timestampCompare(time, user_time) > 0)) // time > user_time user_time = time; - } +} } // namespace diff --git a/atoms.cpp b/atoms.cpp index 0c9b66c5f..5e93b2ad9 100644 --- a/atoms.cpp +++ b/atoms.cpp @@ -27,7 +27,7 @@ namespace KWin { Atoms::Atoms() - { +{ const int max = 50; Atom* atoms[max]; @@ -84,41 +84,41 @@ Atoms::Atoms() atoms[n] = &kde_system_tray_embedding; names[n++] = (char*) "_KDE_SYSTEM_TRAY_EMBEDDING"; - + atoms[n] = &net_wm_take_activity; names[n++] = (char*) "_NET_WM_TAKE_ACTIVITY"; - + atoms[n] = &net_wm_window_opacity; names[n++] = (char*) "_NET_WM_WINDOW_OPACITY"; Atom fake; atoms[n] = &fake; names[n++] = (char *) "_DT_SM_WINDOW_INFO"; - + atoms[n] = &fake; names[n++] = (char *) "_MOTIF_WM_INFO"; // #172028 - + atoms[n] = &xdnd_aware; names[n++] = (char*) "XdndAware"; atoms[n] = &xdnd_position; names[n++] = (char*) "XdndPosition"; - + atoms[n] = &net_frame_extents; names[n++] = (char*) "_NET_FRAME_EXTENTS"; atoms[n] = &kde_net_wm_frame_strut; names[n++] = (char*) "_KDE_NET_WM_FRAME_STRUT"; - + atoms[n] = &net_wm_sync_request_counter; names[n++] = (char*) "_NET_WM_SYNC_REQUEST_COUNTER"; atoms[n] = &net_wm_sync_request; names[n++] = (char*) "_NET_WM_SYNC_REQUEST"; - assert( n <= max ); + assert(n <= max); - XInternAtoms( display(), names, n, false, atoms_return ); - for (int i = 0; i < n; i++ ) + XInternAtoms(display(), names, n, false, atoms_return); + for (int i = 0; i < n; i++) *atoms[i] = atoms_return[i]; - } +} } // namespace diff --git a/atoms.h b/atoms.h index 4002649e5..7d5752c2a 100644 --- a/atoms.h +++ b/atoms.h @@ -29,38 +29,38 @@ namespace KWin { class Atoms - { - public: - Atoms(); +{ +public: + Atoms(); - Atom kwin_running; - Atom activities; + Atom kwin_running; + Atom activities; - Atom wm_protocols; - Atom wm_delete_window; - Atom wm_take_focus; - Atom wm_change_state; - Atom wm_client_leader; - Atom wm_window_role; - Atom wm_state; - Atom sm_client_id; + Atom wm_protocols; + Atom wm_delete_window; + Atom wm_take_focus; + Atom wm_change_state; + Atom wm_client_leader; + Atom wm_window_role; + Atom wm_state; + Atom sm_client_id; - Atom motif_wm_hints; - Atom net_wm_context_help; - Atom net_wm_ping; - Atom kde_wm_change_state; - Atom net_wm_user_time; - Atom kde_net_wm_user_creation_time; - Atom kde_system_tray_embedding; - Atom net_wm_take_activity; - Atom net_wm_window_opacity; - Atom xdnd_aware; - Atom xdnd_position; - Atom net_frame_extents; - Atom kde_net_wm_frame_strut; - Atom net_wm_sync_request_counter; - Atom net_wm_sync_request; - }; + Atom motif_wm_hints; + Atom net_wm_context_help; + Atom net_wm_ping; + Atom kde_wm_change_state; + Atom net_wm_user_time; + Atom kde_net_wm_user_creation_time; + Atom kde_system_tray_embedding; + Atom net_wm_take_activity; + Atom net_wm_window_opacity; + Atom xdnd_aware; + Atom xdnd_position; + Atom net_frame_extents; + Atom kde_net_wm_frame_strut; + Atom net_wm_sync_request_counter; + Atom net_wm_sync_request; +}; extern Atoms* atoms; diff --git a/bridge.cpp b/bridge.cpp index c7bc6679b..5372d5a33 100644 --- a/bridge.cpp +++ b/bridge.cpp @@ -29,155 +29,151 @@ along with this program. If not, see . namespace KWin { -Bridge::Bridge( Client* cl ) - : c( cl ) - { - } +Bridge::Bridge(Client* cl) + : c(cl) +{ +} #define BRIDGE_HELPER( rettype, prototype, args1, args2, cst ) \ -rettype Bridge::prototype ( args1 ) cst \ + rettype Bridge::prototype ( args1 ) cst \ { \ - return c->prototype( args2 ); \ + return c->prototype( args2 ); \ } -BRIDGE_HELPER( bool, isActive,,, const ) -BRIDGE_HELPER( bool, isCloseable,,, const ) -BRIDGE_HELPER( bool, isMaximizable,,, const ) -BRIDGE_HELPER( Bridge::MaximizeMode, maximizeMode,,, const ) -BRIDGE_HELPER( bool, isMinimizable,,, const ) -BRIDGE_HELPER( bool, providesContextHelp,,, const ) -BRIDGE_HELPER( int, desktop,,, const ) -BRIDGE_HELPER( bool, isModal,,, const ) -BRIDGE_HELPER( bool, isShadeable,,, const ) -BRIDGE_HELPER( bool, isShade,,, const ) -BRIDGE_HELPER( bool, keepAbove,,, const ) -BRIDGE_HELPER( bool, keepBelow,,, const ) -BRIDGE_HELPER( bool, isMovable,,, const ) -BRIDGE_HELPER( bool, isResizable,,, const ) -BRIDGE_HELPER( QString, caption,,, const ) -BRIDGE_HELPER( void, processMousePressEvent, QMouseEvent* e, e, ) -BRIDGE_HELPER( QRect, geometry,,, const ) -BRIDGE_HELPER( void, closeWindow,,, ) -BRIDGE_HELPER( void, maximize, MaximizeMode m, m, ) -BRIDGE_HELPER( void, minimize,,, ) -BRIDGE_HELPER( void, showContextHelp,,, ) -BRIDGE_HELPER( void, setDesktop, int desktop, desktop, ) +BRIDGE_HELPER(bool, isActive, , , const) +BRIDGE_HELPER(bool, isCloseable, , , const) +BRIDGE_HELPER(bool, isMaximizable, , , const) +BRIDGE_HELPER(Bridge::MaximizeMode, maximizeMode, , , const) +BRIDGE_HELPER(bool, isMinimizable, , , const) +BRIDGE_HELPER(bool, providesContextHelp, , , const) +BRIDGE_HELPER(int, desktop, , , const) +BRIDGE_HELPER(bool, isModal, , , const) +BRIDGE_HELPER(bool, isShadeable, , , const) +BRIDGE_HELPER(bool, isShade, , , const) +BRIDGE_HELPER(bool, keepAbove, , , const) +BRIDGE_HELPER(bool, keepBelow, , , const) +BRIDGE_HELPER(bool, isMovable, , , const) +BRIDGE_HELPER(bool, isResizable, , , const) +BRIDGE_HELPER(QString, caption, , , const) +BRIDGE_HELPER(void, processMousePressEvent, QMouseEvent* e, e,) +BRIDGE_HELPER(QRect, geometry, , , const) +BRIDGE_HELPER(void, closeWindow, , ,) +BRIDGE_HELPER(void, maximize, MaximizeMode m, m,) +BRIDGE_HELPER(void, minimize, , ,) +BRIDGE_HELPER(void, showContextHelp, , ,) +BRIDGE_HELPER(void, setDesktop, int desktop, desktop,) -void Bridge::setKeepAbove( bool set ) - { - if( c->keepAbove() != set ) - c->workspace()->performWindowOperation( c, KeepAboveOp ); - } +void Bridge::setKeepAbove(bool set) +{ + if (c->keepAbove() != set) + c->workspace()->performWindowOperation(c, KeepAboveOp); +} -void Bridge::setKeepBelow( bool set ) - { - if( c->keepBelow() != set ) - c->workspace()->performWindowOperation( c, KeepBelowOp ); - } +void Bridge::setKeepBelow(bool set) +{ + if (c->keepBelow() != set) + c->workspace()->performWindowOperation(c, KeepBelowOp); +} -NET::WindowType Bridge::windowType( unsigned long supported_types ) const - { - return c->windowType( false, supported_types ); - } +NET::WindowType Bridge::windowType(unsigned long supported_types) const +{ + return c->windowType(false, supported_types); +} QIcon Bridge::icon() const - { - QIcon ret( c->icon()); - ret.addPixmap( c->miniIcon()); +{ + QIcon ret(c->icon()); + ret.addPixmap(c->miniIcon()); return ret; - } +} bool Bridge::isSetShade() const - { +{ return c->shadeMode() != ShadeNone; - } +} -void Bridge::showWindowMenu( const QPoint &p ) - { - c->workspace()->showWindowMenu( p, c ); - } +void Bridge::showWindowMenu(const QPoint &p) +{ + c->workspace()->showWindowMenu(p, c); +} -void Bridge::showWindowMenu( const QRect &p ) - { - c->workspace()->showWindowMenu( p, c ); - } +void Bridge::showWindowMenu(const QRect &p) +{ + c->workspace()->showWindowMenu(p, c); +} -void Bridge::performWindowOperation( WindowOperation op ) - { - c->workspace()->performWindowOperation( c, op ); - } +void Bridge::performWindowOperation(WindowOperation op) +{ + c->workspace()->performWindowOperation(c, op); +} -void Bridge::setMask( const QRegion& r, int mode ) - { - c->setMask( r, mode ); - } +void Bridge::setMask(const QRegion& r, int mode) +{ + c->setMask(r, mode); +} bool Bridge::isPreview() const - { +{ return false; - } +} QRect Bridge::iconGeometry() const - { +{ NETRect r = c->info->iconGeometry(); - return QRect( r.pos.x, r.pos.y, r.size.width, r.size.height ); - } + return QRect(r.pos.x, r.pos.y, r.size.width, r.size.height); +} WId Bridge::windowId() const - { +{ return c->window(); - } +} void Bridge::titlebarDblClickOperation() - { - c->workspace()->performWindowOperation( c, options->operationTitlebarDblClick()); - } +{ + c->workspace()->performWindowOperation(c, options->operationTitlebarDblClick()); +} -void Bridge::titlebarMouseWheelOperation( int delta ) - { - c->performMouseCommand( options->operationTitlebarMouseWheel( delta ), cursorPos()); - } +void Bridge::titlebarMouseWheelOperation(int delta) +{ + c->performMouseCommand(options->operationTitlebarMouseWheel(delta), cursorPos()); +} -void Bridge::setShade( bool set ) - { - c->setShade( set ? ShadeNormal : ShadeNone ); - } +void Bridge::setShade(bool set) +{ + c->setShade(set ? ShadeNormal : ShadeNone); +} int Bridge::currentDesktop() const - { +{ return c->workspace()->currentDesktop(); - } +} QWidget* Bridge::initialParentWidget() const - { +{ return NULL; - } +} Qt::WFlags Bridge::initialWFlags() const - { +{ return 0; - } +} -QRegion Bridge::unobscuredRegion( const QRegion& r ) const - { - QRegion reg( r ); +QRegion Bridge::unobscuredRegion(const QRegion& r) const +{ + QRegion reg(r); const ClientList stacking_order = c->workspace()->stackingOrder(); - int pos = stacking_order.indexOf( c ); + int pos = stacking_order.indexOf(c); ++pos; - for(; pos < stacking_order.count(); ++pos ) - { - if( !stacking_order[pos]->isShown( true )) + for (; pos < stacking_order.count(); ++pos) { + if (!stacking_order[pos]->isShown(true)) continue; // these don't obscure the window - if( c->isOnAllDesktops()) - { - if( !stacking_order[ pos ]->isOnCurrentDesktop()) + if (c->isOnAllDesktops()) { + if (!stacking_order[ pos ]->isOnCurrentDesktop()) continue; - } - else - { - if( !stacking_order[ pos ]->isOnDesktop( c->desktop())) + } else { + if (!stacking_order[ pos ]->isOnDesktop(c->desktop())) continue; - } + } /* the clients all have their mask-regions in local coords so we have to translate them to a shared coord system we choose ours */ @@ -186,121 +182,119 @@ QRegion Bridge::unobscuredRegion( const QRegion& r ) const QRegion creg = stacking_order[ pos ]->mask(); creg.translate(dx, dy); reg -= creg; - if (reg.isEmpty()) - { + if (reg.isEmpty()) { // early out, we are completely obscured break; - } } - return reg; } + return reg; +} -void Bridge::grabXServer( bool grab ) - { - if( grab ) +void Bridge::grabXServer(bool grab) +{ + if (grab) KWin::grabXServer(); else KWin::ungrabXServer(); - } +} bool Bridge::compositingActive() const - { +{ return c->workspace()->compositingActive(); - } +} QRect Bridge::transparentRect() const - { +{ return c->transparentRect().translated(-c->decorationRect().topLeft()); - } +} bool Bridge::isClientGroupActive() - { - if( c->clientGroup() ) +{ + if (c->clientGroup()) return c->clientGroup()->containsActiveClient(); return isActive(); - } +} QList< ClientGroupItem > Bridge::clientGroupItems() const - { - if( c->clientGroup() ) +{ + if (c->clientGroup()) return c->clientGroup()->items(); QList< ClientGroupItem > items; - QIcon icon( c->icon() ); - icon.addPixmap( c->miniIcon() ); - items.append( ClientGroupItem( c->caption(), icon )); + QIcon icon(c->icon()); + icon.addPixmap(c->miniIcon()); + items.append(ClientGroupItem(c->caption(), icon)); return items; - } +} -long Bridge::itemId( int index ) - { - if( !c->clientGroup() ) +long Bridge::itemId(int index) +{ + if (!c->clientGroup()) return 0; const ClientList list = c->clientGroup()->clients(); - return reinterpret_cast( list.at( index )); - } + return reinterpret_cast(list.at(index)); +} int Bridge::visibleClientGroupItem() - { - if( c->clientGroup() ) +{ + if (c->clientGroup()) return c->clientGroup()->indexOfVisibleClient(); return 0; - } +} -void Bridge::setVisibleClientGroupItem( int index ) - { - if( c->clientGroup() ) - c->clientGroup()->setVisible( index ); - } +void Bridge::setVisibleClientGroupItem(int index) +{ + if (c->clientGroup()) + c->clientGroup()->setVisible(index); +} -void Bridge::moveItemInClientGroup( int index, int before ) - { - if( c->clientGroup() ) - c->clientGroup()->move( index, before ); - } +void Bridge::moveItemInClientGroup(int index, int before) +{ + if (c->clientGroup()) + c->clientGroup()->move(index, before); +} -void Bridge::moveItemToClientGroup( long itemId, int before ) - { - Client* item = reinterpret_cast( itemId ); - if( !c->workspace()->hasClient( item )) - { +void Bridge::moveItemToClientGroup(long itemId, int before) +{ + Client* item = reinterpret_cast(itemId); + if (!c->workspace()->hasClient(item)) { kWarning(1212) << "****** ARBITRARY CODE EXECUTION ATTEMPT DETECTED ******"; return; - } - if( item->clientGroup() ) - c->workspace()->moveItemToClientGroup( item->clientGroup(), item->clientGroup()->indexOfClient( item ), - c->clientGroup(), before ); } + if (item->clientGroup()) + c->workspace()->moveItemToClientGroup(item->clientGroup(), item->clientGroup()->indexOfClient(item), + c->clientGroup(), before); +} -void Bridge::removeFromClientGroup( int index, const QRect& newGeom ) - { - if( c->clientGroup() ) - c->clientGroup()->remove( index, newGeom ); - } +void Bridge::removeFromClientGroup(int index, const QRect& newGeom) +{ + if (c->clientGroup()) + c->clientGroup()->remove(index, newGeom); +} -void Bridge::closeClientGroupItem( int index ) - { - if( !c->clientGroup() ) +void Bridge::closeClientGroupItem(int index) +{ + if (!c->clientGroup()) return; const ClientList list = c->clientGroup()->clients(); - if( index >= 0 || index <= list.count() ) - list.at( index )->closeWindow(); - } + if (index >= 0 || index <= list.count()) + list.at(index)->closeWindow(); +} void Bridge::closeAllInClientGroup() - { - if( c->clientGroup() ) +{ + if (c->clientGroup()) c->clientGroup()->closeAll(); - } +} -void Bridge::displayClientMenu( int index, const QPoint& pos ) - { - if( c->clientGroup() ) - c->clientGroup()->displayClientMenu( index, pos ); - } +void Bridge::displayClientMenu(int index, const QPoint& pos) +{ + if (c->clientGroup()) + c->clientGroup()->displayClientMenu(index, pos); +} -KDecoration::WindowOperation Bridge::buttonToWindowOperation( Qt::MouseButtons button ) - { - return c->mouseButtonToWindowOperation( button ); - } +KDecoration::WindowOperation Bridge::buttonToWindowOperation(Qt::MouseButtons button) +{ + return c->mouseButtonToWindowOperation(button); +} } // namespace diff --git a/bridge.h b/bridge.h index 9bd446ccd..3085fda62 100644 --- a/bridge.h +++ b/bridge.h @@ -29,72 +29,72 @@ namespace KWin class Client; class Bridge : public KDecorationBridgeUnstable - { - public: - Bridge( Client* cl ); - virtual bool isActive() const; - virtual bool isCloseable() const; - virtual bool isMaximizable() const; - virtual MaximizeMode maximizeMode() const; - virtual bool isMinimizable() const; - virtual bool providesContextHelp() const; - virtual int desktop() const; - virtual bool isModal() const; - virtual bool isShadeable() const; - virtual bool isShade() const; - virtual bool isSetShade() const; - virtual bool keepAbove() const; - virtual bool keepBelow() const; - virtual bool isMovable() const; - virtual bool isResizable() const; - virtual NET::WindowType windowType( unsigned long supported_types ) const; - virtual QIcon icon() const; - virtual QString caption() const; - virtual void processMousePressEvent( QMouseEvent* ); - virtual void showWindowMenu( const QPoint & ); - virtual void showWindowMenu( const QRect & ); - virtual void performWindowOperation( WindowOperation ); - virtual void setMask( const QRegion&, int ); - virtual bool isPreview() const; - virtual QRect geometry() const; - virtual QRect iconGeometry() const; - virtual QRegion unobscuredRegion( const QRegion& r ) const; - virtual WId windowId() const; - virtual void closeWindow(); - virtual void maximize( MaximizeMode mode ); - virtual void minimize(); - virtual void showContextHelp(); - virtual void setDesktop( int desktop ); - virtual void titlebarDblClickOperation(); - virtual void titlebarMouseWheelOperation( int delta ); - virtual void setShade( bool set ); - virtual void setKeepAbove( bool ); - virtual void setKeepBelow( bool ); - virtual int currentDesktop() const; - virtual QWidget* initialParentWidget() const; - virtual Qt::WFlags initialWFlags() const; - virtual void grabXServer( bool grab ); +{ +public: + Bridge(Client* cl); + virtual bool isActive() const; + virtual bool isCloseable() const; + virtual bool isMaximizable() const; + virtual MaximizeMode maximizeMode() const; + virtual bool isMinimizable() const; + virtual bool providesContextHelp() const; + virtual int desktop() const; + virtual bool isModal() const; + virtual bool isShadeable() const; + virtual bool isShade() const; + virtual bool isSetShade() const; + virtual bool keepAbove() const; + virtual bool keepBelow() const; + virtual bool isMovable() const; + virtual bool isResizable() const; + virtual NET::WindowType windowType(unsigned long supported_types) const; + virtual QIcon icon() const; + virtual QString caption() const; + virtual void processMousePressEvent(QMouseEvent*); + virtual void showWindowMenu(const QPoint &); + virtual void showWindowMenu(const QRect &); + virtual void performWindowOperation(WindowOperation); + virtual void setMask(const QRegion&, int); + virtual bool isPreview() const; + virtual QRect geometry() const; + virtual QRect iconGeometry() const; + virtual QRegion unobscuredRegion(const QRegion& r) const; + virtual WId windowId() const; + virtual void closeWindow(); + virtual void maximize(MaximizeMode mode); + virtual void minimize(); + virtual void showContextHelp(); + virtual void setDesktop(int desktop); + virtual void titlebarDblClickOperation(); + virtual void titlebarMouseWheelOperation(int delta); + virtual void setShade(bool set); + virtual void setKeepAbove(bool); + virtual void setKeepBelow(bool); + virtual int currentDesktop() const; + virtual QWidget* initialParentWidget() const; + virtual Qt::WFlags initialWFlags() const; + virtual void grabXServer(bool grab); - virtual bool compositingActive() const; - virtual QRect transparentRect() const; + virtual bool compositingActive() const; + virtual QRect transparentRect() const; - // Window tabbing - virtual bool isClientGroupActive(); - virtual QList< ClientGroupItem > clientGroupItems() const; - virtual long itemId( int index ); - virtual int visibleClientGroupItem(); - virtual void setVisibleClientGroupItem( int index ); - virtual void moveItemInClientGroup( int index, int before ); - virtual void moveItemToClientGroup( long itemId, int before ); - virtual void removeFromClientGroup( int index, const QRect& newGeom ); - virtual void closeClientGroupItem( int index ); - virtual void closeAllInClientGroup(); - virtual void displayClientMenu( int index, const QPoint& pos ); - virtual WindowOperation buttonToWindowOperation( Qt::MouseButtons button ); + // Window tabbing + virtual bool isClientGroupActive(); + virtual QList< ClientGroupItem > clientGroupItems() const; + virtual long itemId(int index); + virtual int visibleClientGroupItem(); + virtual void setVisibleClientGroupItem(int index); + virtual void moveItemInClientGroup(int index, int before); + virtual void moveItemToClientGroup(long itemId, int before); + virtual void removeFromClientGroup(int index, const QRect& newGeom); + virtual void closeClientGroupItem(int index); + virtual void closeAllInClientGroup(); + virtual void displayClientMenu(int index, const QPoint& pos); + virtual WindowOperation buttonToWindowOperation(Qt::MouseButtons button); - private: - Client* c; - }; +private: + Client* c; +}; } // namespace diff --git a/client.cpp b/client.cpp index 3641c367b..f3132e050 100644 --- a/client.cpp +++ b/client.cpp @@ -84,60 +84,61 @@ namespace KWin * This ctor is "dumb" - it only initializes data. All the real initialization * is done in manage(). */ -Client::Client( Workspace* ws ) - : Toplevel( ws ) - , client( None ) - , wrapper( None ) - , decoration( NULL ) - , bridge( new Bridge( this )) - , move_faked_activity( false ) - , move_resize_grab_window( None ) - , move_resize_has_keyboard_grab( false ) - , transient_for( NULL ) - , transient_for_id( None ) - , original_transient_for_id( None ) - , autoRaiseTimer( NULL ) - , shadeHoverTimer( NULL ) - , delayedMoveResizeTimer( NULL ) - , in_group( NULL ) - , window_group( None ) - , client_group( NULL ) - , in_layer( UnknownLayer ) - , ping_timer( NULL ) - , process_killer( NULL ) - , user_time( CurrentTime ) // Not known yet - , allowed_actions( 0 ) - , block_geometry_updates( 0 ) - , pending_geometry_update( PendingGeometryNone ) - , shade_geometry_change( false ) +Client::Client(Workspace* ws) + : Toplevel(ws) + , client(None) + , wrapper(None) + , decoration(NULL) + , bridge(new Bridge(this)) + , move_faked_activity(false) + , move_resize_grab_window(None) + , move_resize_has_keyboard_grab(false) + , transient_for (NULL) + , transient_for_id(None) + , original_transient_for_id(None) + , autoRaiseTimer(NULL) + , shadeHoverTimer(NULL) + , delayedMoveResizeTimer(NULL) + , in_group(NULL) + , window_group(None) + , client_group(NULL) + , in_layer(UnknownLayer) + , ping_timer(NULL) + , process_killer(NULL) + , user_time(CurrentTime) // Not known yet + , allowed_actions(0) + , block_geometry_updates(0) + , pending_geometry_update(PendingGeometryNone) + , shade_geometry_change(false) #ifdef HAVE_XSYNC - , sync_counter( None ) - , sync_alarm( None ) + , sync_counter(None) + , sync_alarm(None) #endif - , sync_timeout( NULL ) - , sync_resize_pending( false ) - , border_left( 0 ) - , border_right( 0 ) - , border_top( 0 ) - , border_bottom( 0 ) - , padding_left( 0 ) - , padding_right( 0 ) - , padding_top( 0 ) - , padding_bottom( 0 ) - , sm_stacking_order( -1 ) - , demandAttentionKNotifyTimer( NULL ) - , paintRedirector( 0 ) - , electricMaximizing( false ) - , activitiesDefined( false ) + , sync_timeout(NULL) + , sync_resize_pending(false) + , border_left(0) + , border_right(0) + , border_top(0) + , border_bottom(0) + , padding_left(0) + , padding_right(0) + , padding_top(0) + , padding_bottom(0) + , sm_stacking_order(-1) + , demandAttentionKNotifyTimer(NULL) + , paintRedirector(0) + , electricMaximizing(false) + , activitiesDefined(false) , needsSessionInteract(false) - { // TODO: Do all as initialization - +{ + // TODO: Do all as initialization + scriptCache = new QHash(); // Set the initial mapping state mapping_state = Withdrawn; quick_tile_mode = QuickTileNone; - geom_pretile = QRect( 0, 0, 0, 0 ); + geom_pretile = QRect(0, 0, 0, 0); desk = 0; // No desktop yet mode = PositionCenter; @@ -180,278 +181,271 @@ Client::Client( Workspace* ws ) maxmode_restore = MaximizeRestore; cmap = None; - + //Client to workspace connections require that each //client constructed be connected to the workspace wrapper // TabBoxClient m_tabBoxClient = new TabBox::TabBoxClientImpl(); - m_tabBoxClient->setClient( this ); + m_tabBoxClient->setClient(this); - geom = QRect( 0, 0, 100, 100 ); // So that decorations don't start with size being (0,0) - client_size = QSize( 100, 100 ); + geom = QRect(0, 0, 100, 100); // So that decorations don't start with size being (0,0) + client_size = QSize(100, 100); #if defined(HAVE_XSYNC) || defined(HAVE_XDAMAGE) ready_for_painting = false; // wait for first damage or sync reply #endif // SELI TODO: Initialize xsizehints?? - } +} /** * "Dumb" destructor. */ Client::~Client() - { +{ //SWrapper::Client::clientRelease(this); #ifdef HAVE_XSYNC - if( sync_alarm != None ) - XSyncDestroyAlarm( display(), sync_alarm ); + if (sync_alarm != None) + XSyncDestroyAlarm(display(), sync_alarm); #endif assert(!moveResizeMode); - assert( client == None ); - assert( wrapper == None ); + assert(client == None); + assert(wrapper == None); //assert( frameId() == None ); - assert( decoration == NULL ); - assert( block_geometry_updates == 0 ); - assert( !check_active_modal ); + assert(decoration == NULL); + assert(block_geometry_updates == 0); + assert(!check_active_modal); delete bridge; delete m_tabBoxClient; delete scriptCache; - } +} // Use destroyClient() or releaseWindow(), Client instances cannot be deleted directly -void Client::deleteClient( Client* c, allowed_t ) - { +void Client::deleteClient(Client* c, allowed_t) +{ delete c; - } - +} + /** * Releases the window. The client has done its job and the window is still existing. */ -void Client::releaseWindow( bool on_shutdown ) - { - assert( !deleting ); +void Client::releaseWindow(bool on_shutdown) +{ + assert(!deleting); deleting = true; - Deleted* del = Deleted::create( this ); - if( effects ) - { - static_cast(effects)->windowClosed( effectWindow()); - scene->windowClosed( this, del ); - } + Deleted* del = Deleted::create(this); + if (effects) { + static_cast(effects)->windowClosed(effectWindow()); + scene->windowClosed(this, del); + } finishCompositing(); - workspace()->discardUsedWindowRules( this, true ); // Remove ForceTemporarily rules - StackingUpdatesBlocker blocker( workspace()); + workspace()->discardUsedWindowRules(this, true); // Remove ForceTemporarily rules + StackingUpdatesBlocker blocker(workspace()); if (moveResizeMode) - leaveMoveResize(); + leaveMoveResize(); finishWindowRules(); ++block_geometry_updates; - if( isOnCurrentDesktop() && isShown( true )) - addWorkspaceRepaint( visibleRect() ); + if (isOnCurrentDesktop() && isShown(true)) + addWorkspaceRepaint(visibleRect()); // Grab X during the release to make removing of properties, setting to withdrawn state // and repareting to root an atomic operation (http://lists.kde.org/?l=kde-devel&m=116448102901184&w=2) grabXServer(); - exportMappingState( WithdrawnState ); - setModal( false ); // Otherwise its mainwindow wouldn't get focus + exportMappingState(WithdrawnState); + setModal(false); // Otherwise its mainwindow wouldn't get focus hidden = true; // So that it's not considered visible anymore (can't use hideClient(), it would set flags) - if( !on_shutdown ) - workspace()->clientHidden( this ); - XUnmapWindow( display(), frameId()); // Destroying decoration would cause ugly visual effect + if (!on_shutdown) + workspace()->clientHidden(this); + XUnmapWindow(display(), frameId()); // Destroying decoration would cause ugly visual effect destroyDecoration(); cleanGrouping(); - if( clientGroup() ) - clientGroup()->remove( this, QRect(), true ); - if( !on_shutdown ) - { - workspace()->removeClient( this, Allowed ); + if (clientGroup()) + clientGroup()->remove(this, QRect(), true); + if (!on_shutdown) { + workspace()->removeClient(this, Allowed); // Only when the window is being unmapped, not when closing down KWin (NETWM sections 5.5,5.7) - info->setDesktop( 0 ); + info->setDesktop(0); desk = 0; - info->setState( 0, info->state()); // Reset all state flags - } - XDeleteProperty( display(), client, atoms->kde_net_wm_user_creation_time); - XDeleteProperty( display(), client, atoms->net_frame_extents ); - XDeleteProperty( display(), client, atoms->kde_net_wm_frame_strut ); - XReparentWindow( display(), client, rootWindow(), x(), y()); - XRemoveFromSaveSet( display(), client ); - XSelectInput( display(), client, NoEventMask ); - if( on_shutdown ) + info->setState(0, info->state()); // Reset all state flags + } + XDeleteProperty(display(), client, atoms->kde_net_wm_user_creation_time); + XDeleteProperty(display(), client, atoms->net_frame_extents); + XDeleteProperty(display(), client, atoms->kde_net_wm_frame_strut); + XReparentWindow(display(), client, rootWindow(), x(), y()); + XRemoveFromSaveSet(display(), client); + XSelectInput(display(), client, NoEventMask); + if (on_shutdown) // Map the window, so it can be found after another WM is started - XMapWindow( display(), client ); - // TODO: Preserve minimized, shaded etc. state? + XMapWindow(display(), client); + // TODO: Preserve minimized, shaded etc. state? else // Make sure it's not mapped if the app unmapped it (#65279). The app - // may do map+unmap before we initially map the window by calling rawShow() from manage(). - XUnmapWindow( display(), client ); + // may do map+unmap before we initially map the window by calling rawShow() from manage(). + XUnmapWindow(display(), client); client = None; - XDestroyWindow( display(), wrapper ); + XDestroyWindow(display(), wrapper); wrapper = None; - XDestroyWindow( display(), frameId()); + XDestroyWindow(display(), frameId()); //frame = None; --block_geometry_updates; // Don't use GeometryUpdatesBlocker, it would now set the geometry disownDataPassedToDeleted(); del->unrefWindow(); checkNonExistentClients(); - deleteClient( this, Allowed ); + deleteClient(this, Allowed); ungrabXServer(); - } +} /** * Like releaseWindow(), but this one is called when the window has been already destroyed * (E.g. The application closed it) */ void Client::destroyClient() - { - assert( !deleting ); +{ + assert(!deleting); deleting = true; - Deleted* del = Deleted::create( this ); - if( effects ) - { - static_cast(effects)->windowClosed( effectWindow()); - scene->windowClosed( this, del ); - } + Deleted* del = Deleted::create(this); + if (effects) { + static_cast(effects)->windowClosed(effectWindow()); + scene->windowClosed(this, del); + } finishCompositing(); - workspace()->discardUsedWindowRules( this, true ); // Remove ForceTemporarily rules - StackingUpdatesBlocker blocker( workspace()); + workspace()->discardUsedWindowRules(this, true); // Remove ForceTemporarily rules + StackingUpdatesBlocker blocker(workspace()); if (moveResizeMode) - leaveMoveResize(); + leaveMoveResize(); finishWindowRules(); ++block_geometry_updates; - if( isOnCurrentDesktop() && isShown( true )) - addWorkspaceRepaint( visibleRect() ); - setModal( false ); + if (isOnCurrentDesktop() && isShown(true)) + addWorkspaceRepaint(visibleRect()); + setModal(false); hidden = true; // So that it's not considered visible anymore - workspace()->clientHidden( this ); + workspace()->clientHidden(this); destroyDecoration(); cleanGrouping(); - if( clientGroup() ) - clientGroup()->remove( this, QRect(), true ); - workspace()->removeClient( this, Allowed ); + if (clientGroup()) + clientGroup()->remove(this, QRect(), true); + workspace()->removeClient(this, Allowed); client = None; // invalidate - XDestroyWindow( display(), wrapper ); + XDestroyWindow(display(), wrapper); wrapper = None; - XDestroyWindow( display(), frameId()); + XDestroyWindow(display(), frameId()); //frame = None; --block_geometry_updates; // Don't use GeometryUpdatesBlocker, it would now set the geometry disownDataPassedToDeleted(); del->unrefWindow(); checkNonExistentClients(); - deleteClient( this, Allowed ); - } + deleteClient(this, Allowed); +} -void Client::updateDecoration( bool check_workspace_pos, bool force ) - { - if( !force && - (( decoration == NULL && noBorder() ) || ( decoration != NULL && !noBorder() ))) +void Client::updateDecoration(bool check_workspace_pos, bool force) +{ + if (!force && + ((decoration == NULL && noBorder()) || (decoration != NULL && !noBorder()))) return; QRect oldgeom = geometry(); - blockGeometryUpdates( true ); - if( force ) + blockGeometryUpdates(true); + if (force) destroyDecoration(); - if( !noBorder() ) - { - setMask( QRegion()); // Reset shape mask - decoration = workspace()->createDecoration( bridge ); + if (!noBorder()) { + setMask(QRegion()); // Reset shape mask + decoration = workspace()->createDecoration(bridge); // TODO: Check decoration's minimum size? decoration->init(); - decoration->widget()->installEventFilter( this ); - XReparentWindow( display(), decoration->widget()->winId(), frameId(), 0, 0 ); + decoration->widget()->installEventFilter(this); + XReparentWindow(display(), decoration->widget()->winId(), frameId(), 0, 0); decoration->widget()->lower(); - decoration->borders( border_left, border_right, border_top, border_bottom ); + decoration->borders(border_left, border_right, border_top, border_bottom); padding_left = padding_right = padding_top = padding_bottom = 0; if (KDecorationUnstable *deco2 = dynamic_cast(decoration)) - deco2->padding( padding_left, padding_right, padding_top, padding_bottom ); - XMoveWindow( display(), decoration->widget()->winId(), -padding_left, -padding_top ); - move( calculateGravitation( false )); - plainResize( sizeForClientSize( clientSize()), ForceGeometrySet ); - paintRedirector = new PaintRedirector( decoration->widget()); - connect( paintRedirector, SIGNAL( paintPending()), SLOT( repaintDecorationPending())); + deco2->padding(padding_left, padding_right, padding_top, padding_bottom); + XMoveWindow(display(), decoration->widget()->winId(), -padding_left, -padding_top); + move(calculateGravitation(false)); + plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); + paintRedirector = new PaintRedirector(decoration->widget()); + connect(paintRedirector, SIGNAL(paintPending()), SLOT(repaintDecorationPending())); resizeDecorationPixmaps(); - if( compositing() ) + if (compositing()) discardWindowPixmap(); - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), oldgeom ); - } - else + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), oldgeom); + } else destroyDecoration(); - if( check_workspace_pos ) + if (check_workspace_pos) checkWorkspacePosition(); - blockGeometryUpdates( false ); - if( !noBorder() ) + blockGeometryUpdates(false); + if (!noBorder()) decoration->widget()->show(); updateFrameExtents(); - } +} void Client::destroyDecoration() - { +{ QRect oldgeom = geometry(); - if( decoration != NULL ) - { + if (decoration != NULL) { delete decoration; decoration = NULL; - QPoint grav = calculateGravitation( true ); + QPoint grav = calculateGravitation(true); border_left = border_right = border_top = border_bottom = 0; - setMask( QRegion()); // Reset shape mask - plainResize( sizeForClientSize( clientSize()), ForceGeometrySet ); - move( grav ); + setMask(QRegion()); // Reset shape mask + plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); + move(grav); delete paintRedirector; paintRedirector = NULL; decorationPixmapLeft = decorationPixmapRight = decorationPixmapTop = decorationPixmapBottom = QPixmap(); - if( compositing() ) + if (compositing()) discardWindowPixmap(); - if( scene != NULL && !deleting ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL && !deleting ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), oldgeom ); - } + if (scene != NULL && !deleting) + scene->windowGeometryShapeChanged(this); + if (effects != NULL && !deleting) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), oldgeom); } +} -bool Client::checkBorderSizes( bool also_resize ) - { - if( decoration == NULL ) +bool Client::checkBorderSizes(bool also_resize) +{ + if (decoration == NULL) return false; int new_left = 0, new_right = 0, new_top = 0, new_bottom = 0; if (KDecorationUnstable *deco2 = dynamic_cast(decoration)) - deco2->padding( new_left, new_right, new_top, new_bottom ); + deco2->padding(new_left, new_right, new_top, new_bottom); if (padding_left != new_left || padding_top != new_top) - XMoveWindow( display(), decoration->widget()->winId(), -new_left, -new_top ); + XMoveWindow(display(), decoration->widget()->winId(), -new_left, -new_top); padding_left = new_left; padding_right = new_right; padding_top = new_top; padding_bottom = new_bottom; - decoration->borders( new_left, new_right, new_top, new_bottom ); - if( new_left == border_left && new_right == border_right && - new_top == border_top && new_bottom == border_bottom ) + decoration->borders(new_left, new_right, new_top, new_bottom); + if (new_left == border_left && new_right == border_right && + new_top == border_top && new_bottom == border_bottom) return false; - if( !also_resize ) - { + if (!also_resize) { border_left = new_left; border_right = new_right; border_top = new_top; border_bottom = new_bottom; return true; - } - GeometryUpdatesBlocker blocker( this ); - move( calculateGravitation( true )); + } + GeometryUpdatesBlocker blocker(this); + move(calculateGravitation(true)); border_left = new_left; border_right = new_right; border_top = new_top; border_bottom = new_bottom; - move( calculateGravitation( false )); - plainResize( sizeForClientSize( clientSize() ), ForceGeometrySet ); + move(calculateGravitation(false)); + plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); checkWorkspacePosition(); return true; - } +} void Client::triggerDecorationRepaint() - { - if( decoration != NULL ) +{ + if (decoration != NULL) decoration->widget()->update(); - } +} void Client::layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom, Client::CoordinateMode mode) const - { +{ QRect r = decoration->widget()->rect(); if (mode == WindowRelative) r.translate(-padding_left, -padding_top); @@ -461,14 +455,13 @@ void Client::layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect // Ignore the overlap strut when compositing is disabled if (!compositing() || !Workspace::self()->decorationSupportsFrameOverlap()) strut.left = strut.top = strut.right = strut.bottom = 0; - else if (strut.left == -1 && strut.top == -1 && strut.right == -1 && strut.bottom == -1) - { + else if (strut.left == -1 && strut.top == -1 && strut.right == -1 && strut.bottom == -1) { top = QRect(r.x(), r.y(), r.width(), r.height() / 3); left = QRect(r.x(), r.y() + top.height(), width() / 2, r.height() / 3); right = QRect(r.x() + left.width(), r.y() + top.height(), r.width() - left.width(), left.height()); bottom = QRect(r.x(), r.y() + top.height() + left.height(), r.width(), r.height() - left.height() - top.height()); return; - } + } top = QRect(r.x(), r.y(), r.width(), padding_top + border_top + strut.top); bottom = QRect(r.x(), r.y() + r.height() - padding_bottom - border_bottom - strut.bottom, @@ -477,39 +470,37 @@ void Client::layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect padding_left + border_left + strut.left, r.height() - top.height() - bottom.height()); right = QRect(r.x() + r.width() - padding_right - border_right - strut.right, r.y() + top.height(), padding_right + border_right + strut.right, r.height() - top.height() - bottom.height()); - } +} QRegion Client::decorationPendingRegion() const - { +{ if (!paintRedirector) return QRegion(); - return paintRedirector->scheduledRepaintRegion().translated( x() - padding_left, y() - padding_top ); - } + return paintRedirector->scheduledRepaintRegion().translated(x() - padding_left, y() - padding_top); +} void Client::repaintDecorationPending() - { - if (compositing()) - { +{ + if (compositing()) { // The scene will update the decoration pixmaps in the next painting pass // if it has not been already repainted before const QRegion r = paintRedirector->scheduledRepaintRegion(); if (!r.isEmpty()) - Workspace::self()->addRepaint( r.translated( x() - padding_left, y() - padding_top ) ); - } - else + Workspace::self()->addRepaint(r.translated(x() - padding_left, y() - padding_top)); + } else ensureDecorationPixmapsPainted(); - } +} bool Client::decorationPixmapRequiresRepaint() - { +{ if (!paintRedirector) return false; QRegion r = paintRedirector->pendingRegion(); return !r.isEmpty(); - } +} void Client::ensureDecorationPixmapsPainted() - { +{ if (!paintRedirector) return; @@ -520,102 +511,98 @@ void Client::ensureDecorationPixmapsPainted() QPixmap p = paintRedirector->performPendingPaint(); QRect lr, rr, tr, br; - layoutDecorationRects( lr, tr, rr, br, DecorationRelative ); + layoutDecorationRects(lr, tr, rr, br, DecorationRelative); - repaintDecorationPixmap( decorationPixmapLeft, lr, p, r ); - repaintDecorationPixmap( decorationPixmapRight, rr, p, r ); - repaintDecorationPixmap( decorationPixmapTop, tr, p, r ); - repaintDecorationPixmap( decorationPixmapBottom, br, p, r ); + repaintDecorationPixmap(decorationPixmapLeft, lr, p, r); + repaintDecorationPixmap(decorationPixmapRight, rr, p, r); + repaintDecorationPixmap(decorationPixmapTop, tr, p, r); + repaintDecorationPixmap(decorationPixmapBottom, br, p, r); - if (!compositing()) - { + if (!compositing()) { // Blit the pixmaps to the frame window - layoutDecorationRects( lr, tr, rr, br, WindowRelative ); + layoutDecorationRects(lr, tr, rr, br, WindowRelative); #ifdef HAVE_XRENDER - if (Extensions::renderAvailable()) - { - XRenderPictFormat* format = XRenderFindVisualFormat( display(), visual()); + if (Extensions::renderAvailable()) { + XRenderPictFormat* format = XRenderFindVisualFormat(display(), visual()); XRenderPictureAttributes pa; pa.subwindow_mode = IncludeInferiors; - Picture pic = XRenderCreatePicture( display(), frameId(), format, CPSubwindowMode, &pa ); - XRenderComposite( display(), PictOpSrc, decorationPixmapLeft.x11PictureHandle(), None, pic, - 0, 0, 0, 0, lr.x(), lr.y(), lr.width(), lr.height() ); - XRenderComposite( display(), PictOpSrc, decorationPixmapRight.x11PictureHandle(), None, pic, - 0, 0, 0, 0, rr.x(), rr.y(), rr.width(), rr.height() ); - XRenderComposite( display(), PictOpSrc, decorationPixmapTop.x11PictureHandle(), None, pic, - 0, 0, 0, 0, tr.x(), tr.y(), tr.width(), tr.height() ); - XRenderComposite( display(), PictOpSrc, decorationPixmapBottom.x11PictureHandle(), None, pic, - 0, 0, 0, 0, br.x(), br.y(), br.width(), br.height() ); - XRenderFreePicture( display(), pic ); // TODO don't recreate pictures all the time? - } - else + Picture pic = XRenderCreatePicture(display(), frameId(), format, CPSubwindowMode, &pa); + XRenderComposite(display(), PictOpSrc, decorationPixmapLeft.x11PictureHandle(), None, pic, + 0, 0, 0, 0, lr.x(), lr.y(), lr.width(), lr.height()); + XRenderComposite(display(), PictOpSrc, decorationPixmapRight.x11PictureHandle(), None, pic, + 0, 0, 0, 0, rr.x(), rr.y(), rr.width(), rr.height()); + XRenderComposite(display(), PictOpSrc, decorationPixmapTop.x11PictureHandle(), None, pic, + 0, 0, 0, 0, tr.x(), tr.y(), tr.width(), tr.height()); + XRenderComposite(display(), PictOpSrc, decorationPixmapBottom.x11PictureHandle(), None, pic, + 0, 0, 0, 0, br.x(), br.y(), br.width(), br.height()); + XRenderFreePicture(display(), pic); // TODO don't recreate pictures all the time? + } else #endif - { + { XGCValues values; values.subwindow_mode = IncludeInferiors; - GC gc = XCreateGC( display(), rootWindow(), GCSubwindowMode, &values ); - XCopyArea( display(), decorationPixmapLeft.handle(), frameId(), gc, 0, 0, - lr.width(), lr.height(), lr.x(), lr.y() ); - XCopyArea( display(), decorationPixmapRight.handle(), frameId(), gc, 0, 0, - rr.width(), rr.height(), rr.x(), rr.y() ); - XCopyArea( display(), decorationPixmapTop.handle(), frameId(), gc, 0, 0, - tr.width(), tr.height(), tr.x(), tr.y() ); - XCopyArea( display(), decorationPixmapBottom.handle(), frameId(), gc, 0, 0, - br.width(), br.height(), br.x(), br.y() ); - XFreeGC( display(), gc ); - } + GC gc = XCreateGC(display(), rootWindow(), GCSubwindowMode, &values); + XCopyArea(display(), decorationPixmapLeft.handle(), frameId(), gc, 0, 0, + lr.width(), lr.height(), lr.x(), lr.y()); + XCopyArea(display(), decorationPixmapRight.handle(), frameId(), gc, 0, 0, + rr.width(), rr.height(), rr.x(), rr.y()); + XCopyArea(display(), decorationPixmapTop.handle(), frameId(), gc, 0, 0, + tr.width(), tr.height(), tr.x(), tr.y()); + XCopyArea(display(), decorationPixmapBottom.handle(), frameId(), gc, 0, 0, + br.width(), br.height(), br.x(), br.y()); + XFreeGC(display(), gc); } - else - XSync( display(), false ); - } + } else + XSync(display(), false); +} -void Client::repaintDecorationPixmap( QPixmap& pix, const QRect& r, const QPixmap& src, QRegion reg ) - { - if( !r.isValid()) +void Client::repaintDecorationPixmap(QPixmap& pix, const QRect& r, const QPixmap& src, QRegion reg) +{ + if (!r.isValid()) return; QRect b = reg.boundingRect(); reg &= r; - if( reg.isEmpty()) + if (reg.isEmpty()) return; - QPainter pt( &pix ); - pt.translate( -r.topLeft() ); - pt.setCompositionMode( QPainter::CompositionMode_Source ); - pt.setClipRegion( reg ); - pt.drawPixmap( b.topLeft(), src ); + QPainter pt(&pix); + pt.translate(-r.topLeft()); + pt.setCompositionMode(QPainter::CompositionMode_Source); + pt.setClipRegion(reg); + pt.drawPixmap(b.topLeft(), src); pt.end(); - } +} void Client::resizeDecorationPixmaps() - { +{ QRect lr, rr, tr, br; - layoutDecorationRects( lr, tr, rr, br, DecorationRelative ); + layoutDecorationRects(lr, tr, rr, br, DecorationRelative); - if ( decorationPixmapTop.size() != tr.size() ) - decorationPixmapTop = QPixmap( tr.size() ); + if (decorationPixmapTop.size() != tr.size()) + decorationPixmapTop = QPixmap(tr.size()); - if ( decorationPixmapBottom.size() != br.size() ) - decorationPixmapBottom = QPixmap( br.size() ); + if (decorationPixmapBottom.size() != br.size()) + decorationPixmapBottom = QPixmap(br.size()); - if ( decorationPixmapLeft.size() != lr.size() ) - decorationPixmapLeft = QPixmap( lr.size() ); + if (decorationPixmapLeft.size() != lr.size()) + decorationPixmapLeft = QPixmap(lr.size()); - if ( decorationPixmapRight.size() != rr.size() ) - decorationPixmapRight = QPixmap( rr.size() ); + if (decorationPixmapRight.size() != rr.size()) + decorationPixmapRight = QPixmap(rr.size()); #ifdef HAVE_XRENDER - if ( Extensions::renderAvailable() ) { + if (Extensions::renderAvailable()) { // Make sure the pixmaps are created with alpha channels - decorationPixmapLeft.fill( Qt::transparent ); - decorationPixmapRight.fill( Qt::transparent ); - decorationPixmapTop.fill( Qt::transparent ); - decorationPixmapBottom.fill( Qt::transparent ); + decorationPixmapLeft.fill(Qt::transparent); + decorationPixmapRight.fill(Qt::transparent); + decorationPixmapTop.fill(Qt::transparent); + decorationPixmapBottom.fill(Qt::transparent); } #endif triggerDecorationRepaint(); - } +} QRect Client::transparentRect() const - { +{ if (isShade()) return QRect(); @@ -627,60 +614,57 @@ QRect Client::transparentRect() const return QRect(); const QRect r = QRect(clientPos(), clientSize()) - .adjusted(strut.left, strut.top, -strut.right, -strut.bottom); + .adjusted(strut.left, strut.top, -strut.right, -strut.bottom); if (r.isValid()) return r; return QRect(); - } +} void Client::detectNoBorder() - { - if( shape()) - { +{ + if (shape()) { noborder = true; app_noborder = true; return; - } - switch( windowType()) - { - case NET::Desktop : - case NET::Dock : - case NET::TopMenu : - case NET::Splash : - noborder = true; - app_noborder = true; - break; - case NET::Unknown : - case NET::Normal : - case NET::Toolbar : - case NET::Menu : - case NET::Dialog : - case NET::Utility : - noborder = false; - break; - default: - abort(); - } + } + switch(windowType()) { + case NET::Desktop : + case NET::Dock : + case NET::TopMenu : + case NET::Splash : + noborder = true; + app_noborder = true; + break; + case NET::Unknown : + case NET::Normal : + case NET::Toolbar : + case NET::Menu : + case NET::Dialog : + case NET::Utility : + noborder = false; + break; + default: + abort(); + } // NET::Override is some strange beast without clear definition, usually // just meaning "noborder", so let's treat it only as such flag, and ignore it as // a window type otherwise (SUPPORTED_WINDOW_TYPES_MASK doesn't include it) - if( info->windowType( SUPPORTED_MANAGED_WINDOW_TYPES_MASK | NET::OverrideMask ) == NET::Override ) - { + if (info->windowType(SUPPORTED_MANAGED_WINDOW_TYPES_MASK | NET::OverrideMask) == NET::Override) { noborder = true; app_noborder = true; - } } +} void Client::updateFrameExtents() - { +{ NETStrut strut; strut.left = border_left; strut.right = border_right; strut.top = border_top; strut.bottom = border_bottom; - info->setFrameExtents( strut ); - } + info->setFrameExtents(strut); +} /** * Resizes the decoration, and makes sure the decoration widget gets resize event @@ -689,575 +673,554 @@ void Client::updateFrameExtents() * the decoration may turn on/off some borders, but the actual size * of the decoration stays the same). */ -void Client::resizeDecoration( const QSize& s ) - { - if( decoration == NULL ) +void Client::resizeDecoration(const QSize& s) +{ + if (decoration == NULL) return; QSize newSize = s + QSize(padding_left + padding_right, padding_top + padding_bottom); QSize oldSize = decoration->widget()->size(); - decoration->resize( newSize ); - if( oldSize == newSize ) - { - QResizeEvent e( newSize, oldSize ); - QApplication::sendEvent( decoration->widget(), &e ); - } - else // oldSize != newSize - { + decoration->resize(newSize); + if (oldSize == newSize) { + QResizeEvent e(newSize, oldSize); + QApplication::sendEvent(decoration->widget(), &e); + } else { // oldSize != newSize resizeDecorationPixmaps(); - } } +} bool Client::noBorder() const - { +{ return noborder || isFullScreen(); - } +} bool Client::userCanSetNoBorder() const - { - return !isFullScreen() && !isShade() && ( clientGroup() == NULL || !(clientGroup()->items().count() > 1)); - } +{ + return !isFullScreen() && !isShade() && (clientGroup() == NULL || !(clientGroup()->items().count() > 1)); +} -void Client::setNoBorder( bool set ) - { - if( !userCanSetNoBorder() ) +void Client::setNoBorder(bool set) +{ + if (!userCanSetNoBorder()) return; - set = rules()->checkNoBorder( set ); - if( noborder == set ) + set = rules()->checkNoBorder(set); + if (noborder == set) return; noborder = set; - updateDecoration( true, false ); + updateDecoration(true, false); updateWindowRules(); - } +} void Client::checkNoBorder() - { - setNoBorder( app_noborder ); - } +{ + setNoBorder(app_noborder); +} void Client::updateShape() - { - if( shape() ) - { // Workaround for #19644 - Shaped windows shouldn't have decoration - if( !app_noborder ) - { // Only when shape is detected for the first time, still let the user to override +{ + if (shape()) { + // Workaround for #19644 - Shaped windows shouldn't have decoration + if (!app_noborder) { + // Only when shape is detected for the first time, still let the user to override app_noborder = true; noborder = true; - updateDecoration( true ); - } + updateDecoration(true); } - if( shape() && noBorder() ) - XShapeCombineShape( display(), frameId(), ShapeBounding, - clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeSet ); + } + if (shape() && noBorder()) + XShapeCombineShape(display(), frameId(), ShapeBounding, + clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeSet); // Decoration mask (i.e. 'else' here) setting is done in setMask() // when the decoration calls it or when the decoration is created/destroyed updateInputShape(); - if( compositing()) - { + if (compositing()) { addRepaintFull(); - addWorkspaceRepaint( visibleRect() ); // In case shape change removes part of this window - } - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), geometry()); + addWorkspaceRepaint(visibleRect()); // In case shape change removes part of this window } + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), geometry()); +} static Window shape_helper_window = None; void Client::updateInputShape() - { - if( hiddenPreview() ) // Sets it to none, don't change +{ + if (hiddenPreview()) // Sets it to none, don't change return; - if( Extensions::shapeInputAvailable()) - { // There appears to be no way to find out if a window has input - // shape set or not, so always propagate the input shape - // (it's the same like the bounding shape by default). - // Also, build the shape using a helper window, not directly - // in the frame window, because the sequence set-shape-to-frame, - // remove-shape-of-client, add-input-shape-of-client has the problem - // that after the second step there's a hole in the input shape - // until the real shape of the client is added and that can make - // the window lose focus (which is a problem with mouse focus policies) - // TODO: It seems there is, after all - XShapeGetRectangles() - but maybe this is better - if( shape_helper_window == None ) - shape_helper_window = XCreateSimpleWindow( display(), rootWindow(), - 0, 0, 1, 1, 0, 0, 0 ); - XResizeWindow( display(), shape_helper_window, width(), height()); - XShapeCombineShape( display(), shape_helper_window, ShapeInput, 0, 0, - frameId(), ShapeBounding, ShapeSet ); - XShapeCombineShape( display(), shape_helper_window, ShapeInput, - clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeSubtract ); - XShapeCombineShape( display(), shape_helper_window, ShapeInput, - clientPos().x(), clientPos().y(), window(), ShapeInput, ShapeUnion ); - XShapeCombineShape( display(), frameId(), ShapeInput, 0, 0, - shape_helper_window, ShapeInput, ShapeSet ); - } + if (Extensions::shapeInputAvailable()) { + // There appears to be no way to find out if a window has input + // shape set or not, so always propagate the input shape + // (it's the same like the bounding shape by default). + // Also, build the shape using a helper window, not directly + // in the frame window, because the sequence set-shape-to-frame, + // remove-shape-of-client, add-input-shape-of-client has the problem + // that after the second step there's a hole in the input shape + // until the real shape of the client is added and that can make + // the window lose focus (which is a problem with mouse focus policies) + // TODO: It seems there is, after all - XShapeGetRectangles() - but maybe this is better + if (shape_helper_window == None) + shape_helper_window = XCreateSimpleWindow(display(), rootWindow(), + 0, 0, 1, 1, 0, 0, 0); + XResizeWindow(display(), shape_helper_window, width(), height()); + XShapeCombineShape(display(), shape_helper_window, ShapeInput, 0, 0, + frameId(), ShapeBounding, ShapeSet); + XShapeCombineShape(display(), shape_helper_window, ShapeInput, + clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeSubtract); + XShapeCombineShape(display(), shape_helper_window, ShapeInput, + clientPos().x(), clientPos().y(), window(), ShapeInput, ShapeUnion); + XShapeCombineShape(display(), frameId(), ShapeInput, 0, 0, + shape_helper_window, ShapeInput, ShapeSet); } +} -void Client::setMask( const QRegion& reg, int mode ) - { - QRegion r = reg.translated( -padding_left, -padding_right ) & QRect( 0, 0, width(), height() ); - if( _mask == r ) +void Client::setMask(const QRegion& reg, int mode) +{ + QRegion r = reg.translated(-padding_left, -padding_right) & QRect(0, 0, width(), height()); + if (_mask == r) return; _mask = r; Window shape_window = frameId(); - if( shape() ) - { // The same way of applying a shape without strange intermediate states like above - if( shape_helper_window == None ) - shape_helper_window = XCreateSimpleWindow( display(), rootWindow(), - 0, 0, 1, 1, 0, 0, 0 ); + if (shape()) { + // The same way of applying a shape without strange intermediate states like above + if (shape_helper_window == None) + shape_helper_window = XCreateSimpleWindow(display(), rootWindow(), + 0, 0, 1, 1, 0, 0, 0); shape_window = shape_helper_window; - } - if( _mask.isEmpty() ) - XShapeCombineMask( display(), shape_window, ShapeBounding, 0, 0, None, ShapeSet ); - else if( mode == X::Unsorted ) - XShapeCombineRegion( display(), shape_window, ShapeBounding, 0, 0, _mask.handle(), ShapeSet ); - else - { + } + if (_mask.isEmpty()) + XShapeCombineMask(display(), shape_window, ShapeBounding, 0, 0, None, ShapeSet); + else if (mode == X::Unsorted) + XShapeCombineRegion(display(), shape_window, ShapeBounding, 0, 0, _mask.handle(), ShapeSet); + else { QVector< QRect > rects = _mask.rects(); XRectangle* xrects = new XRectangle[rects.count()]; - for( int i = 0; i < rects.count(); ++i ) - { + for (int i = 0; i < rects.count(); ++i) { xrects[i].x = rects[i].x(); xrects[i].y = rects[i].y(); xrects[i].width = rects[i].width(); xrects[i].height = rects[i].height(); - } - XShapeCombineRectangles( display(), shape_window, ShapeBounding, 0, 0, - xrects, rects.count(), ShapeSet, mode ); + } + XShapeCombineRectangles(display(), shape_window, ShapeBounding, 0, 0, + xrects, rects.count(), ShapeSet, mode); delete[] xrects; - } - if( shape() ) - { // The rest of the applyign using a temporary window - XRectangle rec = { 0, 0, clientSize().width(), clientSize().height() }; - XShapeCombineRectangles( display(), shape_helper_window, ShapeBounding, - clientPos().x(), clientPos().y(), &rec, 1, ShapeSubtract, Unsorted ); - XShapeCombineShape( display(), shape_helper_window, ShapeBounding, - clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeUnion ); - XShapeCombineShape( display(), frameId(), ShapeBounding, 0, 0, - shape_helper_window, ShapeBounding, ShapeSet ); - } - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast( effects )->windowGeometryShapeChanged( effectWindow(), geometry() ); - updateShape(); } + if (shape()) { + // The rest of the applyign using a temporary window + XRectangle rec = { 0, 0, clientSize().width(), clientSize().height() }; + XShapeCombineRectangles(display(), shape_helper_window, ShapeBounding, + clientPos().x(), clientPos().y(), &rec, 1, ShapeSubtract, Unsorted); + XShapeCombineShape(display(), shape_helper_window, ShapeBounding, + clientPos().x(), clientPos().y(), window(), ShapeBounding, ShapeUnion); + XShapeCombineShape(display(), frameId(), ShapeBounding, 0, 0, + shape_helper_window, ShapeBounding, ShapeSet); + } + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), geometry()); + updateShape(); +} QRegion Client::mask() const - { - if( _mask.isEmpty() ) - return QRegion( 0, 0, width(), height() ); +{ + if (_mask.isEmpty()) + return QRegion(0, 0, width(), height()); return _mask; - } +} -void Client::hideClient( bool hide ) - { - if( hidden == hide ) +void Client::hideClient(bool hide) +{ + if (hidden == hide) return; hidden = hide; updateVisibility(); - } +} /** * Returns whether the window is minimizable or not */ bool Client::isMinimizable() const - { - if( isSpecialWindow() ) +{ + if (isSpecialWindow()) return false; - if( isTransient() ) - { // #66868 - Let other xmms windows be minimized when the mainwindow is minimized + if (isTransient()) { + // #66868 - Let other xmms windows be minimized when the mainwindow is minimized bool shown_mainwindow = false; ClientList mainclients = mainClients(); - for( ClientList::ConstIterator it = mainclients.constBegin(); - it != mainclients.constEnd(); - ++it ) - if( (*it)->isShown( true )) + for (ClientList::ConstIterator it = mainclients.constBegin(); + it != mainclients.constEnd(); + ++it) + if ((*it)->isShown(true)) shown_mainwindow = true; - if( !shown_mainwindow ) + if (!shown_mainwindow) return true; - } + } #if 0 // This is here because kicker's taskbar doesn't provide separate entries // for windows with an explicitly given parent // TODO: perhaps this should be redone // Disabled for now, since at least modal dialogs should be minimizable // (resulting in the mainwindow being minimized too). - if( transientFor() != NULL ) + if (transientFor() != NULL) return false; #endif - if( !wantsTabFocus() ) // SELI, TODO: - NET::Utility? why wantsTabFocus() - skiptaskbar? ? + if (!wantsTabFocus()) // SELI, TODO: - NET::Utility? why wantsTabFocus() - skiptaskbar? ? return false; return true; - } +} /** * Minimizes this client plus its transients */ -void Client::minimize( bool avoid_animation ) - { - if( !isMinimizable() || isMinimized() ) +void Client::minimize(bool avoid_animation) +{ + if (!isMinimizable() || isMinimized()) return; - + //Scripting call. Does not use a signal/slot mechanism //as ensuring connections was a bit difficult between //so many clients and the workspace SWrapper::WorkspaceProxy* ws_wrap = SWrapper::WorkspaceProxy::instance(); - if(ws_wrap != 0) { + if (ws_wrap != 0) { ws_wrap->sl_clientMinimized(this); } - + emit s_minimized(); - Notify::raise( Notify::Minimize ); + Notify::raise(Notify::Minimize); minimized = true; updateVisibility(); updateAllowedActions(); - workspace()->updateMinimizedOfTransients( this ); + workspace()->updateMinimizedOfTransients(this); updateWindowRules(); - workspace()->updateFocusChains( this, Workspace::FocusChainMakeLast ); - if( effects && !avoid_animation ) // TODO: Shouldn't it tell effects at least about the change? - static_cast(effects)->windowMinimized( effectWindow()); + workspace()->updateFocusChains(this, Workspace::FocusChainMakeLast); + if (effects && !avoid_animation) // TODO: Shouldn't it tell effects at least about the change? + static_cast(effects)->windowMinimized(effectWindow()); // when tiling, request a rearrangement - workspace()->notifyTilingWindowMinimizeToggled( this ); + workspace()->notifyTilingWindowMinimizeToggled(this); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} -void Client::unminimize( bool avoid_animation ) - { - if( !isMinimized()) +void Client::unminimize(bool avoid_animation) +{ + if (!isMinimized()) return; - + SWrapper::WorkspaceProxy* ws_wrap = SWrapper::WorkspaceProxy::instance(); - if(ws_wrap != 0) { + if (ws_wrap != 0) { ws_wrap->sl_clientUnminimized(this); } - + emit s_unminimized(); - Notify::raise( Notify::UnMinimize ); + Notify::raise(Notify::UnMinimize); minimized = false; updateVisibility(); updateAllowedActions(); - workspace()->updateMinimizedOfTransients( this ); + workspace()->updateMinimizedOfTransients(this); updateWindowRules(); workspace()->updateAllTiles(); - if( effects && !avoid_animation ) - static_cast( effects )->windowUnminimized( effectWindow() ); + if (effects && !avoid_animation) + static_cast(effects)->windowUnminimized(effectWindow()); // when tiling, request a rearrangement - workspace()->notifyTilingWindowMinimizeToggled( this ); + workspace()->notifyTilingWindowMinimizeToggled(this); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} QRect Client::iconGeometry() const - { +{ NETRect r = info->iconGeometry(); - QRect geom( r.pos.x, r.pos.y, r.size.width, r.size.height ); - if( geom.isValid() ) + QRect geom(r.pos.x, r.pos.y, r.size.width, r.size.height); + if (geom.isValid()) return geom; - else - { // Check all mainwindows of this window (recursively) - foreach( Client* mainwin, mainClients() ) - { + else { + // Check all mainwindows of this window (recursively) + foreach (Client * mainwin, mainClients()) { geom = mainwin->iconGeometry(); - if( geom.isValid() ) + if (geom.isValid()) return geom; - } + } // No mainwindow (or their parents) with icon geometry was found return QRect(); - } } +} bool Client::isShadeable() const - { +{ return !isSpecialWindow() && !noBorder(); - } +} -void Client::setShade( ShadeMode mode ) - { - if( !isShadeable()) +void Client::setShade(ShadeMode mode) +{ + if (!isShadeable()) return; - mode = rules()->checkShade( mode ); - if( shade_mode == mode ) + mode = rules()->checkShade(mode); + if (shade_mode == mode) return; bool was_shade = isShade(); ShadeMode was_shade_mode = shade_mode; shade_mode = mode; - if( was_shade == isShade()) - { - if( decoration != NULL ) // Decoration may want to update after e.g. hover-shade changes + if (was_shade == isShade()) { + if (decoration != NULL) // Decoration may want to update after e.g. hover-shade changes decoration->shadeChange(); return; // No real change in shaded state - } + } - if( shade_mode == ShadeNormal ) - { - if( isShown( true ) && isOnCurrentDesktop() ) - Notify::raise( Notify::ShadeUp ); - } - else if( shade_mode == ShadeNone ) - { - if( isShown( true ) && isOnCurrentDesktop() ) - Notify::raise( Notify::ShadeDown ); - } + if (shade_mode == ShadeNormal) { + if (isShown(true) && isOnCurrentDesktop()) + Notify::raise(Notify::ShadeUp); + } else if (shade_mode == ShadeNone) { + if (isShown(true) && isOnCurrentDesktop()) + Notify::raise(Notify::ShadeDown); + } - assert( decoration != NULL ); // noborder windows can't be shaded - GeometryUpdatesBlocker blocker( this ); + assert(decoration != NULL); // noborder windows can't be shaded + GeometryUpdatesBlocker blocker(this); // Decorations may turn off some borders when shaded - if( decoration ) - decoration->borders( border_left, border_right, border_top, border_bottom ); + if (decoration) + decoration->borders(border_left, border_right, border_top, border_bottom); // TODO: All this unmapping, resizing etc. feels too much duplicated from elsewhere - if ( isShade()) - { // shade_mode == ShadeNormal - addWorkspaceRepaint( visibleRect() ); + if (isShade()) { + // shade_mode == ShadeNormal + addWorkspaceRepaint(visibleRect()); // Shade shade_geometry_change = true; - QSize s( sizeForClientSize( QSize( clientSize() ))); - s.setHeight( border_top + border_bottom ); - XSelectInput( display(), wrapper, ClientWinMask ); // Avoid getting UnmapNotify - XUnmapWindow( display(), wrapper ); - XUnmapWindow( display(), client ); - XSelectInput( display(), wrapper, ClientWinMask | SubstructureNotifyMask ); - plainResize( s ); + QSize s(sizeForClientSize(QSize(clientSize()))); + s.setHeight(border_top + border_bottom); + XSelectInput(display(), wrapper, ClientWinMask); // Avoid getting UnmapNotify + XUnmapWindow(display(), wrapper); + XUnmapWindow(display(), client); + XSelectInput(display(), wrapper, ClientWinMask | SubstructureNotifyMask); + plainResize(s); shade_geometry_change = false; - if( isActive()) - { - if( was_shade_mode == ShadeHover ) - workspace()->activateNextClient( this ); + if (isActive()) { + if (was_shade_mode == ShadeHover) + workspace()->activateNextClient(this); else workspace()->focusToNull(); - } } - else - { + } else { shade_geometry_change = true; - QSize s( sizeForClientSize( clientSize() )); + QSize s(sizeForClientSize(clientSize())); shade_geometry_change = false; - plainResize( s ); - if( shade_mode == ShadeHover || shade_mode == ShadeActivated ) - setActive( true ); - XMapWindow( display(), wrapperId() ); - XMapWindow( display(), window() ); - if ( isActive() ) - workspace()->requestFocus( this ); - } + plainResize(s); + if (shade_mode == ShadeHover || shade_mode == ShadeActivated) + setActive(true); + XMapWindow(display(), wrapperId()); + XMapWindow(display(), window()); + if (isActive()) + workspace()->requestFocus(this); + } checkMaximizeGeometry(); - info->setState( isShade() ? NET::Shaded : 0, NET::Shaded ); - info->setState( isShown( false ) ? 0 : NET::Hidden, NET::Hidden ); + info->setState(isShade() ? NET::Shaded : 0, NET::Shaded); + info->setState(isShown(false) ? 0 : NET::Hidden, NET::Hidden); discardWindowPixmap(); updateVisibility(); updateAllowedActions(); - if( decoration ) + if (decoration) decoration->shadeChange(); updateWindowRules(); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} void Client::shadeHover() - { - setShade( ShadeHover ); +{ + setShade(ShadeHover); cancelShadeHoverTimer(); - } +} void Client::shadeUnhover() - { - setShade( ShadeNormal ); +{ + setShade(ShadeNormal); cancelShadeHoverTimer(); - } +} void Client::cancelShadeHoverTimer() - { +{ delete shadeHoverTimer; shadeHoverTimer = 0; - } +} void Client::toggleShade() - { // If the mode is ShadeHover or ShadeActive, cancel shade too - setShade( shade_mode == ShadeNone ? ShadeNormal : ShadeNone ); - } +{ + // If the mode is ShadeHover or ShadeActive, cancel shade too + setShade(shade_mode == ShadeNone ? ShadeNormal : ShadeNone); +} void Client::updateVisibility() - { - if( deleting ) +{ + if (deleting) return; - if( hidden && ( clientGroup() == NULL || clientGroup()->visible() == this )) - { - info->setState( NET::Hidden, NET::Hidden ); - setSkipTaskbar( true, false ); // Also hide from taskbar - if( compositing() && options->hiddenPreviews == HiddenPreviewsAlways ) - internalKeep( Allowed ); + if (hidden && (clientGroup() == NULL || clientGroup()->visible() == this)) { + info->setState(NET::Hidden, NET::Hidden); + setSkipTaskbar(true, false); // Also hide from taskbar + if (compositing() && options->hiddenPreviews == HiddenPreviewsAlways) + internalKeep(Allowed); else - internalHide( Allowed ); + internalHide(Allowed); return; - } - if( clientGroup() == NULL || clientGroup()->visible() == this ) - setSkipTaskbar( original_skip_taskbar, false ); // Reset from 'hidden' - if( minimized ) - { - info->setState( NET::Hidden, NET::Hidden ); - if( compositing() && options->hiddenPreviews == HiddenPreviewsAlways ) - internalKeep( Allowed ); + } + if (clientGroup() == NULL || clientGroup()->visible() == this) + setSkipTaskbar(original_skip_taskbar, false); // Reset from 'hidden' + if (minimized) { + info->setState(NET::Hidden, NET::Hidden); + if (compositing() && options->hiddenPreviews == HiddenPreviewsAlways) + internalKeep(Allowed); else - internalHide( Allowed ); + internalHide(Allowed); return; - } - info->setState( 0, NET::Hidden ); - if( !isOnCurrentDesktop()) - { - if( compositing() && options->hiddenPreviews != HiddenPreviewsNever ) - internalKeep( Allowed ); + } + info->setState(0, NET::Hidden); + if (!isOnCurrentDesktop()) { + if (compositing() && options->hiddenPreviews != HiddenPreviewsNever) + internalKeep(Allowed); else - internalHide( Allowed ); + internalHide(Allowed); return; - } - if( !isOnCurrentActivity()) - { - if( compositing() && options->hiddenPreviews != HiddenPreviewsNever ) - internalKeep( Allowed ); + } + if (!isOnCurrentActivity()) { + if (compositing() && options->hiddenPreviews != HiddenPreviewsNever) + internalKeep(Allowed); else - internalHide( Allowed ); + internalHide(Allowed); return; - } + } bool belongs_to_desktop = false; - for( ClientList::ConstIterator it = group()->members().constBegin(); - it != group()->members().constEnd(); - ++it ) - if( (*it)->isDesktop() ) - { + for (ClientList::ConstIterator it = group()->members().constBegin(); + it != group()->members().constEnd(); + ++it) + if ((*it)->isDesktop()) { belongs_to_desktop = true; break; - } - if( !belongs_to_desktop && workspace()->showingDesktop()) - workspace()->resetShowingDesktop( true ); - internalShow( Allowed ); - } + } + if (!belongs_to_desktop && workspace()->showingDesktop()) + workspace()->resetShowingDesktop(true); + internalShow(Allowed); +} /** * Sets the client window's mapping state. Possible values are * WithdrawnState, IconicState, NormalState. */ -void Client::exportMappingState( int s ) - { - assert( client != None ); - assert( !deleting || s == WithdrawnState ); - if( s == WithdrawnState ) - { - XDeleteProperty( display(), window(), atoms->wm_state ); +void Client::exportMappingState(int s) +{ + assert(client != None); + assert(!deleting || s == WithdrawnState); + if (s == WithdrawnState) { + XDeleteProperty(display(), window(), atoms->wm_state); return; - } - assert( s == NormalState || s == IconicState ); + } + assert(s == NormalState || s == IconicState); unsigned long data[2]; data[0] = (unsigned long) s; data[1] = (unsigned long) None; XChangeProperty(display(), window(), atoms->wm_state, atoms->wm_state, 32, - PropModeReplace, (unsigned char*)( data ), 2); - } + PropModeReplace, (unsigned char*)(data), 2); +} -void Client::internalShow( allowed_t ) - { - if( mapping_state == Mapped ) +void Client::internalShow(allowed_t) +{ + if (mapping_state == Mapped) return; MappingState old = mapping_state; mapping_state = Mapped; - if( old == Unmapped || old == Withdrawn ) - map( Allowed ); - if( old == Kept ) + if (old == Unmapped || old == Withdrawn) + map(Allowed); + if (old == Kept) updateHiddenPreview(); workspace()->checkUnredirect(); - } +} -void Client::internalHide( allowed_t ) - { - if( mapping_state == Unmapped ) +void Client::internalHide(allowed_t) +{ + if (mapping_state == Unmapped) return; MappingState old = mapping_state; mapping_state = Unmapped; - if( old == Mapped || old == Kept ) - unmap( Allowed ); - if( old == Kept ) + if (old == Mapped || old == Kept) + unmap(Allowed); + if (old == Kept) updateHiddenPreview(); - addWorkspaceRepaint( visibleRect() ); - workspace()->clientHidden( this ); + addWorkspaceRepaint(visibleRect()); + workspace()->clientHidden(this); workspace()->checkUnredirect(); - } +} -void Client::internalKeep( allowed_t ) - { - assert( compositing() ); - if( mapping_state == Kept ) +void Client::internalKeep(allowed_t) +{ + assert(compositing()); + if (mapping_state == Kept) return; MappingState old = mapping_state; mapping_state = Kept; - if( old == Unmapped || old == Withdrawn ) - map( Allowed ); + if (old == Unmapped || old == Withdrawn) + map(Allowed); updateHiddenPreview(); - addWorkspaceRepaint( visibleRect() ); - workspace()->clientHidden( this ); + addWorkspaceRepaint(visibleRect()); + workspace()->clientHidden(this); workspace()->checkUnredirect(); - } +} /** * Maps (shows) the client. Note that it is mapping state of the frame, * not necessarily the client window itself (i.e. a shaded window is here * considered mapped, even though it is in IconicState). */ -void Client::map( allowed_t ) - { +void Client::map(allowed_t) +{ // XComposite invalidates backing pixmaps on unmap (minimize, different // virtual desktop, etc.). We kept the last known good pixmap around // for use in effects, but now we want to have access to the new pixmap - if( compositing() ) + if (compositing()) discardWindowPixmap(); - if( decoration != NULL ) + if (decoration != NULL) decoration->widget()->show(); // Not really necessary, but let it know the state - XMapWindow( display(), frameId()); - if( !isShade()) - { - XMapWindow( display(), wrapper ); - XMapWindow( display(), client ); - exportMappingState( NormalState ); - } - else - exportMappingState( IconicState ); - } + XMapWindow(display(), frameId()); + if (!isShade()) { + XMapWindow(display(), wrapper); + XMapWindow(display(), client); + exportMappingState(NormalState); + } else + exportMappingState(IconicState); +} /** * Unmaps the client. Again, this is about the frame. */ -void Client::unmap( allowed_t ) - { +void Client::unmap(allowed_t) +{ // Here it may look like a race condition, as some other client might try to unmap // the window between these two XSelectInput() calls. However, they're supposed to // use XWithdrawWindow(), which also sends a synthetic event to the root window, // which won't be missed, so this shouldn't be a problem. The chance the real UnmapNotify // will be missed is also very minimal, so I don't think it's needed to grab the server // here. - XSelectInput( display(), wrapper, ClientWinMask ); // Avoid getting UnmapNotify - XUnmapWindow( display(), frameId() ); - XUnmapWindow( display(), wrapper ); - XUnmapWindow( display(), client ); - XSelectInput( display(), wrapper, ClientWinMask | SubstructureNotifyMask ); - if( decoration != NULL ) + XSelectInput(display(), wrapper, ClientWinMask); // Avoid getting UnmapNotify + XUnmapWindow(display(), frameId()); + XUnmapWindow(display(), wrapper); + XUnmapWindow(display(), client); + XSelectInput(display(), wrapper, ClientWinMask | SubstructureNotifyMask); + if (decoration != NULL) decoration->widget()->hide(); // Not really necessary, but let it know the state - exportMappingState( IconicState ); - } + exportMappingState(IconicState); +} /** * XComposite doesn't keep window pixmaps of unmapped windows, which means @@ -1271,26 +1234,23 @@ void Client::unmap( allowed_t ) * of the actual preview. */ void Client::updateHiddenPreview() - { - if( hiddenPreview() ) - { +{ + if (hiddenPreview()) { workspace()->forceRestacking(); - if( Extensions::shapeInputAvailable() ) - XShapeCombineRectangles( display(), frameId(), ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted ); - } - else - { + if (Extensions::shapeInputAvailable()) + XShapeCombineRectangles(display(), frameId(), ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted); + } else { workspace()->forceRestacking(); updateInputShape(); - } } +} -void Client::sendClientMessage( Window w, Atom a, Atom protocol, long data1, long data2, long data3 ) - { +void Client::sendClientMessage(Window w, Atom a, Atom protocol, long data1, long data2, long data3) +{ XEvent ev; long mask; - memset( &ev, 0, sizeof( ev )); + memset(&ev, 0, sizeof(ev)); ev.xclient.type = ClientMessage; ev.xclient.window = w; ev.xclient.message_type = a; @@ -1301,240 +1261,232 @@ void Client::sendClientMessage( Window w, Atom a, Atom protocol, long data1, lon ev.xclient.data.l[3] = data2; ev.xclient.data.l[4] = data3; mask = 0L; - if( w == rootWindow() ) - mask = SubstructureRedirectMask; // Magic! - XSendEvent( display(), w, False, mask, &ev ); - } + if (w == rootWindow()) + mask = SubstructureRedirectMask; // Magic! + XSendEvent(display(), w, False, mask, &ev); +} /** * Returns whether the window may be closed (have a close button) */ bool Client::isCloseable() const - { - return rules()->checkCloseable( motif_may_close && !isSpecialWindow() ); - } +{ + return rules()->checkCloseable(motif_may_close && !isSpecialWindow()); +} /** * Closes the window by either sending a delete_window message or using XKill. */ void Client::closeWindow() - { - if( !isCloseable() ) +{ + if (!isCloseable()) return; // Update user time, because the window may create a confirming dialog. updateUserTime(); - if ( Pdeletewindow ) - { - Notify::raise( Notify::Close ); - sendClientMessage( window(), atoms->wm_protocols, atoms->wm_delete_window); + if (Pdeletewindow) { + Notify::raise(Notify::Close); + sendClientMessage(window(), atoms->wm_protocols, atoms->wm_delete_window); pingWindow(); - } - else // Client will not react on wm_delete_window. We have not choice - // but destroy his connection to the XServer. + } else // Client will not react on wm_delete_window. We have not choice + // but destroy his connection to the XServer. killWindow(); - } +} /** * Kills the window via XKill */ void Client::killWindow() - { - kDebug( 1212 ) << "Client::killWindow():" << caption(); +{ + kDebug(1212) << "Client::killWindow():" << caption(); // Not sure if we need an Notify::Kill or not.. until then, use // Notify::Close - Notify::raise( Notify::Close ); + Notify::raise(Notify::Close); - if( isDialog() ) - Notify::raise( Notify::TransDelete ); - if( isNormalWindow() ) - Notify::raise( Notify::Delete ); - killProcess( false ); - XKillClient(display(), window() ); // Always kill this client at the server + if (isDialog()) + Notify::raise(Notify::TransDelete); + if (isNormalWindow()) + Notify::raise(Notify::Delete); + killProcess(false); + XKillClient(display(), window()); // Always kill this client at the server destroyClient(); - } +} /** * Send a ping to the window using _NET_WM_PING if possible if it * doesn't respond within a reasonable time, it will be killed. */ void Client::pingWindow() - { - if( !Pping ) +{ + if (!Pping) return; // Can't ping :( - if( options->killPingTimeout == 0 ) + if (options->killPingTimeout == 0) return; // Turned off - if( ping_timer != NULL ) + if (ping_timer != NULL) return; // Pinging already - ping_timer = new QTimer( this ); - connect( ping_timer, SIGNAL( timeout() ), SLOT( pingTimeout() )); - ping_timer->setSingleShot( true ); - ping_timer->start( options->killPingTimeout ); + ping_timer = new QTimer(this); + connect(ping_timer, SIGNAL(timeout()), SLOT(pingTimeout())); + ping_timer->setSingleShot(true); + ping_timer->start(options->killPingTimeout); ping_timestamp = xTime(); - workspace()->sendPingToWindow( window(), ping_timestamp ); - } + workspace()->sendPingToWindow(window(), ping_timestamp); +} -void Client::gotPing( Time timestamp ) - { +void Client::gotPing(Time timestamp) +{ // Just plain compare is not good enough because of 64bit and truncating and whatnot - if( NET::timestampCompare( timestamp, ping_timestamp ) != 0 ) + if (NET::timestampCompare(timestamp, ping_timestamp) != 0) return; delete ping_timer; ping_timer = NULL; - if( process_killer != NULL ) - { + if (process_killer != NULL) { process_killer->kill(); // Recycle when the process manager has noticed that the process exited // a delete process_killer here sometimes causes a hang in waitForFinished - connect(process_killer, SIGNAL( finished(int, QProcess::ExitStatus) ), - process_killer, SLOT( deleteLater() )); + connect(process_killer, SIGNAL(finished(int, QProcess::ExitStatus)), + process_killer, SLOT(deleteLater())); process_killer = NULL; - } } +} void Client::pingTimeout() - { - kDebug( 1212 ) << "Ping timeout:" << caption(); +{ + kDebug(1212) << "Ping timeout:" << caption(); ping_timer->deleteLater(); ping_timer = NULL; - killProcess( true, ping_timestamp ); - } + killProcess(true, ping_timestamp); +} -void Client::killProcess( bool ask, Time timestamp ) - { - if( process_killer != NULL ) +void Client::killProcess(bool ask, Time timestamp) +{ + if (process_killer != NULL) return; - Q_ASSERT( !ask || timestamp != CurrentTime ); - QByteArray machine = wmClientMachine( true ); + Q_ASSERT(!ask || timestamp != CurrentTime); + QByteArray machine = wmClientMachine(true); pid_t pid = info->pid(); - if( pid <= 0 || machine.isEmpty()) // Needed properties missing + if (pid <= 0 || machine.isEmpty()) // Needed properties missing return; - kDebug( 1212 ) << "Kill process:" << pid << "(" << machine << ")"; - if( !ask ) - { - if( machine != "localhost" ) - { + kDebug(1212) << "Kill process:" << pid << "(" << machine << ")"; + if (!ask) { + if (machine != "localhost") { QStringList lst; - lst << machine << "kill" << QString::number( pid ); - QProcess::startDetached( "xon",lst ); - } - else - ::kill( pid, SIGTERM ); - } - else - { - process_killer = new QProcess( this ); - connect( process_killer, SIGNAL( error(QProcess::ProcessError) ), SLOT( processKillerExited() )); - connect( process_killer, SIGNAL( finished(int, QProcess::ExitStatus) ), SLOT( processKillerExited() )); - process_killer->start( KStandardDirs::findExe( "kwin_killer_helper" ), - QStringList() << "--pid" << QByteArray().setNum( unsigned( pid )) << "--hostname" << machine - << "--windowname" << caption() - << "--applicationname" << resourceClass() - << "--wid" << QString::number( window() ) - << "--timestamp" << QString::number( timestamp )); - } + lst << machine << "kill" << QString::number(pid); + QProcess::startDetached("xon", lst); + } else + ::kill(pid, SIGTERM); + } else { + process_killer = new QProcess(this); + connect(process_killer, SIGNAL(error(QProcess::ProcessError)), SLOT(processKillerExited())); + connect(process_killer, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processKillerExited())); + process_killer->start(KStandardDirs::findExe("kwin_killer_helper"), + QStringList() << "--pid" << QByteArray().setNum(unsigned(pid)) << "--hostname" << machine + << "--windowname" << caption() + << "--applicationname" << resourceClass() + << "--wid" << QString::number(window()) + << "--timestamp" << QString::number(timestamp)); } +} void Client::processKillerExited() - { - kDebug( 1212 ) << "Killer exited"; +{ + kDebug(1212) << "Killer exited"; delete process_killer; process_killer = NULL; - } +} -void Client::setSkipTaskbar( bool b, bool from_outside ) - { +void Client::setSkipTaskbar(bool b, bool from_outside) +{ int was_wants_tab_focus = wantsTabFocus(); - if( from_outside ) - { - b = rules()->checkSkipTaskbar( b ); + if (from_outside) { + b = rules()->checkSkipTaskbar(b); original_skip_taskbar = b; - } - if( b == skipTaskbar() ) + } + if (b == skipTaskbar()) return; skip_taskbar = b; - info->setState( b ? NET::SkipTaskbar : 0, NET::SkipTaskbar ); + info->setState(b ? NET::SkipTaskbar : 0, NET::SkipTaskbar); updateWindowRules(); - if( was_wants_tab_focus != wantsTabFocus()) - workspace()->updateFocusChains( this, - isActive() ? Workspace::FocusChainMakeFirst : Workspace::FocusChainUpdate ); - } + if (was_wants_tab_focus != wantsTabFocus()) + workspace()->updateFocusChains(this, + isActive() ? Workspace::FocusChainMakeFirst : Workspace::FocusChainUpdate); +} -void Client::setSkipPager( bool b ) - { - b = rules()->checkSkipPager( b ); - if( b == skipPager() ) +void Client::setSkipPager(bool b) +{ + b = rules()->checkSkipPager(b); + if (b == skipPager()) return; skip_pager = b; - info->setState( b ? NET::SkipPager : 0, NET::SkipPager ); + info->setState(b ? NET::SkipPager : 0, NET::SkipPager); updateWindowRules(); - } +} -void Client::setSkipSwitcher( bool set ) - { - set = rules()->checkSkipSwitcher( set ); - if( set == skipSwitcher() ) +void Client::setSkipSwitcher(bool set) +{ + set = rules()->checkSkipSwitcher(set); + if (set == skipSwitcher()) return; skip_switcher = set; updateWindowRules(); - } +} -void Client::setModal( bool m ) - { // Qt-3.2 can have even modal normal windows :( - if( modal == m ) +void Client::setModal(bool m) +{ + // Qt-3.2 can have even modal normal windows :( + if (modal == m) return; modal = m; - if( !modal ) + if (!modal) return; // Changing modality for a mapped window is weird (?) // _NET_WM_STATE_MODAL should possibly rather be _NET_WM_WINDOW_TYPE_MODAL_DIALOG - } +} -void Client::setDesktop( int desktop ) - { - if( desktop != NET::OnAllDesktops ) // Do range check - desktop = qMax( 1, qMin( workspace()->numberOfDesktops(), desktop )); - desktop = qMin( workspace()->numberOfDesktops(), rules()->checkDesktop( desktop )); - if( desk == desktop ) +void Client::setDesktop(int desktop) +{ + if (desktop != NET::OnAllDesktops) // Do range check + desktop = qMax(1, qMin(workspace()->numberOfDesktops(), desktop)); + desktop = qMin(workspace()->numberOfDesktops(), rules()->checkDesktop(desktop)); + if (desk == desktop) return; int was_desk = desk; desk = desktop; - info->setDesktop( desktop ); - if(( was_desk == NET::OnAllDesktops ) != ( desktop == NET::OnAllDesktops )) - { // onAllDesktops changed - if( isShown( true )) - Notify::raise( isOnAllDesktops() ? Notify::OnAllDesktops : Notify::NotOnAllDesktops ); - workspace()->updateOnAllDesktopsOfTransients( this ); - } - if( decoration != NULL ) + info->setDesktop(desktop); + if ((was_desk == NET::OnAllDesktops) != (desktop == NET::OnAllDesktops)) { + // onAllDesktops changed + if (isShown(true)) + Notify::raise(isOnAllDesktops() ? Notify::OnAllDesktops : Notify::NotOnAllDesktops); + workspace()->updateOnAllDesktopsOfTransients(this); + } + if (decoration != NULL) decoration->desktopChange(); - ClientList transients_stacking_order = workspace()->ensureStackingOrder( transients() ); - for( ClientList::ConstIterator it = transients_stacking_order.constBegin(); - it != transients_stacking_order.constEnd(); - ++it ) - (*it)->setDesktop( desktop ); + ClientList transients_stacking_order = workspace()->ensureStackingOrder(transients()); + for (ClientList::ConstIterator it = transients_stacking_order.constBegin(); + it != transients_stacking_order.constEnd(); + ++it) + (*it)->setDesktop(desktop); - if( isModal()) // if a modal dialog is moved, move the mainwindow with it as otherwise - // the (just moved) modal dialog will confusingly return to the mainwindow with - // the next desktop change - { - foreach( Client* c2, mainClients()) - c2->setDesktop( desktop ); - } + if (isModal()) // if a modal dialog is moved, move the mainwindow with it as otherwise + // the (just moved) modal dialog will confusingly return to the mainwindow with + // the next desktop change + { + foreach (Client * c2, mainClients()) + c2->setDesktop(desktop); + } - workspace()->updateFocusChains( this, Workspace::FocusChainMakeFirst ); + workspace()->updateFocusChains(this, Workspace::FocusChainMakeFirst); updateVisibility(); updateWindowRules(); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} /** * Sets whether the client is on @p activity. @@ -1543,63 +1495,60 @@ void Client::setDesktop( int desktop ) * Note: If it was on all activities and you try to remove it from one, nothing will happen; * I don't think that's an important enough use case to handle here. */ -void Client::setOnActivity( const QString &activity, bool enable ) - { +void Client::setOnActivity(const QString &activity, bool enable) +{ QStringList newActivitiesList = activities(); - if( newActivitiesList.contains(activity) == enable ) //nothing to do + if (newActivitiesList.contains(activity) == enable) //nothing to do return; - if (enable) - { + if (enable) { QStringList allActivities = workspace()->activityList(); - if( !allActivities.contains(activity) ) //bogus ID + if (!allActivities.contains(activity)) //bogus ID return; newActivitiesList.append(activity); - } - else + } else newActivitiesList.removeOne(activity); - setOnActivities( newActivitiesList ); - } + setOnActivities(newActivitiesList); +} /** * set exactly which activities this client is on */ -void Client::setOnActivities( QStringList newActivitiesList ) - { +void Client::setOnActivities(QStringList newActivitiesList) +{ QStringList allActivities = workspace()->activityList(); - if( newActivitiesList.size() == allActivities.size() || newActivitiesList.isEmpty() ) - { + if (newActivitiesList.size() == allActivities.size() || newActivitiesList.isEmpty()) { setOnAllActivities(true); return; - } + } QByteArray joined = newActivitiesList.join(",").toAscii(); char *data = joined.data(); activityList = newActivitiesList; XChangeProperty(display(), window(), atoms->activities, XA_STRING, 8, - PropModeReplace, (unsigned char *)data, joined.size()); + PropModeReplace, (unsigned char *)data, joined.size()); - updateActivities( false ); - } + updateActivities(false); +} /** * update after activities changed */ -void Client::updateActivities( bool includeTransients ) - { +void Client::updateActivities(bool includeTransients) +{ /* FIXME do I need this? - if( decoration != NULL ) + if ( decoration != NULL ) decoration->desktopChange(); */ - if( includeTransients ) - workspace()->updateOnAllActivitiesOfTransients( this ); - workspace()->updateFocusChains( this, Workspace::FocusChainMakeFirst ); + if (includeTransients) + workspace()->updateOnAllActivitiesOfTransients(this); + workspace()->updateFocusChains(this, Workspace::FocusChainMakeFirst); updateVisibility(); updateWindowRules(); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} /** * Returns the virtual desktop within the workspace() the client window @@ -1621,69 +1570,65 @@ int Client::desktop() const * Don't use this, use isOnActivity() and friends (from class Toplevel) */ QStringList Client::activities() const - { +{ if (needsSessionInteract) { return QStringList(); } return activityList; - } +} -void Client::setOnAllDesktops( bool b ) - { - if(( b && isOnAllDesktops() ) || - ( !b && !isOnAllDesktops() )) +void Client::setOnAllDesktops(bool b) +{ + if ((b && isOnAllDesktops()) || + (!b && !isOnAllDesktops())) return; - if( b ) - setDesktop( NET::OnAllDesktops ); + if (b) + setDesktop(NET::OnAllDesktops); else - setDesktop( workspace()->currentDesktop()); + setDesktop(workspace()->currentDesktop()); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} /** * if @p on is true, sets on all activities. * if it's false, sets it to only be on the current activity */ -void Client::setOnAllActivities( bool on ) - { - if( on == isOnAllActivities() ) +void Client::setOnAllActivities(bool on) +{ + if (on == isOnAllActivities()) return; - if( on ) - { + if (on) { activityList.clear(); XChangeProperty(display(), window(), atoms->activities, XA_STRING, 8, PropModeReplace, (const unsigned char *)"ALL", 3); - updateActivities( true ); - } - else - { + updateActivities(true); + } else { setOnActivity(Workspace::self()->currentActivity(), true); - workspace()->updateOnAllActivitiesOfTransients( this ); - } + workspace()->updateOnAllActivitiesOfTransients(this); } +} /** * Performs activation and/or raising of the window */ -void Client::takeActivity( int flags, bool handled, allowed_t ) - { - if( !handled || !Ptakeactivity ) - { - if( flags & ActivityFocus ) - takeFocus( Allowed ); - if( flags & ActivityRaise ) - workspace()->raiseClient( this ); +void Client::takeActivity(int flags, bool handled, allowed_t) +{ + if (!handled || !Ptakeactivity) { + if (flags & ActivityFocus) + takeFocus(Allowed); + if (flags & ActivityRaise) + workspace()->raiseClient(this); return; - } + } #ifndef NDEBUG static Time previous_activity_timestamp; static Client* previous_client; - //if( previous_activity_timestamp == xTime() && previous_client != this ) + //if ( previous_activity_timestamp == xTime() && previous_client != this ) // { // kDebug( 1212 ) << "Repeated use of the same X timestamp for activity"; // kDebug( 1212 ) << kBacktrace(); @@ -1693,19 +1638,19 @@ void Client::takeActivity( int flags, bool handled, allowed_t ) previous_client = this; #endif - workspace()->sendTakeActivity( this, xTime(), flags ); - } + workspace()->sendTakeActivity(this, xTime(), flags); +} /** * Performs the actual focusing of the window using XSetInputFocus and WM_TAKE_FOCUS */ -void Client::takeFocus( allowed_t ) - { +void Client::takeFocus(allowed_t) +{ #ifndef NDEBUG static Time previous_focus_timestamp; static Client* previous_client; - //if( previous_focus_timestamp == xTime() && previous_client != this ) + //if ( previous_focus_timestamp == xTime() && previous_client != this ) // { // kDebug( 1212 ) << "Repeated use of the same X timestamp for focus"; // kDebug( 1212 ) << kBacktrace(); @@ -1714,12 +1659,12 @@ void Client::takeFocus( allowed_t ) previous_focus_timestamp = xTime(); previous_client = this; #endif - if( rules()->checkAcceptFocus( input )) - XSetInputFocus( display(), window(), RevertToPointerRoot, xTime() ); - if( Ptakefocus ) - sendClientMessage( window(), atoms->wm_protocols, atoms->wm_take_focus ); - workspace()->setShouldGetFocus( this ); - } + if (rules()->checkAcceptFocus(input)) + XSetInputFocus(display(), window(), RevertToPointerRoot, xTime()); + if (Ptakefocus) + sendClientMessage(window(), atoms->wm_protocols, atoms->wm_take_focus); + workspace()->setShouldGetFocus(this); +} /** * Returns whether the window provides context help or not. If it does, @@ -1729,9 +1674,9 @@ void Client::takeFocus( allowed_t ) * \sa contextHelp() */ bool Client::providesContextHelp() const - { +{ return Pcontexthelp; - } +} /** * Invokes context help on the window. Only works if the window @@ -1740,32 +1685,31 @@ bool Client::providesContextHelp() const * \sa providesContextHelp() */ void Client::showContextHelp() - { - if( Pcontexthelp ) - { - sendClientMessage( window(), atoms->wm_protocols, atoms->net_wm_context_help ); +{ + if (Pcontexthelp) { + sendClientMessage(window(), atoms->wm_protocols, atoms->net_wm_context_help); QWhatsThis::enterWhatsThisMode(); // SELI TODO: ? - } } +} /** * Fetches the window's caption (WM_NAME property). It will be * stored in the client's caption(). */ void Client::fetchName() - { - setCaption( readName()); - } +{ + setCaption(readName()); +} QString Client::readName() const - { - if( info->name() && info->name()[0] != '\0' ) - return QString::fromUtf8( info->name() ); +{ + if (info->name() && info->name()[0] != '\0') + return QString::fromUtf8(info->name()); else - return KWindowSystem::readNameProperty( window(), XA_WM_NAME ); - } + return KWindowSystem::readNameProperty(window(), XA_WM_NAME); +} -KWIN_COMPARE_PREDICATE( FetchNameInternalPredicate, Client, const Client*, (!cl->isSpecialWindow() || cl->isToolbar()) && cl != value && cl->caption() == value->caption()); +KWIN_COMPARE_PREDICATE(FetchNameInternalPredicate, Client, const Client*, (!cl->isSpecialWindow() || cl->isToolbar()) && cl != value && cl->caption() == value->caption()); // The list is taken from http://www.unicode.org/reports/tr9/ (#154840) QChar LRM(0x200E); @@ -1776,258 +1720,243 @@ QChar LRO(0x202D); QChar RLO(0x202E); QChar PDF(0x202C); -void Client::setCaption( const QString& _s, bool force ) - { +void Client::setCaption(const QString& _s, bool force) +{ QString s = _s; - if( s != cap_normal || force ) - { + if (s != cap_normal || force) { bool reset_name = force; - for( int i = 0; i < s.length(); ++i ) - if( !s[i].isPrint() ) - s[i] = QChar( ' ' ); + for (int i = 0; i < s.length(); ++i) + if (!s[i].isPrint()) + s[i] = QChar(' '); cap_normal = s; - bool was_suffix = ( !cap_suffix.isEmpty() ); + bool was_suffix = (!cap_suffix.isEmpty()); QString machine_suffix; - if( wmClientMachine( false ) != "localhost" && !isLocalMachine( wmClientMachine( false ))) - machine_suffix = QString( " <@" ) + wmClientMachine( true ) + '>' + LRM; - QString shortcut_suffix = !shortcut().isEmpty() ? ( " {" + shortcut().toString() + '}' ) : QString(); + if (wmClientMachine(false) != "localhost" && !isLocalMachine(wmClientMachine(false))) + machine_suffix = QString(" <@") + wmClientMachine(true) + '>' + LRM; + QString shortcut_suffix = !shortcut().isEmpty() ? (" {" + shortcut().toString() + '}') : QString(); cap_suffix = machine_suffix + shortcut_suffix; - if(( !isSpecialWindow() || isToolbar() ) && workspace()->findClient( FetchNameInternalPredicate( this ))) - { + if ((!isSpecialWindow() || isToolbar()) && workspace()->findClient(FetchNameInternalPredicate(this))) { int i = 2; - do - { + do { cap_suffix = machine_suffix + " <" + QString::number(i) + '>' + LRM + shortcut_suffix; i++; - } while ( workspace()->findClient( FetchNameInternalPredicate( this ))); - info->setVisibleName( caption().toUtf8() ); + } while (workspace()->findClient(FetchNameInternalPredicate(this))); + info->setVisibleName(caption().toUtf8()); reset_name = false; - } - if(( was_suffix && cap_suffix.isEmpty() ) || reset_name ) - { // If it was new window, it may have old value still set, if the window is reused - info->setVisibleName( "" ); - info->setVisibleIconName( "" ); - } - else if( !cap_suffix.isEmpty() && !cap_iconic.isEmpty()) + } + if ((was_suffix && cap_suffix.isEmpty()) || reset_name) { + // If it was new window, it may have old value still set, if the window is reused + info->setVisibleName(""); + info->setVisibleIconName(""); + } else if (!cap_suffix.isEmpty() && !cap_iconic.isEmpty()) // Keep the same suffix in iconic name if it's set - info->setVisibleIconName( ( cap_iconic + cap_suffix ).toUtf8() ); + info->setVisibleIconName((cap_iconic + cap_suffix).toUtf8()); - if( isManaged() && decoration != NULL ) - { + if (isManaged() && decoration != NULL) { if (client_group) client_group->updateItems(); decoration->captionChange(); - } } } +} void Client::updateCaption() - { - setCaption( cap_normal, true ); - } +{ + setCaption(cap_normal, true); +} void Client::fetchIconicName() - { +{ QString s; - if( info->iconName() && info->iconName()[0] != '\0' ) - s = QString::fromUtf8( info->iconName() ); + if (info->iconName() && info->iconName()[0] != '\0') + s = QString::fromUtf8(info->iconName()); else - s = KWindowSystem::readNameProperty( window(), XA_WM_ICON_NAME ); - if( s != cap_iconic ) - { + s = KWindowSystem::readNameProperty(window(), XA_WM_ICON_NAME); + if (s != cap_iconic) { bool was_set = !cap_iconic.isEmpty(); cap_iconic = s; - if( !cap_suffix.isEmpty()) - { - if( !cap_iconic.isEmpty()) // Keep the same suffix in iconic name if it's set - info->setVisibleIconName( ( s + cap_suffix ).toUtf8() ); - else if( was_set ) - info->setVisibleIconName( "" ); - } + if (!cap_suffix.isEmpty()) { + if (!cap_iconic.isEmpty()) // Keep the same suffix in iconic name if it's set + info->setVisibleIconName((s + cap_suffix).toUtf8()); + else if (was_set) + info->setVisibleIconName(""); } } +} /** * \reimp */ -QString Client::caption( bool full ) const - { +QString Client::caption(bool full) const +{ return full ? cap_normal + cap_suffix : cap_normal; - } +} void Client::dontMoveResize() - { +{ buttonDown = false; stopDelayedMoveResize(); - if( moveResizeMode ) - finishMoveResize( false ); - } + if (moveResizeMode) + finishMoveResize(false); +} -void Client::setClientShown( bool shown ) - { - if( deleting ) +void Client::setClientShown(bool shown) +{ + if (deleting) return; // Don't change shown status if this client is being deleted - if( shown && hidden ) - { - map( Allowed ); + if (shown && hidden) { + map(Allowed); hidden = false; //updateVisibility(); //updateAllowedActions(); - if( options->inactiveTabsSkipTaskbar ) - setSkipTaskbar( false, false ); - takeFocus( Allowed ); + if (options->inactiveTabsSkipTaskbar) + setSkipTaskbar(false, false); + takeFocus(Allowed); autoRaise(); - workspace()->updateFocusChains( this, Workspace::FocusChainMakeFirst ); - } - if( !shown && !hidden ) - { - unmap( Allowed ); + workspace()->updateFocusChains(this, Workspace::FocusChainMakeFirst); + } + if (!shown && !hidden) { + unmap(Allowed); hidden = true; //updateVisibility(); //updateAllowedActions(); - if( options->inactiveTabsSkipTaskbar ) - setSkipTaskbar( true, false ); // TODO: Causes reshuffle of the taskbar + if (options->inactiveTabsSkipTaskbar) + setSkipTaskbar(true, false); // TODO: Causes reshuffle of the taskbar // Don't move tabs to the end of the list when another tab get's activated - if( !clientGroup() || clientGroup()->visible() == this ) - workspace()->updateFocusChains( this, Workspace::FocusChainMakeLast ); - addWorkspaceRepaint( visibleRect() ); - } + if (!clientGroup() || clientGroup()->visible() == this) + workspace()->updateFocusChains(this, Workspace::FocusChainMakeLast); + addWorkspaceRepaint(visibleRect()); } +} void Client::getWMHints() - { - XWMHints* hints = XGetWMHints( display(), window() ); +{ + XWMHints* hints = XGetWMHints(display(), window()); input = true; window_group = None; urgency = false; - if( hints ) - { - if( hints->flags & InputHint ) + if (hints) { + if (hints->flags & InputHint) input = hints->input; - if( hints->flags & WindowGroupHint ) + if (hints->flags & WindowGroupHint) window_group = hints->window_group; - urgency = !!( hints->flags & UrgencyHint ); // Need boolean, it's a uint bitfield - XFree( (char*)hints ); - } + urgency = !!(hints->flags & UrgencyHint); // Need boolean, it's a uint bitfield + XFree((char*)hints); + } checkGroup(); updateUrgency(); updateAllowedActions(); // Group affects isMinimizable() - } +} -void Client::sl_activated() { +void Client::sl_activated() +{ emit s_activated(); } void Client::getMotifHints() - { +{ bool mgot_noborder, mnoborder, mresize, mmove, mminimize, mmaximize, mclose; - Motif::readFlags( client, mgot_noborder, mnoborder, mresize, mmove, mminimize, mmaximize, mclose ); - if( mgot_noborder ) - { + Motif::readFlags(client, mgot_noborder, mnoborder, mresize, mmove, mminimize, mmaximize, mclose); + if (mgot_noborder) { motif_noborder = mnoborder; // If we just got a hint telling us to hide decorations, we do so. - if ( motif_noborder ) + if (motif_noborder) noborder = true; // If the Motif hint is now telling us to show decorations, we only do so if the app didn't // instruct us to hide decorations in some other way, though. - else if ( !motif_noborder && !app_noborder ) + else if (!motif_noborder && !app_noborder) noborder = false; - } - if( !hasNETSupport() ) - { // NETWM apps should set type and size constraints + } + if (!hasNETSupport()) { + // NETWM apps should set type and size constraints motif_may_resize = mresize; // This should be set using minsize==maxsize, but oh well motif_may_move = mmove; - } - else + } else motif_may_resize = motif_may_move = true; // mminimize; - Ignore, bogus - E.g. shading or sending to another desktop is "minimizing" too // mmaximize; - Ignore, bogus - Maximizing is basically just resizing motif_may_close = mclose; // Motif apps like to crash when they set this hint and WM closes them anyway - if( isManaged() ) - updateDecoration( true ); // Check if noborder state has changed - } + if (isManaged()) + updateDecoration(true); // Check if noborder state has changed +} -void Client::readIcons( Window win, QPixmap* icon, QPixmap* miniicon, QPixmap* bigicon, QPixmap* hugeicon ) - { +void Client::readIcons(Window win, QPixmap* icon, QPixmap* miniicon, QPixmap* bigicon, QPixmap* hugeicon) +{ // Get the icons, allow scaling - if( icon != NULL ) - *icon = KWindowSystem::icon( win, 32, 32, true, KWindowSystem::NETWM | KWindowSystem::WMHints ); - if( miniicon != NULL ) - { - if( icon == NULL || !icon->isNull() ) - *miniicon = KWindowSystem::icon( win, 16, 16, true, KWindowSystem::NETWM | KWindowSystem::WMHints ); + if (icon != NULL) + *icon = KWindowSystem::icon(win, 32, 32, true, KWindowSystem::NETWM | KWindowSystem::WMHints); + if (miniicon != NULL) { + if (icon == NULL || !icon->isNull()) + *miniicon = KWindowSystem::icon(win, 16, 16, true, KWindowSystem::NETWM | KWindowSystem::WMHints); else *miniicon = QPixmap(); - } - if( bigicon != NULL ) - { - if( icon == NULL || !icon->isNull() ) - *bigicon = KWindowSystem::icon( win, 64, 64, false, KWindowSystem::NETWM | KWindowSystem::WMHints ); + } + if (bigicon != NULL) { + if (icon == NULL || !icon->isNull()) + *bigicon = KWindowSystem::icon(win, 64, 64, false, KWindowSystem::NETWM | KWindowSystem::WMHints); else *bigicon = QPixmap(); - } - if( hugeicon != NULL ) - { - if( icon == NULL || !icon->isNull() ) - *hugeicon = KWindowSystem::icon( win, 128, 128, false, KWindowSystem::NETWM | KWindowSystem::WMHints ); + } + if (hugeicon != NULL) { + if (icon == NULL || !icon->isNull()) + *hugeicon = KWindowSystem::icon(win, 128, 128, false, KWindowSystem::NETWM | KWindowSystem::WMHints); else *hugeicon = QPixmap(); - } } +} void Client::getIcons() - { +{ // First read icons from the window itself - readIcons( window(), &icon_pix, &miniicon_pix, &bigicon_pix, &hugeicon_pix ); - if( icon_pix.isNull() ) - { // Then try window group + readIcons(window(), &icon_pix, &miniicon_pix, &bigicon_pix, &hugeicon_pix); + if (icon_pix.isNull()) { + // Then try window group icon_pix = group()->icon(); miniicon_pix = group()->miniIcon(); bigicon_pix = group()->bigIcon(); hugeicon_pix = group()->hugeIcon(); - } - if( icon_pix.isNull() && isTransient() ) - { // Then mainclients + } + if (icon_pix.isNull() && isTransient()) { + // Then mainclients ClientList mainclients = mainClients(); - for( ClientList::ConstIterator it = mainclients.constBegin(); - it != mainclients.constEnd() && icon_pix.isNull(); - ++it ) - { + for (ClientList::ConstIterator it = mainclients.constBegin(); + it != mainclients.constEnd() && icon_pix.isNull(); + ++it) { icon_pix = (*it)->icon(); miniicon_pix = (*it)->miniIcon(); bigicon_pix = (*it)->bigIcon(); hugeicon_pix = (*it)->hugeIcon(); - } } - if( icon_pix.isNull()) - { // And if nothing else, load icon from classhint or xapp icon - icon_pix = KWindowSystem::icon( window(), 32, 32, true, KWindowSystem::ClassHint | KWindowSystem::XApp ); - miniicon_pix = KWindowSystem::icon( window(), 16, 16, true, KWindowSystem::ClassHint | KWindowSystem::XApp ); - bigicon_pix = KWindowSystem::icon( window(), 64, 64, false, KWindowSystem::ClassHint | KWindowSystem::XApp ); - hugeicon_pix = KWindowSystem::icon( window(), 128, 128, false, KWindowSystem::ClassHint | KWindowSystem::XApp ); - } - if( isManaged() && decoration != NULL ) - decoration->iconChange(); } + if (icon_pix.isNull()) { + // And if nothing else, load icon from classhint or xapp icon + icon_pix = KWindowSystem::icon(window(), 32, 32, true, KWindowSystem::ClassHint | KWindowSystem::XApp); + miniicon_pix = KWindowSystem::icon(window(), 16, 16, true, KWindowSystem::ClassHint | KWindowSystem::XApp); + bigicon_pix = KWindowSystem::icon(window(), 64, 64, false, KWindowSystem::ClassHint | KWindowSystem::XApp); + hugeicon_pix = KWindowSystem::icon(window(), 128, 128, false, KWindowSystem::ClassHint | KWindowSystem::XApp); + } + if (isManaged() && decoration != NULL) + decoration->iconChange(); +} -QPixmap Client::icon( const QSize& size ) const - { - const int iconSize = qMin( size.width(), size.height() ); - if( iconSize <= 16 ) +QPixmap Client::icon(const QSize& size) const +{ + const int iconSize = qMin(size.width(), size.height()); + if (iconSize <= 16) return miniIcon(); - else if( iconSize <= 32 ) + else if (iconSize <= 32) return icon(); - if( iconSize <= 64 ) + if (iconSize <= 64) return bigIcon(); else return hugeIcon(); - } +} void Client::getWindowProtocols() - { +{ Atom* p; - int i,n; + int i, n; Pdeletewindow = 0; Ptakefocus = 0; @@ -2035,30 +1964,28 @@ void Client::getWindowProtocols() Pcontexthelp = 0; Pping = 0; - if( XGetWMProtocols( display(), window(), &p, &n )) - { - for( i = 0; i < n; ++i ) - { - if( p[i] == atoms->wm_delete_window ) + if (XGetWMProtocols(display(), window(), &p, &n)) { + for (i = 0; i < n; ++i) { + if (p[i] == atoms->wm_delete_window) Pdeletewindow = 1; - else if( p[i] == atoms->wm_take_focus ) + else if (p[i] == atoms->wm_take_focus) Ptakefocus = 1; - else if( p[i] == atoms->net_wm_take_activity ) + else if (p[i] == atoms->net_wm_take_activity) Ptakeactivity = 1; - else if( p[i] == atoms->net_wm_context_help ) + else if (p[i] == atoms->net_wm_context_help) Pcontexthelp = 1; - else if( p[i] == atoms->net_wm_ping ) + else if (p[i] == atoms->net_wm_ping) Pping = 1; - } - if( n > 0 ) - XFree( p ); } + if (n > 0) + XFree(p); } +} -void Client::getSyncCounter() +void Client::getSyncCounter() { #ifdef HAVE_XSYNC - if( !Extensions::syncAvailable() ) + if (!Extensions::syncAvailable()) return; Atom retType; @@ -2066,32 +1993,30 @@ void Client::getSyncCounter() unsigned long byteRet; int formatRet; unsigned char* propRet; - int ret = XGetWindowProperty( display(), window(), atoms->net_wm_sync_request_counter, - 0, 1, false, XA_CARDINAL, &retType, &formatRet, &nItemRet, &byteRet, &propRet ); + int ret = XGetWindowProperty(display(), window(), atoms->net_wm_sync_request_counter, + 0, 1, false, XA_CARDINAL, &retType, &formatRet, &nItemRet, &byteRet, &propRet); - if( ret == Success && formatRet == 32 ) - { - sync_counter = *(long*)( propRet ); - XSyncIntToValue( &sync_counter_value, 0 ); + if (ret == Success && formatRet == 32) { + sync_counter = *(long*)(propRet); + XSyncIntToValue(&sync_counter_value, 0); XSyncValue zero; - XSyncIntToValue( &zero, 0 ); - XSyncSetCounter( display(), sync_counter, zero ); - if( sync_alarm == None ) - { + XSyncIntToValue(&zero, 0); + XSyncSetCounter(display(), sync_counter, zero); + if (sync_alarm == None) { XSyncAlarmAttributes attrs; attrs.trigger.counter = sync_counter; attrs.trigger.value_type = XSyncRelative; attrs.trigger.test_type = XSyncPositiveTransition; - XSyncIntToValue( &attrs.trigger.wait_value, 1 ); - XSyncIntToValue( &attrs.delta, 1 ); - sync_alarm = XSyncCreateAlarm( display(), - XSyncCACounter | XSyncCAValueType | XSyncCATestType | XSyncCADelta | XSyncCAValue, - &attrs ); - } + XSyncIntToValue(&attrs.trigger.wait_value, 1); + XSyncIntToValue(&attrs.delta, 1); + sync_alarm = XSyncCreateAlarm(display(), + XSyncCACounter | XSyncCAValueType | XSyncCATestType | XSyncCADelta | XSyncCAValue, + &attrs); } + } - if( ret == Success ) - XFree( propRet ); + if (ret == Success) + XFree(propRet); #endif } @@ -2101,7 +2026,7 @@ void Client::getSyncCounter() void Client::sendSyncRequest() { #ifdef HAVE_XSYNC - if( sync_counter == None ) + if (sync_counter == None) return; // We increment before the notify so that after the notify @@ -2109,9 +2034,9 @@ void Client::sendSyncRequest() // in the acknowledgement int overflow; XSyncValue one; - XSyncIntToValue( &one, 1 ); + XSyncIntToValue(&one, 1); #undef XSyncValueAdd // It causes a warning :-/ - XSyncValueAdd( &sync_counter_value, sync_counter_value, one, &overflow ); + XSyncValueAdd(&sync_counter_value, sync_counter_value, one, &overflow); // Send the message to client XEvent ev; @@ -2121,139 +2046,139 @@ void Client::sendSyncRequest() ev.xclient.message_type = atoms->wm_protocols; ev.xclient.data.l[0] = atoms->net_wm_sync_request; ev.xclient.data.l[1] = xTime(); - ev.xclient.data.l[2] = XSyncValueLow32( sync_counter_value ); - ev.xclient.data.l[3] = XSyncValueHigh32( sync_counter_value ); + ev.xclient.data.l[2] = XSyncValueLow32(sync_counter_value); + ev.xclient.data.l[3] = XSyncValueHigh32(sync_counter_value); ev.xclient.data.l[4] = 0; - XSendEvent( display(), window(), False, NoEventMask, &ev ); - XSync( display(), false ); + XSendEvent(display(), window(), False, NoEventMask, &ev); + XSync(display(), false); #endif } bool Client::wantsTabFocus() const - { - return ( isNormalWindow() || isDialog() ) && wantsInput(); - } +{ + return (isNormalWindow() || isDialog()) && wantsInput(); +} bool Client::wantsInput() const - { - return rules()->checkAcceptFocus( input || Ptakefocus ); - } +{ + return rules()->checkAcceptFocus(input || Ptakefocus); +} bool Client::isSpecialWindow() const - { // TODO +{ + // TODO return isDesktop() || isDock() || isSplash() || isTopMenu() || isToolbar(); - } +} /** * Sets an appropriate cursor shape for the logical mouse position \a m */ void Client::updateCursor() - { +{ Position m = mode; - if( !isResizable() || isShade() ) + if (!isResizable() || isShade()) m = PositionCenter; QCursor c; - switch( m ) - { - case PositionTopLeft: - case PositionBottomRight: - c = Qt::SizeFDiagCursor; - break; - case PositionBottomLeft: - case PositionTopRight: - c = Qt::SizeBDiagCursor; - break; - case PositionTop: - case PositionBottom: - c = Qt::SizeVerCursor; - break; - case PositionLeft: - case PositionRight: - c = Qt::SizeHorCursor; - break; - default: - if( moveResizeMode ) - c = Qt::SizeAllCursor; - else - c = Qt::ArrowCursor; - break; - } - if( c.handle() == cursor.handle()) + switch(m) { + case PositionTopLeft: + case PositionBottomRight: + c = Qt::SizeFDiagCursor; + break; + case PositionBottomLeft: + case PositionTopRight: + c = Qt::SizeBDiagCursor; + break; + case PositionTop: + case PositionBottom: + c = Qt::SizeVerCursor; + break; + case PositionLeft: + case PositionRight: + c = Qt::SizeHorCursor; + break; + default: + if (moveResizeMode) + c = Qt::SizeAllCursor; + else + c = Qt::ArrowCursor; + break; + } + if (c.handle() == cursor.handle()) return; cursor = c; - if( decoration != NULL ) - decoration->widget()->setCursor( cursor ); - XDefineCursor( display(), frameId(), cursor.handle() ); - if( moveResizeMode ) // XDefineCursor doesn't change cursor if there's pointer grab active - XChangeActivePointerGrab( display(), - ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask, - cursor.handle(), xTime()); - } + if (decoration != NULL) + decoration->widget()->setCursor(cursor); + XDefineCursor(display(), frameId(), cursor.handle()); + if (moveResizeMode) // XDefineCursor doesn't change cursor if there's pointer grab active + XChangeActivePointerGrab(display(), + ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask, + cursor.handle(), xTime()); +} -Client::Position Client::mousePosition( const QPoint& p ) const - { - if( decoration != NULL ) - return decoration->mousePosition( p ); +Client::Position Client::mousePosition(const QPoint& p) const +{ + if (decoration != NULL) + return decoration->mousePosition(p); return PositionCenter; - } +} -void Client::updateAllowedActions( bool force ) - { - if( !isManaged() && !force ) +void Client::updateAllowedActions(bool force) +{ + if (!isManaged() && !force) return; unsigned long old_allowed_actions = allowed_actions; allowed_actions = 0; - if( isMovable() ) + if (isMovable()) allowed_actions |= NET::ActionMove; - if( isResizable() ) + if (isResizable()) allowed_actions |= NET::ActionResize; - if( isMinimizable() ) + if (isMinimizable()) allowed_actions |= NET::ActionMinimize; - if( isShadeable() ) + if (isShadeable()) allowed_actions |= NET::ActionShade; // Sticky state not supported - if( isMaximizable() ) + if (isMaximizable()) allowed_actions |= NET::ActionMax; - if( userCanSetFullScreen() ) + if (userCanSetFullScreen()) allowed_actions |= NET::ActionFullScreen; allowed_actions |= NET::ActionChangeDesktop; // Always (Pagers shouldn't show Docks etc.) - if( isCloseable() ) + if (isCloseable()) allowed_actions |= NET::ActionClose; - if( old_allowed_actions == allowed_actions ) + if (old_allowed_actions == allowed_actions) return; // TODO: This could be delayed and compressed - It's only for pagers etc. anyway - info->setAllowedActions( allowed_actions ); + info->setAllowedActions(allowed_actions); // TODO: This should also tell the decoration, so that it can update the buttons - } +} void Client::autoRaise() - { - workspace()->raiseClient( this ); +{ + workspace()->raiseClient(this); cancelAutoRaise(); - } +} void Client::cancelAutoRaise() - { +{ delete autoRaiseTimer; autoRaiseTimer = 0; - } +} -void Client::debug( QDebug& stream ) const - { +void Client::debug(QDebug& stream) const +{ stream << "\'ID:" << window() << ";WMCLASS:" << resourceClass() << ":" << resourceName() << ";Caption:" << caption() << "\'"; - } +} QPixmap* kwin_get_menu_pix_hack() - { +{ static QPixmap p; - if( p.isNull() ) - p = SmallIcon( "bx2" ); + if (p.isNull()) + p = SmallIcon("bx2"); return &p; - } +} void Client::checkActivities() - { +{ QStringList newActivitiesList; QByteArray prop = getStringProperty(window(), atoms->activities); activitiesDefined = !prop.isEmpty(); @@ -2261,7 +2186,7 @@ void Client::checkActivities() //copied from setOnAllActivities to avoid a redundant XChangeProperty. if (!activityList.isEmpty()) { activityList.clear(); - updateActivities( true ); + updateActivities(true); } return; } @@ -2269,7 +2194,7 @@ void Client::checkActivities() //note: this makes it *act* like it's on all activities but doesn't set the property to 'ALL' if (!activityList.isEmpty()) { activityList.clear(); - updateActivities( true ); + updateActivities(true); } return; } @@ -2280,22 +2205,19 @@ void Client::checkActivities() //otherwise, somebody else changed it. we need to validate before reacting QStringList allActivities = workspace()->activityList(); - if (allActivities.isEmpty()) - { + if (allActivities.isEmpty()) { kDebug() << "no activities!?!?"; //don't touch anything, there's probably something bad going on and we don't wanna make it worse return; - } - for ( int i = 0; i < newActivitiesList.size(); ++i ) - { - if ( ! allActivities.contains( newActivitiesList.at(i) ) ) - { - kDebug() << "invalid:" << newActivitiesList.at(i); - newActivitiesList.removeAt( i-- ); - } - } - setOnActivities( newActivitiesList ); } + for (int i = 0; i < newActivitiesList.size(); ++i) { + if (! allActivities.contains(newActivitiesList.at(i))) { + kDebug() << "invalid:" << newActivitiesList.at(i); + newActivitiesList.removeAt(i--); + } + } + setOnActivities(newActivitiesList); +} void Client::setSessionInteract(bool needed) { diff --git a/client.h b/client.h index c86071f21..e6f2ef4d4 100644 --- a/client.h +++ b/client.h @@ -56,7 +56,8 @@ class QProcess; class QTimer; class KStartupInfoData; -namespace SWrapper { +namespace SWrapper +{ class Client; } @@ -64,7 +65,8 @@ typedef QPair ClientResolution; namespace KWin { -namespace TabBox { +namespace TabBox +{ class TabBoxClientImpl; } @@ -77,927 +79,946 @@ class PaintRedirector; class Client : public Toplevel - { +{ Q_OBJECT - public: - Client( Workspace* ws ); - Window wrapperId() const; - Window decorationId() const; +public: + Client(Workspace* ws); + Window wrapperId() const; + Window decorationId() const; - const Client* transientFor() const; - Client* transientFor(); - bool isTransient() const; - bool groupTransient() const; - bool wasOriginallyGroupTransient() const; - ClientList mainClients() const; // Call once before loop , is not indirect - ClientList allMainClients() const; // Call once before loop , is indirect - bool hasTransient( const Client* c, bool indirect ) const; - const ClientList& transients() const; // Is not indirect - void checkTransient( Window w ); - Client* findModal( bool allow_itself = false ); - const Group* group() const; - Group* group(); - void checkGroup( Group* gr = NULL, bool force = false ); - void changeClientLeaderGroup( Group* gr ); - const WindowRules* rules() const; - void removeRule( Rules* r ); - void setupWindowRules( bool ignore_temporary ); - void applyWindowRules(); - void updateWindowRules(); - void updateFullscreenMonitors( NETFullscreenMonitors topology ); + const Client* transientFor() const; + Client* transientFor(); + bool isTransient() const; + bool groupTransient() const; + bool wasOriginallyGroupTransient() const; + ClientList mainClients() const; // Call once before loop , is not indirect + ClientList allMainClients() const; // Call once before loop , is indirect + bool hasTransient(const Client* c, bool indirect) const; + const ClientList& transients() const; // Is not indirect + void checkTransient(Window w); + Client* findModal(bool allow_itself = false); + const Group* group() const; + Group* group(); + void checkGroup(Group* gr = NULL, bool force = false); + void changeClientLeaderGroup(Group* gr); + const WindowRules* rules() const; + void removeRule(Rules* r); + void setupWindowRules(bool ignore_temporary); + void applyWindowRules(); + void updateWindowRules(); + void updateFullscreenMonitors(NETFullscreenMonitors topology); - /** - * Returns true for "special" windows and false for windows which are "normal" - * (normal=window which has a border, can be moved by the user, can be closed, etc.) - * true for Desktop, Dock, Splash, Override and TopMenu (and Toolbar??? - for now) - * false for Normal, Dialog, Utility and Menu (and Toolbar??? - not yet) TODO - */ - bool isSpecialWindow() const; - bool hasNETSupport() const; - - /** - * This is a public object with no wrappers or anything to keep it fast, - * so in essence, direct access is allowed. Please be very careful while - * using this object - */ - QHash* scriptCache; + /** + * Returns true for "special" windows and false for windows which are "normal" + * (normal=window which has a border, can be moved by the user, can be closed, etc.) + * true for Desktop, Dock, Splash, Override and TopMenu (and Toolbar??? - for now) + * false for Normal, Dialog, Utility and Menu (and Toolbar??? - not yet) TODO + */ + bool isSpecialWindow() const; + bool hasNETSupport() const; - QSize minSize() const; - QSize maxSize() const; - virtual QPoint clientPos() const; // Inside of geometry() - virtual QSize clientSize() const; - virtual QRect visibleRect() const; + /** + * This is a public object with no wrappers or anything to keep it fast, + * so in essence, direct access is allowed. Please be very careful while + * using this object + */ + QHash* scriptCache; - bool windowEvent( XEvent* e ); - virtual bool eventFilter( QObject* o, QEvent* e ); + QSize minSize() const; + QSize maxSize() const; + virtual QPoint clientPos() const; // Inside of geometry() + virtual QSize clientSize() const; + virtual QRect visibleRect() const; + + bool windowEvent(XEvent* e); + virtual bool eventFilter(QObject* o, QEvent* e); #ifdef HAVE_XSYNC - void syncEvent( XSyncAlarmNotifyEvent* e ); + void syncEvent(XSyncAlarmNotifyEvent* e); #endif - bool manage( Window w, bool isMapped ); - void releaseWindow( bool on_shutdown = false ); - void destroyClient(); + bool manage(Window w, bool isMapped); + void releaseWindow(bool on_shutdown = false); + void destroyClient(); - /// How to resize the window in order to obey constains (mainly aspect ratios) - enum Sizemode - { - SizemodeAny, - SizemodeFixedW, ///< Try not to affect width - SizemodeFixedH, ///< Try not to affect height - SizemodeMax ///< Try not to make it larger in either direction - }; - QSize adjustedSize( const QSize&, Sizemode mode = SizemodeAny ) const; - QSize adjustedSize() const; + /// How to resize the window in order to obey constains (mainly aspect ratios) + enum Sizemode { + SizemodeAny, + SizemodeFixedW, ///< Try not to affect width + SizemodeFixedH, ///< Try not to affect height + SizemodeMax ///< Try not to make it larger in either direction + }; + QSize adjustedSize(const QSize&, Sizemode mode = SizemodeAny) const; + QSize adjustedSize() const; - QPixmap icon() const; - QPixmap icon( const QSize& size ) const; - QPixmap miniIcon() const; - QPixmap bigIcon() const; - QPixmap hugeIcon() const; + QPixmap icon() const; + QPixmap icon(const QSize& size) const; + QPixmap miniIcon() const; + QPixmap bigIcon() const; + QPixmap hugeIcon() const; - bool isActive() const; - void setActive( bool ); + bool isActive() const; + void setActive(bool); - virtual int desktop() const; - void setDesktop( int ); - void setOnAllDesktops( bool set ); + virtual int desktop() const; + void setDesktop(int); + void setOnAllDesktops(bool set); - virtual QStringList activities() const; - void setOnActivity( const QString &activity, bool enable ); - void setOnAllActivities( bool set ); - void setOnActivities( QStringList newActivitiesList ); - void updateActivities( bool includeTransients ); + virtual QStringList activities() const; + void setOnActivity(const QString &activity, bool enable); + void setOnAllActivities(bool set); + void setOnActivities(QStringList newActivitiesList); + void updateActivities(bool includeTransients); - /// Is not minimized and not hidden. I.e. normally visible on some virtual desktop. - bool isShown( bool shaded_is_shown ) const; - bool isHiddenInternal() const; // For compositing + /// Is not minimized and not hidden. I.e. normally visible on some virtual desktop. + bool isShown(bool shaded_is_shown) const; + bool isHiddenInternal() const; // For compositing - bool isShade() const; // True only for ShadeNormal - ShadeMode shadeMode() const; // Prefer isShade() - void setShade( ShadeMode mode ); - bool isShadeable() const; + bool isShade() const; // True only for ShadeNormal + ShadeMode shadeMode() const; // Prefer isShade() + void setShade(ShadeMode mode); + bool isShadeable() const; - bool isMinimized() const; - bool isMaximizable() const; - QRect geometryRestore() const; - MaximizeMode maximizeModeRestore() const; - MaximizeMode maximizeMode() const; - bool isMinimizable() const; - void setMaximize( bool vertically, bool horizontally ); - QRect iconGeometry() const; + bool isMinimized() const; + bool isMaximizable() const; + QRect geometryRestore() const; + MaximizeMode maximizeModeRestore() const; + MaximizeMode maximizeMode() const; + bool isMinimizable() const; + void setMaximize(bool vertically, bool horizontally); + QRect iconGeometry() const; - void setFullScreen( bool set, bool user ); - bool isFullScreen() const; - bool isFullScreenable( bool fullscreen_hack = false ) const; - bool isActiveFullScreen() const; - bool userCanSetFullScreen() const; - QRect geometryFSRestore() const { return geom_fs_restore; } // Only for session saving - int fullScreenMode() const { return fullscreen_mode; } // only for session saving + void setFullScreen(bool set, bool user); + bool isFullScreen() const; + bool isFullScreenable(bool fullscreen_hack = false) const; + bool isActiveFullScreen() const; + bool userCanSetFullScreen() const; + QRect geometryFSRestore() const { + return geom_fs_restore; // Only for session saving + } + int fullScreenMode() const { + return fullscreen_mode; // only for session saving + } - bool noBorder() const; - void setNoBorder( bool set ); - bool userCanSetNoBorder() const; - void checkNoBorder(); + bool noBorder() const; + void setNoBorder(bool set); + bool userCanSetNoBorder() const; + void checkNoBorder(); - bool skipTaskbar( bool from_outside = false ) const; - void setSkipTaskbar( bool set, bool from_outside ); + bool skipTaskbar(bool from_outside = false) const; + void setSkipTaskbar(bool set, bool from_outside); - bool skipPager() const; - void setSkipPager( bool ); + bool skipPager() const; + void setSkipPager(bool); - bool skipSwitcher() const; - void setSkipSwitcher( bool set ); + bool skipSwitcher() const; + void setSkipSwitcher(bool set); - bool keepAbove() const; - void setKeepAbove( bool ); - bool keepBelow() const; - void setKeepBelow( bool ); - Layer layer() const; - Layer belongsToLayer() const; - void invalidateLayer(); - int sessionStackingOrder() const; + bool keepAbove() const; + void setKeepAbove(bool); + bool keepBelow() const; + void setKeepBelow(bool); + Layer layer() const; + Layer belongsToLayer() const; + void invalidateLayer(); + int sessionStackingOrder() const; - void setModal( bool modal ); - bool isModal() const; + void setModal(bool modal); + bool isModal() const; - // Auxiliary functions, depend on the windowType - bool wantsTabFocus() const; - bool wantsInput() const; + // Auxiliary functions, depend on the windowType + bool wantsTabFocus() const; + bool wantsInput() const; - bool isResizable() const; - bool isMovable() const; - bool isMovableAcrossScreens() const; - bool isCloseable() const; ///< May be closed by the user (May have a close button) + bool isResizable() const; + bool isMovable() const; + bool isMovableAcrossScreens() const; + bool isCloseable() const; ///< May be closed by the user (May have a close button) - void takeActivity( int flags, bool handled, allowed_t ); // Takes ActivityFlags as arg (in utils.h) - void takeFocus( allowed_t ); - void demandAttention( bool set = true ); + void takeActivity(int flags, bool handled, allowed_t); // Takes ActivityFlags as arg (in utils.h) + void takeFocus(allowed_t); + void demandAttention(bool set = true); - void setMask( const QRegion& r, int mode = X::Unsorted ); - QRegion mask() const; + void setMask(const QRegion& r, int mode = X::Unsorted); + QRegion mask() const; - void updateDecoration( bool check_workspace_pos, bool force = false ); - bool checkBorderSizes( bool also_resize ); - void triggerDecorationRepaint(); + void updateDecoration(bool check_workspace_pos, bool force = false); + bool checkBorderSizes(bool also_resize); + void triggerDecorationRepaint(); - void updateShape(); + void updateShape(); - void setGeometry( int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true ); - void setGeometry( const QRect& r, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true ); - void move( int x, int y, ForceGeometry_t force = NormalGeometrySet ); - void move( const QPoint& p, ForceGeometry_t force = NormalGeometrySet ); - /// plainResize() simply resizes - void plainResize( int w, int h, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true ); - void plainResize( const QSize& s, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true ); - /// resizeWithChecks() resizes according to gravity, and checks workarea position - void resizeWithChecks( int w, int h, ForceGeometry_t force = NormalGeometrySet ); - void resizeWithChecks( const QSize& s, ForceGeometry_t force = NormalGeometrySet ); - void keepInArea( QRect area, bool partial = false ); - void setElectricBorderMode( ElectricMaximizingMode mode ); - ElectricMaximizingMode electricBorderMode() const; - void setElectricBorderMaximizing( bool maximizing ); - bool isElectricBorderMaximizing() const; - QRect electricBorderMaximizeGeometry(); + void setGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true); + void setGeometry(const QRect& r, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true); + void move(int x, int y, ForceGeometry_t force = NormalGeometrySet); + void move(const QPoint& p, ForceGeometry_t force = NormalGeometrySet); + /// plainResize() simply resizes + void plainResize(int w, int h, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true); + void plainResize(const QSize& s, ForceGeometry_t force = NormalGeometrySet, bool emitJs = true); + /// resizeWithChecks() resizes according to gravity, and checks workarea position + void resizeWithChecks(int w, int h, ForceGeometry_t force = NormalGeometrySet); + void resizeWithChecks(const QSize& s, ForceGeometry_t force = NormalGeometrySet); + void keepInArea(QRect area, bool partial = false); + void setElectricBorderMode(ElectricMaximizingMode mode); + ElectricMaximizingMode electricBorderMode() const; + void setElectricBorderMaximizing(bool maximizing); + bool isElectricBorderMaximizing() const; + QRect electricBorderMaximizeGeometry(); - QSize sizeForClientSize( const QSize&, Sizemode mode = SizemodeAny, bool noframe = false ) const; + QSize sizeForClientSize(const QSize&, Sizemode mode = SizemodeAny, bool noframe = false) const; - /** Set the quick tile mode ("snap") of this window. - * This will also handle preserving and restoring of window geometry as necessary. - * @param mode The tile mode (left/right) to give this window. - */ - void setQuickTileMode( QuickTileMode mode, bool keyboard = false ); + /** Set the quick tile mode ("snap") of this window. + * This will also handle preserving and restoring of window geometry as necessary. + * @param mode The tile mode (left/right) to give this window. + */ + void setQuickTileMode(QuickTileMode mode, bool keyboard = false); - void growHorizontal(); - void shrinkHorizontal(); - void growVertical(); - void shrinkVertical(); + void growHorizontal(); + void shrinkHorizontal(); + void growVertical(); + void shrinkVertical(); - bool providesContextHelp() const; - KShortcut shortcut() const; - void setShortcut( const QString& cut ); + bool providesContextHelp() const; + KShortcut shortcut() const; + void setShortcut(const QString& cut); - WindowOperation mouseButtonToWindowOperation( Qt::MouseButtons button ); - bool performMouseCommand( Options::MouseCommand, const QPoint& globalPos, bool handled = false ); + WindowOperation mouseButtonToWindowOperation(Qt::MouseButtons button); + bool performMouseCommand(Options::MouseCommand, const QPoint& globalPos, bool handled = false); - QRect adjustedClientArea( const QRect& desktop, const QRect& area ) const; + QRect adjustedClientArea(const QRect& desktop, const QRect& area) const; - Colormap colormap() const; + Colormap colormap() const; - /// Updates visibility depending on being shaded, virtual desktop, etc. - void updateVisibility(); - /// Hides a client - Basically like minimize, but without effects, it's simply hidden - void hideClient( bool hide ); - bool hiddenPreview() const; ///< Window is mapped in order to get a window pixmap + /// Updates visibility depending on being shaded, virtual desktop, etc. + void updateVisibility(); + /// Hides a client - Basically like minimize, but without effects, it's simply hidden + void hideClient(bool hide); + bool hiddenPreview() const; ///< Window is mapped in order to get a window pixmap - virtual void setupCompositing(); - virtual void finishCompositing(); + virtual void setupCompositing(); + virtual void finishCompositing(); - QString caption( bool full = true ) const; - void updateCaption(); + QString caption(bool full = true) const; + void updateCaption(); - void keyPressEvent( uint key_code ); // FRAME ?? - void updateMouseGrab(); - Window moveResizeGrabWindow() const; + void keyPressEvent(uint key_code); // FRAME ?? + void updateMouseGrab(); + Window moveResizeGrabWindow() const; - const QPoint calculateGravitation( bool invert, int gravity = 0 ) const; // FRAME public? + const QPoint calculateGravitation(bool invert, int gravity = 0) const; // FRAME public? - void NETMoveResize( int x_root, int y_root, NET::Direction direction ); - void NETMoveResizeWindow( int flags, int x, int y, int width, int height ); - void restackWindow( Window above, int detail, NET::RequestSource source, Time timestamp, - bool send_event = false ); + void NETMoveResize(int x_root, int y_root, NET::Direction direction); + void NETMoveResizeWindow(int flags, int x, int y, int width, int height); + void restackWindow(Window above, int detail, NET::RequestSource source, Time timestamp, + bool send_event = false); - void gotPing( Time timestamp ); + void gotPing(Time timestamp); - void checkWorkspacePosition(); - void updateUserTime( Time time = CurrentTime ); - Time userTime() const; - bool hasUserTimeSupport() const; - bool ignoreFocusStealing() const; + void checkWorkspacePosition(); + void updateUserTime(Time time = CurrentTime); + Time userTime() const; + bool hasUserTimeSupport() const; + bool ignoreFocusStealing() const; - /// Does 'delete c;' - static void deleteClient( Client* c, allowed_t ); + /// Does 'delete c;' + static void deleteClient(Client* c, allowed_t); - static bool belongToSameApplication( const Client* c1, const Client* c2, bool active_hack = false ); - static bool sameAppWindowRoleMatch( const Client* c1, const Client* c2, bool active_hack ); - static void readIcons( Window win, QPixmap* icon, QPixmap* miniicon, QPixmap* bigicon, QPixmap* hugeicon ); + static bool belongToSameApplication(const Client* c1, const Client* c2, bool active_hack = false); + static bool sameAppWindowRoleMatch(const Client* c1, const Client* c2, bool active_hack); + static void readIcons(Window win, QPixmap* icon, QPixmap* miniicon, QPixmap* bigicon, QPixmap* hugeicon); - void minimize( bool avoid_animation = false ); - void unminimize( bool avoid_animation = false ); - void closeWindow(); - void killWindow(); - void maximize( MaximizeMode ); - void toggleShade(); - void showContextHelp(); - void cancelShadeHoverTimer(); - void cancelAutoRaise(); - void checkActiveModal(); - StrutRect strutRect( StrutArea area ) const; - StrutRects strutRects() const; - bool hasStrut() const; + void minimize(bool avoid_animation = false); + void unminimize(bool avoid_animation = false); + void closeWindow(); + void killWindow(); + void maximize(MaximizeMode); + void toggleShade(); + void showContextHelp(); + void cancelShadeHoverTimer(); + void cancelAutoRaise(); + void checkActiveModal(); + StrutRect strutRect(StrutArea area) const; + StrutRects strutRects() const; + bool hasStrut() const; - // Tabbing functions - ClientGroup* clientGroup() const; // Returns a pointer to client_group - void setClientGroup( ClientGroup* group ); - /* - * If shown is true the client is mapped and raised, if false - * the client is unmapped and hidden, this function is called - * when the tabbing group of the client switches its visible - * client. - */ - void setClientShown( bool shown ); - /* - * When a click is done in the decoration and it calls the group - * to change the visible client it starts to move-resize the new - * client, this function stops it. - */ - void dontMoveResize(); + // Tabbing functions + ClientGroup* clientGroup() const; // Returns a pointer to client_group + void setClientGroup(ClientGroup* group); + /* + * If shown is true the client is mapped and raised, if false + * the client is unmapped and hidden, this function is called + * when the tabbing group of the client switches its visible + * client. + */ + void setClientShown(bool shown); + /* + * When a click is done in the decoration and it calls the group + * to change the visible client it starts to move-resize the new + * client, this function stops it. + */ + void dontMoveResize(); - /** - * Whether or not the window has a strut that expands through the invisible area of - * an xinerama setup where the monitors are not the same resolution. - */ - bool hasOffscreenXineramaStrut() const; + /** + * Whether or not the window has a strut that expands through the invisible area of + * an xinerama setup where the monitors are not the same resolution. + */ + bool hasOffscreenXineramaStrut() const; - bool isMove() const - { - return moveResizeMode && mode == PositionCenter; - } - bool isResize() const - { - return moveResizeMode && mode != PositionCenter; - } + bool isMove() const { + return moveResizeMode && mode == PositionCenter; + } + bool isResize() const { + return moveResizeMode && mode != PositionCenter; + } - // Decorations <-> Effects - const QPixmap *topDecoPixmap() const { return &decorationPixmapTop; } - const QPixmap *leftDecoPixmap() const { return &decorationPixmapLeft; } - const QPixmap *bottomDecoPixmap() const { return &decorationPixmapBottom; } - const QPixmap *rightDecoPixmap() const { return &decorationPixmapRight; } + // Decorations <-> Effects + const QPixmap *topDecoPixmap() const { + return &decorationPixmapTop; + } + const QPixmap *leftDecoPixmap() const { + return &decorationPixmapLeft; + } + const QPixmap *bottomDecoPixmap() const { + return &decorationPixmapBottom; + } + const QPixmap *rightDecoPixmap() const { + return &decorationPixmapRight; + } - int paddingLeft() const { return padding_left; } - int paddingRight() const { return padding_right; } - int paddingTop() const { return padding_top; } - int paddingBottom() const { return padding_bottom; } + int paddingLeft() const { + return padding_left; + } + int paddingRight() const { + return padding_right; + } + int paddingTop() const { + return padding_top; + } + int paddingBottom() const { + return padding_bottom; + } - bool decorationPixmapRequiresRepaint(); - void ensureDecorationPixmapsPainted(); + bool decorationPixmapRequiresRepaint(); + void ensureDecorationPixmapsPainted(); - QRect decorationRect() const { - return (decoration && decoration->widget()) ? - decoration->widget()->rect().translated(-padding_left, -padding_top) : - QRect(0, 0, width(), height()); - } + QRect decorationRect() const { + return (decoration && decoration->widget()) ? + decoration->widget()->rect().translated(-padding_left, -padding_top) : + QRect(0, 0, width(), height()); + } - QRect transparentRect() const; + QRect transparentRect() const; - QRegion decorationPendingRegion() const; + QRegion decorationPendingRegion() const; - enum CoordinateMode { - DecorationRelative, // Relative to the top left corner of the decoration - WindowRelative // Relative to the top left corner of the window - }; - void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom, CoordinateMode mode) const; - virtual void addRepaintFull(); + enum CoordinateMode { + DecorationRelative, // Relative to the top left corner of the decoration + WindowRelative // Relative to the top left corner of the window + }; + void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom, CoordinateMode mode) const; + virtual void addRepaintFull(); - TabBox::TabBoxClientImpl* tabBoxClient() const { return m_tabBoxClient; } + TabBox::TabBoxClientImpl* tabBoxClient() const { + return m_tabBoxClient; + } - //sets whether the client should be treated as a SessionInteract window - void setSessionInteract(bool needed); + //sets whether the client should be treated as a SessionInteract window + void setSessionInteract(bool needed); - private slots: - void autoRaise(); - void shadeHover(); - void shadeUnhover(); - void shortcutActivated(); - void delayedMoveResize(); +private slots: + void autoRaise(); + void shadeHover(); + void shadeUnhover(); + void shortcutActivated(); + void delayedMoveResize(); - private: - friend class Bridge; // FRAME - virtual void processMousePressEvent( QMouseEvent* e ); +private: + friend class Bridge; // FRAME + virtual void processMousePressEvent(QMouseEvent* e); - private: - // Use Workspace::createClient() - virtual ~Client(); ///< Use destroyClient() or releaseWindow() +private: + // Use Workspace::createClient() + virtual ~Client(); ///< Use destroyClient() or releaseWindow() - Position mousePosition( const QPoint& ) const; - void updateCursor(); + Position mousePosition(const QPoint&) const; + void updateCursor(); - // Transparent stuff - void drawbound( const QRect& geom ); - void clearbound(); - void doDrawbound( const QRect& geom, bool clear ); + // Transparent stuff + void drawbound(const QRect& geom); + void clearbound(); + void doDrawbound(const QRect& geom, bool clear); - // Handlers for X11 events - bool mapRequestEvent( XMapRequestEvent* e ); - void unmapNotifyEvent( XUnmapEvent* e ); - void destroyNotifyEvent( XDestroyWindowEvent* e ); - void configureRequestEvent( XConfigureRequestEvent* e ); - virtual void propertyNotifyEvent( XPropertyEvent* e ); - void clientMessageEvent( XClientMessageEvent* e ); - void enterNotifyEvent( XCrossingEvent* e ); - void leaveNotifyEvent( XCrossingEvent* e ); - void focusInEvent( XFocusInEvent* e ); - void focusOutEvent( XFocusOutEvent* e ); + // Handlers for X11 events + bool mapRequestEvent(XMapRequestEvent* e); + void unmapNotifyEvent(XUnmapEvent* e); + void destroyNotifyEvent(XDestroyWindowEvent* e); + void configureRequestEvent(XConfigureRequestEvent* e); + virtual void propertyNotifyEvent(XPropertyEvent* e); + void clientMessageEvent(XClientMessageEvent* e); + void enterNotifyEvent(XCrossingEvent* e); + void leaveNotifyEvent(XCrossingEvent* e); + void focusInEvent(XFocusInEvent* e); + void focusOutEvent(XFocusOutEvent* e); #ifdef HAVE_XDAMAGE - virtual void damageNotifyEvent( XDamageNotifyEvent* e ); + virtual void damageNotifyEvent(XDamageNotifyEvent* e); #endif - bool buttonPressEvent( Window w, int button, int state, int x, int y, int x_root, int y_root ); - bool buttonReleaseEvent( Window w, int button, int state, int x, int y, int x_root, int y_root ); - bool motionNotifyEvent( Window w, int state, int x, int y, int x_root, int y_root ); - void checkQuickTilingMaximizationZones( int xroot, int yroot ); + bool buttonPressEvent(Window w, int button, int state, int x, int y, int x_root, int y_root); + bool buttonReleaseEvent(Window w, int button, int state, int x, int y, int x_root, int y_root); + bool motionNotifyEvent(Window w, int state, int x, int y, int x_root, int y_root); + void checkQuickTilingMaximizationZones(int xroot, int yroot); - bool processDecorationButtonPress( int button, int state, int x, int y, int x_root, int y_root, - bool ignoreMenu = false ); + bool processDecorationButtonPress(int button, int state, int x, int y, int x_root, int y_root, + bool ignoreMenu = false); - protected: - virtual void debug( QDebug& stream ) const; - virtual bool shouldUnredirect() const; +protected: + virtual void debug(QDebug& stream) const; + virtual bool shouldUnredirect() const; + +private slots: + void pingTimeout(); + void processKillerExited(); + void demandAttentionKNotify(); + void syncTimeout(); + void delayedSetShortcut(); + void repaintDecorationPending(); - private slots: - void pingTimeout(); - void processKillerExited(); - void demandAttentionKNotify(); - void syncTimeout(); - void delayedSetShortcut(); - void repaintDecorationPending(); - //Signals for the scripting interface //Signals make an excellent way for communication //in between objects as compared to simple function //calls - signals: - void s_clientMoved(); - void clientManaging(KWin::Client*); - void s_minimized(); - void s_unminimized(); - void maximizeSet(QPair); - void s_activated(); - void s_fullScreenSet(bool, bool); - +signals: + void s_clientMoved(); + void clientManaging(KWin::Client*); + void s_minimized(); + void s_unminimized(); + void maximizeSet(QPair); + void s_activated(); + void s_fullScreenSet(bool, bool); + // To make workspace-client calls, a few slots are also // required - public slots: - void sl_activated(); - - private: - void exportMappingState( int s ); // ICCCM 4.1.3.1, 4.1.4, NETWM 2.5.1 - bool isManaged() const; ///< Returns false if this client is not yet managed - void updateAllowedActions( bool force = false ); - QRect fullscreenMonitorsArea( NETFullscreenMonitors topology ) const; - void changeMaximize( bool horizontal, bool vertical, bool adjust ); - void checkMaximizeGeometry(); - int checkFullScreenHack( const QRect& geom ) const; // 0 - None, 1 - One xinerama screen, 2 - Full area - void updateFullScreenHack( const QRect& geom ); - void getWmNormalHints(); - void getMotifHints(); - void getIcons(); - void fetchName(); - void fetchIconicName(); - QString readName() const; - void setCaption( const QString& s, bool force = false ); - bool hasTransientInternal( const Client* c, bool indirect, ConstClientList& set ) const; - void finishWindowRules(); - void setShortcutInternal( const KShortcut& cut ); +public slots: + void sl_activated(); - void checkDirection( int new_diff, int old_diff, QRect& rect, const QRect& area ); - void configureRequest( int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool ); - NETExtendedStrut strut() const; - int checkShadeGeometry( int w, int h ); - void blockGeometryUpdates( bool block ); - void getSyncCounter(); - void sendSyncRequest(); +private: + void exportMappingState(int s); // ICCCM 4.1.3.1, 4.1.4, NETWM 2.5.1 + bool isManaged() const; ///< Returns false if this client is not yet managed + void updateAllowedActions(bool force = false); + QRect fullscreenMonitorsArea(NETFullscreenMonitors topology) const; + void changeMaximize(bool horizontal, bool vertical, bool adjust); + void checkMaximizeGeometry(); + int checkFullScreenHack(const QRect& geom) const; // 0 - None, 1 - One xinerama screen, 2 - Full area + void updateFullScreenHack(const QRect& geom); + void getWmNormalHints(); + void getMotifHints(); + void getIcons(); + void fetchName(); + void fetchIconicName(); + QString readName() const; + void setCaption(const QString& s, bool force = false); + bool hasTransientInternal(const Client* c, bool indirect, ConstClientList& set) const; + void finishWindowRules(); + void setShortcutInternal(const KShortcut& cut); - bool startMoveResize(); - void finishMoveResize( bool cancel ); - void leaveMoveResize(); - void checkUnrestrictedMoveResize(); - void handleMoveResize( int x, int y, int x_root, int y_root ); - void startDelayedMoveResize(); - void stopDelayedMoveResize(); - void positionGeometryTip(); - void grabButton( int mod ); - void ungrabButton( int mod ); - void resetMaximize(); - void resizeDecoration( const QSize& s ); - void performMoveResize(); + void checkDirection(int new_diff, int old_diff, QRect& rect, const QRect& area); + void configureRequest(int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool); + NETExtendedStrut strut() const; + int checkShadeGeometry(int w, int h); + void blockGeometryUpdates(bool block); + void getSyncCounter(); + void sendSyncRequest(); - void pingWindow(); - void killProcess( bool ask, Time timestamp = CurrentTime ); - void updateUrgency(); - static void sendClientMessage( Window w, Atom a, Atom protocol, - long data1 = 0, long data2 = 0, long data3 = 0 ); + bool startMoveResize(); + void finishMoveResize(bool cancel); + void leaveMoveResize(); + void checkUnrestrictedMoveResize(); + void handleMoveResize(int x, int y, int x_root, int y_root); + void startDelayedMoveResize(); + void stopDelayedMoveResize(); + void positionGeometryTip(); + void grabButton(int mod); + void ungrabButton(int mod); + void resetMaximize(); + void resizeDecoration(const QSize& s); + void performMoveResize(); - void embedClient( Window w, const XWindowAttributes& attr ); - void detectNoBorder(); - void destroyDecoration(); - void updateFrameExtents(); + void pingWindow(); + void killProcess(bool ask, Time timestamp = CurrentTime); + void updateUrgency(); + static void sendClientMessage(Window w, Atom a, Atom protocol, + long data1 = 0, long data2 = 0, long data3 = 0); - void internalShow( allowed_t ); - void internalHide( allowed_t ); - void internalKeep( allowed_t ); - void map( allowed_t ); - void unmap( allowed_t ); - void updateHiddenPreview(); + void embedClient(Window w, const XWindowAttributes& attr); + void detectNoBorder(); + void destroyDecoration(); + void updateFrameExtents(); - void updateInputShape(); - void repaintDecorationPixmap( QPixmap& pix, const QRect& r, const QPixmap& src, QRegion reg ); - void resizeDecorationPixmaps(); + void internalShow(allowed_t); + void internalHide(allowed_t); + void internalKeep(allowed_t); + void map(allowed_t); + void unmap(allowed_t); + void updateHiddenPreview(); - Time readUserTimeMapTimestamp( const KStartupInfoId* asn_id, const KStartupInfoData* asn_data, - bool session ) const; - Time readUserCreationTime() const; - void startupIdChanged(); + void updateInputShape(); + void repaintDecorationPixmap(QPixmap& pix, const QRect& r, const QPixmap& src, QRegion reg); + void resizeDecorationPixmaps(); - Window client; - Window wrapper; - KDecoration* decoration; - Bridge* bridge; - int desk; - QStringList activityList; - bool buttonDown; - bool moveResizeMode; - bool move_faked_activity; - Window move_resize_grab_window; - bool move_resize_has_keyboard_grab; - bool unrestrictedMoveResize; + Time readUserTimeMapTimestamp(const KStartupInfoId* asn_id, const KStartupInfoData* asn_data, + bool session) const; + Time readUserCreationTime() const; + void startupIdChanged(); - Position mode; - QPoint moveOffset; - QPoint invertedMoveOffset; - QRect moveResizeGeom; - QRect initialMoveResizeGeom; - XSizeHints xSizeHint; - void sendSyntheticConfigureNotify(); - enum MappingState - { - Withdrawn, ///< Not handled, as per ICCCM WithdrawnState - Mapped, ///< The frame is mapped - Unmapped, ///< The frame is not mapped - Kept ///< The frame should be unmapped, but is kept (For compositing) - }; - MappingState mapping_state; + Window client; + Window wrapper; + KDecoration* decoration; + Bridge* bridge; + int desk; + QStringList activityList; + bool buttonDown; + bool moveResizeMode; + bool move_faked_activity; + Window move_resize_grab_window; + bool move_resize_has_keyboard_grab; + bool unrestrictedMoveResize; - /** The quick tile mode of this window. - */ - QuickTileMode quick_tile_mode; - QRect geom_pretile; - - void readTransient(); - Window verifyTransientFor( Window transient_for, bool set ); - void addTransient( Client* cl ); - void removeTransient( Client* cl ); - void removeFromMainClients(); - void cleanGrouping(); - void checkGroupTransients(); - void setTransient( Window new_transient_for_id ); - Client* transient_for; - Window transient_for_id; - Window original_transient_for_id; - ClientList transients_list; // SELI TODO: Make this ordered in stacking order? - ShadeMode shade_mode; - uint active : 1; - uint deleting : 1; ///< True when doing cleanup and destroying the client - uint keep_above : 1; ///< NET::KeepAbove (was stays_on_top) - uint skip_taskbar : 1; - uint original_skip_taskbar : 1; ///< Unaffected by KWin - uint Pdeletewindow : 1; ///< Does the window understand the DeleteWindow protocol? - uint Ptakefocus : 1;///< Does the window understand the TakeFocus protocol? - uint Ptakeactivity : 1; ///< Does it support _NET_WM_TAKE_ACTIVITY - uint Pcontexthelp : 1; ///< Does the window understand the ContextHelp protocol? - uint Pping : 1; ///< Does it support _NET_WM_PING? - uint input : 1; ///< Does the window want input in its wm_hints - uint skip_pager : 1; - uint skip_switcher : 1; - uint motif_may_resize : 1; - uint motif_may_move : 1; - uint motif_may_close : 1; - uint keep_below : 1; ///< NET::KeepBelow - uint minimized : 1; - uint hidden : 1; ///< Forcibly hidden by calling hide() - uint modal : 1; ///< NET::Modal - uint noborder : 1; - uint app_noborder : 1; ///< App requested no border via window type, shape extension, etc. - uint motif_noborder : 1; ///< App requested no border via Motif WM hints - uint urgency : 1; ///< XWMHints, UrgencyHint - uint ignore_focus_stealing : 1; ///< Don't apply focus stealing prevention to this client - uint demands_attention : 1; - WindowRules client_rules; - void getWMHints(); - void readIcons(); - void getWindowProtocols(); - QPixmap icon_pix; - QPixmap miniicon_pix; - QPixmap bigicon_pix; - QPixmap hugeicon_pix; - QCursor cursor; - // DON'T reorder - Saved to config files !!! - enum FullScreenMode - { - FullScreenNone, - FullScreenNormal, - FullScreenHack ///< Non-NETWM fullscreen (noborder and size of desktop) - }; - FullScreenMode fullscreen_mode; - MaximizeMode max_mode; - QRect geom_restore; - QRect geom_fs_restore; - MaximizeMode maxmode_restore; - QTimer* autoRaiseTimer; - QTimer* shadeHoverTimer; - QTimer* delayedMoveResizeTimer; - Colormap cmap; - QString cap_normal, cap_iconic, cap_suffix; - Group* in_group; - Window window_group; - ClientGroup* client_group; - Layer in_layer; - QTimer* ping_timer; - QProcess* process_killer; - Time ping_timestamp; - Time user_time; - unsigned long allowed_actions; - QSize client_size; - int block_geometry_updates; // > 0 = New geometry is remembered, but not actually set - enum PendingGeometry_t - { - PendingGeometryNone, - PendingGeometryNormal, - PendingGeometryForced - }; - PendingGeometry_t pending_geometry_update; - QRect geom_before_block; - QRect deco_rect_before_block; - bool shade_geometry_change; -#ifdef HAVE_XSYNC - XSyncCounter sync_counter; - XSyncValue sync_counter_value; - XSyncAlarm sync_alarm; -#endif - QTimer* sync_timeout; - bool sync_resize_pending; - int border_left, border_right, border_top, border_bottom; - int padding_left, padding_right, padding_top, padding_bottom; - QRegion _mask; - static bool check_active_modal; ///< \see Client::checkActiveModal() - KShortcut _shortcut; - int sm_stacking_order; - friend struct FetchNameInternalPredicate; - friend struct CheckIgnoreFocusStealingProcedure; - friend struct ResetupRulesProcedure; - friend class GeometryUpdatesBlocker; - QTimer* demandAttentionKNotifyTimer; - QPixmap decorationPixmapLeft, decorationPixmapRight, decorationPixmapTop, decorationPixmapBottom; - PaintRedirector* paintRedirector; - TabBox::TabBoxClientImpl* m_tabBoxClient; - - bool electricMaximizing; - ElectricMaximizingMode electricMode; - - friend bool performTransiencyCheck(); - friend class SWrapper::Client; - - void checkActivities(); - bool activitiesDefined; //whether the x property was actually set - - bool needsSessionInteract; + Position mode; + QPoint moveOffset; + QPoint invertedMoveOffset; + QRect moveResizeGeom; + QRect initialMoveResizeGeom; + XSizeHints xSizeHint; + void sendSyntheticConfigureNotify(); + enum MappingState { + Withdrawn, ///< Not handled, as per ICCCM WithdrawnState + Mapped, ///< The frame is mapped + Unmapped, ///< The frame is not mapped + Kept ///< The frame should be unmapped, but is kept (For compositing) }; + MappingState mapping_state; + + /** The quick tile mode of this window. + */ + QuickTileMode quick_tile_mode; + QRect geom_pretile; + + void readTransient(); + Window verifyTransientFor(Window transient_for, bool set); + void addTransient(Client* cl); + void removeTransient(Client* cl); + void removeFromMainClients(); + void cleanGrouping(); + void checkGroupTransients(); + void setTransient(Window new_transient_for_id); + Client* transient_for; + Window transient_for_id; + Window original_transient_for_id; + ClientList transients_list; // SELI TODO: Make this ordered in stacking order? + ShadeMode shade_mode; + uint active : 1; + uint deleting : 1; ///< True when doing cleanup and destroying the client + uint keep_above : 1; ///< NET::KeepAbove (was stays_on_top) + uint skip_taskbar : 1; + uint original_skip_taskbar : 1; ///< Unaffected by KWin + uint Pdeletewindow : 1; ///< Does the window understand the DeleteWindow protocol? + uint Ptakefocus : 1;///< Does the window understand the TakeFocus protocol? + uint Ptakeactivity : 1; ///< Does it support _NET_WM_TAKE_ACTIVITY + uint Pcontexthelp : 1; ///< Does the window understand the ContextHelp protocol? + uint Pping : 1; ///< Does it support _NET_WM_PING? + uint input : 1; ///< Does the window want input in its wm_hints + uint skip_pager : 1; + uint skip_switcher : 1; + uint motif_may_resize : 1; + uint motif_may_move : 1; + uint motif_may_close : 1; + uint keep_below : 1; ///< NET::KeepBelow + uint minimized : 1; + uint hidden : 1; ///< Forcibly hidden by calling hide() + uint modal : 1; ///< NET::Modal + uint noborder : 1; + uint app_noborder : 1; ///< App requested no border via window type, shape extension, etc. + uint motif_noborder : 1; ///< App requested no border via Motif WM hints + uint urgency : 1; ///< XWMHints, UrgencyHint + uint ignore_focus_stealing : 1; ///< Don't apply focus stealing prevention to this client + uint demands_attention : 1; + WindowRules client_rules; + void getWMHints(); + void readIcons(); + void getWindowProtocols(); + QPixmap icon_pix; + QPixmap miniicon_pix; + QPixmap bigicon_pix; + QPixmap hugeicon_pix; + QCursor cursor; + // DON'T reorder - Saved to config files !!! + enum FullScreenMode { + FullScreenNone, + FullScreenNormal, + FullScreenHack ///< Non-NETWM fullscreen (noborder and size of desktop) + }; + FullScreenMode fullscreen_mode; + MaximizeMode max_mode; + QRect geom_restore; + QRect geom_fs_restore; + MaximizeMode maxmode_restore; + QTimer* autoRaiseTimer; + QTimer* shadeHoverTimer; + QTimer* delayedMoveResizeTimer; + Colormap cmap; + QString cap_normal, cap_iconic, cap_suffix; + Group* in_group; + Window window_group; + ClientGroup* client_group; + Layer in_layer; + QTimer* ping_timer; + QProcess* process_killer; + Time ping_timestamp; + Time user_time; + unsigned long allowed_actions; + QSize client_size; + int block_geometry_updates; // > 0 = New geometry is remembered, but not actually set + enum PendingGeometry_t { + PendingGeometryNone, + PendingGeometryNormal, + PendingGeometryForced + }; + PendingGeometry_t pending_geometry_update; + QRect geom_before_block; + QRect deco_rect_before_block; + bool shade_geometry_change; +#ifdef HAVE_XSYNC + XSyncCounter sync_counter; + XSyncValue sync_counter_value; + XSyncAlarm sync_alarm; +#endif + QTimer* sync_timeout; + bool sync_resize_pending; + int border_left, border_right, border_top, border_bottom; + int padding_left, padding_right, padding_top, padding_bottom; + QRegion _mask; + static bool check_active_modal; ///< \see Client::checkActiveModal() + KShortcut _shortcut; + int sm_stacking_order; + friend struct FetchNameInternalPredicate; + friend struct CheckIgnoreFocusStealingProcedure; + friend struct ResetupRulesProcedure; + friend class GeometryUpdatesBlocker; + QTimer* demandAttentionKNotifyTimer; + QPixmap decorationPixmapLeft, decorationPixmapRight, decorationPixmapTop, decorationPixmapBottom; + PaintRedirector* paintRedirector; + TabBox::TabBoxClientImpl* m_tabBoxClient; + + bool electricMaximizing; + ElectricMaximizingMode electricMode; + + friend bool performTransiencyCheck(); + friend class SWrapper::Client; + + void checkActivities(); + bool activitiesDefined; //whether the x property was actually set + + bool needsSessionInteract; +}; /** * Helper for Client::blockGeometryUpdates() being called in pairs (true/false) */ class GeometryUpdatesBlocker - { - public: - GeometryUpdatesBlocker( Client* c ) - : cl( c ) { cl->blockGeometryUpdates( true ); } - ~GeometryUpdatesBlocker() - { cl->blockGeometryUpdates( false ); } +{ +public: + GeometryUpdatesBlocker(Client* c) + : cl(c) { + cl->blockGeometryUpdates(true); + } + ~GeometryUpdatesBlocker() { + cl->blockGeometryUpdates(false); + } - private: - Client* cl; - }; +private: + Client* cl; +}; /** * NET WM Protocol handler class */ class WinInfo : public NETWinInfo2 - { - private: - typedef KWin::Client Client; // Because of NET::Client +{ +private: + typedef KWin::Client Client; // Because of NET::Client - public: - WinInfo( Client* c, Display * display, Window window, - Window rwin, const unsigned long pr[], int pr_size ); - virtual void changeDesktop(int desktop); - virtual void changeFullscreenMonitors(NETFullscreenMonitors topology); - virtual void changeState( unsigned long state, unsigned long mask ); - void disable(); +public: + WinInfo(Client* c, Display * display, Window window, + Window rwin, const unsigned long pr[], int pr_size); + virtual void changeDesktop(int desktop); + virtual void changeFullscreenMonitors(NETFullscreenMonitors topology); + virtual void changeState(unsigned long state, unsigned long mask); + void disable(); - private: - Client * m_client; - }; +private: + Client * m_client; +}; inline Window Client::wrapperId() const - { +{ return wrapper; - } +} inline Window Client::decorationId() const - { +{ return decoration != NULL ? decoration->widget()->winId() : None; - } +} inline const Client* Client::transientFor() const - { +{ return transient_for; - } +} inline Client* Client::transientFor() - { +{ return transient_for; - } +} inline bool Client::groupTransient() const - { +{ return transient_for_id == rootWindow(); - } +} // Needed because verifyTransientFor() may set transient_for_id to root window, // if the original value has a problem (window doesn't exist, etc.) inline bool Client::wasOriginallyGroupTransient() const - { +{ return original_transient_for_id == rootWindow(); - } +} inline bool Client::isTransient() const - { +{ return transient_for_id != None; - } +} inline const ClientList& Client::transients() const - { +{ return transients_list; - } +} inline const Group* Client::group() const - { +{ return in_group; - } +} inline Group* Client::group() - { +{ return in_group; - } +} -inline void Client::setClientGroup( ClientGroup* group ) - { +inline void Client::setClientGroup(ClientGroup* group) +{ client_group = group; - } +} inline ClientGroup* Client::clientGroup() const - { +{ return client_group; - } +} inline bool Client::isMinimized() const - { +{ return minimized; - } +} inline bool Client::isActive() const - { +{ return active; - } +} -inline bool Client::isShown( bool shaded_is_shown ) const - { - return !isMinimized() && ( !isShade() || shaded_is_shown ) && !hidden && - ( clientGroup() == NULL || clientGroup()->visible() == this ); - } +inline bool Client::isShown(bool shaded_is_shown) const +{ + return !isMinimized() && (!isShade() || shaded_is_shown) && !hidden && + (clientGroup() == NULL || clientGroup()->visible() == this); +} inline bool Client::isHiddenInternal() const - { +{ return hidden; - } +} inline bool Client::isShade() const - { +{ return shade_mode == ShadeNormal; - } +} inline ShadeMode Client::shadeMode() const - { +{ return shade_mode; - } +} inline QPixmap Client::icon() const - { +{ return icon_pix; - } +} inline QPixmap Client::miniIcon() const - { +{ return miniicon_pix; - } +} inline QPixmap Client::bigIcon() const - { +{ return bigicon_pix; - } +} inline QPixmap Client::hugeIcon() const - { +{ return hugeicon_pix; - } +} inline QRect Client::geometryRestore() const - { +{ return geom_restore; - } +} inline Client::MaximizeMode Client::maximizeModeRestore() const - { +{ return maxmode_restore; - } +} inline Client::MaximizeMode Client::maximizeMode() const - { +{ return max_mode; - } +} -inline bool Client::skipTaskbar( bool from_outside ) const - { +inline bool Client::skipTaskbar(bool from_outside) const +{ return from_outside ? original_skip_taskbar : skip_taskbar; - } +} inline bool Client::skipPager() const - { +{ return skip_pager; - } +} inline bool Client::skipSwitcher() const - { +{ return skip_switcher; - } +} inline bool Client::keepAbove() const - { +{ return keep_above; - } +} inline bool Client::keepBelow() const - { +{ return keep_below; - } +} inline bool Client::isFullScreen() const - { +{ return fullscreen_mode != FullScreenNone; - } +} inline bool Client::isModal() const - { +{ return modal; - } +} inline bool Client::hasNETSupport() const - { +{ return info->hasNETSupport(); - } +} inline Colormap Client::colormap() const - { +{ return cmap; - } +} inline void Client::invalidateLayer() - { +{ in_layer = UnknownLayer; - } +} inline int Client::sessionStackingOrder() const - { +{ return sm_stacking_order; - } +} inline bool Client::isManaged() const - { +{ return mapping_state != Withdrawn; - } +} inline QPoint Client::clientPos() const - { - return QPoint( border_left, border_top ); - } +{ + return QPoint(border_left, border_top); +} inline QSize Client::clientSize() const - { +{ return client_size; - } +} inline QRect Client::visibleRect() const - { - return geometry().adjusted( -padding_left, -padding_top, padding_right, padding_bottom ); - } +{ + return geometry().adjusted(-padding_left, -padding_top, padding_right, padding_bottom); +} -inline void Client::setGeometry( const QRect& r, ForceGeometry_t force, bool emitJs ) - { - setGeometry( r.x(), r.y(), r.width(), r.height(), force, emitJs ); - } +inline void Client::setGeometry(const QRect& r, ForceGeometry_t force, bool emitJs) +{ + setGeometry(r.x(), r.y(), r.width(), r.height(), force, emitJs); +} -inline void Client::move( const QPoint& p, ForceGeometry_t force ) - { - move( p.x(), p.y(), force ); - } +inline void Client::move(const QPoint& p, ForceGeometry_t force) +{ + move(p.x(), p.y(), force); +} -inline void Client::plainResize( const QSize& s, ForceGeometry_t force, bool emitJs ) - { - plainResize( s.width(), s.height(), force, emitJs ); - } +inline void Client::plainResize(const QSize& s, ForceGeometry_t force, bool emitJs) +{ + plainResize(s.width(), s.height(), force, emitJs); +} -inline void Client::resizeWithChecks( const QSize& s, ForceGeometry_t force ) - { - resizeWithChecks( s.width(), s.height(), force ); - } +inline void Client::resizeWithChecks(const QSize& s, ForceGeometry_t force) +{ + resizeWithChecks(s.width(), s.height(), force); +} inline bool Client::hasUserTimeSupport() const - { +{ return info->userTime() != -1U; - } +} inline bool Client::ignoreFocusStealing() const - { +{ return ignore_focus_stealing; - } +} inline const WindowRules* Client::rules() const - { +{ return &client_rules; - } +} -KWIN_PROCEDURE( CheckIgnoreFocusStealingProcedure, Client, cl->ignore_focus_stealing = options->checkIgnoreFocusStealing( cl )); +KWIN_PROCEDURE(CheckIgnoreFocusStealingProcedure, Client, cl->ignore_focus_stealing = options->checkIgnoreFocusStealing(cl)); inline Window Client::moveResizeGrabWindow() const - { +{ return move_resize_grab_window; - } +} inline KShortcut Client::shortcut() const - { +{ return _shortcut; - } +} -inline void Client::removeRule( Rules* rule ) - { - client_rules.remove( rule ); - } +inline void Client::removeRule(Rules* rule) +{ + client_rules.remove(rule); +} inline bool Client::hiddenPreview() const - { +{ return mapping_state == Kept; - } +} -KWIN_COMPARE_PREDICATE( WrapperIdMatchPredicate, Client, Window, cl->wrapperId() == value ); +KWIN_COMPARE_PREDICATE(WrapperIdMatchPredicate, Client, Window, cl->wrapperId() == value); } // namespace diff --git a/clientgroup.cpp b/clientgroup.cpp index 92ad7e9e5..a349fff3a 100644 --- a/clientgroup.cpp +++ b/clientgroup.cpp @@ -27,337 +27,323 @@ along with this program. If not, see . namespace KWin { -ClientGroup::ClientGroup( Client *c ) +ClientGroup::ClientGroup(Client *c) : clients_() , items_() - , visible_( 0 ) - , minSize_( 0, 0 ) - , maxSize_( INT_MAX, INT_MAX ) - { - clients_.append( c ); + , visible_(0) + , minSize_(0, 0) + , maxSize_(INT_MAX, INT_MAX) +{ + clients_.append(c); updateItems(); updateMinMaxSize(); - Workspace::self()->addClientGroup( this ); - c->setClientShown( true ); // Ensure the client is visible + Workspace::self()->addClientGroup(this); + c->setClientShown(true); // Ensure the client is visible c->triggerDecorationRepaint(); // TODO: Required? Maybe for creating new group? - } +} ClientGroup::~ClientGroup() - { - Workspace::self()->removeClientGroup( this ); - } +{ + Workspace::self()->removeClientGroup(this); +} -void ClientGroup::add( Client* c, int before, bool becomeVisible ) - { - if( contains( c ) || !c->workspace()->decorationSupportsClientGrouping() ) +void ClientGroup::add(Client* c, int before, bool becomeVisible) +{ + if (contains(c) || !c->workspace()->decorationSupportsClientGrouping()) return; // Remove the Client->ClientGroup reference if the client is already in another group so we // don't change the geometry of other clients in their current group by accident. However // don't REMOVE them from the actual group until we are certain that the client will be moved. ClientGroup* oldGroup = NULL; - if( c->clientGroup() ) - { + if (c->clientGroup()) { oldGroup = c->clientGroup(); - c->setClientGroup( NULL ); - } + c->setClientGroup(NULL); + } // If it's not possible to have the same states then ungroup them, TODO: Check all states // We do this here as the ungroup code in updateStates() cannot be called until add() completes ShadeMode oldShadeMode = c->shadeMode(); - if( c->shadeMode() != clients_[visible_]->shadeMode() ) - c->setShade( clients_[visible_]->shadeMode() ); - if( c->shadeMode() != clients_[visible_]->shadeMode() ) - { - if( oldGroup ) // Re-add to old group if required - c->setClientGroup( oldGroup ); - // One need to trigger decoration repaint on the group to + if (c->shadeMode() != clients_[visible_]->shadeMode()) + c->setShade(clients_[visible_]->shadeMode()); + if (c->shadeMode() != clients_[visible_]->shadeMode()) { + if (oldGroup) // Re-add to old group if required + c->setClientGroup(oldGroup); + // One need to trigger decoration repaint on the group to // make sure hover animations are properly reset. clients_[visible_]->triggerDecorationRepaint(); return; - } + } QRect oldGeom = c->geometry(); - if( c->geometry() != clients_[visible_]->geometry() ) - c->setGeometry( clients_[visible_]->geometry() ); - if( c->geometry() != clients_[visible_]->geometry() ) - { - if( c->shadeMode() != oldShadeMode ) - c->setShade( oldShadeMode ); // Restore old shade mode - if( oldGroup ) // Re-add to old group if required - c->setClientGroup( oldGroup ); + if (c->geometry() != clients_[visible_]->geometry()) + c->setGeometry(clients_[visible_]->geometry()); + if (c->geometry() != clients_[visible_]->geometry()) { + if (c->shadeMode() != oldShadeMode) + c->setShade(oldShadeMode); // Restore old shade mode + if (oldGroup) // Re-add to old group if required + c->setClientGroup(oldGroup); clients_[visible_]->triggerDecorationRepaint(); return; - } - if( c->desktop() != clients_[visible_]->desktop() ) - c->setDesktop( clients_[visible_]->desktop() ); - if( c->desktop() != clients_[visible_]->desktop() ) - { - if( c->geometry() != oldGeom ) - c->setGeometry( oldGeom ); // Restore old geometry - if( c->shadeMode() != oldShadeMode ) - c->setShade( oldShadeMode ); // Restore old shade mode - if( oldGroup ) // Re-add to old group if required - c->setClientGroup( oldGroup ); + } + if (c->desktop() != clients_[visible_]->desktop()) + c->setDesktop(clients_[visible_]->desktop()); + if (c->desktop() != clients_[visible_]->desktop()) { + if (c->geometry() != oldGeom) + c->setGeometry(oldGeom); // Restore old geometry + if (c->shadeMode() != oldShadeMode) + c->setShade(oldShadeMode); // Restore old shade mode + if (oldGroup) // Re-add to old group if required + c->setClientGroup(oldGroup); clients_[visible_]->triggerDecorationRepaint(); return; - } + } // Tabbed windows MUST have a decoration - if( c->noBorder() ) - c->setNoBorder( false ); - if( clients_[visible_]->noBorder() ) - clients_[visible_]->setNoBorder( false ); + if (c->noBorder()) + c->setNoBorder(false); + if (clients_[visible_]->noBorder()) + clients_[visible_]->setNoBorder(false); // Re-add to old group if required for the effect hook - if( oldGroup ) - c->setClientGroup( oldGroup ); + if (oldGroup) + c->setClientGroup(oldGroup); // Notify effects of merge - if( effects != NULL ) + if (effects != NULL) static_cast(effects)->clientGroupItemAdded( - c->effectWindow(), clients_[visible_]->effectWindow() ); + c->effectWindow(), clients_[visible_]->effectWindow()); // Actually remove from old group if required and update - if( c->clientGroup() ) - c->clientGroup()->remove( c ); - c->setClientGroup( this ); // Let the client know which group it belongs to + if (c->clientGroup()) + c->clientGroup()->remove(c); + c->setClientGroup(this); // Let the client know which group it belongs to // Actually add to new group - if( before >= 0 ) - { - if( visible_ >= before ) + if (before >= 0) { + if (visible_ >= before) visible_++; - clients_.insert( before, c ); - } - else - clients_.append( c ); - if( !becomeVisible ) // Hide before adding - c->setClientShown( false ); + clients_.insert(before, c); + } else + clients_.append(c); + if (!becomeVisible) // Hide before adding + c->setClientShown(false); updateItems(); updateMinMaxSize(); - updateStates( clients_[visible_], c ); + updateStates(clients_[visible_], c); - if( becomeVisible ) // Set visible after settings geometry - setVisible( c ); + if (becomeVisible) // Set visible after settings geometry + setVisible(c); // Activate the new visible window - clients_[visible_]->setActive( true ); + clients_[visible_]->setActive(true); //clients_[visible_]->takeFocus( Allowed ); //clients_[visible_]->workspace()->raiseClient( clients_[visible_] ); clients_[visible_]->triggerDecorationRepaint(); - } +} -void ClientGroup::remove( int index, const QRect& newGeom, bool toNullGroup ) - { - remove( clients_[index], newGeom, toNullGroup ); - } +void ClientGroup::remove(int index, const QRect& newGeom, bool toNullGroup) +{ + remove(clients_[index], newGeom, toNullGroup); +} -void ClientGroup::remove( Client* c, const QRect& newGeom, bool toNullGroup ) - { - if( !c ) +void ClientGroup::remove(Client* c, const QRect& newGeom, bool toNullGroup) +{ + if (!c) return; - if( clients_.count() < 2 ) - { - c->setClientGroup( NULL ); - Workspace::self()->removeClientGroup( this ); // Remove immediately + if (clients_.count() < 2) { + c->setClientGroup(NULL); + Workspace::self()->removeClientGroup(this); // Remove immediately delete this; return; - } + } ClientList::const_iterator i; Client* newVisible = clients_[visible_]; - if( newVisible == c ) - newVisible = ( visible_ != clients_.size() - 1 ) ? clients_[visible_ + 1] : clients_[visible_ - 1]; + if (newVisible == c) + newVisible = (visible_ != clients_.size() - 1) ? clients_[visible_ + 1] : clients_[visible_ - 1]; // Notify effects of removal - if( effects ) + if (effects) static_cast(effects)->clientGroupItemRemoved( - c->effectWindow(), newVisible->effectWindow() ); + c->effectWindow(), newVisible->effectWindow()); - setVisible( newVisible ); // Display new window before removing old one - clients_.removeAll( c ); - visible_ = indexOfClient( newVisible ); // Index may have changed + setVisible(newVisible); // Display new window before removing old one + clients_.removeAll(c); + visible_ = indexOfClient(newVisible); // Index may have changed updateItems(); updateMinMaxSize(); - c->setClientGroup( toNullGroup ? NULL : new ClientGroup( c )); - if( newGeom.isValid() ) - { + c->setClientGroup(toNullGroup ? NULL : new ClientGroup(c)); + if (newGeom.isValid()) { // HACK: if the group was maximized, one needs to make some checks on the future client maximize mode // because the transition from maximized to MaximizeRestore is not handled properly in setGeometry when // the new geometry size is unchanged. // since newGeom has the same size as the old client geometry, one just needs to check the topLeft position of newGeom // and compare that to the group maximize mode. // when the new mode is predicted to be MaximizeRestore, one must set it manually, in order to avoid decoration artifacts - Client::MaximizeMode groupMaxMode( newVisible->maximizeMode() ); - if( ( ( groupMaxMode & Client::MaximizeHorizontal ) && newGeom.left() != newVisible->geometry().left() ) || - ( ( groupMaxMode & Client::MaximizeVertical ) && newGeom.top() != newVisible->geometry().top() ) ) - c->maximize( Client::MaximizeRestore ); - c->setGeometry( newGeom ); - } - newVisible->triggerDecorationRepaint(); + Client::MaximizeMode groupMaxMode(newVisible->maximizeMode()); + if (((groupMaxMode & Client::MaximizeHorizontal) && newGeom.left() != newVisible->geometry().left()) || + ((groupMaxMode & Client::MaximizeVertical) && newGeom.top() != newVisible->geometry().top())) + c->maximize(Client::MaximizeRestore); + c->setGeometry(newGeom); } + newVisible->triggerDecorationRepaint(); +} void ClientGroup::removeAll() - { - while( clients_.count() > 1 ) - remove( clients_.at( 1 )); - } +{ + while (clients_.count() > 1) + remove(clients_.at(1)); +} void ClientGroup::closeAll() - { +{ Client* front; - ClientList list( clients_ ); - while( !list.isEmpty() ) - { + ClientList list(clients_); + while (!list.isEmpty()) { front = list.front(); list.pop_front(); - if( front != clients_[visible_] ) + if (front != clients_[visible_]) front->closeWindow(); - } + } clients_[visible_]->closeWindow(); - } +} -void ClientGroup::move( int index, int before ) - { - move( clients_[index], ( before >= 0 && before < clients_.size() ) ? clients_[before] : NULL ); - } +void ClientGroup::move(int index, int before) +{ + move(clients_[index], (before >= 0 && before < clients_.size()) ? clients_[before] : NULL); +} -void ClientGroup::move( Client* c, Client* before ) - { - if( c == before ) // Impossible to do +void ClientGroup::move(Client* c, Client* before) +{ + if (c == before) // Impossible to do return; Client* wasVisible = clients_[visible_]; - clients_.removeAll( c ); - clients_.insert( before ? indexOfClient( before ) : clients_.size(), c ); - visible_ = indexOfClient( wasVisible ); + clients_.removeAll(c); + clients_.insert(before ? indexOfClient(before) : clients_.size(), c); + visible_ = indexOfClient(wasVisible); updateItems(); clients_[visible_]->triggerDecorationRepaint(); - } +} -void ClientGroup::displayClientMenu( int index, const QPoint& pos ) - { - if( index == -1 ) +void ClientGroup::displayClientMenu(int index, const QPoint& pos) +{ + if (index == -1) index = visible_; - displayClientMenu( clients_[index], pos ); - } + displayClientMenu(clients_[index], pos); +} -void ClientGroup::displayClientMenu( Client* c, const QPoint& pos ) - { - c->workspace()->showWindowMenu( pos, c ); - } +void ClientGroup::displayClientMenu(Client* c, const QPoint& pos) +{ + c->workspace()->showWindowMenu(pos, c); +} bool ClientGroup::containsActiveClient() - { - return contains( Workspace::self()->activeClient() ); - } +{ + return contains(Workspace::self()->activeClient()); +} -void ClientGroup::setVisible( int index ) - { - setVisible( clients_[index] ); - } +void ClientGroup::setVisible(int index) +{ + setVisible(clients_[index]); +} -void ClientGroup::setVisible( Client* c ) - { - if( c == clients_[visible_] || !contains( c )) +void ClientGroup::setVisible(Client* c) +{ + if (c == clients_[visible_] || !contains(c)) return; // Notify effects of switch - if( effects != NULL ) + if (effects != NULL) static_cast(effects)->clientGroupItemSwitched( - clients_[visible_]->effectWindow(), c->effectWindow() ); + clients_[visible_]->effectWindow(), c->effectWindow()); - visible_ = indexOfClient( c ); - c->setClientShown( true ); - for( ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i ) - if( (*i) != c ) - (*i)->setClientShown( false ); - } + visible_ = indexOfClient(c); + c->setClientShown(true); + for (ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i) + if ((*i) != c) + (*i)->setClientShown(false); +} -void ClientGroup::updateStates( Client* main, Client* only ) - { - for( ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); i++ ) - if( (*i) != main && ( !only || (*i) == only )) - { - if( (*i)->isMinimized() != main->isMinimized() ) - { - if( main->isMinimized() ) - (*i)->minimize( true ); +void ClientGroup::updateStates(Client* main, Client* only) +{ + for (ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); i++) + if ((*i) != main && (!only || (*i) == only)) { + if ((*i)->isMinimized() != main->isMinimized()) { + if (main->isMinimized()) + (*i)->minimize(true); else - (*i)->unminimize( true ); - } - if( (*i)->isShade() != main->isShade() ) - (*i)->setShade( main->isShade() ? ShadeNormal : ShadeNone ); - if( (*i)->geometry() != main->geometry() ) - (*i)->setGeometry( main->geometry() ); - if( (*i)->desktop() != main->desktop() ) - (*i)->setDesktop( main->desktop() ); - if( (*i)->isOnAllDesktops() != main->isOnAllDesktops() ) - (*i)->setOnAllDesktops( main->isOnAllDesktops() ); - if( (*i)->activities() != main->activities() ) - (*i)->setOnActivities( main->activities() ); - if( (*i)->keepAbove() != main->keepAbove() ) - (*i)->setKeepAbove( main->keepAbove() ); - if( (*i)->keepBelow() != main->keepBelow() ) - (*i)->setKeepBelow( main->keepBelow() ); + (*i)->unminimize(true); + } + if ((*i)->isShade() != main->isShade()) + (*i)->setShade(main->isShade() ? ShadeNormal : ShadeNone); + if ((*i)->geometry() != main->geometry()) + (*i)->setGeometry(main->geometry()); + if ((*i)->desktop() != main->desktop()) + (*i)->setDesktop(main->desktop()); + if ((*i)->isOnAllDesktops() != main->isOnAllDesktops()) + (*i)->setOnAllDesktops(main->isOnAllDesktops()); + if ((*i)->activities() != main->activities()) + (*i)->setOnActivities(main->activities()); + if ((*i)->keepAbove() != main->keepAbove()) + (*i)->setKeepAbove(main->keepAbove()); + if ((*i)->keepBelow() != main->keepBelow()) + (*i)->setKeepBelow(main->keepBelow()); // If it's not possible to have the same states then ungroup them, TODO: Check all states - if( (*i)->geometry() != main->geometry() ) - remove( *i ); - if( (*i)->desktop() != main->desktop() ) - remove( *i ); - } - } + if ((*i)->geometry() != main->geometry()) + remove(*i); + if ((*i)->desktop() != main->desktop()) + remove(*i); + } +} void ClientGroup::updateItems() - { +{ items_.clear(); - for( ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i ) - { - QIcon icon( (*i)->icon() ); - icon.addPixmap( (*i)->miniIcon() ); - items_.append( ClientGroupItem( (*i)->caption(), icon )); - } + for (ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i) { + QIcon icon((*i)->icon()); + icon.addPixmap((*i)->miniIcon()); + items_.append(ClientGroupItem((*i)->caption(), icon)); } +} void ClientGroup::updateMinMaxSize() - { +{ // Determine entire group's minimum and maximum sizes - minSize_ = QSize( 0, 0 ); - maxSize_ = QSize( INT_MAX, INT_MAX ); - for( ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i ) - { - if( (*i)->minSize().width() > minSize_.width() ) - minSize_.setWidth( (*i)->minSize().width() ); - if( (*i)->minSize().height() > minSize_.height() ) - minSize_.setHeight( (*i)->minSize().height() ); - if( (*i)->maxSize().width() < maxSize_.width() ) - maxSize_.setWidth( (*i)->maxSize().width() ); - if( (*i)->maxSize().height() < maxSize_.height() ) - maxSize_.setHeight( (*i)->maxSize().height() ); - } - if( minSize_.width() > maxSize_.width() || - minSize_.height() > maxSize_.height() ) - { + minSize_ = QSize(0, 0); + maxSize_ = QSize(INT_MAX, INT_MAX); + for (ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i) { + if ((*i)->minSize().width() > minSize_.width()) + minSize_.setWidth((*i)->minSize().width()); + if ((*i)->minSize().height() > minSize_.height()) + minSize_.setHeight((*i)->minSize().height()); + if ((*i)->maxSize().width() < maxSize_.width()) + maxSize_.setWidth((*i)->maxSize().width()); + if ((*i)->maxSize().height() < maxSize_.height()) + maxSize_.setHeight((*i)->maxSize().height()); + } + if (minSize_.width() > maxSize_.width() || + minSize_.height() > maxSize_.height()) { //kWarning(1212) << "ClientGroup's min size is greater than its max size. Setting max to min."; maxSize_ = minSize_; - } + } // Ensure all windows are within these sizes const QSize size = clients_[visible_]->clientSize(); QSize newSize( - qBound( minSize_.width(), size.width(), maxSize_.width() ), - qBound( minSize_.height(), size.height(), maxSize_.height() )); - if( newSize != size ) - for( ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i ) + qBound(minSize_.width(), size.width(), maxSize_.width()), + qBound(minSize_.height(), size.height(), maxSize_.height())); + if (newSize != size) + for (ClientList::const_iterator i = clients_.constBegin(); i != clients_.constEnd(); ++i) // TODO: Doesn't affect shaded windows? // There seems to be a race condition when using plainResize() which causes the window // to sometimes be located at new window's location instead of the visible window's location // when a window with a large min size is added to a group with a small window size. - (*i)->setGeometry( QRect( clients_[visible_]->pos(), (*i)->sizeForClientSize( newSize ))); - } + (*i)->setGeometry(QRect(clients_[visible_]->pos(), (*i)->sizeForClientSize(newSize))); +} } diff --git a/clientgroup.h b/clientgroup.h index e0eafc3cb..49d346a07 100644 --- a/clientgroup.h +++ b/clientgroup.h @@ -43,184 +43,185 @@ class Client; * copies of the same client. A client MUST NOT be in two groups at the same * time. All decorated clients SHOULD be in a group, even if it's a group of * one client. - * + * * rohanp: Had to convert this object to a QObject to make it easier for adding * scripting interface to ClientGroup. * * If a group contains multiple clients then only one will ever be mapped at * any given time. */ -class ClientGroup : public QObject { +class ClientGroup : public QObject +{ Q_OBJECT - public: - /** - * Creates a new group containing \p c. - */ - ClientGroup( Client* c ); - ~ClientGroup(); +public: + /** + * Creates a new group containing \p c. + */ + ClientGroup(Client* c); + ~ClientGroup(); - /** - * Adds \p c to the group before \p before in the list. If \p becomeVisible is \i true then - * the added client will become also the visible client. - */ - void add( Client* c, int before = -1, bool becomeVisible = false ); - /** - * Remove the client at index \p index from the group. If \p newGeom is set then the client - * will move and resize to the specified geometry, otherwise it will stay where the group - * is located. If \p toNullGroup is not true then the client will be added to a new group - * of its own. - */ - void remove( int index, const QRect& newGeom = QRect(), bool toNullGroup = false ); - /** - * Remove \p c from the group. If \p newGeom is set then the client will move and resize to - * the specified geometry, otherwise it will stay where the group is located. If - * \p toNullGroup is not true then the client will be added to a new group of its own. - */ - void remove( Client* c, const QRect& newGeom = QRect(), bool toNullGroup = false ); - /** - * Remove all clients from this group. Results in all clients except the first being moved - to a group of their own. - */ - void removeAll(); - /** - * Close all clients in this group. - */ - void closeAll(); - /** - * Move the client at index \p index to the position before the client at index \p before - * in the list. - */ - void move( int index, int before ); - /** - * Move \p c to the position before \p before in the list. - */ - void move( Client* c, Client* before ); - /** - * Display the right-click client menu belonging to the client at index \p index at the - * global coordinates specified by \p pos. - */ - void displayClientMenu( int index, const QPoint& pos ); - /** - * Display the right-click client menu belonging to \p c at the global coordinates - * specified by \p pos. - */ - void displayClientMenu( Client* c, const QPoint& pos ); + /** + * Adds \p c to the group before \p before in the list. If \p becomeVisible is \i true then + * the added client will become also the visible client. + */ + void add(Client* c, int before = -1, bool becomeVisible = false); + /** + * Remove the client at index \p index from the group. If \p newGeom is set then the client + * will move and resize to the specified geometry, otherwise it will stay where the group + * is located. If \p toNullGroup is not true then the client will be added to a new group + * of its own. + */ + void remove(int index, const QRect& newGeom = QRect(), bool toNullGroup = false); + /** + * Remove \p c from the group. If \p newGeom is set then the client will move and resize to + * the specified geometry, otherwise it will stay where the group is located. If + * \p toNullGroup is not true then the client will be added to a new group of its own. + */ + void remove(Client* c, const QRect& newGeom = QRect(), bool toNullGroup = false); + /** + * Remove all clients from this group. Results in all clients except the first being moved + to a group of their own. + */ + void removeAll(); + /** + * Close all clients in this group. + */ + void closeAll(); + /** + * Move the client at index \p index to the position before the client at index \p before + * in the list. + */ + void move(int index, int before); + /** + * Move \p c to the position before \p before in the list. + */ + void move(Client* c, Client* before); + /** + * Display the right-click client menu belonging to the client at index \p index at the + * global coordinates specified by \p pos. + */ + void displayClientMenu(int index, const QPoint& pos); + /** + * Display the right-click client menu belonging to \p c at the global coordinates + * specified by \p pos. + */ + void displayClientMenu(Client* c, const QPoint& pos); - /** - * Returns the list index of \p c. - */ - int indexOfClient( Client* c ); - /** - * Returns the list index of the currently visible client in the group. - */ - int indexOfVisibleClient(); - /** - * Returns whether or not this group contains \p c. - */ - bool contains( Client* c ); - /** - * Returns whether or not this group contains the active client. - */ - bool containsActiveClient(); + /** + * Returns the list index of \p c. + */ + int indexOfClient(Client* c); + /** + * Returns the list index of the currently visible client in the group. + */ + int indexOfVisibleClient(); + /** + * Returns whether or not this group contains \p c. + */ + bool contains(Client* c); + /** + * Returns whether or not this group contains the active client. + */ + bool containsActiveClient(); - /** - * Returns the list of all the clients contained in this group in their current order. - */ - ClientList clients() const; - /** - * Returns a list of the captions and icons of all the clients contained in this group - * in their current order. - */ - QList< ClientGroupItem > items() const; + /** + * Returns the list of all the clients contained in this group in their current order. + */ + ClientList clients() const; + /** + * Returns a list of the captions and icons of all the clients contained in this group + * in their current order. + */ + QList< ClientGroupItem > items() const; - /** - * Returns the currently visible client. - */ - Client* visible(); - /** - * Makes the client at index \p index the visible one in the group. - */ - void setVisible( int index ); - /** - * Makes \p c the visible client in the group. - */ - void setVisible( Client* c ); + /** + * Returns the currently visible client. + */ + Client* visible(); + /** + * Makes the client at index \p index the visible one in the group. + */ + void setVisible(int index); + /** + * Makes \p c the visible client in the group. + */ + void setVisible(Client* c); - /** - * Returns combined minimum size of all clients in the group. - */ - QSize minSize() const; - /** - * Returns combined maximum size of all clients in the group. - */ - QSize maxSize() const; + /** + * Returns combined minimum size of all clients in the group. + */ + QSize minSize() const; + /** + * Returns combined maximum size of all clients in the group. + */ + QSize maxSize() const; - /** - * Ensures that all the clients in the group have identical geometries and states using - * \p main as the primary client to copy the settings off. If \p only is set then only - * that client is updated to match \p main. - */ - void updateStates( Client* main, Client* only = NULL ); + /** + * Ensures that all the clients in the group have identical geometries and states using + * \p main as the primary client to copy the settings off. If \p only is set then only + * that client is updated to match \p main. + */ + void updateStates(Client* main, Client* only = NULL); - private: - /** - * Regenerate the list of client captions and icons. - */ - void updateItems(); - /** - * Determine the combined minimum and maximum sizes of all clients in the group. - */ - void updateMinMaxSize(); +private: + /** + * Regenerate the list of client captions and icons. + */ + void updateItems(); + /** + * Determine the combined minimum and maximum sizes of all clients in the group. + */ + void updateMinMaxSize(); - ClientList clients_; - QList< ClientGroupItem > items_; - int visible_; + ClientList clients_; + QList< ClientGroupItem > items_; + int visible_; - QSize minSize_; - QSize maxSize_; + QSize minSize_; + QSize maxSize_; - friend class Client; - }; + friend class Client; +}; -inline int ClientGroup::indexOfClient( Client* c ) - { - return clients_.indexOf( c ); - } +inline int ClientGroup::indexOfClient(Client* c) +{ + return clients_.indexOf(c); +} inline int ClientGroup::indexOfVisibleClient() - { +{ return visible_; - } +} -inline bool ClientGroup::contains( Client* c ) - { - return clients_.contains( c ); - } +inline bool ClientGroup::contains(Client* c) +{ + return clients_.contains(c); +} inline ClientList ClientGroup::clients() const - { +{ return clients_; - } +} inline QList< ClientGroupItem > ClientGroup::items() const - { +{ return items_; - } +} inline Client* ClientGroup::visible() - { +{ return clients_[visible_]; - } +} inline QSize ClientGroup::minSize() const - { +{ return minSize_; - } +} inline QSize ClientGroup::maxSize() const - { +{ return maxSize_; - } +} } diff --git a/composite.cpp b/composite.cpp index 2758de95e..a3825b0e6 100644 --- a/composite.cpp +++ b/composite.cpp @@ -21,18 +21,18 @@ along with this program. If not, see . /* Code related to compositing (redirecting windows to pixmaps and tracking window damage). - + Docs: - + XComposite (the protocol, but the function calls map to it): http://gitweb.freedesktop.org/?p=xorg/proto/compositeproto.git;a=blob_plain;hb=HEAD;f=compositeproto.txt - + XDamage (again the protocol): http://gitweb.freedesktop.org/?p=xorg/proto/damageproto.git;a=blob_plain;hb=HEAD;f=damageproto.txt Paper including basics on compositing, XGL vs AIGLX, XRender vs OpenGL, etc.: http://www.vis.uni-stuttgart.de/~hopf/pub/LinuxTag2007_compiz_NextGenerationDesktop_Paper.pdf - + Composite HOWTO from Fredrik: http://ktown.kde.org/~fredrik/composite_howto.html @@ -85,177 +85,164 @@ extern int currentRefreshRate(); //**************************************** void Workspace::setupCompositing() - { +{ #ifdef KWIN_HAVE_COMPOSITING - if( scene != NULL ) + if (scene != NULL) return; - if( !options->useCompositing && getenv( "KWIN_COMPOSE") == NULL ) - { - kDebug( 1212 ) << "Compositing is turned off in options or disabled"; + if (!options->useCompositing && getenv("KWIN_COMPOSE") == NULL) { + kDebug(1212) << "Compositing is turned off in options or disabled"; return; - } - else if( compositingSuspended ) - { - kDebug( 1212 ) << "Compositing is suspended"; + } else if (compositingSuspended) { + kDebug(1212) << "Compositing is suspended"; return; - } - else if( !CompositingPrefs::compositingPossible() ) - { - kError( 1212 ) << "Compositing is not possible"; + } else if (!CompositingPrefs::compositingPossible()) { + kError(1212) << "Compositing is not possible"; return; - } + } CompositingType type = options->compositingMode; - if( getenv( "KWIN_COMPOSE" )) - { - char c = getenv( "KWIN_COMPOSE" )[ 0 ]; - switch( c ) - { - case 'O': - kDebug( 1212 ) << "Compositing forced to OpenGL mode by environment variable"; - type = OpenGLCompositing; - break; - case 'X': - kDebug( 1212 ) << "Compositing forced to XRender mode by environment variable"; - type = XRenderCompositing; - break; - case 'N': - if( getenv( "KDE_FAILSAFE" )) - kDebug( 1212 ) << "Compositing disabled forcefully by KDE failsafe mode"; - else - kDebug( 1212 ) << "Compositing disabled forcefully by environment variable"; - return; // Return not break - default: - kDebug( 1212 ) << "Unknown KWIN_COMPOSE mode set, ignoring"; - break; - } + if (getenv("KWIN_COMPOSE")) { + char c = getenv("KWIN_COMPOSE")[ 0 ]; + switch(c) { + case 'O': + kDebug(1212) << "Compositing forced to OpenGL mode by environment variable"; + type = OpenGLCompositing; + break; + case 'X': + kDebug(1212) << "Compositing forced to XRender mode by environment variable"; + type = XRenderCompositing; + break; + case 'N': + if (getenv("KDE_FAILSAFE")) + kDebug(1212) << "Compositing disabled forcefully by KDE failsafe mode"; + else + kDebug(1212) << "Compositing disabled forcefully by environment variable"; + return; // Return not break + default: + kDebug(1212) << "Unknown KWIN_COMPOSE mode set, ignoring"; + break; } + } char selection_name[ 100 ]; - sprintf( selection_name, "_NET_WM_CM_S%d", DefaultScreen( display())); - cm_selection = new KSelectionOwner( selection_name ); - connect( cm_selection, SIGNAL( lostOwnership()), SLOT( lostCMSelection())); - cm_selection->claim( true ); // force claiming + sprintf(selection_name, "_NET_WM_CM_S%d", DefaultScreen(display())); + cm_selection = new KSelectionOwner(selection_name); + connect(cm_selection, SIGNAL(lostOwnership()), SLOT(lostCMSelection())); + cm_selection->claim(true); // force claiming - switch( type ) - { + switch(type) { /*case 'B': kDebug( 1212 ) << "X compositing"; scene = new SceneBasic( this ); break; // don't fall through (this is a testing one) */ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - case OpenGLCompositing: - { - kDebug( 1212 ) << "Initializing OpenGL compositing"; + case OpenGLCompositing: { + kDebug(1212) << "Initializing OpenGL compositing"; - // Some broken drivers crash on glXQuery() so to prevent constant KWin crashes: - KSharedConfigPtr unsafeConfigPtr( KSharedConfig::openConfig( "kwinrc" )); - KConfigGroup unsafeConfig( unsafeConfigPtr, "Compositing" ); - if( unsafeConfig.readEntry( "OpenGLIsUnsafe", false )) - kWarning( 1212 ) << "KWin has detected that your OpenGL library is unsafe to use, " - "falling back to XRender."; - else - { - unsafeConfig.writeEntry( "OpenGLIsUnsafe", true ); - unsafeConfig.sync(); + // Some broken drivers crash on glXQuery() so to prevent constant KWin crashes: + KSharedConfigPtr unsafeConfigPtr(KSharedConfig::openConfig("kwinrc")); + KConfigGroup unsafeConfig(unsafeConfigPtr, "Compositing"); + if (unsafeConfig.readEntry("OpenGLIsUnsafe", false)) + kWarning(1212) << "KWin has detected that your OpenGL library is unsafe to use, " + "falling back to XRender."; + else { + unsafeConfig.writeEntry("OpenGLIsUnsafe", true); + unsafeConfig.sync(); - scene = new SceneOpenGL( this ); + scene = new SceneOpenGL(this); - // TODO: Add 30 second delay to protect against screen freezes as well - unsafeConfig.writeEntry( "OpenGLIsUnsafe", false ); - unsafeConfig.sync(); + // TODO: Add 30 second delay to protect against screen freezes as well + unsafeConfig.writeEntry("OpenGLIsUnsafe", false); + unsafeConfig.sync(); - if( !scene->initFailed()) - break; // --> - delete scene; - scene = NULL; - } + if (!scene->initFailed()) + break; // --> + delete scene; + scene = NULL; + } - // Do not Fall back to XRender - it causes problems when selfcheck fails during startup, but works later on - break; - } + // Do not Fall back to XRender - it causes problems when selfcheck fails during startup, but works later on + break; + } #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - case XRenderCompositing: - kDebug( 1212 ) << "Initializing XRender compositing"; - scene = new SceneXrender( this ); - break; + case XRenderCompositing: + kDebug(1212) << "Initializing XRender compositing"; + scene = new SceneXrender(this); + break; #endif - default: + default: #ifndef KWIN_HAVE_COMPOSITING - kDebug( 1212 ) << "Compositing was not available at compile time"; + kDebug(1212) << "Compositing was not available at compile time"; #else - kDebug( 1212 ) << "No compositing enabled"; + kDebug(1212) << "No compositing enabled"; #endif - delete cm_selection; - return; - } - if( scene == NULL || scene->initFailed()) - { - kError( 1212 ) << "Failed to initialize compositing, compositing disabled"; - kError( 1212 ) << "Consult http://techbase.kde.org/Projects/KWin/4.0-release-notes#Setting_up"; + delete cm_selection; + return; + } + if (scene == NULL || scene->initFailed()) { + kError(1212) << "Failed to initialize compositing, compositing disabled"; + kError(1212) << "Consult http://techbase.kde.org/Projects/KWin/4.0-release-notes#Setting_up"; delete scene; scene = NULL; delete cm_selection; return; - } + } xrrRefreshRate = KWin::currentRefreshRate(); - fpsInterval = (options->maxFpsInterval<<10); - if ( scene->waitSyncAvailable() ) // if we do vsync, set the fps to the next multiple of the vblank rate - { - vBlankInterval = (1000<<10)/xrrRefreshRate; + fpsInterval = (options->maxFpsInterval << 10); + if (scene->waitSyncAvailable()) { // if we do vsync, set the fps to the next multiple of the vblank rate + vBlankInterval = (1000 << 10) / xrrRefreshRate; fpsInterval -= (fpsInterval % vBlankInterval); fpsInterval = qMax(fpsInterval, vBlankInterval); - } - else - vBlankInterval = 1<<10; // no sync - DO NOT set "0", would cause div-by-zero segfaults. + } else + vBlankInterval = 1 << 10; // no sync - DO NOT set "0", would cause div-by-zero segfaults. vBlankPadding = 3; // vblank rounding errors... :-( nextPaintReference = QTime::currentTime(); checkCompositeTimer(); composite_paint_times.clear(); - XCompositeRedirectSubwindows( display(), rootWindow(), CompositeRedirectManual ); - new EffectsHandlerImpl( scene->compositingType() ); // sets also the 'effects' pointer + XCompositeRedirectSubwindows(display(), rootWindow(), CompositeRedirectManual); + new EffectsHandlerImpl(scene->compositingType()); // sets also the 'effects' pointer addRepaintFull(); - foreach( Client* c, clients ) - c->setupCompositing(); - foreach( Client* c, desktops ) - c->setupCompositing(); - foreach( Unmanaged* c, unmanaged ) - c->setupCompositing(); - foreach( Client* c, clients ) - scene->windowAdded( c ); - foreach( Client* c, desktops ) - scene->windowAdded( c ); - foreach( Unmanaged* c, unmanaged ) - scene->windowAdded( c ); + foreach (Client * c, clients) + c->setupCompositing(); + foreach (Client * c, desktops) + c->setupCompositing(); + foreach (Unmanaged * c, unmanaged) + c->setupCompositing(); + foreach (Client * c, clients) + scene->windowAdded(c); + foreach (Client * c, desktops) + scene->windowAdded(c); + foreach (Unmanaged * c, unmanaged) + scene->windowAdded(c); discardPopup(); // force re-creation of the Alt+F3 popup (opacity option) #else - kDebug( 1212 ) << "Compositing was not available at compile time"; + kDebug(1212) << "Compositing was not available at compile time"; #endif - } +} void Workspace::finishCompositing() - { +{ #ifdef KWIN_HAVE_COMPOSITING - if( scene == NULL ) + if (scene == NULL) return; delete cm_selection; - foreach( Client* c, clients ) - scene->windowClosed( c, NULL ); - foreach( Client* c, desktops ) - scene->windowClosed( c, NULL ); - foreach( Unmanaged* c, unmanaged ) - scene->windowClosed( c, NULL ); - foreach( Deleted* c, deleted ) - scene->windowDeleted( c ); - foreach( Client* c, clients ) - c->finishCompositing(); - foreach( Client* c, desktops ) - c->finishCompositing(); - foreach( Unmanaged* c, unmanaged ) - c->finishCompositing(); - foreach( Deleted* c, deleted ) - c->finishCompositing(); - XCompositeUnredirectSubwindows( display(), rootWindow(), CompositeRedirectManual ); + foreach (Client * c, clients) + scene->windowClosed(c, NULL); + foreach (Client * c, desktops) + scene->windowClosed(c, NULL); + foreach (Unmanaged * c, unmanaged) + scene->windowClosed(c, NULL); + foreach (Deleted * c, deleted) + scene->windowDeleted(c); + foreach (Client * c, clients) + c->finishCompositing(); + foreach (Client * c, desktops) + c->finishCompositing(); + foreach (Unmanaged * c, unmanaged) + c->finishCompositing(); + foreach (Deleted * c, deleted) + c->finishCompositing(); + XCompositeUnredirectSubwindows(display(), rootWindow(), CompositeRedirectManual); delete effects; effects = NULL; delete scene; @@ -265,138 +252,131 @@ void Workspace::finishCompositing() compositeTimer = 0; mousePollingTimer.stop(); repaints_region = QRegion(); - for( ClientList::ConstIterator it = clients.constBegin(); - it != clients.constEnd(); - ++it ) - { // forward all opacity values to the frame in case there'll be other CM running - if( (*it)->opacity() != 1.0 ) - { - NETWinInfo2 i( display(), (*it)->frameId(), rootWindow(), 0 ); - i.setOpacity( static_cast< unsigned long >((*it)->opacity() * 0xffffffff )); - } + for (ClientList::ConstIterator it = clients.constBegin(); + it != clients.constEnd(); + ++it) { + // forward all opacity values to the frame in case there'll be other CM running + if ((*it)->opacity() != 1.0) { + NETWinInfo2 i(display(), (*it)->frameId(), rootWindow(), 0); + i.setOpacity(static_cast< unsigned long >((*it)->opacity() * 0xffffffff)); } + } discardPopup(); // force re-creation of the Alt+F3 popup (opacity option) // discard all Deleted windows (#152914) - while( !deleted.isEmpty()) - deleted.first()->discard( Allowed ); + while (!deleted.isEmpty()) + deleted.first()->discard(Allowed); #endif - } +} // OpenGL self-check failed, fallback to XRender void Workspace::fallbackToXRenderCompositing() - { +{ finishCompositing(); options->compositingMode = XRenderCompositing; setupCompositing(); - } +} void Workspace::lostCMSelection() - { - kDebug( 1212 ) << "Lost compositing manager selection"; +{ + kDebug(1212) << "Lost compositing manager selection"; finishCompositing(); - } +} // for the shortcut void Workspace::slotToggleCompositing() - { - suspendCompositing( !compositingSuspended ); - } +{ + suspendCompositing(!compositingSuspended); +} // for the dbus call void Workspace::toggleCompositing() - { +{ slotToggleCompositing(); - if( compositingSuspended ) - { + if (compositingSuspended) { // when disabled show a shortcut how the user can get back compositing QString shortcut, message; - if( KAction* action = qobject_cast( keys->action("Suspend Compositing"))) + if (KAction* action = qobject_cast(keys->action("Suspend Compositing"))) shortcut = action->globalShortcut().primary().toString(QKeySequence::NativeText); - if( !shortcut.isEmpty() && options->useCompositing ) - { + if (!shortcut.isEmpty() && options->useCompositing) { // display notification only if there is the shortcut - message = i18n( "Desktop effects have been suspended by another application.
" - "You can resume using the '%1' shortcut.", shortcut ); - Notify::raise( Notify::CompositingSuspendedDbus, message ); - } + message = i18n("Desktop effects have been suspended by another application.
" + "You can resume using the '%1' shortcut.", shortcut); + Notify::raise(Notify::CompositingSuspendedDbus, message); } } +} void Workspace::suspendCompositing() - { - suspendCompositing( true ); - } +{ + suspendCompositing(true); +} -void Workspace::suspendCompositing( bool suspend ) - { +void Workspace::suspendCompositing(bool suspend) +{ compositingSuspended = suspend; finishCompositing(); setupCompositing(); // will do nothing if suspended // notify decorations that composition state has changed KDecorationFactory* factory = mgr->factory(); factory->reset(SettingCompositing); - emit compositingToggled( !compositingSuspended ); - } + emit compositingToggled(!compositingSuspended); +} void Workspace::resetCompositing() - { - if( compositing()) - { - finishCompositing(); - QTimer::singleShot( 0, this, SLOT( setupCompositing())); - } - } - -void Workspace::addRepaint( int x, int y, int w, int h ) - { - if( !compositing()) - return; - repaints_region += QRegion( x, y, w, h ); - checkCompositeTimer(); - } - -void Workspace::addRepaint( const QRect& r ) - { - if( !compositing()) - return; - repaints_region += r; - checkCompositeTimer(); - } - -void Workspace::addRepaint( const QRegion& r ) - { - if( !compositing()) - return; - repaints_region += r; - checkCompositeTimer(); - } - -void Workspace::addRepaintFull() - { - if( !compositing()) - return; - repaints_region = QRegion( 0, 0, displayWidth(), displayHeight()); - checkCompositeTimer(); - } - -void Workspace::timerEvent( QTimerEvent *te ) { - if ( te->timerId() == compositeTimer ) - { - killTimer( compositeTimer ); + if (compositing()) { + finishCompositing(); + QTimer::singleShot(0, this, SLOT(setupCompositing())); + } +} + +void Workspace::addRepaint(int x, int y, int w, int h) +{ + if (!compositing()) + return; + repaints_region += QRegion(x, y, w, h); + checkCompositeTimer(); +} + +void Workspace::addRepaint(const QRect& r) +{ + if (!compositing()) + return; + repaints_region += r; + checkCompositeTimer(); +} + +void Workspace::addRepaint(const QRegion& r) +{ + if (!compositing()) + return; + repaints_region += r; + checkCompositeTimer(); +} + +void Workspace::addRepaintFull() +{ + if (!compositing()) + return; + repaints_region = QRegion(0, 0, displayWidth(), displayHeight()); + checkCompositeTimer(); +} + +void Workspace::timerEvent(QTimerEvent *te) +{ + if (te->timerId() == compositeTimer) { + killTimer(compositeTimer); compositeTimer = 0; performCompositing(); - } - else - QObject::timerEvent( te ); + } else + QObject::timerEvent(te); } void Workspace::performCompositing() - { +{ #ifdef KWIN_HAVE_COMPOSITING - if((( repaints_region.isEmpty() && !windowRepaintsPending()) // no damage - || !overlay_visible )) // nothing is visible anyway - { + if (((repaints_region.isEmpty() && !windowRepaintsPending()) // no damage + || !overlay_visible)) { // nothing is visible anyway vBlankPadding += 3; scene->idle(); // Note: It would seem here we should undo suspended unredirect, but when scenes need @@ -404,15 +384,14 @@ void Workspace::performCompositing() // need this anymore and paints normally will also reset the suspended unredirect. // Otherwise the window would not be painted normally anyway. return; - } + } // create a list of all windows in the stacking order ToplevelList windows = xStackingOrder(); - foreach( EffectWindow* c, static_cast< EffectsHandlerImpl* >( effects )->elevatedWindows()) - { - Toplevel* t = static_cast< EffectWindowImpl* >( c )->window(); - windows.removeAll( t ); - windows.append( t ); - } + foreach (EffectWindow * c, static_cast< EffectsHandlerImpl* >(effects)->elevatedWindows()) { + Toplevel* t = static_cast< EffectWindowImpl* >(c)->window(); + windows.removeAll(t); + windows.append(t); + } #if 0 // skip windows that are not yet ready for being painted ToplevelList tmp = windows; @@ -420,32 +399,31 @@ void Workspace::performCompositing() // There is a bug somewhere that prevents this from working properly (#160393), but additionally // this cannot be used so carelessly - needs protections against broken clients, the window // should not get focus before it's displayed, handle unredirected windows properly and so on. - foreach( Toplevel* c, tmp ) - if( c->readyForPainting()) - windows.append( c ); + foreach (Toplevel * c, tmp) + if (c->readyForPainting()) + windows.append(c); #endif - foreach( Toplevel* c, windows ) - { // This could be possibly optimized WRT obscuring, but that'd need being already - // past prePaint() phase - probably not worth it. - // TODO I think effects->transformWindowDamage() doesn't need to be called here, - // pre-paint will extend painted window areas as necessary. - repaints_region |= c->repaints().translated( c->pos()); + foreach (Toplevel * c, windows) { + // This could be possibly optimized WRT obscuring, but that'd need being already + // past prePaint() phase - probably not worth it. + // TODO I think effects->transformWindowDamage() doesn't need to be called here, + // pre-paint will extend painted window areas as necessary. + repaints_region |= c->repaints().translated(c->pos()); repaints_region |= c->decorationPendingRegion(); - c->resetRepaints( c->decorationRect()); - } + c->resetRepaints(c->decorationRect()); + } QRegion repaints = repaints_region; // clear all repaints, so that post-pass can add repaints for the next repaint repaints_region = QRegion(); QTime t = QTime::currentTime(); - if ( scene->waitSyncAvailable() ) - { // vsync: paint the scene, than rebase the timer and use the duration for next timeout estimation - scene->paint( repaints, windows ); + if (scene->waitSyncAvailable()) { + // vsync: paint the scene, than rebase the timer and use the duration for next timeout estimation + scene->paint(repaints, windows); nextPaintReference = QTime::currentTime(); - } - else - { // no vsyc -> inversion: reset the timer, then paint the scene, this way we can provide a constant framerate + } else { + // no vsyc -> inversion: reset the timer, then paint the scene, this way we can provide a constant framerate nextPaintReference = QTime::currentTime(); - scene->paint( repaints, windows ); + scene->paint(repaints, windows); } // reset the roundin error corrective... :-( vBlankPadding = 3; @@ -454,624 +432,599 @@ void Workspace::performCompositing() // checkCompositeTime() would restart it again somewhen later, called from functions that // would again add something pending. checkCompositeTimer(); - checkCompositePaintTime( t.elapsed()); + checkCompositePaintTime(t.elapsed()); #endif - } +} void Workspace::performMousePoll() - { +{ checkCursorPos(); - } +} bool Workspace::windowRepaintsPending() const - { - foreach( Toplevel* c, clients ) - if( !c->repaints().isEmpty()) - return true; - foreach( Toplevel* c, desktops ) - if( !c->repaints().isEmpty()) - return true; - foreach( Toplevel* c, unmanaged ) - if( !c->repaints().isEmpty()) - return true; - foreach( Toplevel* c, deleted ) - if( !c->repaints().isEmpty()) - return true; +{ + foreach (Toplevel * c, clients) + if (!c->repaints().isEmpty()) + return true; + foreach (Toplevel * c, desktops) + if (!c->repaints().isEmpty()) + return true; + foreach (Toplevel * c, unmanaged) + if (!c->repaints().isEmpty()) + return true; + foreach (Toplevel * c, deleted) + if (!c->repaints().isEmpty()) + return true; return false; - } +} void Workspace::setCompositeTimer() - { - if( !compositing()) // should not really happen, but there may be e.g. some damage events still pending +{ + if (!compositing()) // should not really happen, but there may be e.g. some damage events still pending return; - - if ( compositeTimer ) - killTimer( compositeTimer ); + + if (compositeTimer) + killTimer(compositeTimer); // interval - "time since last paint completion" - "time we need to paint" - uint passed = nextPaintReference.msecsTo( QTime::currentTime() ) << 10; + uint passed = nextPaintReference.msecsTo(QTime::currentTime()) << 10; uint delay = fpsInterval; - if ( scene->waitSyncAvailable() ) - { - if ( passed > fpsInterval ) - { + if (scene->waitSyncAvailable()) { + if (passed > fpsInterval) { delay = vBlankInterval; passed %= vBlankInterval; - } - delay -= ( (passed + ((scene->estimatedRenderTime() + vBlankPadding)<<10) ) % vBlankInterval ); } - else - delay = qBound( 0, int(delay - passed), 250<<10 ); - compositeTimer = startTimer( delay>>10 ); - } + delay -= ((passed + ((scene->estimatedRenderTime() + vBlankPadding) << 10)) % vBlankInterval); + } else + delay = qBound(0, int(delay - passed), 250 << 10); + compositeTimer = startTimer(delay >> 10); +} void Workspace::startMousePolling() - { - mousePollingTimer.start( 20 ); // 50Hz. TODO: How often do we really need to poll? - } +{ + mousePollingTimer.start(20); // 50Hz. TODO: How often do we really need to poll? +} void Workspace::stopMousePolling() - { +{ mousePollingTimer.stop(); - } +} bool Workspace::createOverlay() - { - assert( overlay == None ); - if( !Extensions::compositeOverlayAvailable()) +{ + assert(overlay == None); + if (!Extensions::compositeOverlayAvailable()) return false; - if( !Extensions::shapeInputAvailable()) // needed in setupOverlay() + if (!Extensions::shapeInputAvailable()) // needed in setupOverlay() return false; #ifdef HAVE_XCOMPOSITE_OVERLAY - overlay = XCompositeGetOverlayWindow( display(), rootWindow()); - if( overlay == None ) + overlay = XCompositeGetOverlayWindow(display(), rootWindow()); + if (overlay == None) return false; XResizeWindow(display(), overlay, displayWidth(), displayHeight()); return true; #else return false; #endif - } +} -void Workspace::checkCompositePaintTime( int msec ) - { - if( options->disableCompositingChecks ) +void Workspace::checkCompositePaintTime(int msec) +{ + if (options->disableCompositingChecks) return; // Sanity check. QTime uses the system clock so if the user changes the time or // timezone our timer will return undefined results. Ideally we would use a system // clock independent timer but I am uncertain if Qt provides a nice wrapper for // one or not. As it's unlikely for a single paint to take 15 seconds it seems // like a good upper bound. - if( msec < 0 || msec > 15000 ) + if (msec < 0 || msec > 15000) return; - composite_paint_times.prepend( msec ); + composite_paint_times.prepend(msec); bool tooslow = false; // If last 3 paints were way too slow, disable and warn. // 1 second seems reasonable, it's not that difficult to get relatively high times // with high system load. const int MAX_LONG_PAINT = 1000; - if( composite_paint_times.count() >= 3 && composite_paint_times[ 0 ] > MAX_LONG_PAINT - && composite_paint_times[ 1 ] > MAX_LONG_PAINT && composite_paint_times[ 2 ] > MAX_LONG_PAINT ) - { - kDebug( 1212 ) << "Too long paint times, suspending"; + if (composite_paint_times.count() >= 3 && composite_paint_times[ 0 ] > MAX_LONG_PAINT + && composite_paint_times[ 1 ] > MAX_LONG_PAINT && composite_paint_times[ 2 ] > MAX_LONG_PAINT) { + kDebug(1212) << "Too long paint times, suspending"; tooslow = true; - } + } // If last 15 seconds all paints (all of them) were quite slow, disable and warn too. Quite slow being 0,1s // should be reasonable, that's 10fps and having constant 10fps is bad. // This may possibly trigger also when activating an expensive effect, so this may need tweaking. const int MAX_SHORT_PAINT = 100; const int SHORT_TIME = 15000; // 15 sec int time = 0; - foreach( int t, composite_paint_times ) - { - if( t < MAX_SHORT_PAINT ) + foreach (int t, composite_paint_times) { + if (t < MAX_SHORT_PAINT) break; time += t; - if( time > SHORT_TIME ) // all paints in the given time were long - { - kDebug( 1212 ) << "Long paint times for long time, suspending"; + if (time > SHORT_TIME) { // all paints in the given time were long + kDebug(1212) << "Long paint times for long time, suspending"; tooslow = true; break; - } } - if( composite_paint_times.count() > 1000 ) + } + if (composite_paint_times.count() > 1000) composite_paint_times.removeLast(); - if( tooslow ) - { - QTimer::singleShot( 0, this, SLOT( suspendCompositing())); + if (tooslow) { + QTimer::singleShot(0, this, SLOT(suspendCompositing())); QString shortcut, message; - if( KAction* action = qobject_cast( keys->action("Suspend Compositing"))) + if (KAction* action = qobject_cast(keys->action("Suspend Compositing"))) shortcut = action->globalShortcut().primary().toString(QKeySequence::NativeText); if (shortcut.isEmpty()) - message = i18n( "Desktop effects were too slow and have been suspended.\n" - "You can disable functionality checks in System Settings (on the Advanced tab in Desktop Effects)." ); + message = i18n("Desktop effects were too slow and have been suspended.\n" + "You can disable functionality checks in System Settings (on the Advanced tab in Desktop Effects)."); else - message = i18n( "Desktop effects were too slow and have been suspended.\n" - "If this was only a temporary problem, you can resume using the '%1' shortcut.\n" - "You can disable functionality checks in System Settings (on the Advanced tab in Desktop Effects).", shortcut ); - Notify::raise( Notify::CompositingSlow, message ); - if ( compositeTimer ) - killTimer( compositeTimer ); - compositeTimer = startTimer( 1000 ); // so that it doesn't trigger sooner than suspendCompositing() - } + message = i18n("Desktop effects were too slow and have been suspended.\n" + "If this was only a temporary problem, you can resume using the '%1' shortcut.\n" + "You can disable functionality checks in System Settings (on the Advanced tab in Desktop Effects).", shortcut); + Notify::raise(Notify::CompositingSlow, message); + if (compositeTimer) + killTimer(compositeTimer); + compositeTimer = startTimer(1000); // so that it doesn't trigger sooner than suspendCompositing() } +} -void Workspace::setupOverlay( Window w ) - { - assert( overlay != None ); - assert( Extensions::shapeInputAvailable()); - XSetWindowBackgroundPixmap( display(), overlay, None ); +void Workspace::setupOverlay(Window w) +{ + assert(overlay != None); + assert(Extensions::shapeInputAvailable()); + XSetWindowBackgroundPixmap(display(), overlay, None); overlay_shape = QRegion(); - setOverlayShape( QRect( 0, 0, displayWidth(), displayHeight())); - if( w != None ) - { - XSetWindowBackgroundPixmap( display(), w, None ); - XShapeCombineRectangles( display(), w, ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted ); - } - XSelectInput( display(), overlay, VisibilityChangeMask ); + setOverlayShape(QRect(0, 0, displayWidth(), displayHeight())); + if (w != None) { + XSetWindowBackgroundPixmap(display(), w, None); + XShapeCombineRectangles(display(), w, ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted); } + XSelectInput(display(), overlay, VisibilityChangeMask); +} void Workspace::showOverlay() - { - assert( overlay != None ); - if( overlay_shown ) +{ + assert(overlay != None); + if (overlay_shown) return; - XMapSubwindows( display(), overlay ); - XMapWindow( display(), overlay ); + XMapSubwindows(display(), overlay); + XMapWindow(display(), overlay); overlay_shown = true; - } +} void Workspace::hideOverlay() - { - assert( overlay != None ); - XUnmapWindow( display(), overlay ); +{ + assert(overlay != None); + XUnmapWindow(display(), overlay); overlay_shown = false; - setOverlayShape( QRect( 0, 0, displayWidth(), displayHeight())); - } + setOverlayShape(QRect(0, 0, displayWidth(), displayHeight())); +} -void Workspace::setOverlayShape( const QRegion& reg ) - { +void Workspace::setOverlayShape(const QRegion& reg) +{ // Avoid setting the same shape again, it causes flicker (apparently it is not a no-op // and triggers something). - if( reg == overlay_shape ) + if (reg == overlay_shape) return; QVector< QRect > rects = reg.rects(); - XRectangle* xrects = new XRectangle[ rects.count() ]; - for( int i = 0; - i < rects.count(); - ++i ) - { + XRectangle* xrects = new XRectangle[ rects.count()]; + for (int i = 0; + i < rects.count(); + ++i) { xrects[ i ].x = rects[ i ].x(); xrects[ i ].y = rects[ i ].y(); xrects[ i ].width = rects[ i ].width(); xrects[ i ].height = rects[ i ].height(); - } - XShapeCombineRectangles( display(), overlay, ShapeBounding, 0, 0, - xrects, rects.count(), ShapeSet, Unsorted ); - delete[] xrects; - XShapeCombineRectangles( display(), overlay, ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted ); - overlay_shape = reg; } + XShapeCombineRectangles(display(), overlay, ShapeBounding, 0, 0, + xrects, rects.count(), ShapeSet, Unsorted); + delete[] xrects; + XShapeCombineRectangles(display(), overlay, ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted); + overlay_shape = reg; +} void Workspace::destroyOverlay() - { - if( overlay == None ) +{ + if (overlay == None) return; // reset the overlay shape XRectangle rec = { 0, 0, displayWidth(), displayHeight() }; - XShapeCombineRectangles( display(), overlay, ShapeBounding, 0, 0, &rec, 1, ShapeSet, Unsorted ); - XShapeCombineRectangles( display(), overlay, ShapeInput, 0, 0, &rec, 1, ShapeSet, Unsorted ); + XShapeCombineRectangles(display(), overlay, ShapeBounding, 0, 0, &rec, 1, ShapeSet, Unsorted); + XShapeCombineRectangles(display(), overlay, ShapeInput, 0, 0, &rec, 1, ShapeSet, Unsorted); #ifdef HAVE_XCOMPOSITE_OVERLAY - XCompositeReleaseOverlayWindow( display(), overlay ); + XCompositeReleaseOverlayWindow(display(), overlay); #endif overlay = None; overlay_shown = false; - } +} bool Workspace::compositingActive() - { +{ return compositing(); - } +} // force is needed when the list of windows changes (e.g. a window goes away) -void Workspace::checkUnredirect( bool force ) - { - if( !compositing() || overlay == None || !options->unredirectFullscreen ) +void Workspace::checkUnredirect(bool force) +{ + if (!compositing() || overlay == None || !options->unredirectFullscreen) return; - if( force ) + if (force) forceUnredirectCheck = true; - if( !unredirectTimer.isActive()) - unredirectTimer.start( 0 ); - } + if (!unredirectTimer.isActive()) + unredirectTimer.start(0); +} void Workspace::delayedCheckUnredirect() - { - if( !compositing() || overlay == None || !options->unredirectFullscreen ) +{ + if (!compositing() || overlay == None || !options->unredirectFullscreen) return; ToplevelList list; bool changed = forceUnredirectCheck; - foreach( Client* c, clients ) - list.append( c ); - foreach( Unmanaged* c, unmanaged ) - list.append( c ); - foreach( Toplevel* c, list ) - { - if( c->updateUnredirectedState()) + foreach (Client * c, clients) + list.append(c); + foreach (Unmanaged * c, unmanaged) + list.append(c); + foreach (Toplevel * c, list) { + if (c->updateUnredirectedState()) changed = true; - } + } // no desktops, no Deleted ones - if( !changed ) + if (!changed) return; forceUnredirectCheck = false; // Cut out parts from the overlay window where unredirected windows are, // so that they are actually visible. - QRegion reg( 0, 0, displayWidth(), displayHeight()); - foreach( Toplevel* c, list ) - { - if( c->unredirected()) + QRegion reg(0, 0, displayWidth(), displayHeight()); + foreach (Toplevel * c, list) { + if (c->unredirected()) reg -= c->geometry(); - } - setOverlayShape( reg ); } + setOverlayShape(reg); +} //**************************************** // Toplevel //**************************************** void Toplevel::setupCompositing() - { +{ #ifdef KWIN_HAVE_COMPOSITING - if( !compositing()) + if (!compositing()) return; - if( damage_handle != None ) + if (damage_handle != None) return; - damage_handle = XDamageCreate( display(), frameId(), XDamageReportRawRectangles ); - damage_region = QRegion( 0, 0, width(), height()); + damage_handle = XDamageCreate(display(), frameId(), XDamageReportRawRectangles); + damage_region = QRegion(0, 0, width(), height()); effect_window = new EffectWindowImpl(); - effect_window->setWindow( this ); + effect_window->setWindow(this); unredirect = false; - workspace()->checkUnredirect( true ); + workspace()->checkUnredirect(true); #endif - } +} void Toplevel::finishCompositing() - { +{ #ifdef KWIN_HAVE_COMPOSITING - if( damage_handle == None ) + if (damage_handle == None) return; - workspace()->checkUnredirect( true ); - if( effect_window->window() == this ) // otherwise it's already passed to Deleted, don't free data - { + workspace()->checkUnredirect(true); + if (effect_window->window() == this) { // otherwise it's already passed to Deleted, don't free data discardWindowPixmap(); delete effect_window; - } - XDamageDestroy( display(), damage_handle ); + } + XDamageDestroy(display(), damage_handle); damage_handle = None; damage_region = QRegion(); repaints_region = QRegion(); effect_window = NULL; #endif - } +} void Toplevel::discardWindowPixmap() - { +{ addDamageFull(); - if( window_pix == None ) + if (window_pix == None) return; - XFreePixmap( display(), window_pix ); + XFreePixmap(display(), window_pix); window_pix = None; - if( effectWindow() != NULL && effectWindow()->sceneWindow() != NULL ) + if (effectWindow() != NULL && effectWindow()->sceneWindow() != NULL) effectWindow()->sceneWindow()->pixmapDiscarded(); - } +} Pixmap Toplevel::createWindowPixmap() - { +{ #ifdef KWIN_HAVE_COMPOSITING - assert( compositing()); - if( unredirected()) + assert(compositing()); + if (unredirected()) return None; grabXServer(); KXErrorHandler err; - Pixmap pix = XCompositeNameWindowPixmap( display(), frameId()); + Pixmap pix = XCompositeNameWindowPixmap(display(), frameId()); // check that the received pixmap is valid and actually matches what we // know about the window (i.e. size) XWindowAttributes attrs; - if( !XGetWindowAttributes( display(), frameId(), &attrs ) - || err.error( false ) - || attrs.width != width() || attrs.height != height() || attrs.map_state != IsViewable ) - { - kDebug( 1212 ) << "Creating window pixmap failed: " << this; - XFreePixmap( display(), pix ); + if (!XGetWindowAttributes(display(), frameId(), &attrs) + || err.error(false) + || attrs.width != width() || attrs.height != height() || attrs.map_state != IsViewable) { + kDebug(1212) << "Creating window pixmap failed: " << this; + XFreePixmap(display(), pix); pix = None; - } + } ungrabXServer(); return pix; #else return None; #endif - } +} #ifdef HAVE_XDAMAGE // We must specify that the two events are a union so the compiler doesn't // complain about strict aliasing rules. -typedef union { XEvent e; XDamageNotifyEvent de; } EventUnion; +typedef union { + XEvent e; + XDamageNotifyEvent de; +} EventUnion; -void Toplevel::damageNotifyEvent( XDamageNotifyEvent* e ) - { - QRegion damage( e->area.x, e->area.y, e->area.width, e->area.height ); +void Toplevel::damageNotifyEvent(XDamageNotifyEvent* e) +{ + QRegion damage(e->area.x, e->area.y, e->area.width, e->area.height); // compress int cnt = 1; - while( XPending( display())) - { + while (XPending(display())) { EventUnion e2; - if( XPeekEvent( display(), &e2.e ) && e2.e.type == Extensions::damageNotifyEvent() - && e2.e.xany.window == frameId()) - { - XNextEvent( display(), &e2.e ); - if( cnt > 200 ) - { + if (XPeekEvent(display(), &e2.e) && e2.e.type == Extensions::damageNotifyEvent() + && e2.e.xany.window == frameId()) { + XNextEvent(display(), &e2.e); + if (cnt > 200) { // If there are way too many damage events in the queue, just discard them // and damage the whole window. Otherwise the X server can just overload // us with a flood of damage events. Should be probably optimized // in the X server, as this is rather lame. damage = rect(); continue; - } - QRect r( e2.de.area.x, e2.de.area.y, e2.de.area.width, e2.de.area.height ); + } + QRect r(e2.de.area.x, e2.de.area.y, e2.de.area.width, e2.de.area.height); ++cnt; // If there are too many damaged rectangles, increase them // to be multiples of 100x100 px grid, since QRegion get quite // slow with many rectangles, and there is little to gain by using // many small rectangles (rather the opposite, several large should // be often faster). - if( cnt > 50 ) - { - r.setLeft( r.left() / 100 * 100 ); - r.setRight(( r.right() + 99 ) / 100 * 100 ); - r.setTop( r.top() / 100 * 100 ); - r.setBottom(( r.bottom() + 99 ) / 100 * 100 ); - } + if (cnt > 50) { + r.setLeft(r.left() / 100 * 100); + r.setRight((r.right() + 99) / 100 * 100); + r.setTop(r.top() / 100 * 100); + r.setBottom((r.bottom() + 99) / 100 * 100); + } damage += r; continue; - } - break; } - foreach( const QRect& r, damage.rects()) - addDamage( r ); + break; } + foreach (const QRect & r, damage.rects()) + addDamage(r); +} -void Client::damageNotifyEvent( XDamageNotifyEvent* e ) - { - Toplevel::damageNotifyEvent( e ); +void Client::damageNotifyEvent(XDamageNotifyEvent* e) +{ + Toplevel::damageNotifyEvent(e); #ifdef HAVE_XSYNC - if( sync_counter == None ) // cannot detect complete redraw, consider done now + if (sync_counter == None) // cannot detect complete redraw, consider done now ready_for_painting = true; #else ready_for_painting = true; // no sync at all, consider done now #endif - } +} #endif -void Toplevel::addDamage( const QRect& r ) - { - addDamage( r.x(), r.y(), r.width(), r.height()); - } +void Toplevel::addDamage(const QRect& r) +{ + addDamage(r.x(), r.y(), r.width(), r.height()); +} -void Toplevel::addDamage( int x, int y, int w, int h ) - { - if( !compositing()) +void Toplevel::addDamage(int x, int y, int w, int h) +{ + if (!compositing()) return; - QRect r( x, y, w, h ); + QRect r(x, y, w, h); // resizing the decoration may lag behind a bit and when shrinking there // may be a damage event coming with size larger than the current window size r &= rect(); damage_region += r; repaints_region += r; - static_cast(effects)->windowDamaged( effectWindow(), r ); + static_cast(effects)->windowDamaged(effectWindow(), r); // discard lanczos texture - if( effect_window ) - { - QVariant cachedTextureVariant = effect_window->data( LanczosCacheRole ); - if( cachedTextureVariant.isValid() ) - { + if (effect_window) { + QVariant cachedTextureVariant = effect_window->data(LanczosCacheRole); + if (cachedTextureVariant.isValid()) { GLTexture *cachedTexture = static_cast< GLTexture*>(cachedTextureVariant.value()); delete cachedTexture; cachedTexture = 0; - effect_window->setData( LanczosCacheRole, QVariant() ); - } + effect_window->setData(LanczosCacheRole, QVariant()); } - workspace()->checkCompositeTimer(); } + workspace()->checkCompositeTimer(); +} void Toplevel::addDamageFull() - { - if( !compositing()) +{ + if (!compositing()) return; damage_region = rect(); repaints_region = rect(); - static_cast(effects)->windowDamaged( effectWindow(), rect()); + static_cast(effects)->windowDamaged(effectWindow(), rect()); // discard lanczos texture - if( effect_window ) - { - QVariant cachedTextureVariant = effect_window->data( LanczosCacheRole ); - if( cachedTextureVariant.isValid() ) - { + if (effect_window) { + QVariant cachedTextureVariant = effect_window->data(LanczosCacheRole); + if (cachedTextureVariant.isValid()) { GLTexture *cachedTexture = static_cast< GLTexture*>(cachedTextureVariant.value()); delete cachedTexture; cachedTexture = 0; - effect_window->setData( LanczosCacheRole, QVariant() ); - } + effect_window->setData(LanczosCacheRole, QVariant()); } + } workspace()->checkCompositeTimer(); - } +} -void Toplevel::resetDamage( const QRect& r ) - { +void Toplevel::resetDamage(const QRect& r) +{ damage_region -= r; - } +} -void Toplevel::addRepaint( const QRect& r ) - { - addRepaint( r.x(), r.y(), r.width(), r.height()); - } +void Toplevel::addRepaint(const QRect& r) +{ + addRepaint(r.x(), r.y(), r.width(), r.height()); +} -void Toplevel::addRepaint( int x, int y, int w, int h ) - { - if( !compositing()) +void Toplevel::addRepaint(int x, int y, int w, int h) +{ + if (!compositing()) return; - QRect r( x, y, w, h ); + QRect r(x, y, w, h); r &= rect(); repaints_region += r; workspace()->checkCompositeTimer(); - } +} void Toplevel::addRepaintFull() - { +{ repaints_region = rect(); workspace()->checkCompositeTimer(); - } +} -void Toplevel::resetRepaints( const QRect& r ) - { +void Toplevel::resetRepaints(const QRect& r) +{ repaints_region -= r; - } +} -void Toplevel::addWorkspaceRepaint( int x, int y, int w, int h ) - { - addWorkspaceRepaint( QRect( x, y, w, h )); - } +void Toplevel::addWorkspaceRepaint(int x, int y, int w, int h) +{ + addWorkspaceRepaint(QRect(x, y, w, h)); +} -void Toplevel::addWorkspaceRepaint( const QRect& r2 ) - { - if( !compositing()) +void Toplevel::addWorkspaceRepaint(const QRect& r2) +{ + if (!compositing()) return; - if( effectWindow() == NULL ) // TODO - this can happen during window destruction - return workspace()->addRepaint( r2 ); - QRect r = effects->transformWindowDamage( effectWindow(), r2 ); - workspace()->addRepaint( r ); - } + if (effectWindow() == NULL) // TODO - this can happen during window destruction + return workspace()->addRepaint(r2); + QRect r = effects->transformWindowDamage(effectWindow(), r2); + workspace()->addRepaint(r); +} bool Toplevel::updateUnredirectedState() - { - assert( compositing()); +{ + assert(compositing()); bool should = shouldUnredirect() && !unredirectSuspend && !shape() && !hasAlpha() && opacity() == 1.0 && - !static_cast( effects )->activeFullScreenEffect(); - if( should && !unredirect ) - { + !static_cast(effects)->activeFullScreenEffect(); + if (should && !unredirect) { unredirect = true; - kDebug( 1212 ) << "Unredirecting:" << this; + kDebug(1212) << "Unredirecting:" << this; #ifdef HAVE_XCOMPOSITE - XCompositeUnredirectWindow( display(), frameId(), CompositeRedirectManual ); + XCompositeUnredirectWindow(display(), frameId(), CompositeRedirectManual); #endif return true; - } - else if( !should && unredirect ) - { + } else if (!should && unredirect) { unredirect = false; - kDebug( 1212 ) << "Redirecting:" << this; + kDebug(1212) << "Redirecting:" << this; #ifdef HAVE_XCOMPOSITE - XCompositeRedirectWindow( display(), frameId(), CompositeRedirectManual ); + XCompositeRedirectWindow(display(), frameId(), CompositeRedirectManual); #endif discardWindowPixmap(); return true; - } - return false; } + return false; +} -void Toplevel::suspendUnredirect( bool suspend ) - { - if( unredirectSuspend == suspend ) +void Toplevel::suspendUnredirect(bool suspend) +{ + if (unredirectSuspend == suspend) return; unredirectSuspend = suspend; workspace()->checkUnredirect(); - } +} //**************************************** // Client //**************************************** void Client::setupCompositing() - { +{ Toplevel::setupCompositing(); updateVisibility(); // for internalKeep() - } +} void Client::finishCompositing() - { +{ Toplevel::finishCompositing(); updateVisibility(); triggerDecorationRepaint(); - } +} bool Client::shouldUnredirect() const - { - if( isActiveFullScreen()) - { +{ + if (isActiveFullScreen()) { ToplevelList stacking = workspace()->xStackingOrder(); - for( int pos = stacking.count() - 1; - pos >= 0; - --pos ) - { - Toplevel* c = stacking.at( pos ); - if( c == this ) // is not covered by any other window, ok to unredirect + for (int pos = stacking.count() - 1; + pos >= 0; + --pos) { + Toplevel* c = stacking.at(pos); + if (c == this) // is not covered by any other window, ok to unredirect return true; - if( c->geometry().intersects( geometry())) + if (c->geometry().intersects(geometry())) return false; - } - abort(); } - return false; + abort(); } + return false; +} void Client::addRepaintFull() - { +{ repaints_region = decorationRect(); workspace()->checkCompositeTimer(); - } +} //**************************************** // Unmanaged //**************************************** bool Unmanaged::shouldUnredirect() const - { +{ // the pixmap is needed for the login effect, a nicer solution would be the login effect increasing // refcount for the window pixmap (which would prevent unredirect), avoiding this hack - if( resourceClass() == "ksplashx" || resourceClass() == "ksplashsimple" ) + if (resourceClass() == "ksplashx" || resourceClass() == "ksplashsimple") return false; // it must cover whole display or one xinerama screen, and be the topmost there - if( geometry() == workspace()->clientArea( FullArea, geometry().center(), workspace()->currentDesktop()) - || geometry() == workspace()->clientArea( ScreenArea, geometry().center(), workspace()->currentDesktop())) - { + if (geometry() == workspace()->clientArea(FullArea, geometry().center(), workspace()->currentDesktop()) + || geometry() == workspace()->clientArea(ScreenArea, geometry().center(), workspace()->currentDesktop())) { ToplevelList stacking = workspace()->xStackingOrder(); - for( int pos = stacking.count() - 1; - pos >= 0; - --pos ) - { - Toplevel* c = stacking.at( pos ); - if( c == this ) // is not covered by any other window, ok to unredirect + for (int pos = stacking.count() - 1; + pos >= 0; + --pos) { + Toplevel* c = stacking.at(pos); + if (c == this) // is not covered by any other window, ok to unredirect return true; - if( c->geometry().intersects( geometry())) + if (c->geometry().intersects(geometry())) return false; - } - abort(); } - return false; + abort(); } + return false; +} //**************************************** // Deleted //**************************************** bool Deleted::shouldUnredirect() const - { +{ return false; - } +} void Deleted::addRepaintFull() - { +{ repaints_region = decorationRect(); workspace()->checkCompositeTimer(); - } +} } // namespace diff --git a/compositingprefs.cpp b/compositingprefs.cpp index 9f9308a88..360238478 100644 --- a/compositingprefs.cpp +++ b/compositingprefs.cpp @@ -36,89 +36,84 @@ namespace KWin { CompositingPrefs::CompositingPrefs() - : mRecommendCompositing( false ) - , mEnableVSync( true ) - , mEnableDirectRendering( true ) - , mStrictBinding( true ) - { - } + : mRecommendCompositing(false) + , mEnableVSync(true) + , mEnableDirectRendering(true) + , mStrictBinding(true) +{ +} CompositingPrefs::~CompositingPrefs() - { - } +{ +} bool CompositingPrefs::recommendCompositing() const - { +{ return mRecommendCompositing; - } +} bool CompositingPrefs::compositingPossible() - { +{ #ifdef KWIN_HAVE_COMPOSITING Extensions::init(); - if( !Extensions::compositeAvailable()) - { - kDebug( 1212 ) << "No composite extension available"; + if (!Extensions::compositeAvailable()) { + kDebug(1212) << "No composite extension available"; return false; - } - if( !Extensions::damageAvailable()) - { - kDebug( 1212 ) << "No damage extension available"; + } + if (!Extensions::damageAvailable()) { + kDebug(1212) << "No damage extension available"; return false; - } + } #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( Extensions::glxAvailable()) + if (Extensions::glxAvailable()) return true; #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( Extensions::renderAvailable() && Extensions::fixesAvailable()) + if (Extensions::renderAvailable() && Extensions::fixesAvailable()) return true; #endif #ifdef KWIN_HAVE_OPENGLES return true; #endif - kDebug( 1212 ) << "No OpenGL or XRender/XFixes support"; + kDebug(1212) << "No OpenGL or XRender/XFixes support"; return false; #else return false; #endif - } +} QString CompositingPrefs::compositingNotPossibleReason() - { +{ #ifdef KWIN_HAVE_COMPOSITING Extensions::init(); - if( !Extensions::compositeAvailable() || !Extensions::damageAvailable()) - { + if (!Extensions::compositeAvailable() || !Extensions::damageAvailable()) { return i18n("Required X extensions (XComposite and XDamage) are not available."); - } + } #if defined( KWIN_HAVE_OPENGL_COMPOSITING ) && !defined( KWIN_HAVE_XRENDER_COMPOSITING ) - if( !Extensions::glxAvailable()) - return i18n( "GLX/OpenGL are not available and only OpenGL support is compiled." ); + if (!Extensions::glxAvailable()) + return i18n("GLX/OpenGL are not available and only OpenGL support is compiled."); #elif !defined( KWIN_HAVE_OPENGL_COMPOSITING ) && defined( KWIN_HAVE_XRENDER_COMPOSITING ) - if( !( Extensions::renderAvailable() && Extensions::fixesAvailable())) - return i18n( "XRender/XFixes extensions are not available and only XRender support" - " is compiled." ); + if (!(Extensions::renderAvailable() && Extensions::fixesAvailable())) + return i18n("XRender/XFixes extensions are not available and only XRender support" + " is compiled."); #else - if( !( Extensions::glxAvailable() - || ( Extensions::renderAvailable() && Extensions::fixesAvailable()))) - { - return i18n( "GLX/OpenGL and XRender/XFixes are not available." ); - } + if (!(Extensions::glxAvailable() + || (Extensions::renderAvailable() && Extensions::fixesAvailable()))) { + return i18n("GLX/OpenGL and XRender/XFixes are not available."); + } #endif return QString(); #else return i18n("Compositing was disabled at compile time.\n" - "It is likely Xorg development headers were not installed."); + "It is likely Xorg development headers were not installed."); #endif - } +} void CompositingPrefs::detect() - { - if( !compositingPossible()) - { +{ + if (!compositingPossible()) { return; - } + } #ifdef KWIN_HAVE_OPENGL_COMPOSITING #ifdef KWIN_HAVE_OPENGLES @@ -144,8 +139,7 @@ void CompositingPrefs::detect() } #else // HACK: This is needed for AIGLX - if( qstrcmp( qgetenv( "KWIN_DIRECT_GL" ), "1" ) != 0 ) - { + if (qstrcmp(qgetenv("KWIN_DIRECT_GL"), "1") != 0) { // Start an external helper program that initializes GLX and returns // 0 if we can use direct rendering, and 1 otherwise. // The reason we have to use an external program is that after GLX @@ -153,40 +147,38 @@ void CompositingPrefs::detect() // environment variable. // Direct rendering is preferred, since not all OpenGL extensions are // available with indirect rendering. - const QString opengl_test = KStandardDirs::findExe( "kwin_opengl_test" ); - if ( QProcess::execute( opengl_test ) != 0 ) - setenv( "LIBGL_ALWAYS_INDIRECT", "1", true ); - } - if( !Extensions::glxAvailable()) - { - kDebug( 1212 ) << "No GLX available"; + const QString opengl_test = KStandardDirs::findExe("kwin_opengl_test"); + if (QProcess::execute(opengl_test) != 0) + setenv("LIBGL_ALWAYS_INDIRECT", "1", true); + } + if (!Extensions::glxAvailable()) { + kDebug(1212) << "No GLX available"; return; - } + } int glxmajor, glxminor; - glXQueryVersion( display(), &glxmajor, &glxminor ); - kDebug( 1212 ) << "glx version is " << glxmajor << "." << glxminor; - bool hasglx13 = ( glxmajor > 1 || ( glxmajor == 1 && glxminor >= 3 )); + glXQueryVersion(display(), &glxmajor, &glxminor); + kDebug(1212) << "glx version is " << glxmajor << "." << glxminor; + bool hasglx13 = (glxmajor > 1 || (glxmajor == 1 && glxminor >= 3)); // remember and later restore active context GLXContext oldcontext = glXGetCurrentContext(); GLXDrawable olddrawable = glXGetCurrentDrawable(); GLXDrawable oldreaddrawable = None; - if( hasglx13 ) + if (hasglx13) oldreaddrawable = glXGetCurrentReadDrawable(); - if( initGLXContext() ) - { + if (initGLXContext()) { detectDriverAndVersion(); applyDriverSpecificOptions(); - } - if( hasglx13 ) - glXMakeContextCurrent( display(), olddrawable, oldreaddrawable, oldcontext ); + } + if (hasglx13) + glXMakeContextCurrent(display(), olddrawable, oldreaddrawable, oldcontext); else - glXMakeCurrent( display(), olddrawable, oldcontext ); + glXMakeCurrent(display(), olddrawable, oldcontext); deleteGLXContext(); #endif #endif - } +} bool CompositingPrefs::initGLXContext() { @@ -202,44 +194,41 @@ bool CompositingPrefs::initGLXContext() attribs << GLX_BLUE_SIZE << 1; attribs << None; - XVisualInfo* visinfo = glXChooseVisual( display(), DefaultScreen( display()), attribs.data() ); - if( !visinfo ) - { + XVisualInfo* visinfo = glXChooseVisual(display(), DefaultScreen(display()), attribs.data()); + if (!visinfo) { attribs.last() = GLX_DOUBLEBUFFER; attribs << None; - visinfo = glXChooseVisual( display(), DefaultScreen( display()), attribs.data() ); - if (!visinfo) - { - kDebug( 1212 ) << "Error: couldn't find RGB GLX visual"; + visinfo = glXChooseVisual(display(), DefaultScreen(display()), attribs.data()); + if (!visinfo) { + kDebug(1212) << "Error: couldn't find RGB GLX visual"; return false; - } } + } - mGLContext = glXCreateContext( display(), visinfo, NULL, True ); - if ( !mGLContext ) - { - kDebug( 1212 ) << "glXCreateContext failed"; - XDestroyWindow( display(), mGLWindow ); + mGLContext = glXCreateContext(display(), visinfo, NULL, True); + if (!mGLContext) { + kDebug(1212) << "glXCreateContext failed"; + XDestroyWindow(display(), mGLWindow); return false; } XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; - attr.colormap = XCreateColormap( display(), rootWindow(), visinfo->visual, AllocNone ); + attr.colormap = XCreateColormap(display(), rootWindow(), visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask; unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; int width = 100, height = 100; - mGLWindow = XCreateWindow( display(), rootWindow(), 0, 0, width, height, - 0, visinfo->depth, InputOutput, - visinfo->visual, mask, &attr ); + mGLWindow = XCreateWindow(display(), rootWindow(), 0, 0, width, height, + 0, visinfo->depth, InputOutput, + visinfo->visual, mask, &attr); - return glXMakeCurrent( display(), mGLWindow, mGLContext ) && !handler.error( true ); + return glXMakeCurrent(display(), mGLWindow, mGLContext) && !handler.error(true); #else return false; #endif #else - return false; + return false; #endif } @@ -247,10 +236,10 @@ void CompositingPrefs::deleteGLXContext() { #ifdef KWIN_HAVE_OPENGL_COMPOSITING #ifndef KWIN_HAVE_OPENGLES - if( mGLContext == NULL ) + if (mGLContext == NULL) return; - glXDestroyContext( display(), mGLContext ); - XDestroyWindow( display(), mGLWindow ); + glXDestroyContext(display(), mGLContext); + XDestroyWindow(display(), mGLWindow); #endif #endif } @@ -258,14 +247,14 @@ void CompositingPrefs::deleteGLXContext() bool CompositingPrefs::initEGLContext() { #ifdef KWIN_HAVE_OPENGLES - mEGLDisplay = eglGetDisplay( display() ); + mEGLDisplay = eglGetDisplay(display()); if (mEGLDisplay == EGL_NO_DISPLAY) { return false; } - if (eglInitialize( mEGLDisplay, 0, 0 ) == EGL_FALSE) { + if (eglInitialize(mEGLDisplay, 0, 0) == EGL_FALSE) { return false; } - eglBindAPI( EGL_OPENGL_ES_API ); + eglBindAPI(EGL_OPENGL_ES_API); const EGLint config_attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, @@ -297,26 +286,26 @@ bool CompositingPrefs::initEGLContext() XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; - attr.colormap = XCreateColormap( display(), rootWindow(), (Visual*)QX11Info::appVisual(), AllocNone ); + attr.colormap = XCreateColormap(display(), rootWindow(), (Visual*)QX11Info::appVisual(), AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask; unsigned long mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; int width = 100, height = 100; - mGLWindow = XCreateWindow( display(), rootWindow(), 0, 0, width, height, - 0, QX11Info::appDepth(), InputOutput, - (Visual*)QX11Info::appVisual(), mask, &attr ); + mGLWindow = XCreateWindow(display(), rootWindow(), 0, 0, width, height, + 0, QX11Info::appDepth(), InputOutput, + (Visual*)QX11Info::appVisual(), mask, &attr); - mEGLSurface = eglCreateWindowSurface( mEGLDisplay, config, mGLWindow, 0 ); + mEGLSurface = eglCreateWindowSurface(mEGLDisplay, config, mGLWindow, 0); const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; - mEGLContext = eglCreateContext( mEGLDisplay, config, EGL_NO_CONTEXT, context_attribs ); + mEGLContext = eglCreateContext(mEGLDisplay, config, EGL_NO_CONTEXT, context_attribs); if (mEGLContext == EGL_NO_CONTEXT) { return false; } - if (eglMakeCurrent( mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext ) == EGL_FALSE) { + if (eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext) == EGL_FALSE) { return false; } EGLint error = eglGetError(); @@ -337,32 +326,32 @@ void CompositingPrefs::deleteEGLContext() eglDestroySurface(mEGLDisplay, mEGLSurface); eglTerminate(mEGLDisplay); eglReleaseThread(); - XDestroyWindow( display(), mGLWindow ); + XDestroyWindow(display(), mGLWindow); #endif } void CompositingPrefs::detectDriverAndVersion() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING GLPlatform *gl = GLPlatform::instance(); gl->detect(); gl->printResults(); #endif - } +} // See http://techbase.kde.org/Projects/KWin/HW for a list of some cards that are known to work. void CompositingPrefs::applyDriverSpecificOptions() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING // Always recommend mRecommendCompositing = true; GLPlatform *gl = GLPlatform::instance(); - mStrictBinding = !gl->supports( LooseBinding ); - if ( gl->driver() == Driver_Intel ) + mStrictBinding = !gl->supports(LooseBinding); + if (gl->driver() == Driver_Intel) mEnableVSync = false; #endif - } +} } // namespace diff --git a/compositingprefs.h b/compositingprefs.h index 73f1c3e1f..89c97a7d5 100644 --- a/compositingprefs.h +++ b/compositingprefs.h @@ -40,9 +40,15 @@ public: static bool compositingPossible(); static QString compositingNotPossibleReason(); bool recommendCompositing() const; - bool enableVSync() const { return mEnableVSync; } - bool enableDirectRendering() const { return mEnableDirectRendering; } - bool strictBinding() const { return mStrictBinding; } + bool enableVSync() const { + return mEnableVSync; + } + bool enableDirectRendering() const { + return mEnableDirectRendering; + } + bool strictBinding() const { + return mStrictBinding; + } void detect(); diff --git a/deleted.cpp b/deleted.cpp index 91cc454d6..a59c7cd5d 100644 --- a/deleted.cpp +++ b/deleted.cpp @@ -27,61 +27,59 @@ along with this program. If not, see . namespace KWin { -Deleted::Deleted( Workspace* ws ) - : Toplevel( ws ) - , delete_refcount( 1 ) - , no_border( true ) - , padding_left( 0 ) - , padding_top( 0 ) - , padding_right( 0 ) - , padding_bottom( 0 ) - { - } +Deleted::Deleted(Workspace* ws) + : Toplevel(ws) + , delete_refcount(1) + , no_border(true) + , padding_left(0) + , padding_top(0) + , padding_right(0) + , padding_bottom(0) +{ +} Deleted::~Deleted() - { - if( delete_refcount != 0 ) +{ + if (delete_refcount != 0) kError(1212) << "Deleted client has non-zero reference count (" << delete_refcount << ")"; - assert( delete_refcount == 0 ); - workspace()->removeDeleted( this, Allowed ); + assert(delete_refcount == 0); + workspace()->removeDeleted(this, Allowed); deleteEffectWindow(); - } +} -Deleted* Deleted::create( Toplevel* c ) - { - Deleted* d = new Deleted( c->workspace()); - d->copyToDeleted( c ); - d->workspace()->addDeleted( d, Allowed ); +Deleted* Deleted::create(Toplevel* c) +{ + Deleted* d = new Deleted(c->workspace()); + d->copyToDeleted(c); + d->workspace()->addDeleted(d, Allowed); return d; - } +} // to be used only from Workspace::finishCompositing() -void Deleted::discard( allowed_t ) - { +void Deleted::discard(allowed_t) +{ delete_refcount = 0; delete this; - } +} -void Deleted::copyToDeleted( Toplevel* c ) - { - assert( dynamic_cast< Deleted* >( c ) == NULL ); - Toplevel::copyToDeleted( c ); +void Deleted::copyToDeleted(Toplevel* c) +{ + assert(dynamic_cast< Deleted* >(c) == NULL); + Toplevel::copyToDeleted(c); desk = c->desktop(); activityList = c->activities(); - contentsRect = QRect( c->clientPos(), c->clientSize()); + contentsRect = QRect(c->clientPos(), c->clientSize()); transparent_rect = c->transparentRect(); - if( WinInfo* cinfo = dynamic_cast< WinInfo* >( info )) + if (WinInfo* cinfo = dynamic_cast< WinInfo* >(info)) cinfo->disable(); Client* client = dynamic_cast(c); - if( client ) - { + if (client) { no_border = client->noBorder(); padding_left = client->paddingLeft(); padding_right = client->paddingRight(); padding_bottom = client->paddingBottom(); padding_top = client->paddingTop(); - if( !no_border ) - { + if (!no_border) { client->layoutDecorationRects(decoration_left, decoration_top, decoration_right, @@ -91,64 +89,64 @@ void Deleted::copyToDeleted( Toplevel* c ) decorationPixmapRight = *client->rightDecoPixmap(); decorationPixmapTop = *client->topDecoPixmap(); decorationPixmapBottom = *client->bottomDecoPixmap(); - } } } +} -void Deleted::unrefWindow( bool delay ) - { - if( --delete_refcount > 0 ) +void Deleted::unrefWindow(bool delay) +{ + if (--delete_refcount > 0) return; // needs to be delayed when calling from effects, otherwise it'd be rather // complicated to handle the case of the window going away during a painting pass - if( delay ) + if (delay) deleteLater(); else delete this; - } +} int Deleted::desktop() const - { +{ return desk; - } +} QStringList Deleted::activities() const - { +{ return activityList; - } +} QPoint Deleted::clientPos() const - { +{ return contentsRect.topLeft(); - } +} QSize Deleted::clientSize() const - { +{ return contentsRect.size(); - } +} -void Deleted::debug( QDebug& stream ) const - { +void Deleted::debug(QDebug& stream) const +{ stream << "\'ID:" << window() << "\' (deleted)"; - } +} void Deleted::layoutDecorationRects(QRect& left, QRect& top, QRect& right, QRect& bottom) const - { +{ left = decoration_left; top = decoration_top; right = decoration_right; bottom = decoration_bottom; - } +} QRect Deleted::decorationRect() const - { +{ return rect().adjusted(-padding_left, -padding_top, padding_top, padding_bottom); - } +} QRect Deleted::transparentRect() const - { +{ return transparent_rect; - } +} } // namespace diff --git a/deleted.h b/deleted.h index 779471d8a..3b0341ae0 100644 --- a/deleted.h +++ b/deleted.h @@ -28,57 +28,67 @@ namespace KWin class Deleted : public Toplevel - { +{ Q_OBJECT - public: - static Deleted* create( Toplevel* c ); - // used by effects to keep the window around for e.g. fadeout effects when it's destroyed - void refWindow(); - void unrefWindow( bool delay = false ); - void discard( allowed_t ); - virtual int desktop() const; - virtual QStringList activities() const; - virtual QPoint clientPos() const; - virtual QSize clientSize() const; - virtual QRect transparentRect() const; - const QPixmap *topDecoPixmap() const { return &decorationPixmapTop; } - const QPixmap *leftDecoPixmap() const { return &decorationPixmapLeft; } - const QPixmap *bottomDecoPixmap() const { return &decorationPixmapBottom; } - const QPixmap *rightDecoPixmap() const { return &decorationPixmapRight; } - bool noBorder() const { return no_border; } - void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const; - virtual void addRepaintFull(); // in composite.cpp - QRect decorationRect() const; - protected: - virtual void debug( QDebug& stream ) const; - virtual bool shouldUnredirect() const; - private: - Deleted( Workspace *ws ); // use create() - void copyToDeleted( Toplevel* c ); - virtual ~Deleted(); // deleted only using unrefWindow() - int delete_refcount; - double window_opacity; - int desk; - QStringList activityList; - QRect contentsRect; // for clientPos()/clientSize() - QRect transparent_rect; +public: + static Deleted* create(Toplevel* c); + // used by effects to keep the window around for e.g. fadeout effects when it's destroyed + void refWindow(); + void unrefWindow(bool delay = false); + void discard(allowed_t); + virtual int desktop() const; + virtual QStringList activities() const; + virtual QPoint clientPos() const; + virtual QSize clientSize() const; + virtual QRect transparentRect() const; + const QPixmap *topDecoPixmap() const { + return &decorationPixmapTop; + } + const QPixmap *leftDecoPixmap() const { + return &decorationPixmapLeft; + } + const QPixmap *bottomDecoPixmap() const { + return &decorationPixmapBottom; + } + const QPixmap *rightDecoPixmap() const { + return &decorationPixmapRight; + } + bool noBorder() const { + return no_border; + } + void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const; + virtual void addRepaintFull(); // in composite.cpp + QRect decorationRect() const; +protected: + virtual void debug(QDebug& stream) const; + virtual bool shouldUnredirect() const; +private: + Deleted(Workspace *ws); // use create() + void copyToDeleted(Toplevel* c); + virtual ~Deleted(); // deleted only using unrefWindow() + int delete_refcount; + double window_opacity; + int desk; + QStringList activityList; + QRect contentsRect; // for clientPos()/clientSize() + QRect transparent_rect; - QPixmap decorationPixmapLeft; - QPixmap decorationPixmapRight; - QPixmap decorationPixmapTop; - QPixmap decorationPixmapBottom; - bool no_border; - QRect decoration_left; - QRect decoration_right; - QRect decoration_top; - QRect decoration_bottom; - int padding_left, padding_top, padding_right, padding_bottom; - }; + QPixmap decorationPixmapLeft; + QPixmap decorationPixmapRight; + QPixmap decorationPixmapTop; + QPixmap decorationPixmapBottom; + bool no_border; + QRect decoration_left; + QRect decoration_right; + QRect decoration_top; + QRect decoration_bottom; + int padding_left, padding_top, padding_right, padding_bottom; +}; inline void Deleted::refWindow() - { +{ ++delete_refcount; - } +} } // namespace diff --git a/desktopchangeosd.cpp b/desktopchangeosd.cpp index 1f0370468..77ff155b7 100644 --- a/desktopchangeosd.cpp +++ b/desktopchangeosd.cpp @@ -38,597 +38,543 @@ along with this program. If not, see . namespace KWin { -DesktopChangeOSD::DesktopChangeOSD( Workspace* ws ) +DesktopChangeOSD::DesktopChangeOSD(Workspace* ws) : QGraphicsView() - , m_wspace( ws ) - , m_scene( 0 ) - , m_active( false ) - , m_show( false ) - , m_delayTime( 0 ) - , m_textOnly( false ) - { - setWindowFlags( Qt::X11BypassWindowManagerHint ); - setFrameStyle( QFrame::NoFrame ); - viewport()->setAutoFillBackground( false ); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setAttribute( Qt::WA_TranslucentBackground ); - m_frame.setImagePath( "dialogs/background" ); - m_frame.setCacheAllRenderedFrames( true ); - m_frame.setEnabledBorders( Plasma::FrameSvg::AllBorders ); + , m_wspace(ws) + , m_scene(0) + , m_active(false) + , m_show(false) + , m_delayTime(0) + , m_textOnly(false) +{ + setWindowFlags(Qt::X11BypassWindowManagerHint); + setFrameStyle(QFrame::NoFrame); + viewport()->setAutoFillBackground(false); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setAttribute(Qt::WA_TranslucentBackground); + m_frame.setImagePath("dialogs/background"); + m_frame.setCacheAllRenderedFrames(true); + m_frame.setEnabledBorders(Plasma::FrameSvg::AllBorders); - m_item_frame.setImagePath( "widgets/pager" ); - m_item_frame.setCacheAllRenderedFrames( true ); - m_item_frame.setEnabledBorders( Plasma::FrameSvg::AllBorders ); + m_item_frame.setImagePath("widgets/pager"); + m_item_frame.setCacheAllRenderedFrames(true); + m_item_frame.setEnabledBorders(Plasma::FrameSvg::AllBorders); - m_delayedHideTimer.setSingleShot( true ); - connect( &m_delayedHideTimer, SIGNAL(timeout()), this, SLOT(hide()) ); + m_delayedHideTimer.setSingleShot(true); + connect(&m_delayedHideTimer, SIGNAL(timeout()), this, SLOT(hide())); - m_scene = new QGraphicsScene( 0 ); - setScene( m_scene ); + m_scene = new QGraphicsScene(0); + setScene(m_scene); reconfigure(); - m_scene->addItem( new DesktopChangeText( m_wspace ) ); - } + m_scene->addItem(new DesktopChangeText(m_wspace)); +} DesktopChangeOSD::~DesktopChangeOSD() - { +{ delete m_scene; - } +} void DesktopChangeOSD::reconfigure() - { +{ KSharedConfigPtr c(KGlobal::config()); - const KConfigGroup cg = c->group( "PopupInfo" ); - m_show = cg.readEntry( "ShowPopup", false ); - m_delayTime = cg.readEntry( "PopupHideDelay", 1000 ); - m_textOnly = cg.readEntry( "TextOnly", false ); + const KConfigGroup cg = c->group("PopupInfo"); + m_show = cg.readEntry("ShowPopup", false); + m_delayTime = cg.readEntry("PopupHideDelay", 1000); + m_textOnly = cg.readEntry("TextOnly", false); numberDesktopsChanged(); - } +} -void DesktopChangeOSD::desktopChanged( int old ) - { - if( !m_show ) +void DesktopChangeOSD::desktopChanged(int old) +{ + if (!m_show) return; // we have to stop in case the old desktop does not exist anymore - if( old > m_wspace->numberOfDesktops() ) + if (old > m_wspace->numberOfDesktops()) return; // calculate where icons have to be shown - QPoint diff = m_wspace->desktopGridCoords( m_wspace->currentDesktop() ) - m_wspace->desktopGridCoords( old ); + QPoint diff = m_wspace->desktopGridCoords(m_wspace->currentDesktop()) - m_wspace->desktopGridCoords(old); QHash< int, DesktopChangeItem::Arrow > hash = QHash< int, DesktopChangeItem::Arrow>(); int desktop = old; int target = m_wspace->currentDesktop(); int x = diff.x(); int y = diff.y(); - if( y >= 0 ) - { + if (y >= 0) { // first go in x direction, then in y - while( desktop != target ) - { - if( x != 0 ) - { - if( x < 0 ) - { + while (desktop != target) { + if (x != 0) { + if (x < 0) { x++; - hash.insert( desktop, DesktopChangeItem::LEFT ); - desktop = m_wspace->desktopToLeft( desktop ); - } - else - { + hash.insert(desktop, DesktopChangeItem::LEFT); + desktop = m_wspace->desktopToLeft(desktop); + } else { x--; - hash.insert( desktop, DesktopChangeItem::RIGHT ); - desktop = m_wspace->desktopToRight( desktop ); - } - continue; + hash.insert(desktop, DesktopChangeItem::RIGHT); + desktop = m_wspace->desktopToRight(desktop); } - y--; - hash.insert( desktop, DesktopChangeItem::DOWN ); - desktop = m_wspace->desktopBelow( desktop ); + continue; } + y--; + hash.insert(desktop, DesktopChangeItem::DOWN); + desktop = m_wspace->desktopBelow(desktop); } - else - { + } else { // first go in y direction, then in x - while( target != desktop ) - { - if( y != 0 ) - { + while (target != desktop) { + if (y != 0) { // only go upward y++; - hash.insert( desktop, DesktopChangeItem::UP ); - desktop = m_wspace->desktopAbove( desktop ); + hash.insert(desktop, DesktopChangeItem::UP); + desktop = m_wspace->desktopAbove(desktop); continue; - } - if( x != 0 ) - { - if( x < 0 ) - { + } + if (x != 0) { + if (x < 0) { x++; - hash.insert( desktop, DesktopChangeItem::LEFT ); - desktop = m_wspace->desktopToLeft( desktop ); - } - else - { + hash.insert(desktop, DesktopChangeItem::LEFT); + desktop = m_wspace->desktopToLeft(desktop); + } else { x--; - hash.insert( desktop, DesktopChangeItem::RIGHT ); - desktop = m_wspace->desktopToRight( desktop ); - } + hash.insert(desktop, DesktopChangeItem::RIGHT); + desktop = m_wspace->desktopToRight(desktop); } } } + } // now we know which desktop has to show an arrow -> set the arrow for each desktop - int numberOfArrows = qAbs( diff.x() ) + qAbs( diff.y() ); - foreach( QGraphicsItem* it, m_scene->items() ) - { - DesktopChangeItem* item = qgraphicsitem_cast< DesktopChangeItem* >( it ); - if( item ) - { - if( hash.contains( item->desktop() ) ) - { - QPoint distance = m_wspace->desktopGridCoords( m_wspace->currentDesktop() ) - - m_wspace->desktopGridCoords( item->desktop() ); - int desktopDistance = numberOfArrows - ( qAbs( distance.x() ) + qAbs( distance.y() ) ); - int start = m_delayTime/numberOfArrows * desktopDistance - m_delayTime*0.15f; - int stop = m_delayTime/numberOfArrows * (desktopDistance + 1) + m_delayTime*0.15f; - start = qMax( start, 0 ); - item->setArrow( hash[ item->desktop() ], start, stop ); - } - else - { - item->setArrow( DesktopChangeItem::NONE, 0, 0 ); - } - if( old != m_wspace->currentDesktop() ) - { - if( item->desktop() == m_wspace->currentDesktop() ) - item->startDesktopHighLightAnimation( m_delayTime * 0.33 ); - if( m_active && item->desktop() == old ) + int numberOfArrows = qAbs(diff.x()) + qAbs(diff.y()); + foreach (QGraphicsItem * it, m_scene->items()) { + DesktopChangeItem* item = qgraphicsitem_cast< DesktopChangeItem* >(it); + if (item) { + if (hash.contains(item->desktop())) { + QPoint distance = m_wspace->desktopGridCoords(m_wspace->currentDesktop()) + - m_wspace->desktopGridCoords(item->desktop()); + int desktopDistance = numberOfArrows - (qAbs(distance.x()) + qAbs(distance.y())); + int start = m_delayTime / numberOfArrows * desktopDistance - m_delayTime * 0.15f; + int stop = m_delayTime / numberOfArrows * (desktopDistance + 1) + m_delayTime * 0.15f; + start = qMax(start, 0); + item->setArrow(hash[ item->desktop()], start, stop); + } else { + item->setArrow(DesktopChangeItem::NONE, 0, 0); + } + if (old != m_wspace->currentDesktop()) { + if (item->desktop() == m_wspace->currentDesktop()) + item->startDesktopHighLightAnimation(m_delayTime * 0.33); + if (m_active && item->desktop() == old) item->stopDesktopHighLightAnimation(); - } } } - if( m_active ) - { + } + if (m_active) { // for text only we need to resize - if( m_textOnly ) + if (m_textOnly) resize(); // already active - just update and reset timer update(); - } - else - { + } else { m_active = true; resize(); show(); raise(); - } + } // Set a zero inputmask, effectively making clicks go "through" the popup // For those who impatiently wait to click on a dialog behind the it - XShapeCombineRectangles( display(), winId(), ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted ); - m_delayedHideTimer.start( m_delayTime ); - } + XShapeCombineRectangles(display(), winId(), ShapeInput, 0, 0, NULL, 0, ShapeSet, Unsorted); + m_delayedHideTimer.start(m_delayTime); +} -void DesktopChangeOSD::hideEvent( QHideEvent* ) - { +void DesktopChangeOSD::hideEvent(QHideEvent*) +{ m_delayedHideTimer.stop(); m_active = false; - } +} -void DesktopChangeOSD::drawBackground( QPainter* painter, const QRectF& rect ) - { +void DesktopChangeOSD::drawBackground(QPainter* painter, const QRectF& rect) +{ painter->save(); - painter->setCompositionMode( QPainter::CompositionMode_Source ); + painter->setCompositionMode(QPainter::CompositionMode_Source); qreal left, top, right, bottom; - m_frame.getMargins( left, top, right, bottom ); - m_frame.paintFrame( painter, rect.adjusted( -left, -top, right, bottom ) ); + m_frame.getMargins(left, top, right, bottom); + m_frame.paintFrame(painter, rect.adjusted(-left, -top, right, bottom)); painter->restore(); - } +} void DesktopChangeOSD::numberDesktopsChanged() - { - foreach( QGraphicsItem* it, m_scene->items() ) - { +{ + foreach (QGraphicsItem * it, m_scene->items()) { DesktopChangeItem* item = qgraphicsitem_cast(it); - if( item ) - { - m_scene->removeItem( item ); - } - } - - if( !m_textOnly ) - { - for( int i=1; i<=m_wspace->numberOfDesktops(); i++ ) - { - DesktopChangeItem* item = new DesktopChangeItem( m_wspace, this, i ); - m_scene->addItem( item ); - } + if (item) { + m_scene->removeItem(item); } } + if (!m_textOnly) { + for (int i = 1; i <= m_wspace->numberOfDesktops(); i++) { + DesktopChangeItem* item = new DesktopChangeItem(m_wspace, this, i); + m_scene->addItem(item); + } + } +} + void DesktopChangeOSD::resize() - { - QRect screenRect = m_wspace->clientArea( ScreenArea, m_wspace->activeScreen(), m_wspace->currentDesktop() ); - QRect fullRect = m_wspace->clientArea( FullArea, m_wspace->activeScreen(), m_wspace->currentDesktop() ); +{ + QRect screenRect = m_wspace->clientArea(ScreenArea, m_wspace->activeScreen(), m_wspace->currentDesktop()); + QRect fullRect = m_wspace->clientArea(FullArea, m_wspace->activeScreen(), m_wspace->currentDesktop()); qreal left, top, right, bottom; - m_frame.getMargins( left, top, right, bottom ); + m_frame.getMargins(left, top, right, bottom); QSize desktopGridSize = m_wspace->desktopGridSize(); - float itemWidth = fullRect.width()*0.1f; - float itemHeight = fullRect.height()*0.1f; + float itemWidth = fullRect.width() * 0.1f; + float itemHeight = fullRect.height() * 0.1f; // 2 px distance between each desktop + each desktop a width of 5 % of full screen + borders - float width = (desktopGridSize.width()-1)*2 + desktopGridSize.width()*itemWidth + left + right; - float height = (desktopGridSize.height()-1)*2 + top + bottom; + float width = (desktopGridSize.width() - 1) * 2 + desktopGridSize.width() * itemWidth + left + right; + float height = (desktopGridSize.height() - 1) * 2 + top + bottom; // bound width between ten and 33 percent of active screen - float tempWidth = qBound( screenRect.width()*0.25f, width, screenRect.width()*0.5f ); - if( tempWidth != width ) - { + float tempWidth = qBound(screenRect.width() * 0.25f, width, screenRect.width() * 0.5f); + if (tempWidth != width) { // have to adjust the height width = tempWidth; - itemWidth = (width - (desktopGridSize.width()-1)*2 - left - right)/desktopGridSize.width(); - itemHeight = itemWidth*(float)((float)fullRect.height()/(float)fullRect.width()); - } - height += itemHeight*desktopGridSize.height(); + itemWidth = (width - (desktopGridSize.width() - 1) * 2 - left - right) / desktopGridSize.width(); + itemHeight = itemWidth * (float)((float)fullRect.height() / (float)fullRect.width()); + } + height += itemHeight * desktopGridSize.height(); height += fontMetrics().height() + 4; // we do not increase height, but it's bound to a third of screen height - float tempHeight = qMin( height, screenRect.height()*0.5f ); + float tempHeight = qMin(height, screenRect.height() * 0.5f); float itemOffset = 0.0f; - if( tempHeight != height ) - { + if (tempHeight != height) { // have to adjust item width height = tempHeight; - itemHeight = (height - (fontMetrics().height() + 4) - top - bottom - (desktopGridSize.height()-1)*2)/ - desktopGridSize.height(); + itemHeight = (height - (fontMetrics().height() + 4) - top - bottom - (desktopGridSize.height() - 1) * 2) / + desktopGridSize.height(); itemOffset = itemWidth; - itemWidth = itemHeight*(float)((float)fullRect.width()/(float)fullRect.height()); + itemWidth = itemHeight * (float)((float)fullRect.width() / (float)fullRect.height()); itemOffset -= itemWidth; - itemOffset *= (float)desktopGridSize.width()*0.5f; - } + itemOffset *= (float)desktopGridSize.width() * 0.5f; + } // set size to the desktop name if the "pager" is not shown - if( m_textOnly ) - { + if (m_textOnly) { height = fontMetrics().height() + 4 + top + bottom; - width = fontMetrics().boundingRect( m_wspace->desktopName( m_wspace->currentDesktop() ) ).width() + + width = fontMetrics().boundingRect(m_wspace->desktopName(m_wspace->currentDesktop())).width() + 4 + left + right; - } + } - QRect rect = QRect( screenRect.x() + (screenRect.width()-width)/2, - screenRect.y() + (screenRect.height()-height)/2, - width, - height ); - setGeometry( rect ); - m_scene->setSceneRect( 0, 0, width, height ); - m_frame.resizeFrame( QSize( width, height ) ); + QRect rect = QRect(screenRect.x() + (screenRect.width() - width) / 2, + screenRect.y() + (screenRect.height() - height) / 2, + width, + height); + setGeometry(rect); + m_scene->setSceneRect(0, 0, width, height); + m_frame.resizeFrame(QSize(width, height)); - if (Plasma::Theme::defaultTheme()->windowTranslucencyEnabled()) - { + if (Plasma::Theme::defaultTheme()->windowTranslucencyEnabled()) { // blur background Plasma::WindowEffects::enableBlurBehind(winId(), true, m_frame.mask()); Plasma::WindowEffects::overrideShadow(winId(), true); - } - else - { + } else { // do not trim to mask with compositing enabled, otherwise shadows are cropped - setMask( m_frame.mask() ); - } + setMask(m_frame.mask()); + } // resize item frame - m_item_frame.setElementPrefix( "normal" ); - m_item_frame.resizeFrame( QSize( itemWidth, itemHeight ) ); - m_item_frame.setElementPrefix( "hover" ); - m_item_frame.resizeFrame( QSize( itemWidth, itemHeight ) ); + m_item_frame.setElementPrefix("normal"); + m_item_frame.resizeFrame(QSize(itemWidth, itemHeight)); + m_item_frame.setElementPrefix("hover"); + m_item_frame.resizeFrame(QSize(itemWidth, itemHeight)); // reset the items - foreach( QGraphicsItem* it, m_scene->items() ) - { + foreach (QGraphicsItem * it, m_scene->items()) { DesktopChangeItem* item = qgraphicsitem_cast(it); - if( item ) - { - item->setWidth( itemWidth ); - item->setHeight( itemHeight ); - QPoint coords = m_wspace->desktopGridCoords( item->desktop() ); - item->setPos( left + itemOffset + coords.x()*(itemWidth+2), - top + fontMetrics().height() + 4 + coords.y()*(itemHeight+4) ); - } + if (item) { + item->setWidth(itemWidth); + item->setHeight(itemHeight); + QPoint coords = m_wspace->desktopGridCoords(item->desktop()); + item->setPos(left + itemOffset + coords.x()*(itemWidth + 2), + top + fontMetrics().height() + 4 + coords.y()*(itemHeight + 4)); + } DesktopChangeText* text = qgraphicsitem_cast(it); - if( text ) - { - text->setPos( left, top ); - text->setWidth( width - left - right ); - if( m_textOnly ) - text->setHeight( fontMetrics().height() + 4 ); + if (text) { + text->setPos(left, top); + text->setWidth(width - left - right); + if (m_textOnly) + text->setHeight(fontMetrics().height() + 4); else - text->setHeight( fontMetrics().height() ); - } + text->setHeight(fontMetrics().height()); } } +} //******************************* // DesktopChangeText //******************************* -DesktopChangeText::DesktopChangeText( Workspace* ws ) +DesktopChangeText::DesktopChangeText(Workspace* ws) : QGraphicsItem() - , m_wspace( ws ) - , m_width( 0.0f ) - , m_height( 0.0f ) - { - } + , m_wspace(ws) + , m_width(0.0f) + , m_height(0.0f) +{ +} DesktopChangeText::~DesktopChangeText() - { - } +{ +} QRectF DesktopChangeText::boundingRect() const - { - return QRectF( 0, 0, m_width, m_height ); - } +{ + return QRectF(0, 0, m_width, m_height); +} -void DesktopChangeText::paint( QPainter* painter, const QStyleOptionGraphicsItem* , QWidget* ) - { - painter->setPen( Plasma::Theme::defaultTheme()->color( Plasma::Theme::TextColor ) ); - painter->drawText( boundingRect(), Qt::AlignCenter | Qt:: AlignVCenter, - m_wspace->desktopName( m_wspace->currentDesktop() ) ); - } +void DesktopChangeText::paint(QPainter* painter, const QStyleOptionGraphicsItem* , QWidget*) +{ + painter->setPen(Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor)); + painter->drawText(boundingRect(), Qt::AlignCenter | Qt:: AlignVCenter, + m_wspace->desktopName(m_wspace->currentDesktop())); +} //******************************* // DesktopChangeItem //******************************* -DesktopChangeItem::DesktopChangeItem( Workspace* ws, DesktopChangeOSD* parent, int desktop ) +DesktopChangeItem::DesktopChangeItem(Workspace* ws, DesktopChangeOSD* parent, int desktop) : QGraphicsItem() - , m_wspace( ws ) - , m_parent( parent ) - , m_desktop( desktop ) - , m_width( 0.0f ) - , m_height( 0.0f ) - , m_arrow( NONE ) - , m_arrowShown( false ) - , m_fadeInArrow( false ) - , m_fadeInHighLight( false ) - , m_arrowValue( 0.0 ) - , m_highLightValue( 0.0 ) - { - m_delayed_show_arrow_timer.setSingleShot( true ); - m_delayed_hide_arrow_timer.setSingleShot( true ); - connect( &m_delayed_show_arrow_timer, SIGNAL(timeout()), this, SLOT(showArrow())); - connect( &m_delayed_hide_arrow_timer, SIGNAL(timeout()), this, SLOT(hideArrow())); - } + , m_wspace(ws) + , m_parent(parent) + , m_desktop(desktop) + , m_width(0.0f) + , m_height(0.0f) + , m_arrow(NONE) + , m_arrowShown(false) + , m_fadeInArrow(false) + , m_fadeInHighLight(false) + , m_arrowValue(0.0) + , m_highLightValue(0.0) +{ + m_delayed_show_arrow_timer.setSingleShot(true); + m_delayed_hide_arrow_timer.setSingleShot(true); + connect(&m_delayed_show_arrow_timer, SIGNAL(timeout()), this, SLOT(showArrow())); + connect(&m_delayed_hide_arrow_timer, SIGNAL(timeout()), this, SLOT(hideArrow())); +} DesktopChangeItem::~DesktopChangeItem() - { - } +{ +} QRectF DesktopChangeItem::boundingRect() const - { - return QRectF( 0, 0, m_width, m_height ); - } +{ + return QRectF(0, 0, m_width, m_height); +} -void DesktopChangeItem::setArrow( Arrow arrow, int start_delay, int hide_delay ) - { +void DesktopChangeItem::setArrow(Arrow arrow, int start_delay, int hide_delay) +{ // stop timers m_delayed_show_arrow_timer.stop(); m_delayed_hide_arrow_timer.stop(); QPropertyAnimation *arrowAnimation = m_arrowAnimation.data(); - if( arrowAnimation ) - { + if (arrowAnimation) { arrowAnimation->stop(); m_arrowAnimation.clear(); - } + } m_arrowShown = false; m_arrow = arrow; - if( m_arrow != NONE ) - { - m_delayed_show_arrow_timer.start( start_delay ); - m_delayed_hide_arrow_timer.start( hide_delay ); - } + if (m_arrow != NONE) { + m_delayed_show_arrow_timer.start(start_delay); + m_delayed_hide_arrow_timer.start(hide_delay); } +} qreal DesktopChangeItem::arrowValue() const - { +{ qCritical() << __func__ << m_arrowValue; return m_arrowValue; - } +} qreal DesktopChangeItem::highLightValue() const - { +{ return m_highLightValue; - } +} -void DesktopChangeItem::setArrowValue( qreal value ) - { +void DesktopChangeItem::setArrowValue(qreal value) +{ m_arrowValue = value; update(); - } +} -void DesktopChangeItem::setHighLightValue( qreal value ) - { +void DesktopChangeItem::setHighLightValue(qreal value) +{ m_highLightValue = value; update(); - } +} void DesktopChangeItem::showArrow() - { +{ m_arrowShown = true; QPropertyAnimation *arrowAnimation = m_arrowAnimation.data(); - if( !arrowAnimation ) - { - arrowAnimation = new QPropertyAnimation( this, "arrowValue" ); - arrowAnimation->setDuration( m_parent->getDelayTime()*0.15f ); - arrowAnimation->setStartValue( 0.0 ); - arrowAnimation->setEndValue( 1.0 ); + if (!arrowAnimation) { + arrowAnimation = new QPropertyAnimation(this, "arrowValue"); + arrowAnimation->setDuration(m_parent->getDelayTime() * 0.15f); + arrowAnimation->setStartValue(0.0); + arrowAnimation->setEndValue(1.0); m_arrowAnimation = arrowAnimation; - } + } m_fadeInArrow = true; - arrowAnimation->setEasingCurve( QEasingCurve::InQuad ); - arrowAnimation->setDirection( QAbstractAnimation::Forward ); + arrowAnimation->setEasingCurve(QEasingCurve::InQuad); + arrowAnimation->setDirection(QAbstractAnimation::Forward); arrowAnimation->start(); - } +} void DesktopChangeItem::hideArrow() - { +{ m_fadeInArrow = false; QPropertyAnimation *arrowAnimation = m_arrowAnimation.data(); - if( arrowAnimation ) - { - arrowAnimation->setEasingCurve( QEasingCurve::OutQuad ); - arrowAnimation->setDirection( QAbstractAnimation::Backward ); - arrowAnimation->start( QAbstractAnimation::DeleteWhenStopped ); + if (arrowAnimation) { + arrowAnimation->setEasingCurve(QEasingCurve::OutQuad); + arrowAnimation->setDirection(QAbstractAnimation::Backward); + arrowAnimation->start(QAbstractAnimation::DeleteWhenStopped); - connect( arrowAnimation, SIGNAL(finished()), this, SLOT(arrowAnimationFinished()) ); - } + connect(arrowAnimation, SIGNAL(finished()), this, SLOT(arrowAnimationFinished())); } +} -void DesktopChangeItem::startDesktopHighLightAnimation( int time ) - { +void DesktopChangeItem::startDesktopHighLightAnimation(int time) +{ QPropertyAnimation *highLightAnimation = m_highLightAnimation.data(); - if( !highLightAnimation ) - { - highLightAnimation = new QPropertyAnimation( this, "highLightValue" ); - highLightAnimation->setDuration( time ); - highLightAnimation->setStartValue( 0.0 ); - highLightAnimation->setEndValue( 1.0 ); + if (!highLightAnimation) { + highLightAnimation = new QPropertyAnimation(this, "highLightValue"); + highLightAnimation->setDuration(time); + highLightAnimation->setStartValue(0.0); + highLightAnimation->setEndValue(1.0); m_highLightAnimation = highLightAnimation; - } + } m_fadeInHighLight = true; - highLightAnimation->setEasingCurve( QEasingCurve::InQuad ); - highLightAnimation->setDirection( QAbstractAnimation::Forward ); + highLightAnimation->setEasingCurve(QEasingCurve::InQuad); + highLightAnimation->setDirection(QAbstractAnimation::Forward); highLightAnimation->start(); - } +} void DesktopChangeItem::stopDesktopHighLightAnimation() - { +{ m_fadeInHighLight = false; QPropertyAnimation *highLightAnimation = m_highLightAnimation.data(); - if(highLightAnimation) - { - highLightAnimation->setEasingCurve( QEasingCurve::OutQuad ); - highLightAnimation->setDirection( QAbstractAnimation::Backward ); - highLightAnimation->start( QAbstractAnimation::DeleteWhenStopped ); - } + if (highLightAnimation) { + highLightAnimation->setEasingCurve(QEasingCurve::OutQuad); + highLightAnimation->setDirection(QAbstractAnimation::Backward); + highLightAnimation->start(QAbstractAnimation::DeleteWhenStopped); } +} void DesktopChangeItem::arrowAnimationFinished() - { - if( !m_fadeInArrow ) +{ + if (!m_fadeInArrow) m_arrowShown = false; +} + +void DesktopChangeItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* , QWidget*) +{ + if (m_wspace->currentDesktop() == m_desktop || (!m_highLightAnimation.isNull() && + m_highLightAnimation.data()->state() == QAbstractAnimation::Running)) { + qreal left, top, right, bottom; + m_parent->itemFrame()->getMargins(left, top, right, bottom); + if (!m_highLightAnimation.isNull() && + m_highLightAnimation.data()->state() == QAbstractAnimation::Running) { + // there is an animation - so we use transition from normal to active or vice versa + if (m_fadeInHighLight) { + m_parent->itemFrame()->setElementPrefix("normal"); + QPixmap normal = m_parent->itemFrame()->framePixmap(); + m_parent->itemFrame()->setElementPrefix("hover"); + QPixmap result = Plasma::PaintUtils::transition(normal, + m_parent->itemFrame()->framePixmap(), m_highLightValue); + painter->drawPixmap(boundingRect().toRect(), result); + } else { + m_parent->itemFrame()->setElementPrefix("hover"); + QPixmap normal = m_parent->itemFrame()->framePixmap(); + m_parent->itemFrame()->setElementPrefix("normal"); + QPixmap result = Plasma::PaintUtils::transition(normal, + m_parent->itemFrame()->framePixmap(), 1.0 - m_highLightValue); + painter->drawPixmap(boundingRect().toRect(), result); + } + } else { + // no animation - just render the active frame + m_parent->itemFrame()->setElementPrefix("hover"); + m_parent->itemFrame()->paintFrame(painter, boundingRect()); + } + QColor rectColor = Plasma::Theme::defaultTheme()->color(Plasma::Theme::TextColor); + rectColor.setAlphaF(0.6 * m_highLightValue); + QBrush rectBrush = QBrush(rectColor); + painter->fillRect(boundingRect().adjusted(left, top, -right, -bottom), rectBrush); + } else { + m_parent->itemFrame()->setElementPrefix("normal"); + m_parent->itemFrame()->paintFrame(painter, boundingRect()); } -void DesktopChangeItem::paint( QPainter* painter, const QStyleOptionGraphicsItem* , QWidget* ) - { - if( m_wspace->currentDesktop() == m_desktop || (!m_highLightAnimation.isNull() && - m_highLightAnimation.data()->state() == QAbstractAnimation::Running) ) - { - qreal left, top, right, bottom; - m_parent->itemFrame()->getMargins( left, top, right, bottom ); - if( !m_highLightAnimation.isNull() && - m_highLightAnimation.data()->state() == QAbstractAnimation::Running ) - { - // there is an animation - so we use transition from normal to active or vice versa - if( m_fadeInHighLight ) - { - m_parent->itemFrame()->setElementPrefix( "normal" ); - QPixmap normal = m_parent->itemFrame()->framePixmap(); - m_parent->itemFrame()->setElementPrefix( "hover" ); - QPixmap result = Plasma::PaintUtils::transition( normal, - m_parent->itemFrame()->framePixmap(), m_highLightValue ); - painter->drawPixmap( boundingRect().toRect(), result); - } - else - { - m_parent->itemFrame()->setElementPrefix( "hover" ); - QPixmap normal = m_parent->itemFrame()->framePixmap(); - m_parent->itemFrame()->setElementPrefix( "normal" ); - QPixmap result = Plasma::PaintUtils::transition( normal, - m_parent->itemFrame()->framePixmap(), 1.0 - m_highLightValue ); - painter->drawPixmap( boundingRect().toRect(), result); - } - } - else - { - // no animation - just render the active frame - m_parent->itemFrame()->setElementPrefix( "hover" ); - m_parent->itemFrame()->paintFrame( painter, boundingRect() ); - } - QColor rectColor = Plasma::Theme::defaultTheme()->color( Plasma::Theme::TextColor ); - rectColor.setAlphaF( 0.6 * m_highLightValue ); - QBrush rectBrush = QBrush( rectColor ); - painter->fillRect( boundingRect().adjusted( left, top, -right, -bottom ), rectBrush ); - } - else - { - m_parent->itemFrame()->setElementPrefix( "normal" ); - m_parent->itemFrame()->paintFrame( painter, boundingRect() ); - } - - if( !m_arrowShown ) + if (!m_arrowShown) return; // paint the arrow QPixmap icon; int iconWidth = 32; - qreal maxsize = qMin( boundingRect().width(), boundingRect().height() ); - if( maxsize > 128.0 ) + qreal maxsize = qMin(boundingRect().width(), boundingRect().height()); + if (maxsize > 128.0) iconWidth = 128; - else if( maxsize > 64.0 ) + else if (maxsize > 64.0) iconWidth = 64.0; - else if( maxsize > 32.0 ) + else if (maxsize > 32.0) iconWidth = 32.0; else iconWidth = 16.0; - QRect iconRect = QRect( boundingRect().x() + boundingRect().width()/2 - iconWidth/2, - boundingRect().y() + boundingRect().height()/2 - iconWidth/2, - iconWidth, iconWidth ); - switch( m_arrow ) - { - case UP: - icon = KIconLoader::global()->loadIcon( "go-up", KIconLoader::Desktop, iconWidth ); - break; - case DOWN: - icon = KIconLoader::global()->loadIcon( "go-down", KIconLoader::Desktop, iconWidth ); - break; - case LEFT: - icon = KIconLoader::global()->loadIcon( "go-previous", KIconLoader::Desktop, iconWidth ); - break; - case RIGHT: - icon = KIconLoader::global()->loadIcon( "go-next", KIconLoader::Desktop, iconWidth ); - break; - default: - break; - } - if( m_arrow != NONE ) - { - if( !m_arrowAnimation.isNull() && + QRect iconRect = QRect(boundingRect().x() + boundingRect().width() / 2 - iconWidth / 2, + boundingRect().y() + boundingRect().height() / 2 - iconWidth / 2, + iconWidth, iconWidth); + switch(m_arrow) { + case UP: + icon = KIconLoader::global()->loadIcon("go-up", KIconLoader::Desktop, iconWidth); + break; + case DOWN: + icon = KIconLoader::global()->loadIcon("go-down", KIconLoader::Desktop, iconWidth); + break; + case LEFT: + icon = KIconLoader::global()->loadIcon("go-previous", KIconLoader::Desktop, iconWidth); + break; + case RIGHT: + icon = KIconLoader::global()->loadIcon("go-next", KIconLoader::Desktop, iconWidth); + break; + default: + break; + } + if (m_arrow != NONE) { + if (!m_arrowAnimation.isNull() && m_arrowAnimation.data()->state() == QAbstractAnimation::Running && - !qFuzzyCompare(m_arrowValue, qreal(1.0)) ) - { - QPixmap temp( icon.size() ); - temp.fill( Qt::transparent ); + !qFuzzyCompare(m_arrowValue, qreal(1.0))) { + QPixmap temp(icon.size()); + temp.fill(Qt::transparent); - QPainter p( &temp ); - p.setCompositionMode( QPainter::CompositionMode_Source ); - p.drawPixmap( 0, 0, icon ); - p.setCompositionMode( QPainter::CompositionMode_DestinationIn ); - p.fillRect( temp.rect(), QColor( 0, 0, 0, 255*m_arrowValue ) ); + QPainter p(&temp); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.drawPixmap(0, 0, icon); + p.setCompositionMode(QPainter::CompositionMode_DestinationIn); + p.fillRect(temp.rect(), QColor(0, 0, 0, 255 * m_arrowValue)); p.end(); icon = temp; - } - painter->drawPixmap( iconRect, icon ); } + painter->drawPixmap(iconRect, icon); } } +} #include "desktopchangeosd.moc" diff --git a/desktopchangeosd.h b/desktopchangeosd.h index 6d8885c6b..270bb8285 100644 --- a/desktopchangeosd.h +++ b/desktopchangeosd.h @@ -37,120 +37,137 @@ namespace KWin class Workspace; class DesktopChangeText : public QGraphicsItem - { - public: - DesktopChangeText( Workspace* ws ); - ~DesktopChangeText(); +{ +public: + DesktopChangeText(Workspace* ws); + ~DesktopChangeText(); - enum { Type = UserType + 2 }; + enum { Type = UserType + 2 }; - inline void setWidth( float width ) { m_width = width;}; - inline void setHeight( float height ) { m_height = height;}; - - virtual QRectF boundingRect() const; - virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem*, QWidget* ); - inline virtual int type() const { return Type; }; - - private: - Workspace* m_wspace; - float m_width; - float m_height; + inline void setWidth(float width) { + m_width = width; }; + inline void setHeight(float height) { + m_height = height; + }; + + virtual QRectF boundingRect() const; + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); + inline virtual int type() const { + return Type; + }; + +private: + Workspace* m_wspace; + float m_width; + float m_height; +}; class DesktopChangeOSD : public QGraphicsView - { - public: - DesktopChangeOSD( Workspace* ws ); - ~DesktopChangeOSD(); +{ +public: + DesktopChangeOSD(Workspace* ws); + ~DesktopChangeOSD(); - void reconfigure(); - void desktopChanged( int old ); - void numberDesktopsChanged(); + void reconfigure(); + void desktopChanged(int old); + void numberDesktopsChanged(); - inline Plasma::FrameSvg* itemFrame() { return &m_item_frame;}; - inline int& getDelayTime() { return m_delayTime; }; - - protected: - virtual void hideEvent( QHideEvent* ); - virtual void drawBackground( QPainter* painter, const QRectF& rect ); - - private: - void resize(); - Workspace* m_wspace; - Plasma::FrameSvg m_frame; - Plasma::FrameSvg m_item_frame; - QGraphicsScene* m_scene; - bool m_active; - QTimer m_delayedHideTimer; - bool m_show; - int m_delayTime; - bool m_textOnly; + inline Plasma::FrameSvg* itemFrame() { + return &m_item_frame; }; + inline int& getDelayTime() { + return m_delayTime; + }; + +protected: + virtual void hideEvent(QHideEvent*); + virtual void drawBackground(QPainter* painter, const QRectF& rect); + +private: + void resize(); + Workspace* m_wspace; + Plasma::FrameSvg m_frame; + Plasma::FrameSvg m_item_frame; + QGraphicsScene* m_scene; + bool m_active; + QTimer m_delayedHideTimer; + bool m_show; + int m_delayTime; + bool m_textOnly; +}; class DesktopChangeItem : public QObject, public QGraphicsItem - { +{ Q_OBJECT - Q_PROPERTY( qreal arrowValue READ arrowValue WRITE setArrowValue ) - Q_PROPERTY( qreal highLightValue READ highLightValue WRITE setHighLightValue ) + Q_PROPERTY(qreal arrowValue READ arrowValue WRITE setArrowValue) + Q_PROPERTY(qreal highLightValue READ highLightValue WRITE setHighLightValue) Q_INTERFACES(QGraphicsItem) - public: - DesktopChangeItem( Workspace* ws, DesktopChangeOSD* parent, int desktop ); - ~DesktopChangeItem(); - enum { Type = UserType + 1 }; - void startDesktopHighLightAnimation( int time ); - void stopDesktopHighLightAnimation(); +public: + DesktopChangeItem(Workspace* ws, DesktopChangeOSD* parent, int desktop); + ~DesktopChangeItem(); + enum { Type = UserType + 1 }; + void startDesktopHighLightAnimation(int time); + void stopDesktopHighLightAnimation(); - inline void setWidth( float width ) { m_width = width;}; - inline void setHeight( float height ) { m_height = height;}; - inline int desktop() const { return m_desktop; }; - - virtual QRectF boundingRect() const; - virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem*, QWidget* ); - inline virtual int type() const { return Type; }; - - enum Arrow - { - NONE, - LEFT, - RIGHT, - UP, - DOWN - }; - void setArrow( Arrow arrow, int start_delay, int hide_delay ); - - qreal arrowValue() const; - qreal highLightValue() const; - - protected slots: - void setArrowValue( qreal value ); - void setHighLightValue( qreal value ); - - private slots: - void showArrow(); - void hideArrow(); - void arrowAnimationFinished(); - - private: - Workspace* m_wspace; - DesktopChangeOSD* m_parent; - int m_desktop; - float m_width; - float m_height; - QTimer m_delayed_show_arrow_timer; - QTimer m_delayed_hide_arrow_timer; - - Arrow m_arrow; - bool m_arrowShown; - bool m_fadeInArrow; - bool m_fadeInHighLight; - - qreal m_arrowValue; - qreal m_highLightValue; - - QWeakPointer m_arrowAnimation; - QWeakPointer m_highLightAnimation; + inline void setWidth(float width) { + m_width = width; }; + inline void setHeight(float height) { + m_height = height; + }; + inline int desktop() const { + return m_desktop; + }; + + virtual QRectF boundingRect() const; + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*); + inline virtual int type() const { + return Type; + }; + + enum Arrow { + NONE, + LEFT, + RIGHT, + UP, + DOWN + }; + void setArrow(Arrow arrow, int start_delay, int hide_delay); + + qreal arrowValue() const; + qreal highLightValue() const; + +protected slots: + void setArrowValue(qreal value); + void setHighLightValue(qreal value); + +private slots: + void showArrow(); + void hideArrow(); + void arrowAnimationFinished(); + +private: + Workspace* m_wspace; + DesktopChangeOSD* m_parent; + int m_desktop; + float m_width; + float m_height; + QTimer m_delayed_show_arrow_timer; + QTimer m_delayed_hide_arrow_timer; + + Arrow m_arrow; + bool m_arrowShown; + bool m_fadeInArrow; + bool m_fadeInHighLight; + + qreal m_arrowValue; + qreal m_highLightValue; + + QWeakPointer m_arrowAnimation; + QWeakPointer m_highLightAnimation; +}; } diff --git a/desktoplayout.cpp b/desktoplayout.cpp index ef8704350..af29df789 100644 --- a/desktoplayout.cpp +++ b/desktoplayout.cpp @@ -26,169 +26,162 @@ namespace KWin { void Workspace::updateDesktopLayout() - { +{ // TODO: Is there a sane way to avoid overriding the existing grid? int width = rootInfo->desktopLayoutColumnsRows().width(); int height = rootInfo->desktopLayoutColumnsRows().height(); - if( width == 0 && height == 0 ) // Not given, set default layout + if (width == 0 && height == 0) // Not given, set default layout height = 2; setNETDesktopLayout( rootInfo->desktopLayoutOrientation() == NET::OrientationHorizontal ? Qt::Horizontal : Qt::Vertical, width, height, 0 //rootInfo->desktopLayoutCorner() // Not really worth implementing right now. - ); - } + ); +} -void Workspace::setNETDesktopLayout( Qt::Orientation orientation, int width, int height, - int startingCorner ) - { - Q_UNUSED( startingCorner ); // Not really worth implementing right now. +void Workspace::setNETDesktopLayout(Qt::Orientation orientation, int width, int height, + int startingCorner) +{ + Q_UNUSED(startingCorner); // Not really worth implementing right now. // Calculate valid grid size - assert( width > 0 || height > 0 ); - if(( width <= 0 ) && ( height > 0 )) - width = ( desktopCount_ + height - 1 ) / height; - else if(( height <= 0 ) && ( width > 0 )) - height = ( desktopCount_ + width - 1 ) / width; - while( width * height < desktopCount_ ) - { - if( orientation == Qt::Horizontal ) + assert(width > 0 || height > 0); + if ((width <= 0) && (height > 0)) + width = (desktopCount_ + height - 1) / height; + else if ((height <= 0) && (width > 0)) + height = (desktopCount_ + width - 1) / width; + while (width * height < desktopCount_) { + if (orientation == Qt::Horizontal) ++width; else ++height; - } + } // Set private variables delete[] desktopGrid_; - desktopGridSize_ = QSize( width, height ); + desktopGridSize_ = QSize(width, height); int size = width * height; desktopGrid_ = new int[size]; // Populate grid int desktop = 1; - if( orientation == Qt::Horizontal ) - for( int y = 0; y < height; y++ ) - for( int x = 0; x < width; x++ ) + if (orientation == Qt::Horizontal) + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) desktopGrid_[y * width + x] = (desktop <= desktopCount_ ? desktop++ : 0); else - for( int x = 0; x < width; x++ ) - for( int y = 0; y < height; y++ ) + for (int x = 0; x < width; x++) + for (int y = 0; y < height; y++) desktopGrid_[y * width + x] = (desktop <= desktopCount_ ? desktop++ : 0); - } +} -QPoint Workspace::desktopGridCoords( int id ) const - { - for( int y = 0; y < desktopGridSize_.height(); y++ ) - for( int x = 0; x < desktopGridSize_.width(); x++ ) - if( desktopGrid_[y * desktopGridSize_.width() + x] == id ) - return QPoint( x, y ); - return QPoint( -1, -1 ); - } +QPoint Workspace::desktopGridCoords(int id) const +{ + for (int y = 0; y < desktopGridSize_.height(); y++) + for (int x = 0; x < desktopGridSize_.width(); x++) + if (desktopGrid_[y * desktopGridSize_.width() + x] == id) + return QPoint(x, y); + return QPoint(-1, -1); +} -QPoint Workspace::desktopCoords( int id ) const - { - QPoint coords = desktopGridCoords( id ); - if( coords.x() == -1 ) - return QPoint( -1, -1 ); - return QPoint( coords.x() * displayWidth(), coords.y() * displayHeight() ); - } +QPoint Workspace::desktopCoords(int id) const +{ + QPoint coords = desktopGridCoords(id); + if (coords.x() == -1) + return QPoint(-1, -1); + return QPoint(coords.x() * displayWidth(), coords.y() * displayHeight()); +} -int Workspace::desktopAbove( int id, bool wrap ) const - { - if( id == 0 ) +int Workspace::desktopAbove(int id, bool wrap) const +{ + if (id == 0) id = currentDesktop(); - QPoint coords = desktopGridCoords( id ); - assert( coords.x() >= 0 ); - for(;;) - { + QPoint coords = desktopGridCoords(id); + assert(coords.x() >= 0); + for (;;) { coords.ry()--; - if( coords.y() < 0 ) - { - if( wrap ) - coords.setY( desktopGridSize_.height() - 1 ); + if (coords.y() < 0) { + if (wrap) + coords.setY(desktopGridSize_.height() - 1); else return id; // Already at the top-most desktop - } - int desktop = desktopAtCoords( coords ); - if( desktop > 0 ) - return desktop; } + int desktop = desktopAtCoords(coords); + if (desktop > 0) + return desktop; } +} -int Workspace::desktopToRight( int id, bool wrap ) const - { - if( id == 0 ) +int Workspace::desktopToRight(int id, bool wrap) const +{ + if (id == 0) id = currentDesktop(); - QPoint coords = desktopGridCoords( id ); - assert( coords.x() >= 0 ); - for(;;) - { + QPoint coords = desktopGridCoords(id); + assert(coords.x() >= 0); + for (;;) { coords.rx()++; - if( coords.x() >= desktopGridSize_.width() ) - { - if( wrap ) - coords.setX( 0 ); + if (coords.x() >= desktopGridSize_.width()) { + if (wrap) + coords.setX(0); else return id; // Already at the right-most desktop - } - int desktop = desktopAtCoords( coords ); - if( desktop > 0 ) - return desktop; } + int desktop = desktopAtCoords(coords); + if (desktop > 0) + return desktop; } +} -int Workspace::desktopBelow( int id, bool wrap ) const - { - if( id == 0 ) +int Workspace::desktopBelow(int id, bool wrap) const +{ + if (id == 0) id = currentDesktop(); - QPoint coords = desktopGridCoords( id ); - assert( coords.x() >= 0 ); - for(;;) - { + QPoint coords = desktopGridCoords(id); + assert(coords.x() >= 0); + for (;;) { coords.ry()++; - if( coords.y() >= desktopGridSize_.height() ) - { - if( wrap ) - coords.setY( 0 ); + if (coords.y() >= desktopGridSize_.height()) { + if (wrap) + coords.setY(0); else return id; // Already at the bottom-most desktop - } - int desktop = desktopAtCoords( coords ); - if( desktop > 0 ) - return desktop; } + int desktop = desktopAtCoords(coords); + if (desktop > 0) + return desktop; } +} -int Workspace::desktopToLeft( int id, bool wrap ) const - { - if( id == 0 ) +int Workspace::desktopToLeft(int id, bool wrap) const +{ + if (id == 0) id = currentDesktop(); - QPoint coords = desktopGridCoords( id ); - assert( coords.x() >= 0 ); - for(;;) - { + QPoint coords = desktopGridCoords(id); + assert(coords.x() >= 0); + for (;;) { coords.rx()--; - if( coords.x() < 0 ) - { - if( wrap ) - coords.setX( desktopGridSize_.width() - 1 ); + if (coords.x() < 0) { + if (wrap) + coords.setX(desktopGridSize_.width() - 1); else return id; // Already at the left-most desktop - } - int desktop = desktopAtCoords( coords ); - if( desktop > 0 ) - return desktop; } + int desktop = desktopAtCoords(coords); + if (desktop > 0) + return desktop; } +} -int Workspace::addDesktop( QPoint coords ) - { // TODO - Q_UNUSED( coords ); +int Workspace::addDesktop(QPoint coords) +{ + // TODO + Q_UNUSED(coords); return 0; - } +} -void Workspace::deleteDesktop( int id ) - { // TODO - Q_UNUSED( id ); - } +void Workspace::deleteDesktop(int id) +{ + // TODO + Q_UNUSED(id); +} } // namespace diff --git a/effects.cpp b/effects.cpp index cad8b7ae4..4ff8e9baf 100644 --- a/effects.cpp +++ b/effects.cpp @@ -49,724 +49,698 @@ namespace KWin //--------------------- // Static -static QByteArray readWindowProperty( Window win, long atom, long type, int format ) - { +static QByteArray readWindowProperty(Window win, long atom, long type, int format) +{ int len = 32768; - for(;;) - { + for (;;) { unsigned char* data; Atom rtype; int rformat; unsigned long nitems, after; - if( XGetWindowProperty( QX11Info::display(), win, - atom, 0, len, False, AnyPropertyType, - &rtype, &rformat, &nitems, &after, &data ) == Success ) - { - if( after > 0 ) - { - XFree( data ); + if (XGetWindowProperty(QX11Info::display(), win, + atom, 0, len, False, AnyPropertyType, + &rtype, &rformat, &nitems, &after, &data) == Success) { + if (after > 0) { + XFree(data); len *= 2; continue; - } - if( long( rtype ) == type && rformat == format ) - { - int bytelen = format == 8 ? nitems : format == 16 ? nitems * sizeof( short ) : nitems * sizeof( long ); - QByteArray ret( reinterpret_cast< const char* >( data ), bytelen ); - XFree( data ); - return ret; - } - else // wrong format, type or something - { - XFree( data ); - return QByteArray(); - } } - else // XGetWindowProperty() failed + if (long(rtype) == type && rformat == format) { + int bytelen = format == 8 ? nitems : format == 16 ? nitems * sizeof(short) : nitems * sizeof(long); + QByteArray ret(reinterpret_cast< const char* >(data), bytelen); + XFree(data); + return ret; + } else { // wrong format, type or something + XFree(data); + return QByteArray(); + } + } else // XGetWindowProperty() failed return QByteArray(); - } } +} -static void deleteWindowProperty( Window win, long int atom ) - { - XDeleteProperty( QX11Info::display(), win, atom ); - } +static void deleteWindowProperty(Window win, long int atom) +{ + XDeleteProperty(QX11Info::display(), win, atom); +} //--------------------- EffectsHandlerImpl::EffectsHandlerImpl(CompositingType type) : EffectsHandler(type) - , keyboard_grab_effect( NULL ) - , fullscreen_effect( 0 ) - , next_window_quad_type( EFFECT_QUAD_TYPE_START ) - , mouse_poll_ref_count( 0 ) - , current_paint_effectframe( 0 ) - { + , keyboard_grab_effect(NULL) + , fullscreen_effect(0) + , next_window_quad_type(EFFECT_QUAD_TYPE_START) + , mouse_poll_ref_count(0) + , current_paint_effectframe(0) +{ reconfigure(); - } +} EffectsHandlerImpl::~EffectsHandlerImpl() - { - if( keyboard_grab_effect != NULL ) +{ + if (keyboard_grab_effect != NULL) ungrabKeyboard(); - foreach( const EffectPair &ep, loaded_effects ) - unloadEffect( ep.first ); - foreach( const InputWindowPair &pos, input_windows ) - XDestroyWindow( display(), pos.second ); - } + foreach (const EffectPair & ep, loaded_effects) + unloadEffect(ep.first); + foreach (const InputWindowPair & pos, input_windows) + XDestroyWindow(display(), pos.second); +} void EffectsHandlerImpl::reconfigure() - { +{ KSharedConfig::Ptr _config = KGlobal::config(); KConfigGroup conf(_config, "Plugins"); KService::List offers = KServiceTypeTrader::self()->query("KWin/Effect"); QStringList effectsToBeLoaded; // First unload necessary effects - foreach( const KService::Ptr &service, offers ) - { - KPluginInfo plugininfo( service ); - plugininfo.load( conf ); + foreach (const KService::Ptr & service, offers) { + KPluginInfo plugininfo(service); + plugininfo.load(conf); - bool isloaded = isEffectLoaded( plugininfo.pluginName() ); + bool isloaded = isEffectLoaded(plugininfo.pluginName()); bool shouldbeloaded = plugininfo.isPluginEnabled(); - if( !shouldbeloaded && isloaded ) - unloadEffect( plugininfo.pluginName() ); - if( shouldbeloaded ) - effectsToBeLoaded.append( plugininfo.pluginName() ); - } + if (!shouldbeloaded && isloaded) + unloadEffect(plugininfo.pluginName()); + if (shouldbeloaded) + effectsToBeLoaded.append(plugininfo.pluginName()); + } QStringList newLoaded; // Then load those that should be loaded - foreach( const QString &effectName, effectsToBeLoaded ) - { - if( !isEffectLoaded( effectName )) - { - loadEffect( effectName ); - newLoaded.append( effectName ); - } - } - foreach( const EffectPair &ep, loaded_effects ) - { - if( !newLoaded.contains( ep.first )) // don't reconfigure newly loaded effects - ep.second->reconfigure( Effect::ReconfigureAll ); + foreach (const QString & effectName, effectsToBeLoaded) { + if (!isEffectLoaded(effectName)) { + loadEffect(effectName); + newLoaded.append(effectName); } } + foreach (const EffectPair & ep, loaded_effects) { + if (!newLoaded.contains(ep.first)) // don't reconfigure newly loaded effects + ep.second->reconfigure(Effect::ReconfigureAll); + } +} // the idea is that effects call this function again which calls the next one -void EffectsHandlerImpl::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( current_paint_screen < loaded_effects.size()) - { - loaded_effects[current_paint_screen++].second->prePaintScreen( data, time ); +void EffectsHandlerImpl::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (current_paint_screen < loaded_effects.size()) { + loaded_effects[current_paint_screen++].second->prePaintScreen(data, time); --current_paint_screen; - } + } // no special final code - } +} -void EffectsHandlerImpl::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( current_paint_screen < loaded_effects.size()) - { - loaded_effects[current_paint_screen++].second->paintScreen( mask, region, data ); +void EffectsHandlerImpl::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (current_paint_screen < loaded_effects.size()) { + loaded_effects[current_paint_screen++].second->paintScreen(mask, region, data); --current_paint_screen; - } - else - scene->finalPaintScreen( mask, region, data ); - } + } else + scene->finalPaintScreen(mask, region, data); +} void EffectsHandlerImpl::postPaintScreen() - { - if( current_paint_screen < loaded_effects.size()) - { +{ + if (current_paint_screen < loaded_effects.size()) { loaded_effects[current_paint_screen++].second->postPaintScreen(); --current_paint_screen; - } + } // no special final code - } +} -void EffectsHandlerImpl::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( current_paint_window < loaded_effects.size()) - { - loaded_effects[current_paint_window++].second->prePaintWindow( w, data, time ); +void EffectsHandlerImpl::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (current_paint_window < loaded_effects.size()) { + loaded_effects[current_paint_window++].second->prePaintWindow(w, data, time); --current_paint_window; - } + } // no special final code - } +} -void EffectsHandlerImpl::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( current_paint_window < loaded_effects.size()) - { - loaded_effects[current_paint_window++].second->paintWindow( w, mask, region, data ); +void EffectsHandlerImpl::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (current_paint_window < loaded_effects.size()) { + loaded_effects[current_paint_window++].second->paintWindow(w, mask, region, data); --current_paint_window; - } - else - scene->finalPaintWindow( static_cast( w ), mask, region, data ); - } + } else + scene->finalPaintWindow(static_cast(w), mask, region, data); +} -void EffectsHandlerImpl::paintEffectFrame( EffectFrame* frame, QRegion region, double opacity, double frameOpacity ) - { - if( current_paint_effectframe < loaded_effects.size()) - { - loaded_effects[current_paint_effectframe++].second->paintEffectFrame( frame, region, opacity, frameOpacity ); +void EffectsHandlerImpl::paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) +{ + if (current_paint_effectframe < loaded_effects.size()) { + loaded_effects[current_paint_effectframe++].second->paintEffectFrame(frame, region, opacity, frameOpacity); --current_paint_effectframe; - } - else - { - const EffectFrameImpl* frameImpl = static_cast( frame ); - frameImpl->finalRender( region, opacity, frameOpacity ); - } + } else { + const EffectFrameImpl* frameImpl = static_cast(frame); + frameImpl->finalRender(region, opacity, frameOpacity); } +} -void EffectsHandlerImpl::postPaintWindow( EffectWindow* w ) - { - if( current_paint_window < loaded_effects.size()) - { - loaded_effects[current_paint_window++].second->postPaintWindow( w ); +void EffectsHandlerImpl::postPaintWindow(EffectWindow* w) +{ + if (current_paint_window < loaded_effects.size()) { + loaded_effects[current_paint_window++].second->postPaintWindow(w); --current_paint_window; - } - // no special final code } + // no special final code +} -bool EffectsHandlerImpl::provides( Effect::Feature ef ) - { - for( int i = 0; i < loaded_effects.size(); ++i ) - if( loaded_effects.at(i).second->provides( ef ) ) +bool EffectsHandlerImpl::provides(Effect::Feature ef) +{ + for (int i = 0; i < loaded_effects.size(); ++i) + if (loaded_effects.at(i).second->provides(ef)) return true; return false; - } +} -void EffectsHandlerImpl::drawWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( current_draw_window < loaded_effects.size()) - { - loaded_effects[current_draw_window++].second->drawWindow( w, mask, region, data ); +void EffectsHandlerImpl::drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (current_draw_window < loaded_effects.size()) { + loaded_effects[current_draw_window++].second->drawWindow(w, mask, region, data); --current_draw_window; - } - else - scene->finalDrawWindow( static_cast( w ), mask, region, data ); - } + } else + scene->finalDrawWindow(static_cast(w), mask, region, data); +} -void EffectsHandlerImpl::buildQuads( EffectWindow* w, WindowQuadList& quadList ) - { - if( current_build_quads < loaded_effects.size()) - { - loaded_effects[current_build_quads++].second->buildQuads( w, quadList ); +void EffectsHandlerImpl::buildQuads(EffectWindow* w, WindowQuadList& quadList) +{ + if (current_build_quads < loaded_effects.size()) { + loaded_effects[current_build_quads++].second->buildQuads(w, quadList); --current_build_quads; - } } +} bool EffectsHandlerImpl::hasDecorationShadows() const - { +{ return Workspace::self()->hasDecorationShadows(); - } +} bool EffectsHandlerImpl::decorationsHaveAlpha() const - { +{ return Workspace::self()->decorationHasAlpha(); - } +} bool EffectsHandlerImpl::decorationSupportsBlurBehind() const - { +{ return Workspace::self()->decorationSupportsBlurBehind(); - } +} // start another painting pass void EffectsHandlerImpl::startPaint() - { - assert( current_paint_screen == 0 ); - assert( current_paint_window == 0 ); - assert( current_draw_window == 0 ); - assert( current_build_quads == 0 ); - assert( current_transform == 0 ); - } +{ + assert(current_paint_screen == 0); + assert(current_paint_window == 0); + assert(current_draw_window == 0); + assert(current_build_quads == 0); + assert(current_transform == 0); +} -void EffectsHandlerImpl::windowUserMovedResized( EffectWindow* c, bool first, bool last ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowUserMovedResized( c, first, last ); - } +void EffectsHandlerImpl::windowUserMovedResized(EffectWindow* c, bool first, bool last) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowUserMovedResized(c, first, last); +} -void EffectsHandlerImpl::windowMoveResizeGeometryUpdate( EffectWindow* c, const QRect& geometry ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowMoveResizeGeometryUpdate( c, geometry ); - } +void EffectsHandlerImpl::windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowMoveResizeGeometryUpdate(c, geometry); +} -void EffectsHandlerImpl::windowOpacityChanged( EffectWindow* c, double old_opacity ) - { - if (!c) - return; - if( static_cast(c)->window()->opacity() == old_opacity ) +void EffectsHandlerImpl::windowOpacityChanged(EffectWindow* c, double old_opacity) +{ + if (!c) return; - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowOpacityChanged( c, old_opacity ); - } - -void EffectsHandlerImpl::windowAdded( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowAdded( c ); - } - -void EffectsHandlerImpl::windowDeleted( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowDeleted( c ); - elevated_windows.removeAll( c ); - } - -void EffectsHandlerImpl::windowClosed( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowClosed( c ); - } - -void EffectsHandlerImpl::windowActivated( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowActivated( c ); - } - -void EffectsHandlerImpl::windowMinimized( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowMinimized( c ); - } - -void EffectsHandlerImpl::windowUnminimized( EffectWindow* c ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowUnminimized( c ); - } - -void EffectsHandlerImpl::clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->clientGroupItemSwitched( from, to ); - } - -void EffectsHandlerImpl::clientGroupItemAdded( EffectWindow* from, EffectWindow* to ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->clientGroupItemAdded( from, to ); - } - -void EffectsHandlerImpl::clientGroupItemRemoved( EffectWindow* c, EffectWindow* group ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->clientGroupItemRemoved( c, group ); - } - -void EffectsHandlerImpl::desktopChanged( int old ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->desktopChanged( old ); - } - -void EffectsHandlerImpl::windowDamaged( EffectWindow* w, const QRect& r ) - { - if( w == NULL ) + if (static_cast(c)->window()->opacity() == old_opacity) return; - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowDamaged( w, r ); - } + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowOpacityChanged(c, old_opacity); +} -void EffectsHandlerImpl::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - if( w == NULL ) // during late cleanup effectWindow() may be already NULL +void EffectsHandlerImpl::windowAdded(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowAdded(c); +} + +void EffectsHandlerImpl::windowDeleted(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowDeleted(c); + elevated_windows.removeAll(c); +} + +void EffectsHandlerImpl::windowClosed(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowClosed(c); +} + +void EffectsHandlerImpl::windowActivated(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowActivated(c); +} + +void EffectsHandlerImpl::windowMinimized(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowMinimized(c); +} + +void EffectsHandlerImpl::windowUnminimized(EffectWindow* c) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowUnminimized(c); +} + +void EffectsHandlerImpl::clientGroupItemSwitched(EffectWindow* from, EffectWindow* to) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->clientGroupItemSwitched(from, to); +} + +void EffectsHandlerImpl::clientGroupItemAdded(EffectWindow* from, EffectWindow* to) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->clientGroupItemAdded(from, to); +} + +void EffectsHandlerImpl::clientGroupItemRemoved(EffectWindow* c, EffectWindow* group) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->clientGroupItemRemoved(c, group); +} + +void EffectsHandlerImpl::desktopChanged(int old) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->desktopChanged(old); +} + +void EffectsHandlerImpl::windowDamaged(EffectWindow* w, const QRect& r) +{ + if (w == NULL) + return; + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowDamaged(w, r); +} + +void EffectsHandlerImpl::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + if (w == NULL) // during late cleanup effectWindow() may be already NULL return; // in some functions that may still call this - foreach( const EffectPair &ep, loaded_effects ) - ep.second->windowGeometryShapeChanged( w, old ); - } + foreach (const EffectPair & ep, loaded_effects) + ep.second->windowGeometryShapeChanged(w, old); +} -void EffectsHandlerImpl::tabBoxAdded( int mode ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->tabBoxAdded( mode ); - } +void EffectsHandlerImpl::tabBoxAdded(int mode) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->tabBoxAdded(mode); +} void EffectsHandlerImpl::tabBoxClosed() - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->tabBoxClosed(); - } +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->tabBoxClosed(); +} void EffectsHandlerImpl::tabBoxUpdated() - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->tabBoxUpdated(); - } +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->tabBoxUpdated(); +} -void EffectsHandlerImpl::tabBoxKeyEvent( QKeyEvent* event ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->tabBoxKeyEvent( event ); - } +void EffectsHandlerImpl::tabBoxKeyEvent(QKeyEvent* event) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->tabBoxKeyEvent(event); +} -void EffectsHandlerImpl::setActiveFullScreenEffect( Effect* e ) - { +void EffectsHandlerImpl::setActiveFullScreenEffect(Effect* e) +{ fullscreen_effect = e; Workspace::self()->checkUnredirect(); - } +} Effect* EffectsHandlerImpl::activeFullScreenEffect() const - { +{ return fullscreen_effect; - } +} -bool EffectsHandlerImpl::borderActivated( ElectricBorder border ) - { +bool EffectsHandlerImpl::borderActivated(ElectricBorder border) +{ bool ret = false; - foreach( const EffectPair &ep, loaded_effects ) - if( ep.second->borderActivated( border )) - ret = true; // bail out or tell all? + foreach (const EffectPair & ep, loaded_effects) + if (ep.second->borderActivated(border)) + ret = true; // bail out or tell all? return ret; - } +} -void EffectsHandlerImpl::mouseChanged( const QPoint& pos, const QPoint& oldpos, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->mouseChanged( pos, oldpos, buttons, oldbuttons, modifiers, oldmodifiers ); - } +void EffectsHandlerImpl::mouseChanged(const QPoint& pos, const QPoint& oldpos, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->mouseChanged(pos, oldpos, buttons, oldbuttons, modifiers, oldmodifiers); +} -bool EffectsHandlerImpl::grabKeyboard( Effect* effect ) - { - if( keyboard_grab_effect != NULL ) +bool EffectsHandlerImpl::grabKeyboard(Effect* effect) +{ + if (keyboard_grab_effect != NULL) return false; bool ret = grabXKeyboard(); - if( !ret ) + if (!ret) return false; keyboard_grab_effect = effect; return true; - } +} void EffectsHandlerImpl::ungrabKeyboard() - { - assert( keyboard_grab_effect != NULL ); +{ + assert(keyboard_grab_effect != NULL); ungrabXKeyboard(); keyboard_grab_effect = NULL; - } +} -void EffectsHandlerImpl::grabbedKeyboardEvent( QKeyEvent* e ) - { - if( keyboard_grab_effect != NULL ) - keyboard_grab_effect->grabbedKeyboardEvent( e ); - } +void EffectsHandlerImpl::grabbedKeyboardEvent(QKeyEvent* e) +{ + if (keyboard_grab_effect != NULL) + keyboard_grab_effect->grabbedKeyboardEvent(e); +} -void* EffectsHandlerImpl::getProxy( QString name ) - { +void* EffectsHandlerImpl::getProxy(QString name) +{ // All effects start with "kwin4_effect_", prepend it to the name - name.prepend( "kwin4_effect_" ); + name.prepend("kwin4_effect_"); - for( QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) - if ( (*it).first == name ) + for (QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) + if ((*it).first == name) return (*it).second->proxy(); return NULL; - } +} void EffectsHandlerImpl::startMousePolling() - { - if( !mouse_poll_ref_count ) // Start timer if required +{ + if (!mouse_poll_ref_count) // Start timer if required Workspace::self()->startMousePolling(); mouse_poll_ref_count++; - } +} void EffectsHandlerImpl::stopMousePolling() - { - assert( mouse_poll_ref_count ); +{ + assert(mouse_poll_ref_count); mouse_poll_ref_count--; - if( !mouse_poll_ref_count ) // Stop timer if required + if (!mouse_poll_ref_count) // Stop timer if required Workspace::self()->stopMousePolling(); - } +} bool EffectsHandlerImpl::hasKeyboardGrab() const - { +{ return keyboard_grab_effect != NULL; - } +} -void EffectsHandlerImpl::propertyNotify( EffectWindow* c, long atom ) - { - if( !registered_atoms.contains( atom )) +void EffectsHandlerImpl::propertyNotify(EffectWindow* c, long atom) +{ + if (!registered_atoms.contains(atom)) return; - foreach( const EffectPair &ep, loaded_effects ) - ep.second->propertyNotify( c, atom ); - } + foreach (const EffectPair & ep, loaded_effects) + ep.second->propertyNotify(c, atom); +} -void EffectsHandlerImpl::numberDesktopsChanged( int old ) - { - foreach( const EffectPair &ep, loaded_effects ) - ep.second->numberDesktopsChanged( old ); - } +void EffectsHandlerImpl::numberDesktopsChanged(int old) +{ + foreach (const EffectPair & ep, loaded_effects) + ep.second->numberDesktopsChanged(old); +} -void EffectsHandlerImpl::registerPropertyType( long atom, bool reg ) - { - if( reg ) +void EffectsHandlerImpl::registerPropertyType(long atom, bool reg) +{ + if (reg) ++registered_atoms[ atom ]; // initialized to 0 if not present yet - else - { - if( --registered_atoms[ atom ] == 0 ) - registered_atoms.remove( atom ); - } + else { + if (--registered_atoms[ atom ] == 0) + registered_atoms.remove(atom); } +} -QByteArray EffectsHandlerImpl::readRootProperty( long atom, long type, int format ) const - { - return readWindowProperty( rootWindow(), atom, type, format ); - } +QByteArray EffectsHandlerImpl::readRootProperty(long atom, long type, int format) const +{ + return readWindowProperty(rootWindow(), atom, type, format); +} -void EffectsHandlerImpl::deleteRootProperty( long atom ) const - { - deleteWindowProperty( rootWindow(), atom ); - } +void EffectsHandlerImpl::deleteRootProperty(long atom) const +{ + deleteWindowProperty(rootWindow(), atom); +} -void EffectsHandlerImpl::activateWindow( EffectWindow* c ) - { - if( Client* cl = dynamic_cast< Client* >( static_cast(c)->window())) - Workspace::self()->activateClient( cl, true ); - } +void EffectsHandlerImpl::activateWindow(EffectWindow* c) +{ + if (Client* cl = dynamic_cast< Client* >(static_cast(c)->window())) + Workspace::self()->activateClient(cl, true); +} EffectWindow* EffectsHandlerImpl::activeWindow() const - { +{ return Workspace::self()->activeClient() ? Workspace::self()->activeClient()->effectWindow() : NULL; - } +} -void EffectsHandlerImpl::moveWindow( EffectWindow* w, const QPoint& pos, bool snap, double snapAdjust ) - { - Client* cl = dynamic_cast< Client* >( static_cast(w)->window()); +void EffectsHandlerImpl::moveWindow(EffectWindow* w, const QPoint& pos, bool snap, double snapAdjust) +{ + Client* cl = dynamic_cast< Client* >(static_cast(w)->window()); if (!cl || !cl->isMovable()) return; if (snap) cl->move(Workspace::self()->adjustClientPosition(cl, pos, true, snapAdjust)); else - cl->move( pos ); - } + cl->move(pos); +} -void EffectsHandlerImpl::windowToDesktop( EffectWindow* w, int desktop ) - { - Client* cl = dynamic_cast< Client* >( static_cast(w)->window()); - if( cl && !cl->isDesktop() && !cl->isDock() && !cl->isTopMenu()) - Workspace::self()->sendClientToDesktop( cl, desktop, true ); - } +void EffectsHandlerImpl::windowToDesktop(EffectWindow* w, int desktop) +{ + Client* cl = dynamic_cast< Client* >(static_cast(w)->window()); + if (cl && !cl->isDesktop() && !cl->isDock() && !cl->isTopMenu()) + Workspace::self()->sendClientToDesktop(cl, desktop, true); +} -void EffectsHandlerImpl::windowToScreen( EffectWindow* w, int screen ) - { - Client* cl = dynamic_cast< Client* >( static_cast(w)->window()); - if( cl && !cl->isDesktop() && !cl->isDock() && !cl->isTopMenu()) - Workspace::self()->sendClientToScreen( cl, screen ); - } +void EffectsHandlerImpl::windowToScreen(EffectWindow* w, int screen) +{ + Client* cl = dynamic_cast< Client* >(static_cast(w)->window()); + if (cl && !cl->isDesktop() && !cl->isDock() && !cl->isTopMenu()) + Workspace::self()->sendClientToScreen(cl, screen); +} -void EffectsHandlerImpl::setShowingDesktop( bool showing ) - { - Workspace::self()->setShowingDesktop( showing ); - } +void EffectsHandlerImpl::setShowingDesktop(bool showing) +{ + Workspace::self()->setShowingDesktop(showing); +} int EffectsHandlerImpl::currentDesktop() const - { +{ return Workspace::self()->currentDesktop(); - } +} int EffectsHandlerImpl::numberOfDesktops() const - { +{ return Workspace::self()->numberOfDesktops(); - } +} -void EffectsHandlerImpl::setCurrentDesktop( int desktop ) - { - Workspace::self()->setCurrentDesktop( desktop ); - } +void EffectsHandlerImpl::setCurrentDesktop(int desktop) +{ + Workspace::self()->setCurrentDesktop(desktop); +} -void EffectsHandlerImpl::setNumberOfDesktops( int desktops ) - { - Workspace::self()->setNumberOfDesktops( desktops ); - } +void EffectsHandlerImpl::setNumberOfDesktops(int desktops) +{ + Workspace::self()->setNumberOfDesktops(desktops); +} QSize EffectsHandlerImpl::desktopGridSize() const - { +{ return Workspace::self()->desktopGridSize(); - } +} int EffectsHandlerImpl::desktopGridWidth() const - { +{ return Workspace::self()->desktopGridWidth(); - } +} int EffectsHandlerImpl::desktopGridHeight() const - { +{ return Workspace::self()->desktopGridHeight(); - } +} int EffectsHandlerImpl::workspaceWidth() const - { +{ return Workspace::self()->workspaceWidth(); - } +} int EffectsHandlerImpl::workspaceHeight() const - { +{ return Workspace::self()->workspaceHeight(); - } +} -int EffectsHandlerImpl::desktopAtCoords( QPoint coords ) const - { - return Workspace::self()->desktopAtCoords( coords ); - } +int EffectsHandlerImpl::desktopAtCoords(QPoint coords) const +{ + return Workspace::self()->desktopAtCoords(coords); +} -QPoint EffectsHandlerImpl::desktopGridCoords( int id ) const - { - return Workspace::self()->desktopGridCoords( id ); - } +QPoint EffectsHandlerImpl::desktopGridCoords(int id) const +{ + return Workspace::self()->desktopGridCoords(id); +} -QPoint EffectsHandlerImpl::desktopCoords( int id ) const - { - return Workspace::self()->desktopCoords( id ); - } +QPoint EffectsHandlerImpl::desktopCoords(int id) const +{ + return Workspace::self()->desktopCoords(id); +} -int EffectsHandlerImpl::desktopAbove( int desktop, bool wrap ) const - { - return Workspace::self()->desktopAbove( desktop, wrap ); - } +int EffectsHandlerImpl::desktopAbove(int desktop, bool wrap) const +{ + return Workspace::self()->desktopAbove(desktop, wrap); +} -int EffectsHandlerImpl::desktopToRight( int desktop, bool wrap ) const - { - return Workspace::self()->desktopToRight( desktop, wrap ); - } +int EffectsHandlerImpl::desktopToRight(int desktop, bool wrap) const +{ + return Workspace::self()->desktopToRight(desktop, wrap); +} -int EffectsHandlerImpl::desktopBelow( int desktop, bool wrap ) const - { - return Workspace::self()->desktopBelow( desktop, wrap ); - } +int EffectsHandlerImpl::desktopBelow(int desktop, bool wrap) const +{ + return Workspace::self()->desktopBelow(desktop, wrap); +} -int EffectsHandlerImpl::desktopToLeft( int desktop, bool wrap ) const - { - return Workspace::self()->desktopToLeft( desktop, wrap ); - } +int EffectsHandlerImpl::desktopToLeft(int desktop, bool wrap) const +{ + return Workspace::self()->desktopToLeft(desktop, wrap); +} bool EffectsHandlerImpl::isDesktopLayoutDynamic() const - { +{ return Workspace::self()->isDesktopLayoutDynamic(); - } +} -int EffectsHandlerImpl::addDesktop( QPoint coords ) - { - return Workspace::self()->addDesktop( coords ); - } +int EffectsHandlerImpl::addDesktop(QPoint coords) +{ + return Workspace::self()->addDesktop(coords); +} -void EffectsHandlerImpl::deleteDesktop( int id ) - { - Workspace::self()->deleteDesktop( id ); - } +void EffectsHandlerImpl::deleteDesktop(int id) +{ + Workspace::self()->deleteDesktop(id); +} -QString EffectsHandlerImpl::desktopName( int desktop ) const - { - return Workspace::self()->desktopName( desktop ); - } +QString EffectsHandlerImpl::desktopName(int desktop) const +{ + return Workspace::self()->desktopName(desktop); +} bool EffectsHandlerImpl::optionRollOverDesktops() const - { +{ return options->rollOverDesktops; - } +} double EffectsHandlerImpl::animationTimeFactor() const - { +{ return options->animationTimeFactor(); - } +} WindowQuadType EffectsHandlerImpl::newWindowQuadType() - { - return WindowQuadType( next_window_quad_type++ ); - } +{ + return WindowQuadType(next_window_quad_type++); +} int EffectsHandlerImpl::displayWidth() const - { +{ return KWin::displayWidth(); - } +} int EffectsHandlerImpl::displayHeight() const - { +{ return KWin::displayWidth(); - } +} -EffectWindow* EffectsHandlerImpl::findWindow( WId id ) const - { - if( Client* w = Workspace::self()->findClient( WindowMatchPredicate( id ))) +EffectWindow* EffectsHandlerImpl::findWindow(WId id) const +{ + if (Client* w = Workspace::self()->findClient(WindowMatchPredicate(id))) return w->effectWindow(); - if( Unmanaged* w = Workspace::self()->findUnmanaged( WindowMatchPredicate( id ))) + if (Unmanaged* w = Workspace::self()->findUnmanaged(WindowMatchPredicate(id))) return w->effectWindow(); return NULL; - } +} EffectWindowList EffectsHandlerImpl::stackingOrder() const - { +{ ClientList list = Workspace::self()->stackingOrder(); EffectWindowList ret; - foreach( Client* c, list ) - ret.append( effectWindow( c )); + foreach (Client * c, list) + ret.append(effectWindow(c)); return ret; - } +} -void EffectsHandlerImpl::setElevatedWindow( EffectWindow* w, bool set ) - { - elevated_windows.removeAll( w ); - if( set ) - elevated_windows.append( w ); - } +void EffectsHandlerImpl::setElevatedWindow(EffectWindow* w, bool set) +{ + elevated_windows.removeAll(w); + if (set) + elevated_windows.append(w); +} void EffectsHandlerImpl::setTabBoxWindow(EffectWindow* w) - { - if( Client* c = dynamic_cast< Client* >( static_cast< EffectWindowImpl* >( w )->window())) - Workspace::self()->setTabBoxClient( c ); - } +{ + if (Client* c = dynamic_cast< Client* >(static_cast< EffectWindowImpl* >(w)->window())) + Workspace::self()->setTabBoxClient(c); +} void EffectsHandlerImpl::setTabBoxDesktop(int desktop) - { - Workspace::self()->setTabBoxDesktop( desktop ); - } +{ + Workspace::self()->setTabBoxDesktop(desktop); +} EffectWindowList EffectsHandlerImpl::currentTabBoxWindowList() const - { +{ EffectWindowList ret; ClientList clients = Workspace::self()->currentTabBoxClientList(); - foreach( Client* c, clients ) - ret.append( c->effectWindow()); + foreach (Client * c, clients) + ret.append(c->effectWindow()); return ret; - } +} void EffectsHandlerImpl::refTabBox() - { +{ Workspace::self()->refTabBox(); - } +} void EffectsHandlerImpl::unrefTabBox() - { +{ Workspace::self()->unrefTabBox(); - } +} void EffectsHandlerImpl::closeTabBox() - { +{ Workspace::self()->closeTabBox(); - } +} QList< int > EffectsHandlerImpl::currentTabBoxDesktopList() const - { +{ return Workspace::self()->currentTabBoxDesktopList(); - } +} int EffectsHandlerImpl::currentTabBoxDesktop() const - { +{ return Workspace::self()->currentTabBoxDesktop(); - } +} EffectWindow* EffectsHandlerImpl::currentTabBoxWindow() const - { - if( Client* c = Workspace::self()->currentTabBoxClient()) +{ + if (Client* c = Workspace::self()->currentTabBoxClient()) return c->effectWindow(); return NULL; - } +} void EffectsHandlerImpl::pushRenderTarget(GLRenderTarget* target) { @@ -781,7 +755,7 @@ GLRenderTarget* EffectsHandlerImpl::popRenderTarget() #ifdef KWIN_HAVE_OPENGL_COMPOSITING GLRenderTarget* ret = render_targets.pop(); ret->disable(); - if( !render_targets.isEmpty() ) + if (!render_targets.isEmpty()) render_targets.top()->enable(); return ret; #else @@ -790,873 +764,839 @@ GLRenderTarget* EffectsHandlerImpl::popRenderTarget() } bool EffectsHandlerImpl::isRenderTargetBound() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING return !render_targets.isEmpty(); #else return false; #endif - } +} void EffectsHandlerImpl::addRepaintFull() - { +{ Workspace::self()->addRepaintFull(); - } +} -void EffectsHandlerImpl::addRepaint( const QRect& r ) - { - Workspace::self()->addRepaint( r ); - } +void EffectsHandlerImpl::addRepaint(const QRect& r) +{ + Workspace::self()->addRepaint(r); +} -void EffectsHandlerImpl::addRepaint( const QRegion& r ) - { - Workspace::self()->addRepaint( r ); - } +void EffectsHandlerImpl::addRepaint(const QRegion& r) +{ + Workspace::self()->addRepaint(r); +} -void EffectsHandlerImpl::addRepaint( int x, int y, int w, int h ) - { - Workspace::self()->addRepaint( x, y, w, h ); - } +void EffectsHandlerImpl::addRepaint(int x, int y, int w, int h) +{ + Workspace::self()->addRepaint(x, y, w, h); +} int EffectsHandlerImpl::activeScreen() const - { +{ return Workspace::self()->activeScreen(); - } +} int EffectsHandlerImpl::numScreens() const - { +{ return Workspace::self()->numScreens(); - } +} -int EffectsHandlerImpl::screenNumber( const QPoint& pos ) const - { - return Workspace::self()->screenNumber( pos ); - } +int EffectsHandlerImpl::screenNumber(const QPoint& pos) const +{ + return Workspace::self()->screenNumber(pos); +} -QRect EffectsHandlerImpl::clientArea( clientAreaOption opt, int screen, int desktop ) const - { - return Workspace::self()->clientArea( opt, screen, desktop ); - } +QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, int screen, int desktop) const +{ + return Workspace::self()->clientArea(opt, screen, desktop); +} -QRect EffectsHandlerImpl::clientArea( clientAreaOption opt, const EffectWindow* c ) const - { +QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, const EffectWindow* c) const +{ const Toplevel* t = static_cast< const EffectWindowImpl* >(c)->window(); - if( const Client* cl = dynamic_cast< const Client* >( t )) - return Workspace::self()->clientArea( opt, cl ); + if (const Client* cl = dynamic_cast< const Client* >(t)) + return Workspace::self()->clientArea(opt, cl); else - return Workspace::self()->clientArea( opt, t->geometry().center(), Workspace::self()->currentDesktop()); - } + return Workspace::self()->clientArea(opt, t->geometry().center(), Workspace::self()->currentDesktop()); +} -QRect EffectsHandlerImpl::clientArea( clientAreaOption opt, const QPoint& p, int desktop ) const - { - return Workspace::self()->clientArea( opt, p, desktop ); - } +QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, const QPoint& p, int desktop) const +{ + return Workspace::self()->clientArea(opt, p, desktop); +} -Window EffectsHandlerImpl::createInputWindow( Effect* e, int x, int y, int w, int h, const QCursor& cursor ) - { +Window EffectsHandlerImpl::createInputWindow(Effect* e, int x, int y, int w, int h, const QCursor& cursor) +{ XSetWindowAttributes attrs; attrs.override_redirect = True; - Window win = XCreateWindow( display(), rootWindow(), x, y, w, h, 0, 0, InputOnly, CopyFromParent, - CWOverrideRedirect, &attrs ); + Window win = XCreateWindow(display(), rootWindow(), x, y, w, h, 0, 0, InputOnly, CopyFromParent, + CWOverrideRedirect, &attrs); // TODO keeping on top? // TODO enter/leave notify? - XSelectInput( display(), win, ButtonPressMask | ButtonReleaseMask | PointerMotionMask ); - XDefineCursor( display(), win, cursor.handle()); - XMapWindow( display(), win ); - input_windows.append( qMakePair( e, win )); + XSelectInput(display(), win, ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + XDefineCursor(display(), win, cursor.handle()); + XMapWindow(display(), win); + input_windows.append(qMakePair(e, win)); // Raise electric border windows above the input windows // so they can still be triggered. Workspace::self()->raiseElectricBorderWindows(); return win; - } +} -void EffectsHandlerImpl::destroyInputWindow( Window w ) - { - foreach( const InputWindowPair &pos, input_windows ) - { - if( pos.second == w ) - { - input_windows.removeAll( pos ); - XDestroyWindow( display(), w ); +void EffectsHandlerImpl::destroyInputWindow(Window w) +{ + foreach (const InputWindowPair & pos, input_windows) { + if (pos.second == w) { + input_windows.removeAll(pos); + XDestroyWindow(display(), w); return; - } } + } abort(); - } +} -bool EffectsHandlerImpl::checkInputWindowEvent( XEvent* e ) - { - if( e->type != ButtonPress && e->type != ButtonRelease && e->type != MotionNotify ) +bool EffectsHandlerImpl::checkInputWindowEvent(XEvent* e) +{ + if (e->type != ButtonPress && e->type != ButtonRelease && e->type != MotionNotify) return false; - foreach( const InputWindowPair &pos, input_windows ) - { - if( pos.second == e->xany.window ) - { - switch( e->type ) - { - case ButtonPress: - { - XButtonEvent* e2 = &e->xbutton; - Qt::MouseButton button = x11ToQtMouseButton( e2->button ); - Qt::MouseButtons buttons = x11ToQtMouseButtons( e2->state ) | button; - QMouseEvent ev( QEvent::MouseButtonPress, - QPoint( e2->x, e2->y ), QPoint( e2->x_root, e2->y_root ), - button, buttons, x11ToQtKeyboardModifiers( e2->state )); - pos.first->windowInputMouseEvent( pos.second, &ev ); - break; // ---> - } - case ButtonRelease: - { - XButtonEvent* e2 = &e->xbutton; - Qt::MouseButton button = x11ToQtMouseButton( e2->button ); - Qt::MouseButtons buttons = x11ToQtMouseButtons( e2->state ) & ~button; - QMouseEvent ev( QEvent::MouseButtonRelease, - QPoint( e2->x, e2->y ), QPoint( e2->x_root, e2->y_root ), - button, buttons, x11ToQtKeyboardModifiers( e2->state )); - pos.first->windowInputMouseEvent( pos.second, &ev ); - break; // ---> - } - case MotionNotify: - { - XMotionEvent* e2 = &e->xmotion; - QMouseEvent ev( QEvent::MouseMove, QPoint( e2->x, e2->y ), QPoint( e2->x_root, e2->y_root ), - Qt::NoButton, x11ToQtMouseButtons( e2->state ), x11ToQtKeyboardModifiers( e2->state )); - pos.first->windowInputMouseEvent( pos.second, &ev ); - break; // ---> - } - } - return true; // eat event + foreach (const InputWindowPair & pos, input_windows) { + if (pos.second == e->xany.window) { + switch(e->type) { + case ButtonPress: { + XButtonEvent* e2 = &e->xbutton; + Qt::MouseButton button = x11ToQtMouseButton(e2->button); + Qt::MouseButtons buttons = x11ToQtMouseButtons(e2->state) | button; + QMouseEvent ev(QEvent::MouseButtonPress, + QPoint(e2->x, e2->y), QPoint(e2->x_root, e2->y_root), + button, buttons, x11ToQtKeyboardModifiers(e2->state)); + pos.first->windowInputMouseEvent(pos.second, &ev); + break; // ---> } + case ButtonRelease: { + XButtonEvent* e2 = &e->xbutton; + Qt::MouseButton button = x11ToQtMouseButton(e2->button); + Qt::MouseButtons buttons = x11ToQtMouseButtons(e2->state) & ~button; + QMouseEvent ev(QEvent::MouseButtonRelease, + QPoint(e2->x, e2->y), QPoint(e2->x_root, e2->y_root), + button, buttons, x11ToQtKeyboardModifiers(e2->state)); + pos.first->windowInputMouseEvent(pos.second, &ev); + break; // ---> + } + case MotionNotify: { + XMotionEvent* e2 = &e->xmotion; + QMouseEvent ev(QEvent::MouseMove, QPoint(e2->x, e2->y), QPoint(e2->x_root, e2->y_root), + Qt::NoButton, x11ToQtMouseButtons(e2->state), x11ToQtKeyboardModifiers(e2->state)); + pos.first->windowInputMouseEvent(pos.second, &ev); + break; // ---> + } + } + return true; // eat event } - return false; } + return false; +} void EffectsHandlerImpl::checkInputWindowStacking() - { - if( input_windows.count() == 0 ) +{ + if (input_windows.count() == 0) return; - Window* wins = new Window[ input_windows.count() ]; + Window* wins = new Window[ input_windows.count()]; int pos = 0; - foreach( const InputWindowPair &it, input_windows ) - wins[ pos++ ] = it.second; - XRaiseWindow( display(), wins[ 0 ] ); - XRestackWindows( display(), wins, pos ); + foreach (const InputWindowPair & it, input_windows) + wins[ pos++ ] = it.second; + XRaiseWindow(display(), wins[ 0 ]); + XRestackWindows(display(), wins, pos); delete[] wins; // Raise electric border windows above the input windows // so they can still be triggered. TODO: Do both at once. Workspace::self()->raiseElectricBorderWindows(); - } +} QPoint EffectsHandlerImpl::cursorPos() const - { +{ return Workspace::self()->cursorPos(); - } +} void EffectsHandlerImpl::checkElectricBorder(const QPoint &pos, Time time) - { - Workspace::self()->checkElectricBorder( pos, time ); - } +{ + Workspace::self()->checkElectricBorder(pos, time); +} -void EffectsHandlerImpl::reserveElectricBorder( ElectricBorder border ) - { - Workspace::self()->reserveElectricBorder( border ); - } +void EffectsHandlerImpl::reserveElectricBorder(ElectricBorder border) +{ + Workspace::self()->reserveElectricBorder(border); +} -void EffectsHandlerImpl::unreserveElectricBorder( ElectricBorder border ) - { - Workspace::self()->unreserveElectricBorder( border ); - } +void EffectsHandlerImpl::unreserveElectricBorder(ElectricBorder border) +{ + Workspace::self()->unreserveElectricBorder(border); +} -void EffectsHandlerImpl::reserveElectricBorderSwitching( bool reserve ) - { - Workspace::self()->reserveElectricBorderSwitching( reserve ); - } +void EffectsHandlerImpl::reserveElectricBorderSwitching(bool reserve) +{ + Workspace::self()->reserveElectricBorderSwitching(reserve); +} unsigned long EffectsHandlerImpl::xrenderBufferPicture() - { +{ #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( SceneXrender* s = dynamic_cast< SceneXrender* >( scene )) + if (SceneXrender* s = dynamic_cast< SceneXrender* >(scene)) return s->bufferPicture(); #endif return None; - } +} -KLibrary* EffectsHandlerImpl::findEffectLibrary( KService* service ) - { +KLibrary* EffectsHandlerImpl::findEffectLibrary(KService* service) +{ QString libname = service->library(); KLibrary* library = new KLibrary(libname); - if( !library ) - { - kError( 1212 ) << "couldn't open library for effect '" << - service->name() << "'" << endl; + if (!library) { + kError(1212) << "couldn't open library for effect '" << + service->name() << "'" << endl; return 0; - } + } return library; - } +} -void EffectsHandlerImpl::toggleEffect( const QString& name ) - { - if( isEffectLoaded( name )) - unloadEffect( name ); +void EffectsHandlerImpl::toggleEffect(const QString& name) +{ + if (isEffectLoaded(name)) + unloadEffect(name); else - loadEffect( name ); - } + loadEffect(name); +} QStringList EffectsHandlerImpl::loadedEffects() const - { +{ QStringList listModules; - for(QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) - { - listModules <<(*it).first; - } - return listModules; + for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { + listModules << (*it).first; } + return listModules; +} QStringList EffectsHandlerImpl::listOfEffects() const - { +{ KService::List offers = KServiceTypeTrader::self()->query("KWin/Effect"); QStringList listOfModules; // First unload necessary effects - foreach( const KService::Ptr &service, offers ) - { - KPluginInfo plugininfo( service ); - listOfModules<addRepaintFull(); - assert( current_paint_screen == 0 ); - assert( current_paint_window == 0 ); - assert( current_draw_window == 0 ); - assert( current_build_quads == 0 ); - assert( current_transform == 0 ); + assert(current_paint_screen == 0); + assert(current_paint_window == 0); + assert(current_draw_window == 0); + assert(current_build_quads == 0); + assert(current_transform == 0); - if( !name.startsWith(QLatin1String("kwin4_effect_")) ) - kWarning( 1212 ) << "Effect names usually have kwin4_effect_ prefix" ; + if (!name.startsWith(QLatin1String("kwin4_effect_"))) + kWarning(1212) << "Effect names usually have kwin4_effect_ prefix" ; // Make sure a single effect won't be loaded multiple times - for(QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) - { - if( (*it).first == name ) - { - kDebug( 1212 ) << "EffectsHandler::loadEffect : Effect already loaded : " << name; + for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { + if ((*it).first == name) { + kDebug(1212) << "EffectsHandler::loadEffect : Effect already loaded : " << name; return true; - } } + } - kDebug( 1212 ) << "Trying to load " << name; + kDebug(1212) << "Trying to load " << name; QString internalname = name.toLower(); QString constraint = QString("[X-KDE-PluginInfo-Name] == '%1'").arg(internalname); KService::List offers = KServiceTypeTrader::self()->query("KWin/Effect", constraint); - if(offers.isEmpty()) - { - kError( 1212 ) << "Couldn't find effect " << name << endl; + if (offers.isEmpty()) { + kError(1212) << "Couldn't find effect " << name << endl; return false; } KService::Ptr service = offers.first(); - KLibrary* library = findEffectLibrary( service.data() ); - if( !library ) - { + KLibrary* library = findEffectLibrary(service.data()); + if (!library) { return false; - } + } QString version_symbol = "effect_version_" + name; KLibrary::void_function_ptr version_func = library->resolveFunction(version_symbol.toAscii()); - if( version_func == NULL ) - { - kWarning( 1212 ) << "Effect " << name << " does not provide required API version, ignoring."; + if (version_func == NULL) { + kWarning(1212) << "Effect " << name << " does not provide required API version, ignoring."; return false; - } + } typedef int (*t_versionfunc)(); - int version = reinterpret_cast< t_versionfunc >( version_func )(); // call it + int version = reinterpret_cast< t_versionfunc >(version_func)(); // call it // Version must be the same or less, but major must be the same. // With major 0 minor must match exactly. - if( version > KWIN_EFFECT_API_VERSION - || ( version >> 8 ) != KWIN_EFFECT_API_VERSION_MAJOR - || ( KWIN_EFFECT_API_VERSION_MAJOR == 0 && version != KWIN_EFFECT_API_VERSION )) - { - kWarning( 1212 ) << "Effect " << name << " requires unsupported API version " << version; + if (version > KWIN_EFFECT_API_VERSION + || (version >> 8) != KWIN_EFFECT_API_VERSION_MAJOR + || (KWIN_EFFECT_API_VERSION_MAJOR == 0 && version != KWIN_EFFECT_API_VERSION)) { + kWarning(1212) << "Effect " << name << " requires unsupported API version " << version; return false; - } + } QString supported_symbol = "effect_supported_" + name; KLibrary::void_function_ptr supported_func = library->resolveFunction(supported_symbol.toAscii().data()); QString create_symbol = "effect_create_" + name; KLibrary::void_function_ptr create_func = library->resolveFunction(create_symbol.toAscii().data()); - if( supported_func ) - { + if (supported_func) { typedef bool (*t_supportedfunc)(); t_supportedfunc supported = reinterpret_cast(supported_func); - if(!supported()) - { - kWarning( 1212 ) << "EffectsHandler::loadEffect : Effect " << name << " is not supported" ; + if (!supported()) { + kWarning(1212) << "EffectsHandler::loadEffect : Effect " << name << " is not supported" ; library->unload(); return false; - } } - if(!create_func) - { - kError( 1212 ) << "EffectsHandler::loadEffect : effect_create function not found" << endl; + } + if (!create_func) { + kError(1212) << "EffectsHandler::loadEffect : effect_create function not found" << endl; library->unload(); return false; - } - typedef Effect* (*t_createfunc)(); + } + typedef Effect*(*t_createfunc)(); t_createfunc create = reinterpret_cast(create_func); // Make sure all depenedencies have been loaded // TODO: detect circular deps - KPluginInfo plugininfo( service ); + KPluginInfo plugininfo(service); QStringList dependencies = plugininfo.dependencies(); - foreach( const QString &depName, dependencies ) - { - if( !loadEffect(depName)) - { + foreach (const QString & depName, dependencies) { + if (!loadEffect(depName)) { kError(1212) << "EffectsHandler::loadEffect : Couldn't load dependencies for effect " << name << endl; library->unload(); return false; - } } + } Effect* e = create(); - effect_order.insert( service->property( "X-KDE-Ordering" ).toInt(), EffectPair( name, e )); + effect_order.insert(service->property("X-KDE-Ordering").toInt(), EffectPair(name, e)); effectsChanged(); effect_libraries[ name ] = library; return true; - } +} -void EffectsHandlerImpl::unloadEffect( const QString& name ) - { +void EffectsHandlerImpl::unloadEffect(const QString& name) +{ Workspace::self()->addRepaintFull(); - assert( current_paint_screen == 0 ); - assert( current_paint_window == 0 ); - assert( current_draw_window == 0 ); - assert( current_build_quads == 0 ); - assert( current_transform == 0 ); + assert(current_paint_screen == 0); + assert(current_paint_window == 0); + assert(current_draw_window == 0); + assert(current_build_quads == 0); + assert(current_transform == 0); - for( QMap< int, EffectPair >::iterator it = effect_order.begin(); it != effect_order.end(); ++it) - { - if ( it.value().first == name ) - { - kDebug( 1212 ) << "EffectsHandler::unloadEffect : Unloading Effect : " << name; - if( activeFullScreenEffect() == it.value().second ) - { - setActiveFullScreenEffect( 0 ); - } + for (QMap< int, EffectPair >::iterator it = effect_order.begin(); it != effect_order.end(); ++it) { + if (it.value().first == name) { + kDebug(1212) << "EffectsHandler::unloadEffect : Unloading Effect : " << name; + if (activeFullScreenEffect() == it.value().second) { + setActiveFullScreenEffect(0); + } delete it.value().second; effect_order.erase(it); effectsChanged(); effect_libraries[ name ]->unload(); return; - } } - - kDebug( 1212 ) << "EffectsHandler::unloadEffect : Effect not loaded : " << name; } -void EffectsHandlerImpl::reconfigureEffect( const QString& name ) - { - for( QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) - if ( (*it).first == name ) - { - (*it).second->reconfigure( Effect::ReconfigureAll ); + kDebug(1212) << "EffectsHandler::unloadEffect : Effect not loaded : " << name; +} + +void EffectsHandlerImpl::reconfigureEffect(const QString& name) +{ + for (QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) + if ((*it).first == name) { + (*it).second->reconfigure(Effect::ReconfigureAll); return; - } - } + } +} -bool EffectsHandlerImpl::isEffectLoaded( const QString& name ) - { - for( QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) - if ( (*it).first == name ) +bool EffectsHandlerImpl::isEffectLoaded(const QString& name) +{ + for (QVector< EffectPair >::iterator it = loaded_effects.begin(); it != loaded_effects.end(); ++it) + if ((*it).first == name) return true; return false; - } +} void EffectsHandlerImpl::effectsChanged() - { +{ loaded_effects.clear(); // kDebug(1212) << "Recreating effects' list:"; - foreach( const EffectPair &effect, effect_order ) - { + foreach (const EffectPair & effect, effect_order) { // kDebug(1212) << effect.first; - loaded_effects.append( effect ); - } + loaded_effects.append(effect); } +} -EffectFrame* EffectsHandlerImpl::effectFrame( EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment ) const - { - return new EffectFrameImpl( style, staticSize, position, alignment ); - } +EffectFrame* EffectsHandlerImpl::effectFrame(EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment) const +{ + return new EffectFrameImpl(style, staticSize, position, alignment); +} //**************************************** // EffectWindowImpl //**************************************** EffectWindowImpl::EffectWindowImpl() : EffectWindow() - , toplevel( NULL ) - , sw( NULL ) - { - } + , toplevel(NULL) + , sw(NULL) +{ +} EffectWindowImpl::~EffectWindowImpl() - { - QVariant cachedTextureVariant = data( LanczosCacheRole ); - if( cachedTextureVariant.isValid() ) - { +{ + QVariant cachedTextureVariant = data(LanczosCacheRole); + if (cachedTextureVariant.isValid()) { GLTexture *cachedTexture = static_cast< GLTexture*>(cachedTextureVariant.value()); delete cachedTexture; - } } +} bool EffectWindowImpl::isPaintingEnabled() - { +{ return sceneWindow()->isPaintingEnabled(); - } +} -void EffectWindowImpl::enablePainting( int reason ) - { - sceneWindow()->enablePainting( reason ); - } +void EffectWindowImpl::enablePainting(int reason) +{ + sceneWindow()->enablePainting(reason); +} -void EffectWindowImpl::disablePainting( int reason ) - { - sceneWindow()->disablePainting( reason ); - } +void EffectWindowImpl::disablePainting(int reason) +{ + sceneWindow()->disablePainting(reason); +} -void EffectWindowImpl::addRepaint( const QRect& r ) - { - toplevel->addRepaint( r ); - } +void EffectWindowImpl::addRepaint(const QRect& r) +{ + toplevel->addRepaint(r); +} -void EffectWindowImpl::addRepaint( int x, int y, int w, int h ) - { - toplevel->addRepaint( x, y, w, h ); - } +void EffectWindowImpl::addRepaint(int x, int y, int w, int h) +{ + toplevel->addRepaint(x, y, w, h); +} void EffectWindowImpl::addRepaintFull() - { +{ toplevel->addRepaintFull(); - } +} int EffectWindowImpl::desktop() const - { +{ return toplevel->desktop(); - } +} bool EffectWindowImpl::isOnAllDesktops() const - { +{ return desktop() == NET::OnAllDesktops; - } +} QString EffectWindowImpl::caption() const - { - if( Client* c = dynamic_cast( toplevel )) +{ + if (Client* c = dynamic_cast(toplevel)) return c->caption(); else return ""; - } +} QString EffectWindowImpl::windowClass() const - { +{ return toplevel->resourceName() + ' ' + toplevel->resourceClass(); - } +} QString EffectWindowImpl::windowRole() const - { +{ return toplevel->windowRole(); - } +} QPixmap EffectWindowImpl::icon() const - { - if( Client* c = dynamic_cast( toplevel )) +{ + if (Client* c = dynamic_cast(toplevel)) return c->icon(); return QPixmap(); // TODO - } +} const EffectWindowGroup* EffectWindowImpl::group() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->group()->effectGroup(); return NULL; // TODO - } +} bool EffectWindowImpl::isMinimized() const - { - if( Client* c = dynamic_cast( toplevel )) +{ + if (Client* c = dynamic_cast(toplevel)) return c->isMinimized(); else return false; - } +} double EffectWindowImpl::opacity() const - { +{ return toplevel->opacity(); - } +} bool EffectWindowImpl::hasAlpha() const - { +{ return toplevel->hasAlpha(); - } +} bool EffectWindowImpl::isDeleted() const - { - return (dynamic_cast( toplevel ) != 0); - } +{ + return (dynamic_cast(toplevel) != 0); +} void EffectWindowImpl::refWindow() - { - if( Deleted* d = dynamic_cast< Deleted* >( toplevel )) +{ + if (Deleted* d = dynamic_cast< Deleted* >(toplevel)) return d->refWindow(); abort(); // TODO - } +} void EffectWindowImpl::unrefWindow() - { - if( Deleted* d = dynamic_cast< Deleted* >( toplevel )) - return d->unrefWindow( true ); // delayed +{ + if (Deleted* d = dynamic_cast< Deleted* >(toplevel)) + return d->unrefWindow(true); // delayed abort(); // TODO - } +} -void EffectWindowImpl::setWindow( Toplevel* w ) - { +void EffectWindowImpl::setWindow(Toplevel* w) +{ toplevel = w; - } +} -void EffectWindowImpl::setSceneWindow( Scene::Window* w ) - { +void EffectWindowImpl::setSceneWindow(Scene::Window* w) +{ sw = w; - } +} int EffectWindowImpl::x() const - { +{ return toplevel->x(); - } +} int EffectWindowImpl::y() const - { +{ return toplevel->y(); - } +} int EffectWindowImpl::width() const - { +{ return toplevel->width(); - } +} int EffectWindowImpl::height() const - { +{ return toplevel->height(); - } +} QRect EffectWindowImpl::geometry() const - { +{ return toplevel->geometry(); - } +} QRegion EffectWindowImpl::shape() const - { +{ return sw ? sw->shape() : geometry(); - } +} int EffectWindowImpl::screen() const - { +{ return toplevel->screen(); - } +} bool EffectWindowImpl::hasOwnShape() const - { +{ return toplevel->shape(); - } +} QSize EffectWindowImpl::size() const - { +{ return toplevel->size(); - } +} QPoint EffectWindowImpl::pos() const - { +{ return toplevel->pos(); - } +} QRect EffectWindowImpl::rect() const - { +{ return toplevel->rect(); - } +} QRect EffectWindowImpl::contentsRect() const - { - return QRect( toplevel->clientPos(), toplevel->clientSize()); - } +{ + return QRect(toplevel->clientPos(), toplevel->clientSize()); +} QRect EffectWindowImpl::decorationInnerRect() const - { +{ Client *client = dynamic_cast(toplevel); return client ? client->transparentRect() : contentsRect(); - } +} -QByteArray EffectWindowImpl::readProperty( long atom, long type, int format ) const - { - return readWindowProperty( window()->window(), atom, type, format ); - } +QByteArray EffectWindowImpl::readProperty(long atom, long type, int format) const +{ + return readWindowProperty(window()->window(), atom, type, format); +} void EffectWindowImpl::deleteProperty(long int atom) const - { - deleteWindowProperty( window()->window(), atom ); - } +{ + deleteWindowProperty(window()->window(), atom); +} bool EffectWindowImpl::isMovable() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->isMovable(); return false; - } +} bool EffectWindowImpl::isMovableAcrossScreens() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->isMovableAcrossScreens(); return false; - } +} bool EffectWindowImpl::isUserMove() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->isMove(); return false; - } +} bool EffectWindowImpl::isUserResize() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->isResize(); return false; - } +} QRect EffectWindowImpl::iconGeometry() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->iconGeometry(); return QRect(); - } +} bool EffectWindowImpl::isDesktop() const - { +{ return toplevel->isDesktop(); - } +} bool EffectWindowImpl::isDock() const - { +{ return toplevel->isDock(); - } +} bool EffectWindowImpl::isToolbar() const - { +{ return toplevel->isToolbar(); - } +} bool EffectWindowImpl::isTopMenu() const - { +{ return toplevel->isTopMenu(); - } +} bool EffectWindowImpl::isMenu() const - { +{ return toplevel->isMenu(); - } +} bool EffectWindowImpl::isNormalWindow() const - { +{ return toplevel->isNormalWindow(); - } +} bool EffectWindowImpl::isSpecialWindow() const - { - if( Client* c = dynamic_cast( toplevel )) +{ + if (Client* c = dynamic_cast(toplevel)) return c->isSpecialWindow(); else return true; - } +} bool EffectWindowImpl::isDialog() const - { +{ return toplevel->isDialog(); - } +} bool EffectWindowImpl::isSplash() const - { +{ return toplevel->isSplash(); - } +} bool EffectWindowImpl::isUtility() const - { +{ return toplevel->isUtility(); - } +} bool EffectWindowImpl::isDropdownMenu() const - { +{ return toplevel->isDropdownMenu(); - } +} bool EffectWindowImpl::isPopupMenu() const - { +{ return toplevel->isPopupMenu(); - } +} bool EffectWindowImpl::isTooltip() const - { +{ return toplevel->isTooltip(); - } +} bool EffectWindowImpl::isNotification() const - { +{ return toplevel->isNotification(); - } +} bool EffectWindowImpl::isComboBox() const - { +{ return toplevel->isComboBox(); - } +} bool EffectWindowImpl::isDNDIcon() const - { +{ return toplevel->isDNDIcon(); - } +} bool EffectWindowImpl::isManaged() const - { - return dynamic_cast< const Client* >( toplevel ) != NULL; - } +{ + return dynamic_cast< const Client* >(toplevel) != NULL; +} bool EffectWindowImpl::acceptsFocus() const - { - const Client* client = dynamic_cast< const Client* >( toplevel ); - if( !client ) +{ + const Client* client = dynamic_cast< const Client* >(toplevel); + if (!client) return true; // We don't actually know... return client->wantsInput(); - } +} bool EffectWindowImpl::keepAbove() const - { - const Client* client = dynamic_cast< const Client* >( toplevel ); - if( !client ) +{ + const Client* client = dynamic_cast< const Client* >(toplevel); + if (!client) return true; return client->keepAbove(); - } +} bool EffectWindowImpl::isModal() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->isModal(); return false; - } +} EffectWindow* EffectWindowImpl::findModal() - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { - if( Client* c2 = c->findModal()) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { + if (Client* c2 = c->findModal()) return c2->effectWindow(); - } - return NULL; } + return NULL; +} EffectWindowList EffectWindowImpl::mainWindows() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { EffectWindowList ret; ClientList mainclients = c->mainClients(); - foreach( Client* tmp, mainclients ) - ret.append( tmp->effectWindow()); + foreach (Client * tmp, mainclients) + ret.append(tmp->effectWindow()); return ret; - } - return EffectWindowList(); } + return EffectWindowList(); +} bool EffectWindowImpl::isSkipSwitcher() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) return c->skipSwitcher(); return false; - } +} -WindowQuadList EffectWindowImpl::buildQuads( bool force ) const - { - return sceneWindow()->buildQuads( force ); - } +WindowQuadList EffectWindowImpl::buildQuads(bool force) const +{ + return sceneWindow()->buildQuads(force); +} void EffectWindowImpl::minimize() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { c->minimize(); - } } +} void EffectWindowImpl::unminimize() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { c->unminimize(); - } } +} void EffectWindowImpl::closeWindow() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { c->closeWindow(); - } } +} bool EffectWindowImpl::visibleInClientGroup() const - { - if( Client* c = dynamic_cast< Client* >( toplevel )) - { - if( !c->clientGroup() ) +{ + if (Client* c = dynamic_cast< Client* >(toplevel)) { + if (!c->clientGroup()) return true; return c == c->clientGroup()->visible(); - } - return false; } + return false; +} -void EffectWindowImpl::setData( int role, const QVariant &data ) - { - if ( !data.isNull() ) +void EffectWindowImpl::setData(int role, const QVariant &data) +{ + if (!data.isNull()) dataMap[ role ] = data; else - dataMap.remove( role ); - } + dataMap.remove(role); +} -QVariant EffectWindowImpl::data( int role ) const - { - if( !dataMap.contains( role ) ) +QVariant EffectWindowImpl::data(int role) const +{ + if (!dataMap.contains(role)) return QVariant(); return dataMap[ role ]; - } +} -EffectWindow* effectWindow( Toplevel* w ) - { +EffectWindow* effectWindow(Toplevel* w) +{ EffectWindowImpl* ret = w->effectWindow(); return ret; - } +} -EffectWindow* effectWindow( Scene::Window* w ) - { +EffectWindow* effectWindow(Scene::Window* w) +{ EffectWindowImpl* ret = w->window()->effectWindow(); - ret->setSceneWindow( w ); + ret->setSceneWindow(w); return ret; - } +} //**************************************** // EffectWindowGroupImpl @@ -1664,273 +1604,252 @@ EffectWindow* effectWindow( Scene::Window* w ) EffectWindowList EffectWindowGroupImpl::members() const - { +{ EffectWindowList ret; - foreach( Toplevel* c, group->members()) - ret.append( c->effectWindow()); + foreach (Toplevel * c, group->members()) + ret.append(c->effectWindow()); return ret; - } +} //**************************************** // EffectFrameImpl //**************************************** -EffectFrameImpl::EffectFrameImpl( EffectFrameStyle style, bool staticSize, QPoint position, Qt::Alignment alignment ) - : QObject ( 0 ) +EffectFrameImpl::EffectFrameImpl(EffectFrameStyle style, bool staticSize, QPoint position, Qt::Alignment alignment) + : QObject(0) , EffectFrame() - , m_style( style ) - , m_static( staticSize ) - , m_point( position ) - , m_alignment( alignment ) - , m_shader( NULL ) - { - if( m_style == EffectFrameStyled ) - { - m_frame.setImagePath( "widgets/background" ); - m_frame.setCacheAllRenderedFrames( true ); - m_selection.setImagePath( "widgets/viewitem" ); - m_selection.setElementPrefix( "hover" ); - m_selection.setCacheAllRenderedFrames( true ); - m_selection.setEnabledBorders( Plasma::FrameSvg::AllBorders ); - connect( Plasma::Theme::defaultTheme(), SIGNAL( themeChanged() ), this, SLOT( plasmaThemeChanged() )); - } + , m_style(style) + , m_static(staticSize) + , m_point(position) + , m_alignment(alignment) + , m_shader(NULL) +{ + if (m_style == EffectFrameStyled) { + m_frame.setImagePath("widgets/background"); + m_frame.setCacheAllRenderedFrames(true); + m_selection.setImagePath("widgets/viewitem"); + m_selection.setElementPrefix("hover"); + m_selection.setCacheAllRenderedFrames(true); + m_selection.setEnabledBorders(Plasma::FrameSvg::AllBorders); + connect(Plasma::Theme::defaultTheme(), SIGNAL(themeChanged()), this, SLOT(plasmaThemeChanged())); + } - if( effects->compositingType() == OpenGLCompositing ) - { + if (effects->compositingType() == OpenGLCompositing) { #ifdef KWIN_HAVE_OPENGL_COMPOSITING - m_sceneFrame = new SceneOpenGL::EffectFrame( this ); + m_sceneFrame = new SceneOpenGL::EffectFrame(this); #endif - } - else if( effects->compositingType() == XRenderCompositing ) - { - m_sceneFrame = new SceneXrender::EffectFrame( this ); - } - else - { + } else if (effects->compositingType() == XRenderCompositing) { + m_sceneFrame = new SceneXrender::EffectFrame(this); + } else { // that should not happen and will definitely crash! m_sceneFrame = NULL; - } } +} EffectFrameImpl::~EffectFrameImpl() - { +{ delete m_sceneFrame; - } +} const QFont& EffectFrameImpl::font() const - { +{ return m_font; - } +} -void EffectFrameImpl::setFont( const QFont& font ) - { - if (m_font == font) - { +void EffectFrameImpl::setFont(const QFont& font) +{ + if (m_font == font) { return; - } + } m_font = font; QRect oldGeom = m_geometry; - if( !m_text.isEmpty() ) - { + if (!m_text.isEmpty()) { autoResize(); - } - if( oldGeom == m_geometry ) - { // Wasn't updated in autoResize() - m_sceneFrame->freeTextFrame(); - } } + if (oldGeom == m_geometry) { + // Wasn't updated in autoResize() + m_sceneFrame->freeTextFrame(); + } +} void EffectFrameImpl::free() - { +{ m_sceneFrame->free(); - } +} const QRect& EffectFrameImpl::geometry() const - { +{ return m_geometry; - } +} -void EffectFrameImpl::setGeometry( const QRect& geometry, bool force ) - { +void EffectFrameImpl::setGeometry(const QRect& geometry, bool force) +{ QRect oldGeom = m_geometry; m_geometry = geometry; - if( m_geometry == oldGeom && !force ) - { + if (m_geometry == oldGeom && !force) { return; - } - effects->addRepaint( oldGeom ); - effects->addRepaint( m_geometry ); - if( m_geometry.size() == oldGeom.size() && !force ) - { + } + effects->addRepaint(oldGeom); + effects->addRepaint(m_geometry); + if (m_geometry.size() == oldGeom.size() && !force) { return; - } + } - if( m_style == EffectFrameStyled ) - { + if (m_style == EffectFrameStyled) { qreal left, top, right, bottom; - m_frame.getMargins( left, top, right, bottom ); // m_geometry is the inner geometry - m_frame.resizeFrame( m_geometry.adjusted( -left, -top, right, bottom ).size() ); - } + m_frame.getMargins(left, top, right, bottom); // m_geometry is the inner geometry + m_frame.resizeFrame(m_geometry.adjusted(-left, -top, right, bottom).size()); + } free(); - } +} const QPixmap& EffectFrameImpl::icon() const - { +{ return m_icon; - } +} -void EffectFrameImpl::setIcon( const QPixmap& icon ) - { +void EffectFrameImpl::setIcon(const QPixmap& icon) +{ m_icon = icon; - if( isCrossFade() ) - { + if (isCrossFade()) { m_sceneFrame->crossFadeIcon(); - } - if( m_iconSize.isEmpty() ) // Set a size if we don't already have one - { - setIconSize( m_icon.size() ); - } - m_sceneFrame->freeIconFrame(); } + if (m_iconSize.isEmpty()) { // Set a size if we don't already have one + setIconSize(m_icon.size()); + } + m_sceneFrame->freeIconFrame(); +} const QSize& EffectFrameImpl::iconSize() const - { +{ return m_iconSize; - } +} -void EffectFrameImpl::setIconSize( const QSize& size ) - { - if( m_iconSize == size ) - { +void EffectFrameImpl::setIconSize(const QSize& size) +{ + if (m_iconSize == size) { return; - } + } m_iconSize = size; autoResize(); m_sceneFrame->freeIconFrame(); - } +} void EffectFrameImpl::plasmaThemeChanged() - { +{ free(); - } +} -void EffectFrameImpl::render( QRegion region, double opacity, double frameOpacity ) - { - if( m_geometry.isEmpty() ) - { +void EffectFrameImpl::render(QRegion region, double opacity, double frameOpacity) +{ + if (m_geometry.isEmpty()) { return; // Nothing to display - } - m_shader = NULL; - effects->paintEffectFrame( this, region, opacity, frameOpacity ); } + m_shader = NULL; + effects->paintEffectFrame(this, region, opacity, frameOpacity); +} -void EffectFrameImpl::finalRender( QRegion region, double opacity, double frameOpacity ) const - { +void EffectFrameImpl::finalRender(QRegion region, double opacity, double frameOpacity) const +{ region = infiniteRegion(); // TODO: Old region doesn't seem to work with OpenGL - m_sceneFrame->render( region, opacity, frameOpacity ); - } + m_sceneFrame->render(region, opacity, frameOpacity); +} Qt::Alignment EffectFrameImpl::alignment() const - { - return m_alignment; - } - - -void -EffectFrameImpl::align( QRect &geometry ) { - if( m_alignment & Qt::AlignLeft ) - geometry.moveLeft( m_point.x() ); - else if( m_alignment & Qt::AlignRight ) - geometry.moveLeft( m_point.x() - geometry.width() ); - else - geometry.moveLeft( m_point.x() - geometry.width() / 2 ); - if( m_alignment & Qt::AlignTop ) - geometry.moveTop( m_point.y() ); - else if( m_alignment & Qt::AlignBottom ) - geometry.moveTop( m_point.y() - geometry.height() ); - else - geometry.moveTop( m_point.y() - geometry.height() / 2 ); + return m_alignment; } -void EffectFrameImpl::setAlignment( Qt::Alignment alignment ) - { - m_alignment = alignment; - align( m_geometry ); - setGeometry( m_geometry ); - } +void +EffectFrameImpl::align(QRect &geometry) +{ + if (m_alignment & Qt::AlignLeft) + geometry.moveLeft(m_point.x()); + else if (m_alignment & Qt::AlignRight) + geometry.moveLeft(m_point.x() - geometry.width()); + else + geometry.moveLeft(m_point.x() - geometry.width() / 2); + if (m_alignment & Qt::AlignTop) + geometry.moveTop(m_point.y()); + else if (m_alignment & Qt::AlignBottom) + geometry.moveTop(m_point.y() - geometry.height()); + else + geometry.moveTop(m_point.y() - geometry.height() / 2); +} -void EffectFrameImpl::setPosition( const QPoint& point ) - { + +void EffectFrameImpl::setAlignment(Qt::Alignment alignment) +{ + m_alignment = alignment; + align(m_geometry); + setGeometry(m_geometry); +} + +void EffectFrameImpl::setPosition(const QPoint& point) +{ m_point = point; QRect geometry = m_geometry; // this is important, setGeometry need call repaint for old & new geometry - align( geometry ); - setGeometry( geometry ); - } + align(geometry); + setGeometry(geometry); +} const QString& EffectFrameImpl::text() const - { +{ return m_text; - } +} -void EffectFrameImpl::setText( const QString& text ) - { - if( m_text == text ) - { +void EffectFrameImpl::setText(const QString& text) +{ + if (m_text == text) { return; - } - if( isCrossFade() ) - { + } + if (isCrossFade()) { m_sceneFrame->crossFadeText(); - } + } m_text = text; QRect oldGeom = m_geometry; autoResize(); - if( oldGeom == m_geometry ) - { // Wasn't updated in autoResize() + if (oldGeom == m_geometry) { + // Wasn't updated in autoResize() m_sceneFrame->freeTextFrame(); - } } +} -void EffectFrameImpl::setSelection( const QRect& selection ) - { - if( selection == m_selectionGeometry ) - { +void EffectFrameImpl::setSelection(const QRect& selection) +{ + if (selection == m_selectionGeometry) { return; - } + } m_selectionGeometry = selection; - if( m_selectionGeometry.size() != m_selection.frameSize().toSize() ) - { - m_selection.resizeFrame( m_selectionGeometry.size() ); - } + if (m_selectionGeometry.size() != m_selection.frameSize().toSize()) { + m_selection.resizeFrame(m_selectionGeometry.size()); + } // TODO; optimize to only recreate when resizing m_sceneFrame->freeSelection(); - } +} void EffectFrameImpl::autoResize() - { - if( m_static ) +{ + if (m_static) return; // Not automatically resizing QRect geometry; // Set size - if( !m_text.isEmpty() ) - { - QFontMetrics metrics( m_font ); - geometry.setSize( metrics.size( 0, m_text )); - } - if( !m_icon.isNull() && !m_iconSize.isEmpty() ) - { - geometry.setLeft( -m_iconSize.width() ); - if( m_iconSize.height() > geometry.height() ) - geometry.setHeight( m_iconSize.height() ); - } - - align( geometry ); - setGeometry( geometry ); + if (!m_text.isEmpty()) { + QFontMetrics metrics(m_font); + geometry.setSize(metrics.size(0, m_text)); + } + if (!m_icon.isNull() && !m_iconSize.isEmpty()) { + geometry.setLeft(-m_iconSize.width()); + if (m_iconSize.height() > geometry.height()) + geometry.setHeight(m_iconSize.height()); } + align(geometry); + setGeometry(geometry); +} + } // namespace diff --git a/effects.h b/effects.h index aef751d93..57faa48fd 100644 --- a/effects.h +++ b/effects.h @@ -37,406 +37,399 @@ namespace KWin class EffectsHandlerImpl : public EffectsHandler { - public: - EffectsHandlerImpl(CompositingType type); - virtual ~EffectsHandlerImpl(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - virtual void paintEffectFrame( EffectFrame* frame, QRegion region, double opacity, double frameOpacity ); +public: + EffectsHandlerImpl(CompositingType type); + virtual ~EffectsHandlerImpl(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity); - bool provides( Effect::Feature ef ); + bool provides(Effect::Feature ef); - virtual void drawWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); + virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); - virtual void buildQuads( EffectWindow* w, WindowQuadList& quadList ); + virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList); - virtual void activateWindow( EffectWindow* c ); - virtual EffectWindow* activeWindow() const; - virtual void moveWindow( EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0 ); - virtual void windowToDesktop( EffectWindow* w, int desktop ); - virtual void windowToScreen( EffectWindow* w, int screen ); - virtual void setShowingDesktop( bool showing ); + virtual void activateWindow(EffectWindow* c); + virtual EffectWindow* activeWindow() const; + virtual void moveWindow(EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0); + virtual void windowToDesktop(EffectWindow* w, int desktop); + virtual void windowToScreen(EffectWindow* w, int screen); + virtual void setShowingDesktop(bool showing); - virtual int currentDesktop() const; - virtual int numberOfDesktops() const; - virtual void setCurrentDesktop( int desktop ); - virtual void setNumberOfDesktops( int desktops ); - virtual QSize desktopGridSize() const; - virtual int desktopGridWidth() const; - virtual int desktopGridHeight() const; - virtual int workspaceWidth() const; - virtual int workspaceHeight() const; - virtual int desktopAtCoords( QPoint coords ) const; - virtual QPoint desktopGridCoords( int id ) const; - virtual QPoint desktopCoords( int id ) const; - virtual int desktopAbove( int desktop = 0, bool wrap = true ) const; - virtual int desktopToRight( int desktop = 0, bool wrap = true ) const; - virtual int desktopBelow( int desktop = 0, bool wrap = true ) const; - virtual int desktopToLeft( int desktop = 0, bool wrap = true ) const; - virtual bool isDesktopLayoutDynamic() const; - virtual int addDesktop( QPoint coords ); - virtual void deleteDesktop( int id ); - virtual QString desktopName( int desktop ) const; - virtual bool optionRollOverDesktops() const; + virtual int currentDesktop() const; + virtual int numberOfDesktops() const; + virtual void setCurrentDesktop(int desktop); + virtual void setNumberOfDesktops(int desktops); + virtual QSize desktopGridSize() const; + virtual int desktopGridWidth() const; + virtual int desktopGridHeight() const; + virtual int workspaceWidth() const; + virtual int workspaceHeight() const; + virtual int desktopAtCoords(QPoint coords) const; + virtual QPoint desktopGridCoords(int id) const; + virtual QPoint desktopCoords(int id) const; + virtual int desktopAbove(int desktop = 0, bool wrap = true) const; + virtual int desktopToRight(int desktop = 0, bool wrap = true) const; + virtual int desktopBelow(int desktop = 0, bool wrap = true) const; + virtual int desktopToLeft(int desktop = 0, bool wrap = true) const; + virtual bool isDesktopLayoutDynamic() const; + virtual int addDesktop(QPoint coords); + virtual void deleteDesktop(int id); + virtual QString desktopName(int desktop) const; + virtual bool optionRollOverDesktops() const; - virtual int displayWidth() const; - virtual int displayHeight() const; - virtual QPoint cursorPos() const; - virtual bool grabKeyboard( Effect* effect ); - virtual void ungrabKeyboard(); - virtual void* getProxy( QString name ); - virtual void startMousePolling(); - virtual void stopMousePolling(); - virtual EffectWindow* findWindow( WId id ) const; - virtual EffectWindowList stackingOrder() const; - virtual void setElevatedWindow( EffectWindow* w, bool set ); + virtual int displayWidth() const; + virtual int displayHeight() const; + virtual QPoint cursorPos() const; + virtual bool grabKeyboard(Effect* effect); + virtual void ungrabKeyboard(); + virtual void* getProxy(QString name); + virtual void startMousePolling(); + virtual void stopMousePolling(); + virtual EffectWindow* findWindow(WId id) const; + virtual EffectWindowList stackingOrder() const; + virtual void setElevatedWindow(EffectWindow* w, bool set); - virtual void setTabBoxWindow(EffectWindow*); - virtual void setTabBoxDesktop(int); - virtual EffectWindowList currentTabBoxWindowList() const; - virtual void refTabBox(); - virtual void unrefTabBox(); - virtual void closeTabBox(); - virtual QList< int > currentTabBoxDesktopList() const; - virtual int currentTabBoxDesktop() const; - virtual EffectWindow* currentTabBoxWindow() const; + virtual void setTabBoxWindow(EffectWindow*); + virtual void setTabBoxDesktop(int); + virtual EffectWindowList currentTabBoxWindowList() const; + virtual void refTabBox(); + virtual void unrefTabBox(); + virtual void closeTabBox(); + virtual QList< int > currentTabBoxDesktopList() const; + virtual int currentTabBoxDesktop() const; + virtual EffectWindow* currentTabBoxWindow() const; - virtual void setActiveFullScreenEffect( Effect* e ); - virtual Effect* activeFullScreenEffect() const; + virtual void setActiveFullScreenEffect(Effect* e); + virtual Effect* activeFullScreenEffect() const; - virtual void pushRenderTarget(GLRenderTarget* target); - virtual GLRenderTarget* popRenderTarget(); - virtual bool isRenderTargetBound(); + virtual void pushRenderTarget(GLRenderTarget* target); + virtual GLRenderTarget* popRenderTarget(); + virtual bool isRenderTargetBound(); - virtual void addRepaintFull(); - virtual void addRepaint( const QRect& r ); - virtual void addRepaint( const QRegion& r ); - virtual void addRepaint( int x, int y, int w, int h ); - virtual int activeScreen() const; - virtual int numScreens() const; - virtual int screenNumber( const QPoint& pos ) const; - virtual QRect clientArea( clientAreaOption, int screen, int desktop ) const; - virtual QRect clientArea( clientAreaOption, const EffectWindow* c ) const; - virtual QRect clientArea( clientAreaOption, const QPoint& p, int desktop ) const; - virtual double animationTimeFactor() const; - virtual WindowQuadType newWindowQuadType(); + virtual void addRepaintFull(); + virtual void addRepaint(const QRect& r); + virtual void addRepaint(const QRegion& r); + virtual void addRepaint(int x, int y, int w, int h); + virtual int activeScreen() const; + virtual int numScreens() const; + virtual int screenNumber(const QPoint& pos) const; + virtual QRect clientArea(clientAreaOption, int screen, int desktop) const; + virtual QRect clientArea(clientAreaOption, const EffectWindow* c) const; + virtual QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const; + virtual double animationTimeFactor() const; + virtual WindowQuadType newWindowQuadType(); - virtual Window createInputWindow( Effect* e, int x, int y, int w, int h, const QCursor& cursor ); - using EffectsHandler::createInputWindow; - virtual void destroyInputWindow( Window w ); - virtual bool checkInputWindowEvent( XEvent* e ); - virtual void checkInputWindowStacking(); + virtual Window createInputWindow(Effect* e, int x, int y, int w, int h, const QCursor& cursor); + using EffectsHandler::createInputWindow; + virtual void destroyInputWindow(Window w); + virtual bool checkInputWindowEvent(XEvent* e); + virtual void checkInputWindowStacking(); - virtual void checkElectricBorder(const QPoint &pos, Time time); - virtual void reserveElectricBorder( ElectricBorder border ); - virtual void unreserveElectricBorder( ElectricBorder border ); - virtual void reserveElectricBorderSwitching( bool reserve ); + virtual void checkElectricBorder(const QPoint &pos, Time time); + virtual void reserveElectricBorder(ElectricBorder border); + virtual void unreserveElectricBorder(ElectricBorder border); + virtual void reserveElectricBorderSwitching(bool reserve); - virtual unsigned long xrenderBufferPicture(); - virtual void reconfigure(); - virtual void registerPropertyType( long atom, bool reg ); - virtual QByteArray readRootProperty( long atom, long type, int format ) const; - virtual void deleteRootProperty( long atom ) const; + virtual unsigned long xrenderBufferPicture(); + virtual void reconfigure(); + virtual void registerPropertyType(long atom, bool reg); + virtual QByteArray readRootProperty(long atom, long type, int format) const; + virtual void deleteRootProperty(long atom) const; - virtual bool hasDecorationShadows() const; + virtual bool hasDecorationShadows() const; - virtual bool decorationsHaveAlpha() const; + virtual bool decorationsHaveAlpha() const; - virtual bool decorationSupportsBlurBehind() const; + virtual bool decorationSupportsBlurBehind() const; - virtual EffectFrame* effectFrame( EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment ) const; + virtual EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment) const; - // internal (used by kwin core or compositing code) - void startPaint(); - void windowUserMovedResized( EffectWindow* c, bool first, bool last ); - void windowMoveResizeGeometryUpdate( EffectWindow* c, const QRect& geometry ); - void windowOpacityChanged( EffectWindow* c, double old_opacity ); - void windowAdded( EffectWindow* c ); - void windowClosed( EffectWindow* c ); - void windowDeleted( EffectWindow* c ); - void windowActivated( EffectWindow* c ); - void windowMinimized( EffectWindow* c ); - void windowUnminimized( EffectWindow* c ); - void clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ); - void clientGroupItemAdded( EffectWindow* from, EffectWindow* to ); - void clientGroupItemRemoved( EffectWindow* c, EffectWindow* group ); - void desktopChanged( int old ); - void windowDamaged( EffectWindow* w, const QRect& r ); - void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - void tabBoxAdded( int mode ); - void tabBoxClosed(); - void tabBoxUpdated(); - void tabBoxKeyEvent( QKeyEvent* event ); - bool borderActivated( ElectricBorder border ); - void mouseChanged( const QPoint& pos, const QPoint& oldpos, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - void grabbedKeyboardEvent( QKeyEvent* e ); - bool hasKeyboardGrab() const; - void propertyNotify( EffectWindow* c, long atom ); - void numberDesktopsChanged( int old ); + // internal (used by kwin core or compositing code) + void startPaint(); + void windowUserMovedResized(EffectWindow* c, bool first, bool last); + void windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry); + void windowOpacityChanged(EffectWindow* c, double old_opacity); + void windowAdded(EffectWindow* c); + void windowClosed(EffectWindow* c); + void windowDeleted(EffectWindow* c); + void windowActivated(EffectWindow* c); + void windowMinimized(EffectWindow* c); + void windowUnminimized(EffectWindow* c); + void clientGroupItemSwitched(EffectWindow* from, EffectWindow* to); + void clientGroupItemAdded(EffectWindow* from, EffectWindow* to); + void clientGroupItemRemoved(EffectWindow* c, EffectWindow* group); + void desktopChanged(int old); + void windowDamaged(EffectWindow* w, const QRect& r); + void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + void tabBoxAdded(int mode); + void tabBoxClosed(); + void tabBoxUpdated(); + void tabBoxKeyEvent(QKeyEvent* event); + bool borderActivated(ElectricBorder border); + void mouseChanged(const QPoint& pos, const QPoint& oldpos, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); + void grabbedKeyboardEvent(QKeyEvent* e); + bool hasKeyboardGrab() const; + void propertyNotify(EffectWindow* c, long atom); + void numberDesktopsChanged(int old); - bool loadEffect( const QString& name ); - void toggleEffect( const QString& name ); - void unloadEffect( const QString& name ); - void reconfigureEffect( const QString& name ); - bool isEffectLoaded( const QString& name ); - QStringList loadedEffects() const; - QStringList listOfEffects() const; + bool loadEffect(const QString& name); + void toggleEffect(const QString& name); + void unloadEffect(const QString& name); + void reconfigureEffect(const QString& name); + bool isEffectLoaded(const QString& name); + QStringList loadedEffects() const; + QStringList listOfEffects() const; - QList elevatedWindows() const; + QList elevatedWindows() const; - protected: - KLibrary* findEffectLibrary( KService* service ); - void effectsChanged(); +protected: + KLibrary* findEffectLibrary(KService* service); + void effectsChanged(); - Effect* keyboard_grab_effect; - QStack render_targets; - Effect* fullscreen_effect; - QList elevated_windows; - QMultiMap< int, EffectPair > effect_order; - QHash< long, int > registered_atoms; - int next_window_quad_type; - int mouse_poll_ref_count; - int current_paint_effectframe; + Effect* keyboard_grab_effect; + QStack render_targets; + Effect* fullscreen_effect; + QList elevated_windows; + QMultiMap< int, EffectPair > effect_order; + QHash< long, int > registered_atoms; + int next_window_quad_type; + int mouse_poll_ref_count; + int current_paint_effectframe; }; class EffectWindowImpl : public EffectWindow { - public: - EffectWindowImpl(); - virtual ~EffectWindowImpl(); +public: + EffectWindowImpl(); + virtual ~EffectWindowImpl(); - virtual void enablePainting( int reason ); - virtual void disablePainting( int reason ); - virtual bool isPaintingEnabled(); - virtual void addRepaint( const QRect& r ); - virtual void addRepaint( int x, int y, int w, int h ); - virtual void addRepaintFull(); + virtual void enablePainting(int reason); + virtual void disablePainting(int reason); + virtual bool isPaintingEnabled(); + virtual void addRepaint(const QRect& r); + virtual void addRepaint(int x, int y, int w, int h); + virtual void addRepaintFull(); - virtual void refWindow(); - virtual void unrefWindow(); - virtual bool isDeleted() const; + virtual void refWindow(); + virtual void unrefWindow(); + virtual bool isDeleted() const; - virtual bool isOnAllDesktops() const; - virtual int desktop() const; // prefer isOnXXX() - virtual bool isMinimized() const; - virtual double opacity() const; - virtual bool hasAlpha() const; - virtual QString caption() const; - virtual QPixmap icon() const; - virtual QString windowClass() const; - virtual QString windowRole() const; - virtual const EffectWindowGroup* group() const; + virtual bool isOnAllDesktops() const; + virtual int desktop() const; // prefer isOnXXX() + virtual bool isMinimized() const; + virtual double opacity() const; + virtual bool hasAlpha() const; + virtual QString caption() const; + virtual QPixmap icon() const; + virtual QString windowClass() const; + virtual QString windowRole() const; + virtual const EffectWindowGroup* group() const; - virtual int x() const; - virtual int y() const; - virtual int width() const; - virtual int height() const; - virtual QRect geometry() const; - virtual QRegion shape() const; - virtual int screen() const; - virtual bool hasOwnShape() const; - virtual QPoint pos() const; - virtual QSize size() const; - virtual QRect rect() const; - virtual bool isMovable() const; - virtual bool isMovableAcrossScreens() const; - virtual bool isUserMove() const; - virtual bool isUserResize() const; - virtual QRect iconGeometry() const; - virtual QRect contentsRect() const; - virtual QRect decorationInnerRect() const; - virtual QByteArray readProperty( long atom, long type, int format ) const; - virtual void deleteProperty( long atom ) const; + virtual int x() const; + virtual int y() const; + virtual int width() const; + virtual int height() const; + virtual QRect geometry() const; + virtual QRegion shape() const; + virtual int screen() const; + virtual bool hasOwnShape() const; + virtual QPoint pos() const; + virtual QSize size() const; + virtual QRect rect() const; + virtual bool isMovable() const; + virtual bool isMovableAcrossScreens() const; + virtual bool isUserMove() const; + virtual bool isUserResize() const; + virtual QRect iconGeometry() const; + virtual QRect contentsRect() const; + virtual QRect decorationInnerRect() const; + virtual QByteArray readProperty(long atom, long type, int format) const; + virtual void deleteProperty(long atom) const; - virtual bool isDesktop() const; - virtual bool isDock() const; - virtual bool isToolbar() const; - virtual bool isTopMenu() const; - virtual bool isMenu() const; - virtual bool isNormalWindow() const; // normal as in 'NET::Normal or NET::Unknown non-transient' - virtual bool isSpecialWindow() const; - virtual bool isDialog() const; - virtual bool isSplash() const; - virtual bool isUtility() const; - virtual bool isDropdownMenu() const; - virtual bool isPopupMenu() const; // a context popup, not dropdown, not torn-off - virtual bool isTooltip() const; - virtual bool isNotification() const; - virtual bool isComboBox() const; - virtual bool isDNDIcon() const; - virtual bool isManaged() const; // managed or override-redirect - virtual bool acceptsFocus() const; - virtual bool keepAbove() const; + virtual bool isDesktop() const; + virtual bool isDock() const; + virtual bool isToolbar() const; + virtual bool isTopMenu() const; + virtual bool isMenu() const; + virtual bool isNormalWindow() const; // normal as in 'NET::Normal or NET::Unknown non-transient' + virtual bool isSpecialWindow() const; + virtual bool isDialog() const; + virtual bool isSplash() const; + virtual bool isUtility() const; + virtual bool isDropdownMenu() const; + virtual bool isPopupMenu() const; // a context popup, not dropdown, not torn-off + virtual bool isTooltip() const; + virtual bool isNotification() const; + virtual bool isComboBox() const; + virtual bool isDNDIcon() const; + virtual bool isManaged() const; // managed or override-redirect + virtual bool acceptsFocus() const; + virtual bool keepAbove() const; - virtual bool isModal() const; - virtual EffectWindow* findModal(); - virtual EffectWindowList mainWindows() const; + virtual bool isModal() const; + virtual EffectWindow* findModal(); + virtual EffectWindowList mainWindows() const; - virtual bool isSkipSwitcher() const; + virtual bool isSkipSwitcher() const; - virtual WindowQuadList buildQuads( bool force = false ) const; + virtual WindowQuadList buildQuads(bool force = false) const; - virtual void minimize() const; - virtual void unminimize() const; - virtual void closeWindow() const; + virtual void minimize() const; + virtual void unminimize() const; + virtual void closeWindow() const; - virtual bool visibleInClientGroup() const; + virtual bool visibleInClientGroup() const; - const Toplevel* window() const; - Toplevel* window(); + const Toplevel* window() const; + Toplevel* window(); - void setWindow( Toplevel* w ); // internal - void setSceneWindow( Scene::Window* w ); // internal - const Scene::Window* sceneWindow() const; // internal - Scene::Window* sceneWindow(); // internal + void setWindow(Toplevel* w); // internal + void setSceneWindow(Scene::Window* w); // internal + const Scene::Window* sceneWindow() const; // internal + Scene::Window* sceneWindow(); // internal - void setData( int role, const QVariant &data ); - QVariant data( int role ) const; - private: - Toplevel* toplevel; - Scene::Window* sw; // This one is used only during paint pass. - QHash dataMap; + void setData(int role, const QVariant &data); + QVariant data(int role) const; +private: + Toplevel* toplevel; + Scene::Window* sw; // This one is used only during paint pass. + QHash dataMap; }; class EffectWindowGroupImpl : public EffectWindowGroup - { - public: - EffectWindowGroupImpl( Group* g ); - virtual EffectWindowList members() const; - private: - Group* group; - }; +{ +public: + EffectWindowGroupImpl(Group* g); + virtual EffectWindowList members() const; +private: + Group* group; +}; class EffectFrameImpl : public QObject, public EffectFrame - { +{ Q_OBJECT - public: - explicit EffectFrameImpl( EffectFrameStyle style, bool staticSize = true, QPoint position = QPoint( -1, -1 ), - Qt::Alignment alignment = Qt::AlignCenter ); - virtual ~EffectFrameImpl(); +public: + explicit EffectFrameImpl(EffectFrameStyle style, bool staticSize = true, QPoint position = QPoint(-1, -1), + Qt::Alignment alignment = Qt::AlignCenter); + virtual ~EffectFrameImpl(); - virtual void free(); - virtual void render( QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0 ); - virtual Qt::Alignment alignment() const; - virtual void setAlignment( Qt::Alignment alignment ); - virtual const QFont& font() const; - virtual void setFont( const QFont& font ); - virtual const QRect& geometry() const; - virtual void setGeometry( const QRect& geometry, bool force = false ); - virtual const QPixmap& icon() const; - virtual void setIcon( const QPixmap& icon ); - virtual const QSize& iconSize() const; - virtual void setIconSize( const QSize& size ); - virtual void setPosition( const QPoint& point ); - virtual const QString& text() const; - virtual void setText( const QString& text ); - EffectFrameStyle style() const - { - return m_style; - }; - Plasma::FrameSvg& frame() - { - return m_frame; - } - bool isStatic() const - { - return m_static; - }; - void finalRender( QRegion region, double opacity, double frameOpacity ) const; - virtual void setShader( GLShader* shader ) - { - m_shader = shader; - } - virtual GLShader* shader() const - { - return m_shader; - } - virtual void setSelection( const QRect& selection ); - const QRect& selection() const - { - return m_selectionGeometry; - } - Plasma::FrameSvg& selectionFrame() - { - return m_selection; - } - - private Q_SLOTS: - void plasmaThemeChanged(); - - private: - Q_DISABLE_COPY( EffectFrameImpl ) // As we need to use Qt slots we cannot copy this class - void align( QRect &geometry ); // positions geometry around m_point respecting m_alignment - void autoResize(); // Auto-resize if not a static size - - EffectFrameStyle m_style; - Plasma::FrameSvg m_frame; // TODO: share between all EffectFrames - Plasma::FrameSvg m_selection; - - // Position - bool m_static; - QPoint m_point; - Qt::Alignment m_alignment; - QRect m_geometry; - - // Contents - QString m_text; - QFont m_font; - QPixmap m_icon; - QSize m_iconSize; - QRect m_selectionGeometry; - - Scene::EffectFrame* m_sceneFrame; - GLShader* m_shader; + virtual void free(); + virtual void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0); + virtual Qt::Alignment alignment() const; + virtual void setAlignment(Qt::Alignment alignment); + virtual const QFont& font() const; + virtual void setFont(const QFont& font); + virtual const QRect& geometry() const; + virtual void setGeometry(const QRect& geometry, bool force = false); + virtual const QPixmap& icon() const; + virtual void setIcon(const QPixmap& icon); + virtual const QSize& iconSize() const; + virtual void setIconSize(const QSize& size); + virtual void setPosition(const QPoint& point); + virtual const QString& text() const; + virtual void setText(const QString& text); + EffectFrameStyle style() const { + return m_style; }; + Plasma::FrameSvg& frame() { + return m_frame; + } + bool isStatic() const { + return m_static; + }; + void finalRender(QRegion region, double opacity, double frameOpacity) const; + virtual void setShader(GLShader* shader) { + m_shader = shader; + } + virtual GLShader* shader() const { + return m_shader; + } + virtual void setSelection(const QRect& selection); + const QRect& selection() const { + return m_selectionGeometry; + } + Plasma::FrameSvg& selectionFrame() { + return m_selection; + } + +private Q_SLOTS: + void plasmaThemeChanged(); + +private: + Q_DISABLE_COPY(EffectFrameImpl) // As we need to use Qt slots we cannot copy this class + void align(QRect &geometry); // positions geometry around m_point respecting m_alignment + void autoResize(); // Auto-resize if not a static size + + EffectFrameStyle m_style; + Plasma::FrameSvg m_frame; // TODO: share between all EffectFrames + Plasma::FrameSvg m_selection; + + // Position + bool m_static; + QPoint m_point; + Qt::Alignment m_alignment; + QRect m_geometry; + + // Contents + QString m_text; + QFont m_font; + QPixmap m_icon; + QSize m_iconSize; + QRect m_selectionGeometry; + + Scene::EffectFrame* m_sceneFrame; + GLShader* m_shader; +}; inline QList EffectsHandlerImpl::elevatedWindows() const - { +{ return elevated_windows; - } +} inline -EffectWindowGroupImpl::EffectWindowGroupImpl( Group* g ) - : group( g ) - { - } +EffectWindowGroupImpl::EffectWindowGroupImpl(Group* g) + : group(g) +{ +} -EffectWindow* effectWindow( Toplevel* w ); -EffectWindow* effectWindow( Scene::Window* w ); +EffectWindow* effectWindow(Toplevel* w); +EffectWindow* effectWindow(Scene::Window* w); inline const Scene::Window* EffectWindowImpl::sceneWindow() const - { +{ return sw; - } +} inline Scene::Window* EffectWindowImpl::sceneWindow() - { +{ return sw; - } +} inline const Toplevel* EffectWindowImpl::window() const - { +{ return toplevel; - } +} inline Toplevel* EffectWindowImpl::window() - { +{ return toplevel; - } +} } // namespace diff --git a/effects/_test/demo_liquid.cpp b/effects/_test/demo_liquid.cpp index 3a75bae75..5b1ef0385 100644 --- a/effects/_test/demo_liquid.cpp +++ b/effects/_test/demo_liquid.cpp @@ -31,36 +31,35 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( demo_liquid, LiquidEffect ) -KWIN_EFFECT_SUPPORTED( demo_liquid, LiquidEffect::supported() ) +KWIN_EFFECT(demo_liquid, LiquidEffect) +KWIN_EFFECT_SUPPORTED(demo_liquid, LiquidEffect::supported()) LiquidEffect::LiquidEffect() : Effect() - { +{ mTexture = 0; mRenderTarget = 0; mShader = 0; mTime = 0.0f; mValid = loadData(); - } +} LiquidEffect::~LiquidEffect() - { +{ delete mTexture; delete mRenderTarget; delete mShader; - } +} bool LiquidEffect::loadData() - { +{ // If NPOT textures are not supported, use nearest power-of-two sized // texture. It wastes memory, but it's possible to support systems without // NPOT textures that way int texw = displayWidth(); int texh = displayHeight(); - if( !GLTexture::NPOTTextureSupported() ) - { - kWarning( 1212 ) << "NPOT textures not supported, wasting some memory" ; + if (!GLTexture::NPOTTextureSupported()) { + kWarning(1212) << "NPOT textures not supported, wasting some memory" ; texw = nearestPowerOfTwo(texw); texh = nearestPowerOfTwo(texh); } @@ -70,19 +69,17 @@ bool LiquidEffect::loadData() mTexture->setWrapMode(GL_CLAMP); mRenderTarget = new GLRenderTarget(mTexture); - if( !mRenderTarget->valid() ) + if (!mRenderTarget->valid()) return false; QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/liquid.frag"); QString vertexshader = KGlobal::dirs()->findResource("data", "kwin/liquid.vert"); - if(fragmentshader.isEmpty() || vertexshader.isEmpty()) - { + if (fragmentshader.isEmpty() || vertexshader.isEmpty()) { kError(1212) << "Couldn't locate shader files" << endl; return false; } mShader = new GLShader(vertexshader, fragmentshader); - if(!mShader->isValid()) - { + if (!mShader->isValid()) { kError(1212) << "The shader failed to load!" << endl; return false; } @@ -93,38 +90,36 @@ bool LiquidEffect::loadData() mShader->unbind(); return true; - } +} bool LiquidEffect::supported() - { +{ return GLRenderTarget::supported() && - GLShader::fragmentShaderSupported() && - (effects->compositingType() == OpenGLCompositing); - } + GLShader::fragmentShaderSupported() && + (effects->compositingType() == OpenGLCompositing); +} -void LiquidEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void LiquidEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ mTime += time / 1000.0f; - if(mValid) - { + if (mValid) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; // Start rendering to texture effects->pushRenderTarget(mRenderTarget); - } - - effects->prePaintScreen(data, time); } + effects->prePaintScreen(data, time); +} + void LiquidEffect::postPaintScreen() - { +{ // Call the next effect. effects->postPaintScreen(); - if(mValid) - { + if (mValid) { // Disable render texture - assert( effects->popRenderTarget() == mRenderTarget ); + assert(effects->popRenderTarget() == mRenderTarget); mTexture->bind(); // Use the shader @@ -133,10 +128,10 @@ void LiquidEffect::postPaintScreen() // Render fullscreen quad with screen contents glBegin(GL_QUADS); - glVertex2f(0.0, displayHeight()); - glVertex2f(displayWidth(), displayHeight()); - glVertex2f(displayWidth(), 0.0); - glVertex2f(0.0, 0.0); + glVertex2f(0.0, displayHeight()); + glVertex2f(displayWidth(), displayHeight()); + glVertex2f(displayWidth(), 0.0); + glVertex2f(0.0, 0.0); glEnd(); mShader->unbind(); @@ -144,10 +139,10 @@ void LiquidEffect::postPaintScreen() // Make sure the animation continues effects->addRepaintFull(); - } - } +} + } // namespace diff --git a/effects/_test/demo_liquid.h b/effects/_test/demo_liquid.h index 42dbab18b..03063d951 100644 --- a/effects/_test/demo_liquid.h +++ b/effects/_test/demo_liquid.h @@ -35,27 +35,27 @@ class GLShader; * Turns your desktop into a wavy (liquid) surface **/ class LiquidEffect : public Effect - { - public: - LiquidEffect(); - ~LiquidEffect(); +{ +public: + LiquidEffect(); + ~LiquidEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); - static bool supported(); + static bool supported(); - protected: - bool loadData(); +protected: + bool loadData(); - private: - GLTexture* mTexture; - GLRenderTarget* mRenderTarget; - GLShader* mShader; - bool mValid; +private: + GLTexture* mTexture; + GLRenderTarget* mRenderTarget; + GLShader* mShader; + bool mValid; - double mTime; - }; + double mTime; +}; } // namespace diff --git a/effects/_test/demo_shakymove.cpp b/effects/_test/demo_shakymove.cpp index a3a7a2e15..1b7ff8456 100644 --- a/effects/_test/demo_shakymove.cpp +++ b/effects/_test/demo_shakymove.cpp @@ -13,77 +13,73 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( demo_shakymove, ShakyMoveEffect ) +KWIN_EFFECT(demo_shakymove, ShakyMoveEffect) ShakyMoveEffect::ShakyMoveEffect() - { - connect( &timer, SIGNAL( timeout()), SLOT( tick())); - } +{ + connect(&timer, SIGNAL(timeout()), SLOT(tick())); +} static const int shaky_diff[] = { 0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1 }; -static const int SHAKY_MAX = sizeof( shaky_diff ) / sizeof( shaky_diff[ 0 ] ); +static const int SHAKY_MAX = sizeof(shaky_diff) / sizeof(shaky_diff[ 0 ]); -void ShakyMoveEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty()) +void ShakyMoveEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void ShakyMoveEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( windows.contains( w )) +void ShakyMoveEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (windows.contains(w)) data.setTransformed(); - effects->prePaintWindow( w, data, time ); - } + effects->prePaintWindow(w, data, time); +} -void ShakyMoveEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( windows.contains( w )) +void ShakyMoveEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (windows.contains(w)) data.xTranslate += shaky_diff[ windows[ w ]]; - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); +} -void ShakyMoveEffect::windowUserMovedResized( EffectWindow* c, bool first, bool last ) - { - if( first ) - { - if( windows.isEmpty()) - timer.start( 50 ); +void ShakyMoveEffect::windowUserMovedResized(EffectWindow* c, bool first, bool last) +{ + if (first) { + if (windows.isEmpty()) + timer.start(50); windows[ c ] = 0; - } - else if( last ) - { - windows.remove( c ); + } else if (last) { + windows.remove(c); // just repaint whole screen, transformation is involved effects->addRepaintFull(); - if( windows.isEmpty()) + if (windows.isEmpty()) timer.stop(); - } } +} -void ShakyMoveEffect::windowClosed( EffectWindow* c ) - { - windows.remove( c ); - if( windows.isEmpty()) +void ShakyMoveEffect::windowClosed(EffectWindow* c) +{ + windows.remove(c); + if (windows.isEmpty()) timer.stop(); - } +} // TODO use time provided with prePaintWindow() instead void ShakyMoveEffect::tick() - { - for( QHash< const EffectWindow*, int >::Iterator it = windows.begin(); - it != windows.end(); - ++it ) - { - if( *it == SHAKY_MAX - 1 ) +{ + for (QHash< const EffectWindow*, int >::Iterator it = windows.begin(); + it != windows.end(); + ++it) { + if (*it == SHAKY_MAX - 1) *it = 0; else ++(*it); // just repaint whole screen, transformation is involved effects->addRepaintFull(); - } } +} } // namespace diff --git a/effects/_test/demo_shakymove.h b/effects/_test/demo_shakymove.h index e2de1bf8c..5fc4917af 100644 --- a/effects/_test/demo_shakymove.h +++ b/effects/_test/demo_shakymove.h @@ -20,21 +20,21 @@ namespace KWin class ShakyMoveEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - ShakyMoveEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowUserMovedResized( EffectWindow* c, bool first, bool last ); - virtual void windowClosed( EffectWindow* c ); - private slots: - void tick(); - private: - QHash< const EffectWindow*, int > windows; - QTimer timer; - }; +public: + ShakyMoveEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowUserMovedResized(EffectWindow* c, bool first, bool last); + virtual void windowClosed(EffectWindow* c); +private slots: + void tick(); +private: + QHash< const EffectWindow*, int > windows; + QTimer timer; +}; } // namespace diff --git a/effects/_test/demo_shiftworkspaceup.cpp b/effects/_test/demo_shiftworkspaceup.cpp index ce2121754..96498c230 100644 --- a/effects/_test/demo_shiftworkspaceup.cpp +++ b/effects/_test/demo_shiftworkspaceup.cpp @@ -13,46 +13,46 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( demo_shiftworkspaceup, ShiftWorkspaceUpEffect ) +KWIN_EFFECT(demo_shiftworkspaceup, ShiftWorkspaceUpEffect) ShiftWorkspaceUpEffect::ShiftWorkspaceUpEffect() - : up( false ) - , diff( 0 ) - { - connect( &timer, SIGNAL( timeout()), SLOT( tick())); - timer.start( 2000 ); - } + : up(false) + , diff(0) +{ + connect(&timer, SIGNAL(timeout()), SLOT(tick())); + timer.start(2000); +} -void ShiftWorkspaceUpEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( up && diff < 1000 ) - diff = qBound( 0, diff + time, 1000 ); // KDE3: note this differs from KCLAMP - if( !up && diff > 0 ) - diff = qBound( 0, diff - time, 1000 ); - if( diff != 0 ) +void ShiftWorkspaceUpEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (up && diff < 1000) + diff = qBound(0, diff + time, 1000); // KDE3: note this differs from KCLAMP + if (!up && diff > 0) + diff = qBound(0, diff - time, 1000); + if (diff != 0) data.mask |= PAINT_SCREEN_TRANSFORMED; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void ShiftWorkspaceUpEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( diff != 0 ) +void ShiftWorkspaceUpEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (diff != 0) data.yTranslate -= diff / 100; - effects->paintScreen( mask, region, data ); - } + effects->paintScreen(mask, region, data); +} void ShiftWorkspaceUpEffect::postPaintScreen() - { - if( up ? diff < 1000 : diff > 0 ) +{ + if (up ? diff < 1000 : diff > 0) effects->addRepaintFull(); // trigger next animation repaint effects->postPaintScreen(); - } +} void ShiftWorkspaceUpEffect::tick() - { +{ up = !up; effects->addRepaintFull(); - } +} } // namespace diff --git a/effects/_test/demo_shiftworkspaceup.h b/effects/_test/demo_shiftworkspaceup.h index 1f97f251a..2de830ce6 100644 --- a/effects/_test/demo_shiftworkspaceup.h +++ b/effects/_test/demo_shiftworkspaceup.h @@ -20,20 +20,20 @@ namespace KWin class ShiftWorkspaceUpEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - ShiftWorkspaceUpEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - private slots: - void tick(); - private: - QTimer timer; - bool up; - int diff; - }; +public: + ShiftWorkspaceUpEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); +private slots: + void tick(); +private: + QTimer timer; + bool up; + int diff; +}; } // namespace diff --git a/effects/_test/demo_showpicture.cpp b/effects/_test/demo_showpicture.cpp index e69cb61b5..943b20a1a 100644 --- a/effects/_test/demo_showpicture.cpp +++ b/effects/_test/demo_showpicture.cpp @@ -16,49 +16,47 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( demo_showpicture, ShowPictureEffect ) +KWIN_EFFECT(demo_showpicture, ShowPictureEffect) ShowPictureEffect::ShowPictureEffect() - : init( true ) - , picture( NULL ) - { - } + : init(true) + , picture(NULL) +{ +} ShowPictureEffect::~ShowPictureEffect() - { +{ delete picture; - } +} -void ShowPictureEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( init ) - { +void ShowPictureEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (init) { loadPicture(); init = false; - } - if( picture && region.intersects( pictureRect )) - { - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + } + if (picture && region.intersects(pictureRect)) { + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); picture->bind(); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - picture->render( region, pictureRect ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + picture->render(region, pictureRect); picture->unbind(); glPopAttrib(); - } } +} void ShowPictureEffect::loadPicture() - { - QString file = KGlobal::dirs()->findResource( "appdata", "showpicture.png" ); - if( file.isEmpty()) +{ + QString file = KGlobal::dirs()->findResource("appdata", "showpicture.png"); + if (file.isEmpty()) return; - QImage im( file ); - QRect area = effects->clientArea( PlacementArea, effects->activeScreen(), effects->currentDesktop()); - picture = new GLTexture( im ); - pictureRect = QRect( area.x() + ( area.width() - im.width()) / 2, - area.y() + ( area.height() - im.height()) / 2, im.width(), im.height()); - } + QImage im(file); + QRect area = effects->clientArea(PlacementArea, effects->activeScreen(), effects->currentDesktop()); + picture = new GLTexture(im); + pictureRect = QRect(area.x() + (area.width() - im.width()) / 2, + area.y() + (area.height() - im.height()) / 2, im.width(), im.height()); +} } // namespace diff --git a/effects/_test/demo_showpicture.h b/effects/_test/demo_showpicture.h index dacd02a7d..531ea99d4 100644 --- a/effects/_test/demo_showpicture.h +++ b/effects/_test/demo_showpicture.h @@ -19,17 +19,17 @@ namespace KWin class ShowPictureEffect : public Effect - { - public: - ShowPictureEffect(); - virtual ~ShowPictureEffect(); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - private: - void loadPicture(); - bool init; - GLTexture* picture; - QRect pictureRect; - }; +{ +public: + ShowPictureEffect(); + virtual ~ShowPictureEffect(); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); +private: + void loadPicture(); + bool init; + GLTexture* picture; + QRect pictureRect; +}; } // namespace diff --git a/effects/_test/demo_wavywindows.cpp b/effects/_test/demo_wavywindows.cpp index e7a0634ee..a0af6d1f1 100644 --- a/effects/_test/demo_wavywindows.cpp +++ b/effects/_test/demo_wavywindows.cpp @@ -26,16 +26,16 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( demo_wavywindows, WavyWindowsEffect ) +KWIN_EFFECT(demo_wavywindows, WavyWindowsEffect) WavyWindowsEffect::WavyWindowsEffect() - { +{ mTimeElapsed = 0.0f; - } +} -void WavyWindowsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void WavyWindowsEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ // Adjust elapsed time mTimeElapsed += (time / 1000.0f); // We need to mark the screen windows as transformed. Otherwise the whole @@ -43,55 +43,53 @@ void WavyWindowsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void WavyWindowsEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void WavyWindowsEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // This window will be transformed by the effect data.setTransformed(); // Check if OpenGL compositing is used // Request the window to be divided into cells which are at most 30x30 // pixels big - data.quads = data.quads.makeGrid( 30 ); + data.quads = data.quads.makeGrid(30); - effects->prePaintWindow( w, data, time ); - } + effects->prePaintWindow(w, data, time); +} -void WavyWindowsEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void WavyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ // Make sure we have OpenGL compositing and the window is vidible and not a // special window -// TODO if( w->isVisible() && !w->isSpecialWindow() ) - if( !w->isSpecialWindow() ) - { +// TODO if ( w->isVisible() && !w->isSpecialWindow() ) + if (!w->isSpecialWindow()) { // We have OpenGL compositing and the window has been subdivided // because of our request (in pre-paint pass) // Transform all the vertices to create wavy effect - for( int i = 0; - i < data.quads.count(); - ++i ) - for( int j = 0; - j < 4; - ++j ) - { + for (int i = 0; + i < data.quads.count(); + ++i) + for (int j = 0; + j < 4; + ++j) { WindowVertex& v = data.quads[ i ][ j ]; - v.move( v.x() + sin(mTimeElapsed + v.originalY() / 60 + 0.5f) * 10, - v.y() + sin(mTimeElapsed + v.originalX() / 80) * 10 ); + v.move(v.x() + sin(mTimeElapsed + v.originalY() / 60 + 0.5f) * 10, + v.y() + sin(mTimeElapsed + v.originalX() / 80) * 10); } - } - - // Call the next effect. - effects->paintWindow( w, mask, region, data ); } + // Call the next effect. + effects->paintWindow(w, mask, region, data); +} + void WavyWindowsEffect::postPaintScreen() - { +{ // Repaint the workspace so that everything would be repainted next time effects->addRepaintFull(); // Call the next effect. effects->postPaintScreen(); - } +} } // namespace diff --git a/effects/_test/demo_wavywindows.h b/effects/_test/demo_wavywindows.h index d143961b1..9b85e273e 100644 --- a/effects/_test/demo_wavywindows.h +++ b/effects/_test/demo_wavywindows.h @@ -32,18 +32,18 @@ namespace KWin **/ class WavyWindowsEffect : public Effect - { - public: - WavyWindowsEffect(); +{ +public: + WavyWindowsEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); - private: - double mTimeElapsed; - }; +private: + double mTimeElapsed; +}; } // namespace diff --git a/effects/_test/drunken.cpp b/effects/_test/drunken.cpp index 05287e9ab..3896c0d13 100644 --- a/effects/_test/drunken.cpp +++ b/effects/_test/drunken.cpp @@ -15,63 +15,61 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( drunken, DrunkenEffect ) +KWIN_EFFECT(drunken, DrunkenEffect) -void DrunkenEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty()) +void DrunkenEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void DrunkenEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( windows.contains( w )) - { +void DrunkenEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (windows.contains(w)) { windows[ w ] += time / 1000.; - if( windows[ w ] < 1 ) + if (windows[ w ] < 1) data.setTransformed(); else - windows.remove( w ); - } - effects->prePaintWindow( w, data, time ); + windows.remove(w); } + effects->prePaintWindow(w, data, time); +} -void DrunkenEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( !windows.contains( w )) - { - effects->paintWindow( w, mask, region, data ); +void DrunkenEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (!windows.contains(w)) { + effects->paintWindow(w, mask, region, data); return; - } + } WindowPaintData d1 = data; // 4 cycles, decreasing amplitude - int diff = int( sin( windows[ w ] * 8 * M_PI ) * ( 1 - windows[ w ] ) * 10 ); + int diff = int(sin(windows[ w ] * 8 * M_PI) * (1 - windows[ w ]) * 10); d1.xTranslate -= diff; d1.opacity *= 0.5; - effects->paintWindow( w, mask, region, d1 ); + effects->paintWindow(w, mask, region, d1); WindowPaintData d2 = data; d2.xTranslate += diff; d2.opacity *= 0.5; - effects->paintWindow( w, mask, region, d2 ); - } + effects->paintWindow(w, mask, region, d2); +} -void DrunkenEffect::postPaintWindow( EffectWindow* w ) - { - if( windows.contains( w )) +void DrunkenEffect::postPaintWindow(EffectWindow* w) +{ + if (windows.contains(w)) w->addRepaintFull(); - effects->postPaintWindow( w ); - } + effects->postPaintWindow(w); +} -void DrunkenEffect::windowAdded( EffectWindow* w ) - { +void DrunkenEffect::windowAdded(EffectWindow* w) +{ windows[ w ] = 0; w->addRepaintFull(); - } +} -void DrunkenEffect::windowClosed( EffectWindow* w ) - { - windows.remove( w ); - } +void DrunkenEffect::windowClosed(EffectWindow* w) +{ + windows.remove(w); +} } // namespace diff --git a/effects/_test/drunken.h b/effects/_test/drunken.h index 2b665c453..cb14ca56c 100644 --- a/effects/_test/drunken.h +++ b/effects/_test/drunken.h @@ -18,17 +18,17 @@ namespace KWin class DrunkenEffect : public Effect - { - public: - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - virtual void windowAdded( EffectWindow* w ); - virtual void windowClosed( EffectWindow* w ); - private: - QHash< EffectWindow*, double > windows; // progress - }; +{ +public: + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + virtual void windowAdded(EffectWindow* w); + virtual void windowClosed(EffectWindow* w); +private: + QHash< EffectWindow*, double > windows; // progress +}; } // namespace diff --git a/effects/_test/flame.cpp b/effects/_test/flame.cpp index 0322080dc..31328bec8 100644 --- a/effects/_test/flame.cpp +++ b/effects/_test/flame.cpp @@ -16,70 +16,64 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( flame, FlameEffect ) +KWIN_EFFECT(flame, FlameEffect) -void FlameEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty()) +void FlameEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void FlameEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( windows.contains( w )) - { - if( windows[ w ] < 1 ) - { +void FlameEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (windows.contains(w)) { + if (windows[ w ] < 1) { windows[ w ] += time / 500.; data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - data.quads = data.quads.splitAtY( windows[ w ] * w->height()); - } - else - { - windows.remove( w ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); + data.quads = data.quads.splitAtY(windows[ w ] * w->height()); + } else { + windows.remove(w); w->unrefWindow(); - } } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void FlameEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( windows.contains( w )) - { +void FlameEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (windows.contains(w)) { WindowQuadList new_quads; double ylimit = windows[ w ] * w->height(); // parts above this are already away - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() <= ylimit ) + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() <= ylimit) continue; - new_quads.append( quad ); - } - if( new_quads.isEmpty()) + new_quads.append(quad); + } + if (new_quads.isEmpty()) return; // nothing to paint data.quads = new_quads; - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void FlameEffect::postPaintWindow( EffectWindow* w ) - { - if( windows.contains( w )) - effects->addRepaint( w->geometry()); // workspace, since the window under it will need painting too +void FlameEffect::postPaintWindow(EffectWindow* w) +{ + if (windows.contains(w)) + effects->addRepaint(w->geometry()); // workspace, since the window under it will need painting too effects->postPaintScreen(); - } +} -void FlameEffect::windowClosed( EffectWindow* c ) - { +void FlameEffect::windowClosed(EffectWindow* c) +{ windows[ c ] = 0; c->refWindow(); - } +} -void FlameEffect::windowDeleted( EffectWindow* c ) - { - windows.remove( c ); - } +void FlameEffect::windowDeleted(EffectWindow* c) +{ + windows.remove(c); +} } // namespace diff --git a/effects/_test/flame.h b/effects/_test/flame.h index ee3ac7da5..a93aba379 100644 --- a/effects/_test/flame.h +++ b/effects/_test/flame.h @@ -18,17 +18,17 @@ namespace KWin class FlameEffect : public Effect - { - public: - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); - private: - QHash< const EffectWindow*, double > windows; - }; +{ +public: + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); +private: + QHash< const EffectWindow*, double > windows; +}; } // namespace diff --git a/effects/_test/gears.cpp b/effects/_test/gears.cpp index cc45c3199..2c8075ea5 100644 --- a/effects/_test/gears.cpp +++ b/effects/_test/gears.cpp @@ -33,77 +33,74 @@ Which is based on glxgears.c by Brian Paul: namespace KWin { -KWIN_EFFECT( gears, GearsEffect ) -KWIN_EFFECT_SUPPORTED( gears, GearsEffect::supported() ) +KWIN_EFFECT(gears, GearsEffect) +KWIN_EFFECT_SUPPORTED(gears, GearsEffect::supported()) GearsEffect::GearsEffect() : CubeInsideEffect() - , m_active( false ) - , m_contentRotation( 0.0f ) - , m_angle( 0.0f ) - { + , m_active(false) + , m_contentRotation(0.0f) + , m_angle(0.0f) +{ CubeEffectProxy* proxy = - static_cast( effects->getProxy( "cube" ) ); - if( proxy ) - proxy->registerCubeInsideEffect( this ); - } + static_cast(effects->getProxy("cube")); + if (proxy) + proxy->registerCubeInsideEffect(this); +} GearsEffect::~GearsEffect() - { +{ CubeEffectProxy* proxy = - static_cast( effects->getProxy( "cube" ) ); - if( proxy ) - proxy->unregisterCubeInsideEffect( this ); - } + static_cast(effects->getProxy("cube")); + if (proxy) + proxy->unregisterCubeInsideEffect(this); +} bool GearsEffect::supported() { return effects->compositingType() == OpenGLCompositing; } -void GearsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( m_active ) - { +void GearsEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (m_active) { m_contentRotation += time * 360.0f / 20000.0f; - if( m_contentRotation > 360.0f ) + if (m_contentRotation > 360.0f) m_contentRotation -= 360.0f; m_angle += time * 360.0f / 8000.0f; - if( m_angle > 360.0f ) + if (m_angle > 360.0f) m_angle -= 360.0f; - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} void GearsEffect::postPaintScreen() - { - if( m_active ) - { +{ + if (m_active) { effects->addRepaintFull(); - } - effects->postPaintScreen(); } + effects->postPaintScreen(); +} void GearsEffect::paint() - { - if( m_active ) - { +{ + if (m_active) { paintGears(); - } } +} -void GearsEffect::setActive( bool active ) - { +void GearsEffect::setActive(bool active) +{ m_active = active; - if( active ) + if (active) initGears(); else endGears(); - } +} -void GearsEffect::gear( float inner_radius, float outer_radius, float width, int teeth, float tooth_depth ) - { +void GearsEffect::gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth) +{ GLint i; GLfloat r0, r1, r2, maxr2, minr2; GLfloat angle, da; @@ -116,204 +113,196 @@ void GearsEffect::gear( float inner_radius, float outer_radius, float width, int da = 2.0 * M_PI / teeth / 4.0; - glShadeModel( GL_FLAT ); + glShadeModel(GL_FLAT); - glNormal3f( 0.0, 0.0, 1.0 ); + glNormal3f(0.0, 0.0, 1.0); /* draw front face */ - glBegin( GL_QUAD_STRIP ); + glBegin(GL_QUAD_STRIP); - for( i = 0; i <= teeth; ++i ) - { + for (i = 0; i <= teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), width * 0.5 ); - glVertex3f( r1 * cos( angle ), r1 * sin( angle ), width * 0.5 ); + glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); + glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); - if( i < teeth ) - { - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), width * 0.5 ); - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), width * 0.5 ); - } + if (i < teeth) { + glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); } + } glEnd(); /* draw front sides of teeth */ - glBegin( GL_QUADS ); + glBegin(GL_QUADS); - for( i = 0; i < teeth; ++i ) - { + for (i = 0; i < teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glVertex3f( r1 * cos( angle ), r1 * sin( angle ), width * 0.5 ); - glVertex3f( r2 * cos( angle + da ), r2 * sin( angle + da ), width * 0.5 ); - glVertex3f( r2 * cos( angle + 2 * da ), r2 * sin( angle + 2 * da ), width * 0.5 ); - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), width * 0.5 ); + glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); + glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5); + glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5); + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); r2 = minr2; - } + } r2 = maxr2; glEnd(); - glNormal3f( 0.0, 0.0, -1.0 ); + glNormal3f(0.0, 0.0, -1.0); /* draw back face */ - glBegin( GL_QUAD_STRIP ); + glBegin(GL_QUAD_STRIP); - for( i = 0; i <= teeth; ++i ) - { + for (i = 0; i <= teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glVertex3f( r1 * cos( angle ), r1 * sin( angle ), -width * 0.5 ); - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), -width * 0.5 ); + glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); + glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); - if( i < teeth ) - { - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), -width * 0.5 ); - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), -width * 0.5 ); - } + if (i < teeth) { + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); + glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); } + } glEnd(); /* draw back sides of teeth */ - glBegin( GL_QUADS ); + glBegin(GL_QUADS); da = 2.0 * M_PI / teeth / 4.0; - for( i = 0; i < teeth; ++i ) - { + for (i = 0; i < teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), -width * 0.5 ); - glVertex3f( r2 * cos( angle + 2 * da ), r2 * sin( angle + 2 * da ), -width * 0.5 ); - glVertex3f( r2 * cos (angle + da), r2 * sin (angle + da), -width * 0.5 ); - glVertex3f( r1 * cos (angle), r1 * sin (angle), -width * 0.5 ); + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); + glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5); + glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5); + glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); r2 = minr2; - } + } r2 = maxr2; glEnd(); /* draw outward faces of teeth */ - glBegin( GL_QUAD_STRIP ); + glBegin(GL_QUAD_STRIP); - for( i = 0; i < teeth; ++i ) - { + for (i = 0; i < teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glVertex3f( r1 * cos( angle ), r1 * sin( angle ), width * 0.5 ); - glVertex3f( r1 * cos( angle ), r1 * sin( angle ), -width * 0.5 ); - u = r2 * cos( angle + da ) - r1 * cos( angle ); - v = r2 * sin( angle + da ) - r1 * sin( angle ); - len = sqrt( u * u + v * v ); + glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); + glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); + u = r2 * cos(angle + da) - r1 * cos(angle); + v = r2 * sin(angle + da) - r1 * sin(angle); + len = sqrt(u * u + v * v); u /= len; v /= len; - glNormal3f( v, -u, 0.0 ); - glVertex3f( r2 * cos( angle + da ), r2 * sin( angle + da ), width * 0.5 ); - glVertex3f( r2 * cos( angle + da ), r2 * sin( angle + da ), -width * 0.5 ); - glNormal3f( cos( angle + 1.5 * da ), sin( angle + 1.5 * da ), 0.0 ); - glVertex3f( r2 * cos( angle + 2 * da ), r2 * sin( angle + 2 * da ), width * 0.5 ); - glVertex3f( r2 * cos( angle + 2 * da ), r2 * sin( angle + 2 * da ), -width * 0.5 ); - u = r1 * cos( angle + 3 * da ) - r2 * cos( angle + 2 * da ); - v = r1 * sin( angle + 3 * da ) - r2 * sin( angle + 2 * da ); - glNormal3f( v, -u, 0.0 ); - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), width * 0.5 ); - glVertex3f( r1 * cos( angle + 3 * da ), r1 * sin( angle + 3 * da ), -width * 0.5 ); - glNormal3f( cos( angle + 3.5 * da ), sin( angle + 3.5 * da ), 0.0 ); + glNormal3f(v, -u, 0.0); + glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5); + glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5); + glNormal3f(cos(angle + 1.5 * da), sin(angle + 1.5 * da), 0.0); + glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5); + glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5); + u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da); + v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da); + glNormal3f(v, -u, 0.0); + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); + glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); + glNormal3f(cos(angle + 3.5 * da), sin(angle + 3.5 * da), 0.0); r2 = minr2; - } + } r2 = maxr2; - glVertex3f( r1 * cos( 0 ), r1 * sin( 0 ), width * 0.5 ); - glVertex3f( r1 * cos( 0 ), r1 * sin( 0 ), -width * 0.5 ); + glVertex3f(r1 * cos(0), r1 * sin(0), width * 0.5); + glVertex3f(r1 * cos(0), r1 * sin(0), -width * 0.5); glEnd(); - glShadeModel( GL_SMOOTH ); + glShadeModel(GL_SMOOTH); /* draw inside radius cylinder */ - glBegin( GL_QUAD_STRIP ); + glBegin(GL_QUAD_STRIP); - for( i = 0; i <= teeth; ++i ) - { + for (i = 0; i <= teeth; ++i) { angle = i * 2.0 * M_PI / teeth; - glNormal3f( -cos( angle ), -sin( angle ), 0.0 ); - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), -width * 0.5 ); - glVertex3f( r0 * cos( angle ), r0 * sin( angle ), width * 0.5 ); - } - glEnd(); + glNormal3f(-cos(angle), -sin(angle), 0.0); + glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); + glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); } + glEnd(); +} void GearsEffect::paintGears() - { +{ static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 }; - QRect rect = effects->clientArea( FullArea, effects->activeScreen(), effects->currentDesktop() ); + QRect rect = effects->clientArea(FullArea, effects->activeScreen(), effects->currentDesktop()); glPushMatrix(); // invert scale float fovy = 60.0f; float zNear = 0.1f; - float ymax = zNear * tan( fovy * M_PI / 360.0f ); + float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin; float xmax = ymax; - float scaleFactor = 1.1 * tan( fovy * M_PI / 360.0f )/ymax; - glScalef( 1.0f/((xmax-xmin)*scaleFactor/displayWidth()), 1.0f/(-(ymax-ymin)*scaleFactor/displayHeight()), 1000.0f ); + float scaleFactor = 1.1 * tan(fovy * M_PI / 360.0f) / ymax; + glScalef(1.0f / ((xmax - xmin)*scaleFactor / displayWidth()), 1.0f / (-(ymax - ymin)*scaleFactor / displayHeight()), 1000.0f); - glPushAttrib( GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT ); + glPushAttrib(GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT); - glDisable( GL_BLEND ); + glDisable(GL_BLEND); glPushMatrix(); // content rotation requires depth test - so disabled // glRotatef( m_contentRotation, 0.0, 1.0, 0.0 ); - glScalef( 0.05, 0.05, 0.05 ); + glScalef(0.05, 0.05, 0.05); - glEnable( GL_NORMALIZE ); - glEnable( GL_LIGHTING ); - glEnable( GL_LIGHT1 ); - glDisable( GL_COLOR_MATERIAL ); + glEnable(GL_NORMALIZE); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT1); + glDisable(GL_COLOR_MATERIAL); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glPushMatrix(); - glTranslatef( -3.0, -2.0, 0.0 ); - glRotatef( m_angle, 0.0, 0.0, 1.0 ); - glCallList( m_gear1 ); + glTranslatef(-3.0, -2.0, 0.0); + glRotatef(m_angle, 0.0, 0.0, 1.0); + glCallList(m_gear1); glPopMatrix(); glPushMatrix(); - glTranslatef( 3.1, -2.0, 0.0 ); - glRotatef( -2.0 * m_angle - 9.0, 0.0, 0.0, 1.0 ); - glCallList( m_gear2 ); + glTranslatef(3.1, -2.0, 0.0); + glRotatef(-2.0 * m_angle - 9.0, 0.0, 0.0, 1.0); + glCallList(m_gear2); glPopMatrix(); glPushMatrix(); - glTranslatef( -3.1, 4.2, 0.0 ); - glRotatef( -2.0 * m_angle - 25.0, 0.0, 0.0, 1.0 ); - glCallList( m_gear3 ); + glTranslatef(-3.1, 4.2, 0.0); + glRotatef(-2.0 * m_angle - 25.0, 0.0, 0.0, 1.0); + glCallList(m_gear3); glPopMatrix(); - glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white ); + glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, white); glPopMatrix(); - glDisable( GL_LIGHT1 ); - glDisable( GL_NORMALIZE ); - glEnable( GL_COLOR_MATERIAL ); + glDisable(GL_LIGHT1); + glDisable(GL_NORMALIZE); + glEnable(GL_COLOR_MATERIAL); - glDisable( GL_LIGHTING ); + glDisable(GL_LIGHTING); glPopMatrix(); glPopAttrib(); - } +} void GearsEffect::initGears() - { +{ static GLfloat pos[4] = { 5.0f, 5.0f, 10.0f, 0.0f }; static GLfloat red[4] = { 0.8f, 0.1f, 0.0f, 1.0f }; static GLfloat green[4] = { 0.0f, 0.8f, 0.2f, 1.0f }; @@ -321,34 +310,34 @@ void GearsEffect::initGears() static GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 0.3f }; static GLfloat diffuseLight[] = { 0.5f, 0.5f, 0.5f, 0.5f }; - glLightfv( GL_LIGHT1, GL_AMBIENT, ambientLight ); - glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuseLight ); - glLightfv( GL_LIGHT1, GL_POSITION, pos ); + glLightfv(GL_LIGHT1, GL_AMBIENT, ambientLight); + glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuseLight); + glLightfv(GL_LIGHT1, GL_POSITION, pos); - m_gear1 = glGenLists( 1 ); - glNewList( m_gear1, GL_COMPILE ); - glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red ); - gear( 1.0f, 4.0f, 1.0f, 20, 0.7f ); + m_gear1 = glGenLists(1); + glNewList(m_gear1, GL_COMPILE); + glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red); + gear(1.0f, 4.0f, 1.0f, 20, 0.7f); glEndList(); - m_gear2 = glGenLists( 1 ); - glNewList( m_gear2, GL_COMPILE ); - glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green ); - gear( 0.5f, 2.0f, 2.0f, 10, 0.7f ); + m_gear2 = glGenLists(1); + glNewList(m_gear2, GL_COMPILE); + glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green); + gear(0.5f, 2.0f, 2.0f, 10, 0.7f); glEndList(); - m_gear3 = glGenLists( 1 ); - glNewList( m_gear3, GL_COMPILE ); - glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue ); - gear( 1.3f, 2.0f, 0.5f, 10, 0.7f ); + m_gear3 = glGenLists(1); + glNewList(m_gear3, GL_COMPILE); + glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue); + gear(1.3f, 2.0f, 0.5f, 10, 0.7f); glEndList(); - } +} void GearsEffect::endGears() - { - glDeleteLists( m_gear1, 1 ); - glDeleteLists( m_gear2, 1 ); - glDeleteLists( m_gear3, 1 ); - } +{ + glDeleteLists(m_gear1, 1); + glDeleteLists(m_gear2, 1); + glDeleteLists(m_gear3, 1); +} } // namespace diff --git a/effects/_test/gears.h b/effects/_test/gears.h index 72c396a8c..b7e7fbc4f 100644 --- a/effects/_test/gears.h +++ b/effects/_test/gears.h @@ -33,28 +33,28 @@ namespace KWin class GearsEffect : public CubeInsideEffect { - public: - GearsEffect(); - ~GearsEffect(); +public: + GearsEffect(); + ~GearsEffect(); - virtual void paint(); - virtual void setActive( bool active ); - virtual void prePaintScreen(ScreenPrePaintData& data, int time); - virtual void postPaintScreen(); + virtual void paint(); + virtual void setActive(bool active); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); - static bool supported(); - private: - void gear( float inner_radius, float outer_radius, float width, int teeth, float tooth_depth ); - void paintGears(); - void initGears(); - void endGears(); + static bool supported(); +private: + void gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth); + void paintGears(); + void initGears(); + void endGears(); - bool m_active; - GLuint m_gear1; - GLuint m_gear2; - GLuint m_gear3; - float m_contentRotation; - float m_angle; + bool m_active; + GLuint m_gear1; + GLuint m_gear2; + GLuint m_gear3; + float m_contentRotation; + float m_angle; }; } //namespace diff --git a/effects/_test/howto.cpp b/effects/_test/howto.cpp index a4150f993..f031dcb34 100644 --- a/effects/_test/howto.cpp +++ b/effects/_test/howto.cpp @@ -14,7 +14,7 @@ License. See the file "COPYING" for the exact licensing terms. effect that fades out and again in a window after it has been activated. Please see file howto.h first. - + */ // Include the class definition. @@ -24,7 +24,7 @@ namespace KWin { // This macro creates entry function for the plugin. First argument is name, second is class name. -KWIN_EFFECT( howto, HowtoEffect ) +KWIN_EFFECT(howto, HowtoEffect) // A pre-paint function that tells the compositing code how this effect will affect // the painting. During every painting pass this function is called first, before @@ -36,33 +36,29 @@ KWIN_EFFECT( howto, HowtoEffect ) // region - the region of the screen that needs to be painted, support for modifying it // is not fully implemented yet, do not use // time - time in milliseconds since the last paint, useful for animations -void HowtoEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void HowtoEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // Is this window the one that is going to be faded out and in again? - if( w == fade_window ) - { + if (w == fade_window) { // Simply add the time to the total progress. The value of progress will be used // to determine how far in effect is. progress += time; // If progress is < 1000 (milliseconds), the effect is still in progress. - if( progress < 1000 ) // complete change in 1000ms - { + if (progress < 1000) { // complete change in 1000ms // Since the effect will make the window translucent, explicitly change // the flags so that the window will be painted only as translucent. // Use a helper that also takes care of changing the clipping rectangle. data.setTranslucent(); - } - else - { + } else { // If progress has reached 1000 (milliseconds), it means the effect is done // and there is no window to fade anymore. fade_window = NULL; - } } + } // Call the next effect (or the actual window painting code if this is the last effect). // Effects are chained and they all modify something if needed and then call the next one. - effects->prePaintWindow( w, data, time ); - } + effects->prePaintWindow(w, data, time); +} // The function that handles the actual painting. Some simple modifications are possible // by only changing the painting data. More complicated effects would do some painting @@ -74,73 +70,67 @@ void HowtoEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int // then special care needs to be taken, because the region may be infiniteRegion(), meaning // everything needs to be painted // data - painting data that can be modified to do some simple transformations -void HowtoEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void HowtoEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ // Is this the window to be faded out and in again? - if( w == fade_window ) - { + if (w == fade_window) { // This effect, after a window has been activated, fades it out to only 50% transparency // and then fades it in again to be fully opaque (assuming it's otherwise a fully opaque // window, otherwise the transparencies will be added). - if( progress <= 500 ) - { + if (progress <= 500) { // For the first 500 milliseconds (progress being 0 to 500), the window is faded out. // progress == 0 -> opacity *= 1 // progress == 500 -> opacity *= 0.5 // Note that the division is floating-point division to avoid integer rounding down. // Note that data.opacity is not set but multiplied - this allows chaining of effects, // for example if another effect always changes opacity of some window types. - data.opacity *= 1 - 0.5 * ( progress / 500.0 ); - } - else - { + data.opacity *= 1 - 0.5 * (progress / 500.0); + } else { // For the second 500 milliseconds (progress being 500 to 1000), the window is // faded in again. // progress == 500 -> opacity *= 0.5 // progress == 1000 -> opacity *= 1 - data.opacity *= 0.5 + 0.5 * ( progress - 500 ) / 500.0; - } + data.opacity *= 0.5 + 0.5 * (progress - 500) / 500.0; } - // Call the next effect. - effects->paintWindow( w, mask, region, data ); } + // Call the next effect. + effects->paintWindow(w, mask, region, data); +} // The function that is called after the painting pass is finished. When an animation is going on, // it can add repaints of some areas so that the next painting pass has to repaint them again. -void HowtoEffect::postPaintWindow( EffectWindow* w ) - { +void HowtoEffect::postPaintWindow(EffectWindow* w) +{ // Is this the window to be faded out and in again? - if( w == fade_window ) - { + if (w == fade_window) { // Trigger repaint of the whole window, this will cause it to be repainted the next painting pass. w->addRepaintFull(); // trigger next animation repaint - } - // Call the next effect. - effects->postPaintWindow( w ); } + // Call the next effect. + effects->postPaintWindow(w); +} // This function is called when a new window becomes active. -void HowtoEffect::windowActivated( EffectWindow* c ) - { +void HowtoEffect::windowActivated(EffectWindow* c) +{ // Set the window to be faded (or NULL if no window is active). fade_window = c; - if( fade_window != NULL ) - { + if (fade_window != NULL) { // If there is a window to be faded, reset the progress to zero. progress = 0; // And add repaint to the window so that it needs to be repainted. c->addRepaintFull(); - } } +} // This function is called when a window is closed. -void HowtoEffect::windowClosed( EffectWindow* c ) - { +void HowtoEffect::windowClosed(EffectWindow* c) +{ // If the window to be faded out and in is closed, just reset the pointer. // This effect then will do nothing and just call the next effect. - if( fade_window == c ) + if (fade_window == c) fade_window = NULL; - } +} // That's all. Now only the matching .desktop file is needed. diff --git a/effects/_test/howto.h b/effects/_test/howto.h index 50b9ea225..ff4eb7402 100644 --- a/effects/_test/howto.h +++ b/effects/_test/howto.h @@ -30,39 +30,39 @@ namespace KWin class HowtoEffect // Inherit from the base class for effects. : public Effect - { - public: - // There are two kinds of functions in an effect: - - // Functions related to painting: These allow the effect to affect painting. +{ +public: + // There are two kinds of functions in an effect: - // A pre-paint function. It tells the compositing code how the painting will - // be affected by this effect. - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - - // A paint function. It actually performs the modifications to the painting. - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - - // A post-paint function. It can be used for cleanups after painting, but with animations - // it is also used to trigger repaints during the next painting pass by manually "damaging" - // areas of the window. - virtual void postPaintWindow( EffectWindow* w ); - - // Notification functions: These inform the effect about changes such as a new window - // being activated. + // Functions related to painting: These allow the effect to affect painting. - // The given window has been closed. - virtual void windowClosed( EffectWindow* c ); - - // The given window has been activated. - virtual void windowActivated( EffectWindow* c ); - private: - // The window that will be faded out and in again. - EffectWindow* fade_window; - - // The progress of the fading. - int progress; - }; + // A pre-paint function. It tells the compositing code how the painting will + // be affected by this effect. + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + + // A paint function. It actually performs the modifications to the painting. + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + + // A post-paint function. It can be used for cleanups after painting, but with animations + // it is also used to trigger repaints during the next painting pass by manually "damaging" + // areas of the window. + virtual void postPaintWindow(EffectWindow* w); + + // Notification functions: These inform the effect about changes such as a new window + // being activated. + + // The given window has been closed. + virtual void windowClosed(EffectWindow* c); + + // The given window has been activated. + virtual void windowActivated(EffectWindow* c); +private: + // The window that will be faded out and in again. + EffectWindow* fade_window; + + // The progress of the fading. + int progress; +}; } // namespace diff --git a/effects/_test/kicker/kicker.cpp b/effects/_test/kicker/kicker.cpp index f8966fe9b..227d4ea9d 100644 --- a/effects/_test/kicker/kicker.cpp +++ b/effects/_test/kicker/kicker.cpp @@ -29,230 +29,212 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( kicker, KickerEffect ) +KWIN_EFFECT(kicker, KickerEffect) KickerEffect::KickerEffect() - : m_page( new QWebPage( this ) ) - , m_timer( new QTimer( this ) ) - , m_goalTimer( new QTimer( this ) ) - , m_goalActive( false ) - , m_ascending( false ) - { + : m_page(new QWebPage(this)) + , m_timer(new QTimer(this)) + , m_goalTimer(new QTimer(this)) + , m_goalActive(false) + , m_ascending(false) +{ connect(m_page, SIGNAL(loadFinished(bool)), this, SLOT(slotLoadFinished(bool))); connect(m_timer, SIGNAL(timeout()), this, SLOT(timeout())); connect(m_goalTimer, SIGNAL(timeout()), this, SLOT(goalTimeout())); - reconfigure( ReconfigureAll ); + reconfigure(ReconfigureAll); // reload the webpage each half a minute - m_timer->start(30*1000); + m_timer->start(30 * 1000); // goal animation should end after seven seconds - m_goalTimer->setInterval( 7 * 1000 ); - m_goalTimer->setSingleShot( true ); + m_goalTimer->setInterval(7 * 1000); + m_goalTimer->setSingleShot(true); // the animations should have a duration of half a second with an // ease in out curve - m_timeLine.setCurveShape( TimeLine::EaseInOutCurve ); - m_timeLine.setDuration( 500 ); + m_timeLine.setCurveShape(TimeLine::EaseInOutCurve); + m_timeLine.setDuration(500); // let's download the webpage immediatelly timeout(); - } +} KickerEffect::~KickerEffect() - { - while( !m_frames.isEmpty() ) - { +{ + while (!m_frames.isEmpty()) { delete m_frames.first(); m_frames.removeFirst(); - } - while( !m_goalFrames.isEmpty() ) - { + } + while (!m_goalFrames.isEmpty()) { delete m_goalFrames.first(); m_goalFrames.removeFirst(); - } } +} -void KickerEffect::reconfigure( ReconfigureFlags ) - { - } +void KickerEffect::reconfigure(ReconfigureFlags) +{ +} -void KickerEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void KickerEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ // the goal animation uses a KWin::TimeLine to modify the opacity values // as long as the goal timer has not timed out m_goalActive is true // after the timeout an animation might still be running, so we continue // till progress reaches 0.0 again - if( m_goalActive || m_timeLine.progress() != 0.0 ) - { + if (m_goalActive || m_timeLine.progress() != 0.0) { // the animation might either be ascending (increasing opacity) or // descending (decreasing opacity). In case of ascending we add time // to the timeline till progress reaches 1.0. There we switch direction // to descending. In descending case of course vice versa. - if( m_ascending ) - { - m_timeLine.addTime( time ); - if( m_timeLine.progress() == 1.0 ) - { + if (m_ascending) { + m_timeLine.addTime(time); + if (m_timeLine.progress() == 1.0) { m_ascending = false; - } } - else - { - m_timeLine.removeTime( time ); + } else { + m_timeLine.removeTime(time); // it is possible that this is the last animation. Therefore the // anding with goalActive. If it has been the last animation we // do not need to keep the goal EffectFrame around any more, so // we delete them. - if( m_timeLine.progress() == 0.0 && m_goalActive ) - { + if (m_timeLine.progress() == 0.0 && m_goalActive) { m_ascending = true; - } - else if( m_timeLine.progress() == 0.0 ) - { + } else if (m_timeLine.progress() == 0.0) { // goal animation finshed, let's delete the EffectFrames - while( !m_goalFrames.isEmpty() ) - { + while (!m_goalFrames.isEmpty()) { delete m_goalFrames.first(); m_goalFrames.removeFirst(); - } - m_goalFrames.clear(); } + m_goalFrames.clear(); } } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void KickerEffect::paintScreen( int mask, QRegion region, ScreenPaintData &data ) - { - effects->paintScreen( mask, region, data ); +void KickerEffect::paintScreen(int mask, QRegion region, ScreenPaintData &data) +{ + effects->paintScreen(mask, region, data); - if( m_size.isValid() ) - { + if (m_size.isValid()) { // let's paint the score EffectFrame with unmodified opacity. As it // uses Plasma styled textures it's still translucent, but the text // is fully opaque. - foreach( EffectFrame* frame, m_frames ) - frame->render( region, 1.0 ); - } - if( m_goalActive || m_timeLine.progress() != 0.0 ) - { + foreach (EffectFrame * frame, m_frames) + frame->render(region, 1.0); + } + if (m_goalActive || m_timeLine.progress() != 0.0) { // the goal animation changes the opacity. Therefore we modify the // opacity by multiplying with the timeline's progress. // The text should be fully opaque (1.0), while the background should // be translucent (0.75) - foreach( EffectFrame* frame, m_goalFrames ) - frame->render( region, 1.0 * m_timeLine.progress(), 0.75 * m_timeLine.progress() ); + foreach (EffectFrame * frame, m_goalFrames) + frame->render(region, 1.0 * m_timeLine.progress(), 0.75 * m_timeLine.progress()); // we are animating: need a new frame effects->addRepaintFull(); - } } +} -void KickerEffect::slotLoadFinished( bool ok ) - { +void KickerEffect::slotLoadFinished(bool ok) +{ // if connection failed let's keep the last score - if( !ok ) + if (!ok) return; QWebElement doc = m_page->mainFrame()->documentElement(); // CSS selector for the teams QWebElementCollection teams = doc.findAll("td.lttabver h1 a"); - if( teams.count() != 2 ) + if (teams.count() != 2) return; QString firstTeam = teams[0].toPlainText(); QString secondTeam = teams[1].toPlainText(); // CSS selector for the current score QString result = doc.findFirst("td.lttaberg h1").toPlainText(); - if( m_score != result ) - { + if (m_score != result) { // the score changed, a goal might have been scored bool activate = true; // but not if the web page has been loaded for the first time - if( m_score.isNull() ) + if (m_score.isNull()) activate = false; // not if we entered extra time - if( !m_score.contains("i.V.") && result.contains("i.V.") ) + if (!m_score.contains("i.V.") && result.contains("i.V.")) activate = false; // not if extra time ended - if( !m_score.contains("n.V.") && result.contains("n.V.") ) + if (!m_score.contains("n.V.") && result.contains("n.V.")) activate = false; // not if penality shootout begins - if( !m_score.contains("i.E.") && result.contains("i.E.") ) + if (!m_score.contains("i.E.") && result.contains("i.E.")) activate = false; // not if first or second half starts. - if( m_score.count( '-' ) > result.count( '-' ) ) + if (m_score.count('-') > result.count('-')) activate = false; // yeah it's a goal - generate the EffectFrame and start the animation - if( activate ) - { + if (activate) { generateGoalImage(); m_goalActive = true; m_ascending = true; m_goalTimer->start(); - } - m_score = result; } + m_score = result; + } QString text = firstTeam + ' ' + result + ' ' + secondTeam; QFont font; - font.setBold( true ); + font.setBold(true); QFontMetrics fm(font); m_size = fm.boundingRect(text).adjusted(-10, -10, 10, 10).size(); // we don't want to reposition the EffectFrames, therefore we delete the // old ones. Normally you wouldn't do that, but as we only update once in // half a minute and it's easier to code... - while( !m_frames.isEmpty() ) - { + while (!m_frames.isEmpty()) { delete m_frames.first(); m_frames.removeFirst(); - } + } m_frames.clear(); // and properly position the frame on each screen - for( int i = 0; i < effects->numScreens(); i++ ) - { - QRect area = effects->clientArea( ScreenArea, i, effects->currentDesktop()); - QRect geometry = QRect( area.x() + area.width() - m_size.width() - 20, area.y() + 20, m_size.width(), m_size.height() ); - EffectFrame *frame = new EffectFrame( EffectFrame::Styled ); - frame->setText( text ); - frame->setFont( font ); - frame->setGeometry( geometry ); + for (int i = 0; i < effects->numScreens(); i++) { + QRect area = effects->clientArea(ScreenArea, i, effects->currentDesktop()); + QRect geometry = QRect(area.x() + area.width() - m_size.width() - 20, area.y() + 20, m_size.width(), m_size.height()); + EffectFrame *frame = new EffectFrame(EffectFrame::Styled); + frame->setText(text); + frame->setFont(font); + frame->setGeometry(geometry); m_frames.append(frame); - } + } // effect frame changed and animation might have started - we need a full repaint effects->addRepaintFull(); - } +} void KickerEffect::timeout() - { +{ // hard coded URL to the liveticker of the match Argentina vs Germany at World Cup 2010. // If this URL is not valid anymore you can find newer examples on the referrenced web site. m_page->mainFrame()->load(QUrl("http://www.kicker.de/news/fussball/wm/spielplan/weltmeisterschaft/2010/5/833353/livematch_argentinien_deutschland.html")); - } +} void KickerEffect::generateGoalImage() - { - QFont font( "FreeMono", 172 ); - QString goal( "GOAL" ); - QFontMetrics fm( font ); - QSize size = fm.boundingRect( goal ).adjusted(-10, -10, 10, 10).size(); - for( int i = 0; i < effects->numScreens(); i++ ) - { +{ + QFont font("FreeMono", 172); + QString goal("GOAL"); + QFontMetrics fm(font); + QSize size = fm.boundingRect(goal).adjusted(-10, -10, 10, 10).size(); + for (int i = 0; i < effects->numScreens(); i++) { // place one frame on the center of each screen - QRect area = effects->clientArea( ScreenArea, i, effects->currentDesktop()); - QRect geometry = QRect( area.x() + (area.width() - size.width())/2, - area.y() + (area.height() - size.height())/2, - size.width(), size.height()); - EffectFrame *frame = new EffectFrame( EffectFrame::Unstyled, false ); - frame->setText( goal ); - frame->setFont( font ); - frame->setGeometry( geometry ); + QRect area = effects->clientArea(ScreenArea, i, effects->currentDesktop()); + QRect geometry = QRect(area.x() + (area.width() - size.width()) / 2, + area.y() + (area.height() - size.height()) / 2, + size.width(), size.height()); + EffectFrame *frame = new EffectFrame(EffectFrame::Unstyled, false); + frame->setText(goal); + frame->setFont(font); + frame->setGeometry(geometry); m_goalFrames.append(frame); - } } +} void KickerEffect::goalTimeout() - { +{ // stop the animation m_goalActive = false; effects->addRepaintFull(); - } +} } // namespace diff --git a/effects/_test/kicker/kicker.h b/effects/_test/kicker/kicker.h index f5ef430f4..332d987a0 100644 --- a/effects/_test/kicker/kicker.h +++ b/effects/_test/kicker/kicker.h @@ -51,33 +51,33 @@ namespace KWin * @author Martin Gräßlin */ class KickerEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - KickerEffect(); - ~KickerEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); +public: + KickerEffect(); + ~KickerEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); - private Q_SLOTS: - void slotLoadFinished(bool ok); - void timeout(); - void goalTimeout(); +private Q_SLOTS: + void slotLoadFinished(bool ok); + void timeout(); + void goalTimeout(); - private: - void generateGoalImage(); - QWebPage *m_page; - QTimer *m_timer; - QTimer *m_goalTimer; - QSize m_size; - QList m_frames; - QList m_goalFrames; - bool m_goalActive; - QString m_score; - TimeLine m_timeLine; - bool m_ascending; - }; +private: + void generateGoalImage(); + QWebPage *m_page; + QTimer *m_timer; + QTimer *m_goalTimer; + QSize m_size; + QList m_frames; + QList m_goalFrames; + bool m_goalActive; + QString m_score; + TimeLine m_timeLine; + bool m_ascending; +}; } diff --git a/effects/_test/slidetabs/slidetabs.cpp b/effects/_test/slidetabs/slidetabs.cpp index 7ffd56397..0b7061fe9 100644 --- a/effects/_test/slidetabs/slidetabs.cpp +++ b/effects/_test/slidetabs/slidetabs.cpp @@ -26,169 +26,160 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( slidetabs, SlideTabsEffect ) +KWIN_EFFECT(slidetabs, SlideTabsEffect) SlideTabsEffect::SlideTabsEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} -void SlideTabsEffect::reconfigure( ReconfigureFlags ) - { +void SlideTabsEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("SlideTabs"); - switching = conf.readEntry("SlideSwitching", true ); - grouping = conf.readEntry("SlideGrouping", true ); - totalTime = conf.readEntry("SlideDuration", 500 ); - } + switching = conf.readEntry("SlideSwitching", true); + grouping = conf.readEntry("SlideGrouping", true); + totalTime = conf.readEntry("SlideDuration", 500); +} -void SlideTabsEffect::prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ) - { - if( motionManager.isManaging( w ) ) - { +void SlideTabsEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) +{ + if (motionManager.isManaging(w)) { data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED ); - timeLine.addTime( time ); - } - effects->prePaintWindow( w, data, time ); + w->enablePainting(EffectWindow::PAINT_DISABLED); + timeLine.addTime(time); } + effects->prePaintWindow(w, data, time); +} -void SlideTabsEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( motionManager.isManaging( w ) && w == inMove ) - motionManager.apply( w, data ); - effects->paintWindow( w, mask, region, data ); - } +void SlideTabsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (motionManager.isManaging(w) && w == inMove) + motionManager.apply(w, data); + effects->paintWindow(w, mask, region, data); +} -void SlideTabsEffect::postPaintWindow( EffectWindow* w ) - { - if( motionManager.isManaging( w ) ) - { - if( w == inMove ) - { +void SlideTabsEffect::postPaintWindow(EffectWindow* w) +{ + if (motionManager.isManaging(w)) { + if (w == inMove) { QRect moving = calculateNextMove(); - motionManager.moveWindow( w, moving ); - if( direction && timeLine.progress() >= 0.5 ) - { + motionManager.moveWindow(w, moving); + if (direction && timeLine.progress() >= 0.5) { moving = target; target = source; source = moving; direction = false; - effects->setElevatedWindow( notMoving, false ); - effects->setElevatedWindow( w, true ); - } - else if( timeLine.progress() >= 1.0 ) - { - effects->setElevatedWindow( notMoving, false ); - effects->setElevatedWindow( inMove, false ); - motionManager.unmanage( notMoving ); - motionManager.unmanage( inMove ); + effects->setElevatedWindow(notMoving, false); + effects->setElevatedWindow(w, true); + } else if (timeLine.progress() >= 1.0) { + effects->setElevatedWindow(notMoving, false); + effects->setElevatedWindow(inMove, false); + motionManager.unmanage(notMoving); + motionManager.unmanage(inMove); notMoving = NULL; inMove = NULL; wasD = false; effects->addRepaintFull(); - } } - else if( w == notMoving && !direction && target != w->geometry() && !wasD ) - { + } else if (w == notMoving && !direction && target != w->geometry() && !wasD) { target = w->geometry(); - } + } w->addRepaintFull(); - } - effects->postPaintWindow( w ); } + effects->postPaintWindow(w); +} -void SlideTabsEffect::prePaintScreen( ScreenPrePaintData &data, int time ) - { - if( motionManager.managingWindows() ) - { - motionManager.calculate( time ); +void SlideTabsEffect::prePaintScreen(ScreenPrePaintData &data, int time) +{ + if (motionManager.managingWindows()) { + motionManager.calculate(time); data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} void SlideTabsEffect::postPaintScreen() - { - if( motionManager.managingWindows() ) +{ + if (motionManager.managingWindows()) effects->addRepaintFull(); effects->postPaintScreen(); - } +} -void SlideTabsEffect::clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ) - { - if( !switching ) +void SlideTabsEffect::clientGroupItemSwitched(EffectWindow* from, EffectWindow* to) +{ + if (!switching) return; inMove = to; notMoving = from; source = notMoving->geometry(); QRect window = notMoving->geometry(); - int leftSpace = window.x(), rightSpace = displayWidth() - ( window.x() + window.width() ), - upSpace = window.y(), downSpace = displayHeight() - ( window.y() + window.height() ); + int leftSpace = window.x(), rightSpace = displayWidth() - (window.x() + window.width()), + upSpace = window.y(), downSpace = displayHeight() - (window.y() + window.height()); - if( leftSpace >= rightSpace && leftSpace >= upSpace && leftSpace >= downSpace ) - target = QRect( source.x() - ( 1.2 * source.width() ), source.y(), source.width(), source.height() ); - else if( rightSpace >= leftSpace && rightSpace >= upSpace && rightSpace >= downSpace ) - target = QRect( source.x() + ( 1.2 * source.width() ), source.y(), source.width(), source.height() ); - else if( upSpace >= leftSpace && upSpace >= rightSpace && upSpace >= downSpace ) - target = QRect( source.x(), source.y() - ( 1.2 * source.height() ), source.width(), source.height() ); + if (leftSpace >= rightSpace && leftSpace >= upSpace && leftSpace >= downSpace) + target = QRect(source.x() - (1.2 * source.width()), source.y(), source.width(), source.height()); + else if (rightSpace >= leftSpace && rightSpace >= upSpace && rightSpace >= downSpace) + target = QRect(source.x() + (1.2 * source.width()), source.y(), source.width(), source.height()); + else if (upSpace >= leftSpace && upSpace >= rightSpace && upSpace >= downSpace) + target = QRect(source.x(), source.y() - (1.2 * source.height()), source.width(), source.height()); else - target = QRect( source.x(), source.y() + ( 1.2 * source.height() ), source.width(), source.height() ); + target = QRect(source.x(), source.y() + (1.2 * source.height()), source.width(), source.height()); - timeLine.setCurveShape( TimeLine::LinearCurve ); - timeLine.setDuration( animationTime( totalTime ) ); - timeLine.setProgress( 0.0f ); - motionManager.manage( inMove ); - motionManager.manage( notMoving ); - distance = sqrt( ( ( source.x()-target.x() ) * ( source.x()-target.x() ) ) + ( ( source.y()-target.y() ) * ( source.y()-target.y() ) ) ); - effects->setElevatedWindow( notMoving, true ); + timeLine.setCurveShape(TimeLine::LinearCurve); + timeLine.setDuration(animationTime(totalTime)); + timeLine.setProgress(0.0f); + motionManager.manage(inMove); + motionManager.manage(notMoving); + distance = sqrt(((source.x() - target.x()) * (source.x() - target.x())) + ((source.y() - target.y()) * (source.y() - target.y()))); + effects->setElevatedWindow(notMoving, true); direction = wasD = true; QRect moving = calculateNextMove(); - motionManager.moveWindow( inMove, moving ); - } + motionManager.moveWindow(inMove, moving); +} -void SlideTabsEffect::clientGroupItemAdded( EffectWindow* from, EffectWindow* to ) - { - if( !grouping || from->desktop() != to->desktop() || from->isMinimized() || to->isMinimized() ) +void SlideTabsEffect::clientGroupItemAdded(EffectWindow* from, EffectWindow* to) +{ + if (!grouping || from->desktop() != to->desktop() || from->isMinimized() || to->isMinimized()) return; - timeLine.setCurveShape( TimeLine::LinearCurve ); - timeLine.setDuration( animationTime( totalTime ) ); - timeLine.setProgress( 0.0f ); + timeLine.setCurveShape(TimeLine::LinearCurve); + timeLine.setDuration(animationTime(totalTime)); + timeLine.setProgress(0.0f); inMove = from; notMoving = to; source = inMove->geometry(); target = notMoving->geometry(); - distance = sqrt( ( ( source.x()-target.x() ) * ( source.x()-target.x() ) ) + ( ( source.y()-target.y() ) * ( source.y()-target.y() ) ) ); - motionManager.manage( inMove ); - motionManager.manage( notMoving ); + distance = sqrt(((source.x() - target.x()) * (source.x() - target.x())) + ((source.y() - target.y()) * (source.y() - target.y()))); + motionManager.manage(inMove); + motionManager.manage(notMoving); QRect moving = calculateNextMove(); - motionManager.moveWindow( inMove, moving ); - effects->setElevatedWindow( notMoving, true ); + motionManager.moveWindow(inMove, moving); + effects->setElevatedWindow(notMoving, true); direction = wasD = false; - } +} -QPoint SlideTabsEffect::calculatePointTarget( const QPoint &a, const QPoint &b ) - { +QPoint SlideTabsEffect::calculatePointTarget(const QPoint &a, const QPoint &b) +{ double dy, dx, x, y, k; - k = direction? (2.0*timeLine.progress()):(wasD?((timeLine.progress()-0.5)*2):timeLine.progress()); - dx = fabs( a.x() - b.x() ); - dy = fabs( a.y() - b.y() ); - y = k*dy; - x = k*dx; - if( a.x() > b.x() ) + k = direction ? (2.0 * timeLine.progress()) : (wasD ? ((timeLine.progress() - 0.5) * 2) : timeLine.progress()); + dx = fabs(a.x() - b.x()); + dy = fabs(a.y() - b.y()); + y = k * dy; + x = k * dx; + if (a.x() > b.x()) x = -x; - if( a.y() > b.y() ) + if (a.y() > b.y()) y = -y; - return QPoint( a.x() + x, a.y() + y ); - } + return QPoint(a.x() + x, a.y() + y); +} QRect SlideTabsEffect::calculateNextMove() - { +{ QPoint topLeft, bottomRight; int mw = source.width(), mh = source.height(), tw = target.width(), th = target.height(); - topLeft = calculatePointTarget( QPoint( source.x(), source.y() ), QPoint( target.x(), target.y() ) ); - bottomRight = calculatePointTarget( QPoint( source.x() + mw, source.y() + mh ), QPoint( target.x() + tw, target.y() + th ) ); - return QRect( topLeft.x(), topLeft.y(), bottomRight.x() - topLeft.x(), bottomRight.y() - topLeft.y() ); - } + topLeft = calculatePointTarget(QPoint(source.x(), source.y()), QPoint(target.x(), target.y())); + bottomRight = calculatePointTarget(QPoint(source.x() + mw, source.y() + mh), QPoint(target.x() + tw, target.y() + th)); + return QRect(topLeft.x(), topLeft.y(), bottomRight.x() - topLeft.x(), bottomRight.y() - topLeft.y()); +} } diff --git a/effects/_test/slidetabs/slidetabs.h b/effects/_test/slidetabs/slidetabs.h index 7f83ba11d..b79261a33 100644 --- a/effects/_test/slidetabs/slidetabs.h +++ b/effects/_test/slidetabs/slidetabs.h @@ -27,29 +27,29 @@ namespace KWin { class SlideTabsEffect : public Effect - { - public: - SlideTabsEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void postPaintScreen(); - virtual void clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ); - virtual void clientGroupItemAdded( EffectWindow* from, EffectWindow* to ); +{ +public: + SlideTabsEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void postPaintScreen(); + virtual void clientGroupItemSwitched(EffectWindow* from, EffectWindow* to); + virtual void clientGroupItemAdded(EffectWindow* from, EffectWindow* to); - private: - QRect calculateNextMove(); - QPoint calculatePointTarget( const QPoint &a, const QPoint &b ); - WindowMotionManager motionManager; - EffectWindow* inMove; - EffectWindow* notMoving; - TimeLine timeLine; - QRect target, source; - bool direction, wasD, grouping, switching; - int totalTime, distance; - }; +private: + QRect calculateNextMove(); + QPoint calculatePointTarget(const QPoint &a, const QPoint &b); + WindowMotionManager motionManager; + EffectWindow* inMove; + EffectWindow* notMoving; + TimeLine timeLine; + QRect target, source; + bool direction, wasD, grouping, switching; + int totalTime, distance; +}; } diff --git a/effects/_test/slidetabs/slidetabs_config.cpp b/effects/_test/slidetabs/slidetabs_config.cpp index 2fd530afa..b4c466414 100644 --- a/effects/_test/slidetabs/slidetabs_config.cpp +++ b/effects/_test/slidetabs/slidetabs_config.cpp @@ -32,63 +32,63 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY -SlideTabsEffectConfigForm::SlideTabsEffectConfigForm( QWidget* parent ) : QWidget( parent ) - { - setupUi( this ); - } +SlideTabsEffectConfigForm::SlideTabsEffectConfigForm(QWidget* parent) : QWidget(parent) +{ + setupUi(this); +} SlideTabsEffectConfig::SlideTabsEffectConfig(QWidget* parent, const QVariantList& args) - : KCModule( EffectFactory::componentData(), parent, args ) - { - m_ui = new SlideTabsEffectConfigForm( this ); + : KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new SlideTabsEffectConfigForm(this); - QVBoxLayout* layout = new QVBoxLayout( this ); + QVBoxLayout* layout = new QVBoxLayout(this); - layout->addWidget( m_ui ); + layout->addWidget(m_ui); - connect( m_ui->grouping, SIGNAL( toggled( bool )), this, SLOT( changed() ) ); - connect( m_ui->switching, SIGNAL( toggled( bool )), this, SLOT( changed() ) ); - connect( m_ui->duration, SIGNAL( valueChanged( int ) ), this, SLOT( changed() ) ); + connect(m_ui->grouping, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_ui->switching, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_ui->duration, SIGNAL(valueChanged(int)), this, SLOT(changed())); load(); - } +} void SlideTabsEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "SlideTabs" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("SlideTabs"); - conf.writeEntry( "SlideGrouping", m_ui->grouping->isChecked() ); - conf.writeEntry( "SlideSwitching", m_ui->switching->isChecked() ); - conf.writeEntry( "SlideDuration", m_ui->duration->value() ); + conf.writeEntry("SlideGrouping", m_ui->grouping->isChecked()); + conf.writeEntry("SlideSwitching", m_ui->switching->isChecked()); + conf.writeEntry("SlideDuration", m_ui->duration->value()); conf.sync(); KCModule::save(); - emit changed( false ); - EffectsHandler::sendReloadMessage( "slidetabs" ); - } + emit changed(false); + EffectsHandler::sendReloadMessage("slidetabs"); +} void SlideTabsEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "SlideTabs" ); + KConfigGroup conf = EffectsHandler::effectConfig("SlideTabs"); - bool switching = conf.readEntry( "SlideSwitching", true ); - bool grouping = conf.readEntry( "SlideGrouping", true ); - int duration = conf.readEntry("SlideDuration", 500 ); - m_ui->switching->setChecked( switching ); - m_ui->grouping->setChecked( grouping ); - m_ui->duration->setValue( duration ); - emit changed( false ); - } + bool switching = conf.readEntry("SlideSwitching", true); + bool grouping = conf.readEntry("SlideGrouping", true); + int duration = conf.readEntry("SlideDuration", 500); + m_ui->switching->setChecked(switching); + m_ui->grouping->setChecked(grouping); + m_ui->duration->setValue(duration); + emit changed(false); +} void SlideTabsEffectConfig::defaults() - { - m_ui->grouping->setChecked( true ); - m_ui->switching->setChecked( true ); - m_ui->duration->setValue( 500 ); - emit changed( true ); - } +{ + m_ui->grouping->setChecked(true); + m_ui->switching->setChecked(true); + m_ui->duration->setValue(500); + emit changed(true); +} } diff --git a/effects/_test/slidetabs/slidetabs_config.h b/effects/_test/slidetabs/slidetabs_config.h index c6101002c..e0edf4197 100644 --- a/effects/_test/slidetabs/slidetabs_config.h +++ b/effects/_test/slidetabs/slidetabs_config.h @@ -29,24 +29,24 @@ namespace KWin { class SlideTabsEffectConfigForm : public QWidget, public Ui::SlideTabsEffectConfigForm - { +{ Q_OBJECT - public: - explicit SlideTabsEffectConfigForm( QWidget* parent ); - }; +public: + explicit SlideTabsEffectConfigForm(QWidget* parent); +}; class SlideTabsEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit SlideTabsEffectConfig( QWidget* parent = 0, const QVariantList& args = QVariantList() ); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); - private: - SlideTabsEffectConfigForm* m_ui; - }; +public: + explicit SlideTabsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); +private: + SlideTabsEffectConfigForm* m_ui; +}; } diff --git a/effects/_test/swiveltabs/swiveltabs.cpp b/effects/_test/swiveltabs/swiveltabs.cpp index 37543813a..dd5ad9ea4 100644 --- a/effects/_test/swiveltabs/swiveltabs.cpp +++ b/effects/_test/swiveltabs/swiveltabs.cpp @@ -24,134 +24,123 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( swiveltabs, SwivelTabsEffect ) -KWIN_EFFECT_SUPPORTED( swiveltabs, SwivelTabsEffect::supported() ) +KWIN_EFFECT(swiveltabs, SwivelTabsEffect) +KWIN_EFFECT_SUPPORTED(swiveltabs, SwivelTabsEffect::supported()) SwivelTabsEffect::SwivelTabsEffect() - { +{ isActive = false; - PI = 2.0 * acos( 0.0 ); - reconfigure( ReconfigureAll ); - } + PI = 2.0 * acos(0.0); + reconfigure(ReconfigureAll); +} bool SwivelTabsEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void SwivelTabsEffect::reconfigure( ReconfigureFlags ) - { +void SwivelTabsEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("SwivelTabs"); - vertical = conf.readEntry("SwivelVertical", true ); - horizontal = conf.readEntry("SwivelHorizontal", true ); - totalTime = conf.readEntry("SwivelDuration", 500 ); - } + vertical = conf.readEntry("SwivelVertical", true); + horizontal = conf.readEntry("SwivelHorizontal", true); + totalTime = conf.readEntry("SwivelDuration", 500); +} -void SwivelTabsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( isActive ) +void SwivelTabsEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (isActive) data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void SwivelTabsEffect::prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ) - { - if( isActive && ( w == windows.show || w == windows.hide ) ) - { - data.quads = data.quads.makeGrid( 40 ); +void SwivelTabsEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) +{ + if (isActive && (w == windows.show || w == windows.hide)) { + data.quads = data.quads.makeGrid(40); data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED ); - windows.time.addTime( time ); - } - effects->prePaintWindow( w, data, time ); + w->enablePainting(EffectWindow::PAINT_DISABLED); + windows.time.addTime(time); } + effects->prePaintWindow(w, data, time); +} -void SwivelTabsEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( isActive && ( w == windows.show || w == windows.hide ) ) - { - for( int i = 0; i < data.quads.count(); ++i ) - transformQuad( data.quads[i] ); - } - effects->paintWindow( w, mask, region, data ); +void SwivelTabsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (isActive && (w == windows.show || w == windows.hide)) { + for (int i = 0; i < data.quads.count(); ++i) + transformQuad(data.quads[i]); } + effects->paintWindow(w, mask, region, data); +} -void SwivelTabsEffect::postPaintWindow( EffectWindow* w ) - { - if( isActive && ( w == windows.show || w == windows.hide ) ) +void SwivelTabsEffect::postPaintWindow(EffectWindow* w) +{ + if (isActive && (w == windows.show || w == windows.hide)) w->addRepaintFull(); - effects->postPaintWindow( w ); - } + effects->postPaintWindow(w); +} -void SwivelTabsEffect::transformQuad( WindowQuad &quad ) - { +void SwivelTabsEffect::transformQuad(WindowQuad &quad) +{ double F = windows.time.progress(); - int width = quad[1].x()-quad[0].x(); + int width = quad[1].x() - quad[0].x(); int height = quad[3].y() - quad[0].y(); - int cx = quad[0].x() + ( width/2 ); - int cy = quad[0].y() + ( height/2 ); - if( lastF < 0.5 && F > 0.5 ) - { - effects->setElevatedWindow( windows.hide, false ); - effects->setElevatedWindow( windows.show, true ); - } + int cx = quad[0].x() + (width / 2); + int cy = quad[0].y() + (height / 2); + if (lastF < 0.5 && F > 0.5) { + effects->setElevatedWindow(windows.hide, false); + effects->setElevatedWindow(windows.show, true); + } lastF = F; - if( F >= 1.0 ) - { + if (F >= 1.0) { isActive = false; - effects->setElevatedWindow( windows.hide, false ); - effects->setElevatedWindow( windows.show, false ); + effects->setElevatedWindow(windows.hide, false); + effects->setElevatedWindow(windows.show, false); + } + if (F < 0.5) { + if (horizontal) { + quad[0].setX(quad[0].x() + (width * F)); + quad[3].setX(quad[3].x() + (width * F)); + quad[1].setX(quad[1].x() - (width * F)); + quad[2].setX(quad[2].x() - (width * F)); } - if( F < 0.5 ) - { - if( horizontal ) - { - quad[0].setX( quad[0].x() + ( width * F ) ); - quad[3].setX( quad[3].x() + ( width * F ) ); - quad[1].setX( quad[1].x() - ( width * F ) ); - quad[2].setX( quad[2].x() - ( width * F ) ); - } - if( vertical ) - { - quad[0].setY( quad[0].y() + ( height * F ) ); - quad[3].setY( quad[3].y() - ( height * F ) ); - quad[1].setY( quad[1].y() + ( height * F ) ); - quad[2].setY( quad[2].y() - ( height * F ) ); - } + if (vertical) { + quad[0].setY(quad[0].y() + (height * F)); + quad[3].setY(quad[3].y() - (height * F)); + quad[1].setY(quad[1].y() + (height * F)); + quad[2].setY(quad[2].y() - (height * F)); } - else - { + } else { F -= 0.5; - if( horizontal ) - { - quad[0].setX( cx - ( width * F ) ); - quad[3].setX( cx - ( width * F ) ); - quad[1].setX( cx + ( width * F ) ); - quad[2].setX( cx + ( width * F ) ); - } - if( vertical ) - { - quad[0].setY( cy - ( height * F ) ); - quad[3].setY( cy + ( height * F ) ); - quad[1].setY( cy - ( height * F ) ); - quad[2].setY( cy + ( height * F ) ); - } + if (horizontal) { + quad[0].setX(cx - (width * F)); + quad[3].setX(cx - (width * F)); + quad[1].setX(cx + (width * F)); + quad[2].setX(cx + (width * F)); + } + if (vertical) { + quad[0].setY(cy - (height * F)); + quad[3].setY(cy + (height * F)); + quad[1].setY(cy - (height * F)); + quad[2].setY(cy + (height * F)); } } +} -void SwivelTabsEffect::clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ) - { - if( isActive || from->isMinimized() ) +void SwivelTabsEffect::clientGroupItemSwitched(EffectWindow* from, EffectWindow* to) +{ + if (isActive || from->isMinimized()) return; windows.show = to; windows.hide = from; - windows.time.setCurveShape( TimeLine::LinearCurve ); - windows.time.setDuration( animationTime( totalTime ) ); - windows.time.setProgress( 0.0f ); + windows.time.setCurveShape(TimeLine::LinearCurve); + windows.time.setDuration(animationTime(totalTime)); + windows.time.setProgress(0.0f); lastF = 0.0; isActive = true; - effects->setElevatedWindow( to, false ); - effects->setElevatedWindow( from, true ); - } + effects->setElevatedWindow(to, false); + effects->setElevatedWindow(from, true); +} } diff --git a/effects/_test/swiveltabs/swiveltabs.h b/effects/_test/swiveltabs/swiveltabs.h index df6a54336..89d3b747d 100644 --- a/effects/_test/swiveltabs/swiveltabs.h +++ b/effects/_test/swiveltabs/swiveltabs.h @@ -27,35 +27,34 @@ namespace KWin { class SwivelTabsEffect : public Effect - { - public: - SwivelTabsEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - virtual void clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ); - static bool supported(); - private: - struct swivel - { - EffectWindow* hide; - EffectWindow* show; - TimeLine time; - // The points of the transformed window - QPoint topLeft, topRight, bottomLeft, bottomRight; - // The size of the transformed window - double left, top, right, bottom; - }; - swivel windows; - bool isActive, horizontal, vertical; - int totalTime, kal; - double PI, lastF; - void nextStep( EffectWindow *w ); - void transformQuad( WindowQuad &quad ); - double calculateCoords( double original, double space, double newSpace ); +{ +public: + SwivelTabsEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + virtual void clientGroupItemSwitched(EffectWindow* from, EffectWindow* to); + static bool supported(); +private: + struct swivel { + EffectWindow* hide; + EffectWindow* show; + TimeLine time; + // The points of the transformed window + QPoint topLeft, topRight, bottomLeft, bottomRight; + // The size of the transformed window + double left, top, right, bottom; }; + swivel windows; + bool isActive, horizontal, vertical; + int totalTime, kal; + double PI, lastF; + void nextStep(EffectWindow *w); + void transformQuad(WindowQuad &quad); + double calculateCoords(double original, double space, double newSpace); +}; } diff --git a/effects/_test/swiveltabs/swiveltabs_config.cpp b/effects/_test/swiveltabs/swiveltabs_config.cpp index 295d01b17..71f2477cb 100644 --- a/effects/_test/swiveltabs/swiveltabs_config.cpp +++ b/effects/_test/swiveltabs/swiveltabs_config.cpp @@ -29,63 +29,63 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY -SwivelTabsEffectConfigForm::SwivelTabsEffectConfigForm( QWidget* parent ) : QWidget( parent ) - { - setupUi( this ); - } +SwivelTabsEffectConfigForm::SwivelTabsEffectConfigForm(QWidget* parent) : QWidget(parent) +{ + setupUi(this); +} SwivelTabsEffectConfig::SwivelTabsEffectConfig(QWidget* parent, const QVariantList& args) - : KCModule( EffectFactory::componentData(), parent, args ) - { - m_ui = new SwivelTabsEffectConfigForm( this ); - QVBoxLayout* layout = new QVBoxLayout( this ); - layout->addWidget( m_ui ); - connect( m_ui->vertical, SIGNAL( toggled( bool )), this, SLOT( changed() ) ); - connect( m_ui->horizontal, SIGNAL( toggled( bool )), this, SLOT( changed() ) ); - connect( m_ui->duration, SIGNAL( valueChanged( int ) ), this, SLOT( changed() ) ); + : KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new SwivelTabsEffectConfigForm(this); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_ui); + connect(m_ui->vertical, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_ui->horizontal, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_ui->duration, SIGNAL(valueChanged(int)), this, SLOT(changed())); load(); - } +} SwivelTabsEffectConfig::~SwivelTabsEffectConfig() - { +{ delete m_ui; - } +} void SwivelTabsEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "SwivelTabs" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("SwivelTabs"); - conf.writeEntry( "SwivelVertical", m_ui->vertical->isChecked() ); - conf.writeEntry( "SwivelHorizontal", m_ui->horizontal->isChecked() ); - conf.writeEntry( "SwivelDuration", m_ui->duration->value() ); + conf.writeEntry("SwivelVertical", m_ui->vertical->isChecked()); + conf.writeEntry("SwivelHorizontal", m_ui->horizontal->isChecked()); + conf.writeEntry("SwivelDuration", m_ui->duration->value()); conf.sync(); KCModule::save(); - emit changed( false ); - EffectsHandler::sendReloadMessage( "swiveltabs" ); - } + emit changed(false); + EffectsHandler::sendReloadMessage("swiveltabs"); +} void SwivelTabsEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "SwivelTabs" ); + KConfigGroup conf = EffectsHandler::effectConfig("SwivelTabs"); - bool vertical = conf.readEntry( "SwivelVertical", true ); - bool horizontal = conf.readEntry( "SwivelHorizontal", true ); - int duration = conf.readEntry("SwivelDuration", 500 ); - m_ui->vertical->setChecked( vertical ); - m_ui->horizontal->setChecked( horizontal ); - m_ui->duration->setValue( duration ); - emit changed( false ); - } + bool vertical = conf.readEntry("SwivelVertical", true); + bool horizontal = conf.readEntry("SwivelHorizontal", true); + int duration = conf.readEntry("SwivelDuration", 500); + m_ui->vertical->setChecked(vertical); + m_ui->horizontal->setChecked(horizontal); + m_ui->duration->setValue(duration); + emit changed(false); +} void SwivelTabsEffectConfig::defaults() - { - m_ui->vertical->setChecked( true ); - m_ui->horizontal->setChecked( true ); - m_ui->duration->setValue( 500 ); - emit changed( true ); - } +{ + m_ui->vertical->setChecked(true); + m_ui->horizontal->setChecked(true); + m_ui->duration->setValue(500); + emit changed(true); +} } diff --git a/effects/_test/swiveltabs/swiveltabs_config.h b/effects/_test/swiveltabs/swiveltabs_config.h index 285e297a9..80a7c66fc 100644 --- a/effects/_test/swiveltabs/swiveltabs_config.h +++ b/effects/_test/swiveltabs/swiveltabs_config.h @@ -28,25 +28,25 @@ namespace KWin { class SwivelTabsEffectConfigForm : public QWidget, public Ui::SwivelTabsEffectConfigForm - { +{ Q_OBJECT - public: - explicit SwivelTabsEffectConfigForm( QWidget* parent ); - }; +public: + explicit SwivelTabsEffectConfigForm(QWidget* parent); +}; class SwivelTabsEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit SwivelTabsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~SwivelTabsEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); - private: - SwivelTabsEffectConfigForm *m_ui; - }; +public: + explicit SwivelTabsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~SwivelTabsEffectConfig(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); +private: + SwivelTabsEffectConfigForm *m_ui; +}; } diff --git a/effects/_test/test_fbo.cpp b/effects/_test/test_fbo.cpp index 3b12b535d..4cb646ff9 100644 --- a/effects/_test/test_fbo.cpp +++ b/effects/_test/test_fbo.cpp @@ -27,12 +27,12 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( test_fbo, TestFBOEffect ) -KWIN_EFFECT_SUPPORTED( test_fbo, TestFBOEffect::supported() ) +KWIN_EFFECT(test_fbo, TestFBOEffect) +KWIN_EFFECT_SUPPORTED(test_fbo, TestFBOEffect::supported()) TestFBOEffect::TestFBOEffect() : Effect() - { +{ mRot = 0.0f; // Create texture and render target @@ -42,66 +42,64 @@ TestFBOEffect::TestFBOEffect() : Effect() mRenderTarget = new GLRenderTarget(mTexture); mValid = mRenderTarget->valid(); - } +} TestFBOEffect::~TestFBOEffect() - { +{ delete mTexture; delete mRenderTarget; - } +} bool TestFBOEffect::supported() - { +{ return GLRenderTarget::supported() && GLTexture::NPOTTextureSupported() && - (effects->compositingType() == OpenGLCompositing); - } + (effects->compositingType() == OpenGLCompositing); +} -void TestFBOEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if(mValid) - { +void TestFBOEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (mValid) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; // Start rendering to texture effects->pushRenderTarget(mRenderTarget); - } - - effects->prePaintScreen(data, time); } + effects->prePaintScreen(data, time); +} + void TestFBOEffect::postPaintScreen() - { +{ // Call the next effect. effects->postPaintScreen(); - if(mValid) - { + if (mValid) { // Disable render texture - assert( effects->popRenderTarget() == mRenderTarget ); + assert(effects->popRenderTarget() == mRenderTarget); mTexture->bind(); // Render fullscreen quad with screen contents glBegin(GL_QUADS); - glTexCoord2f(0.0, 0.0); glVertex2f(0.0, displayHeight()); - glTexCoord2f(1.0, 0.0); glVertex2f(displayWidth(), displayHeight()); - glTexCoord2f(1.0, 1.0); glVertex2f(displayWidth(), 0.0); - glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0); + glTexCoord2f(0.0, 0.0); glVertex2f(0.0, displayHeight()); + glTexCoord2f(1.0, 0.0); glVertex2f(displayWidth(), displayHeight()); + glTexCoord2f(1.0, 1.0); glVertex2f(displayWidth(), 0.0); + glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0); glEnd(); // Render rotated screen thumbnail mRot += 0.5f; - glTranslatef(displayWidth()/2.0f, displayHeight()/2.0f, 0.0f); + glTranslatef(displayWidth() / 2.0f, displayHeight() / 2.0f, 0.0f); glRotatef(mRot, 0.0, 0.0, 1.0); glScalef(0.2, 0.2, 0.2); - glTranslatef(-displayWidth()/2.0f, -displayHeight()/2.0f, 0.0f); + glTranslatef(-displayWidth() / 2.0f, -displayHeight() / 2.0f, 0.0f); glEnable(GL_BLEND); glColor4f(1.0, 1.0, 1.0, 0.8); glBegin(GL_QUADS); - glTexCoord2f(0.0, 0.0); glVertex2f(0.0, displayHeight()); - glTexCoord2f(1.0, 0.0); glVertex2f(displayWidth(), displayHeight()); - glTexCoord2f(1.0, 1.0); glVertex2f(displayWidth(), 0.0); - glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0); + glTexCoord2f(0.0, 0.0); glVertex2f(0.0, displayHeight()); + glTexCoord2f(1.0, 0.0); glVertex2f(displayWidth(), displayHeight()); + glTexCoord2f(1.0, 1.0); glVertex2f(displayWidth(), 0.0); + glTexCoord2f(0.0, 1.0); glVertex2f(0.0, 0.0); glEnd(); glColor4f(1.0, 1.0, 1.0, 1.0); glDisable(GL_BLEND); @@ -113,10 +111,10 @@ void TestFBOEffect::postPaintScreen() // Make sure the animation continues effects->addRepaintFull(); - } - } +} + } // namespace diff --git a/effects/_test/test_fbo.h b/effects/_test/test_fbo.h index 0cb1ed993..f3bfd66df 100644 --- a/effects/_test/test_fbo.h +++ b/effects/_test/test_fbo.h @@ -36,23 +36,23 @@ class GLTexture; * on top of the usual scene. **/ class TestFBOEffect : public Effect - { - public: - TestFBOEffect(); - ~TestFBOEffect(); +{ +public: + TestFBOEffect(); + ~TestFBOEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); - static bool supported(); + static bool supported(); - private: - GLTexture* mTexture; - GLRenderTarget* mRenderTarget; - bool mValid; +private: + GLTexture* mTexture; + GLRenderTarget* mRenderTarget; + bool mValid; - double mRot; - }; + double mRot; +}; } // namespace diff --git a/effects/_test/test_input.cpp b/effects/_test/test_input.cpp index 9eb94ffec..7fefbea3b 100644 --- a/effects/_test/test_input.cpp +++ b/effects/_test/test_input.cpp @@ -29,46 +29,44 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( test_input, TestInputEffect ) +KWIN_EFFECT(test_input, TestInputEffect) TestInputEffect::TestInputEffect() - { - input = effects->createInputWindow( this, 0, 0, displayWidth(), displayHeight(), Qt::CrossCursor ); - } +{ + input = effects->createInputWindow(this, 0, 0, displayWidth(), displayHeight(), Qt::CrossCursor); +} TestInputEffect::~TestInputEffect() - { - effects->destroyInputWindow( input ); - } +{ + effects->destroyInputWindow(input); +} -void TestInputEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void TestInputEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ data.mask |= PAINT_SCREEN_TRANSFORMED; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void TestInputEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { +void TestInputEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ data.yTranslate += 100; - effects->paintScreen( mask, region, data ); - } + effects->paintScreen(mask, region, data); +} -void TestInputEffect::windowInputMouseEvent( Window w, QEvent* e ) - { - assert( w == input ); - if( e->type() != QEvent::MouseButtonPress ) +void TestInputEffect::windowInputMouseEvent(Window w, QEvent* e) +{ + assert(w == input); + if (e->type() != QEvent::MouseButtonPress) return; - QPoint pos = static_cast< QMouseEvent* >( e )->pos(); - pos -= QPoint( 0, 100 ); // adjust for transformation - foreach( EffectWindow* c, effects->stackingOrder()) - { - if( /* TODO c->isShown( true ) && */c->isOnCurrentDesktop() - && c->geometry().contains( pos )) - { - effects->activateWindow( c ); + QPoint pos = static_cast< QMouseEvent* >(e)->pos(); + pos -= QPoint(0, 100); // adjust for transformation + foreach (EffectWindow * c, effects->stackingOrder()) { + if (/* TODO c->isShown( true ) && */c->isOnCurrentDesktop() + && c->geometry().contains(pos)) { + effects->activateWindow(c); return; - } } } +} } // namespace diff --git a/effects/_test/test_input.h b/effects/_test/test_input.h index bfb814f30..6e4fedac1 100644 --- a/effects/_test/test_input.h +++ b/effects/_test/test_input.h @@ -24,16 +24,16 @@ namespace KWin class TestInputEffect : public Effect - { - public: - TestInputEffect(); - virtual ~TestInputEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void windowInputMouseEvent( Window w, QEvent* e ); - private: - Window input; - }; +{ +public: + TestInputEffect(); + virtual ~TestInputEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void windowInputMouseEvent(Window w, QEvent* e); +private: + Window input; +}; } // namespace diff --git a/effects/_test/test_thumbnail.cpp b/effects/_test/test_thumbnail.cpp index db74bff21..3017ed306 100644 --- a/effects/_test/test_thumbnail.cpp +++ b/effects/_test/test_thumbnail.cpp @@ -20,58 +20,56 @@ License. See the file "COPYING" for the exact licensing terms. namespace KWin { -KWIN_EFFECT( test_thumbnail, TestThumbnailEffect ) +KWIN_EFFECT(test_thumbnail, TestThumbnailEffect) TestThumbnailEffect::TestThumbnailEffect() - : active_window( NULL ) - { - } + : active_window(NULL) +{ +} -void TestThumbnailEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( active_window != NULL && region.contains( thumbnailRect())) - { - WindowPaintData data( active_window ); +void TestThumbnailEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (active_window != NULL && region.contains(thumbnailRect())) { + WindowPaintData data(active_window); QRect region; - setPositionTransformations( data, region, active_window, thumbnailRect(), Qt::KeepAspectRatio ); - effects->drawWindow( active_window, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSLUCENT | PAINT_WINDOW_TRANSFORMED, - region, data ); - } + setPositionTransformations(data, region, active_window, thumbnailRect(), Qt::KeepAspectRatio); + effects->drawWindow(active_window, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSLUCENT | PAINT_WINDOW_TRANSFORMED, + region, data); } +} -void TestThumbnailEffect::windowActivated( EffectWindow* act ) - { +void TestThumbnailEffect::windowActivated(EffectWindow* act) +{ active_window = act; - effects->addRepaint( thumbnailRect()); - } + effects->addRepaint(thumbnailRect()); +} -void TestThumbnailEffect::windowDamaged( EffectWindow* w, const QRect& ) - { - if( w == active_window ) - effects->addRepaint( thumbnailRect()); +void TestThumbnailEffect::windowDamaged(EffectWindow* w, const QRect&) +{ + if (w == active_window) + effects->addRepaint(thumbnailRect()); // TODO maybe just the relevant part of the area should be repainted? - } +} -void TestThumbnailEffect::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - if( w == active_window && w->size() != old.size()) - effects->addRepaint( thumbnailRect()); - } +void TestThumbnailEffect::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + if (w == active_window && w->size() != old.size()) + effects->addRepaint(thumbnailRect()); +} -void TestThumbnailEffect::windowClosed( EffectWindow* w ) - { - if( w == active_window ) - { +void TestThumbnailEffect::windowClosed(EffectWindow* w) +{ + if (w == active_window) { active_window = NULL; - effects->addRepaint( thumbnailRect()); - } + effects->addRepaint(thumbnailRect()); } +} QRect TestThumbnailEffect::thumbnailRect() const - { - return QRect( displayWidth() - 100, displayHeight() - 100, 100, 100 ); - } +{ + return QRect(displayWidth() - 100, displayHeight() - 100, 100, 100); +} } // namespace diff --git a/effects/_test/test_thumbnail.h b/effects/_test/test_thumbnail.h index 0028a6471..be11601fd 100644 --- a/effects/_test/test_thumbnail.h +++ b/effects/_test/test_thumbnail.h @@ -24,18 +24,18 @@ namespace KWin class TestThumbnailEffect : public Effect - { - public: - TestThumbnailEffect(); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void windowActivated( EffectWindow* w ); - virtual void windowDamaged( EffectWindow* w, const QRect& damage ); - virtual void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - virtual void windowClosed( EffectWindow* w ); - private: - QRect thumbnailRect() const; - EffectWindow* active_window; - }; +{ +public: + TestThumbnailEffect(); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void windowActivated(EffectWindow* w); + virtual void windowDamaged(EffectWindow* w, const QRect& damage); + virtual void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + virtual void windowClosed(EffectWindow* w); +private: + QRect thumbnailRect() const; + EffectWindow* active_window; +}; } // namespace diff --git a/effects/_test/videorecord.cpp b/effects/_test/videorecord.cpp index c3a7cbb18..475ef30d7 100644 --- a/effects/_test/videorecord.cpp +++ b/effects/_test/videorecord.cpp @@ -59,59 +59,56 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( videorecord, VideoRecordEffect ) +KWIN_EFFECT(videorecord, VideoRecordEffect) VideoRecordEffect::VideoRecordEffect() - : client( NULL ) - { - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = static_cast< KAction* >( actionCollection->addAction( "VideoRecord" )); - a->setText( i18n("Toggle Video Recording" )); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::META + Qt::Key_V )); - connect( a, SIGNAL( triggered( bool )), this, SLOT( toggleRecording())); - area = QRect( 0, 0, displayWidth(), displayHeight()); - } + : client(NULL) +{ + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = static_cast< KAction* >(actionCollection->addAction("VideoRecord")); + a->setText(i18n("Toggle Video Recording")); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_V)); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggleRecording())); + area = QRect(0, 0, displayWidth(), displayHeight()); +} VideoRecordEffect::~VideoRecordEffect() - { +{ stopRecording(); - } +} -void VideoRecordEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( client != NULL ) - capture_region = ( mask & ( PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_TRANSFORMED )) - ? QRect( 0, 0, displayWidth(), displayHeight()) : region; - } +void VideoRecordEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (client != NULL) + capture_region = (mask & (PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_TRANSFORMED)) + ? QRect(0, 0, displayWidth(), displayHeight()) : region; +} void VideoRecordEffect::postPaintScreen() - { +{ effects->postPaintScreen(); - if( client != NULL ) - { + if (client != NULL) { #if 1 - if( CapturyProcessRegionStart( client ) == CAPTURY_SUCCESS ) - { - capture_region &= QRect( 0, 0, displayWidth(), displayHeight()); // limit to screen - foreach( const QRect &r, capture_region.rects()) - { + if (CapturyProcessRegionStart(client) == CAPTURY_SUCCESS) { + capture_region &= QRect(0, 0, displayWidth(), displayHeight()); // limit to screen + foreach (const QRect & r, capture_region.rects()) { int gly = displayHeight() - r.y() - r.height(); // opengl coords - CapturyProcessRegion( client, r.x(), gly, r.width(), r.height()); - } - CapturyProcessRegionCommit( client ); + CapturyProcessRegion(client, r.x(), gly, r.width(), r.height()); } -#else - CapturyProcessFrame( client ); -#endif + CapturyProcessRegionCommit(client); } +#else + CapturyProcessFrame(client); +#endif } +} void VideoRecordEffect::startRecording() - { - if( client != NULL ) +{ + if (client != NULL) stopRecording(); - bzero( &config, sizeof( config )); + bzero(&config, sizeof(config)); config.x = area.x(); config.y = area.y(); config.width = area.width(); @@ -122,58 +119,56 @@ void VideoRecordEffect::startRecording() config.deviceHandle = display(); config.windowHandle = rootWindow(); // TODO config.cursor = true; - client = CapturyOpen( &config ); - if( client == NULL ) - { - kDebug( 1212 ) << "Video recording init failed"; + client = CapturyOpen(&config); + if (client == NULL) { + kDebug(1212) << "Video recording init failed"; return; - } + } KConfigGroup conf = EffectsHandler::effectConfig("VideoRecord"); - QString videoPath =conf.readEntry( "videopath", KGlobalSettings::documentPath() ); - QString videoName(videoPath +"/kwin_video1.cps" ); - while(QFile::exists( videoName )) { - autoincFilename( videoName ); + QString videoPath = conf.readEntry("videopath", KGlobalSettings::documentPath()); + QString videoName(videoPath + "/kwin_video1.cps"); + while (QFile::exists(videoName)) { + autoincFilename(videoName); } - if( CapturySetOutputFileName( client, QFile::encodeName( videoName ).constData() ) != CAPTURY_SUCCESS ) - { - kDebug( 1212 ) << "Video recording file open failed"; + if (CapturySetOutputFileName(client, QFile::encodeName(videoName).constData()) != CAPTURY_SUCCESS) { + kDebug(1212) << "Video recording file open failed"; return; - } - effects->addRepaintFull(); // trigger reading initial screen contents into buffer - kDebug( 1212 ) << "Video recording start"; } + effects->addRepaintFull(); // trigger reading initial screen contents into buffer + kDebug(1212) << "Video recording start"; +} void VideoRecordEffect::autoincFilename(QString & name) - { - // If the name contains a number then increment it - QRegExp numSearch( "(^|[^\\d])(\\d+)" ); // we want to match as far left as possible, and when the number is at the start of the name - // Does it have a number? - int start = numSearch.lastIndexIn( name ); - if (start != -1) { - // It has a number, increment it - start = numSearch.pos( 2 ); // we are only interested in the second group - QString numAsStr = numSearch.capturedTexts()[ 2 ]; - QString number = QString::number( numAsStr.toInt() + 1 ); - number = number.rightJustified( numAsStr.length(), '0' ); - name.replace( start, number.length(), number ); - } +{ + // If the name contains a number then increment it + QRegExp numSearch("(^|[^\\d])(\\d+)"); // we want to match as far left as possible, and when the number is at the start of the name + // Does it have a number? + int start = numSearch.lastIndexIn(name); + if (start != -1) { + // It has a number, increment it + start = numSearch.pos(2); // we are only interested in the second group + QString numAsStr = numSearch.capturedTexts()[ 2 ]; + QString number = QString::number(numAsStr.toInt() + 1); + number = number.rightJustified(numAsStr.length(), '0'); + name.replace(start, number.length(), number); } +} void VideoRecordEffect::stopRecording() - { - if( client == NULL ) +{ + if (client == NULL) return; - kDebug( 1212 ) << "Video recording stop"; - CapturyClose( client ); + kDebug(1212) << "Video recording stop"; + CapturyClose(client); client = NULL; - } +} void VideoRecordEffect::toggleRecording() - { - if( client == NULL ) +{ + if (client == NULL) startRecording(); else stopRecording(); - } +} } // namespace diff --git a/effects/_test/videorecord.h b/effects/_test/videorecord.h index 1dc6f7ab5..ba72432fd 100644 --- a/effects/_test/videorecord.h +++ b/effects/_test/videorecord.h @@ -30,24 +30,24 @@ namespace KWin class VideoRecordEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - VideoRecordEffect(); - virtual ~VideoRecordEffect(); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - private slots: - void toggleRecording(); - private: - void startRecording(); - void stopRecording(); - void autoincFilename(QString & url); - captury_config_t config; - captury_t* client; - QRect area; - QRegion capture_region; - }; +public: + VideoRecordEffect(); + virtual ~VideoRecordEffect(); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); +private slots: + void toggleRecording(); +private: + void startRecording(); + void stopRecording(); + void autoincFilename(QString & url); + captury_config_t config; + captury_t* client; + QRect area; + QRegion capture_region; +}; } // namespace diff --git a/effects/_test/videorecord_config.cpp b/effects/_test/videorecord_config.cpp index 6742b3c81..53ca9f6eb 100644 --- a/effects/_test/videorecord_config.cpp +++ b/effects/_test/videorecord_config.cpp @@ -38,35 +38,35 @@ along with this program. If not, see . KWIN_EFFECT_CONFIG_FACTORY #endif K_PLUGIN_FACTORY_DEFINITION(EffectFactory, - registerPlugin("videorecord"); - ) + registerPlugin("videorecord"); + ) K_EXPORT_PLUGIN(EffectFactory("kwin")) namespace KWin { VideoRecordEffectConfig::VideoRecordEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ QVBoxLayout* layout = new QVBoxLayout(this); - QHBoxLayout* hlayout = new QHBoxLayout( this ); - QLabel *label = new QLabel( i18n( "Path to save video:" ), this ); - hlayout->addWidget( label ); - saveVideo = new KUrlRequester( this ); - saveVideo->setMode( KFile::Directory | KFile::LocalOnly ); - hlayout->addWidget( saveVideo ); - layout->addLayout( hlayout ); + QHBoxLayout* hlayout = new QHBoxLayout(this); + QLabel *label = new QLabel(i18n("Path to save video:"), this); + hlayout->addWidget(label); + saveVideo = new KUrlRequester(this); + saveVideo->setMode(KFile::Directory | KFile::LocalOnly); + hlayout->addWidget(saveVideo); + layout->addLayout(hlayout); // Shortcut config. The shortcut belongs to the component "kwin"! - KActionCollection* actionCollection = new KActionCollection( this, KComponentData("kwin") ); + KActionCollection* actionCollection = new KActionCollection(this, KComponentData("kwin")); - KAction* a = static_cast(actionCollection->addAction( "VideoRecord" )); - a->setText( i18n("Toggle Video Recording" )); + KAction* a = static_cast(actionCollection->addAction("VideoRecord")); + a->setText(i18n("Toggle Video Recording")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_V)); mShortcutEditor = new KShortcutsEditor(actionCollection, this, - KShortcutsEditor::GlobalAction, KShortcutsEditor::LetterShortcutsDisallowed); + KShortcutsEditor::GlobalAction, KShortcutsEditor::LetterShortcutsDisallowed); layout->addWidget(mShortcutEditor); connect(saveVideo, SIGNAL(textChanged(const QString&)), this, SLOT(changed())); @@ -75,48 +75,48 @@ VideoRecordEffectConfig::VideoRecordEffectConfig(QWidget* parent, const QVariant layout->addStretch(); load(); - } +} VideoRecordEffectConfig::~VideoRecordEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts mShortcutEditor->undoChanges(); - } +} void VideoRecordEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("VideoRecord"); - saveVideo->setPath( conf.readEntry( "videopath", KGlobalSettings::documentPath() ) ); + saveVideo->setPath(conf.readEntry("videopath", KGlobalSettings::documentPath())); emit changed(false); - } +} void VideoRecordEffectConfig::save() - { +{ KCModule::save(); KConfigGroup conf = EffectsHandler::effectConfig("VideoRecord"); - if( saveVideo->url().isEmpty() ) - conf.writeEntry("videopath", KGlobalSettings::documentPath()); + if (saveVideo->url().isEmpty()) + conf.writeEntry("videopath", KGlobalSettings::documentPath()); else - conf.writeEntry("videopath", saveVideo->url().path()); + conf.writeEntry("videopath", saveVideo->url().path()); conf.sync(); mShortcutEditor->save(); // undo() will restore to this state from now on emit changed(false); - EffectsHandler::sendReloadMessage( "videorecord" ); - } + EffectsHandler::sendReloadMessage("videorecord"); +} void VideoRecordEffectConfig::defaults() - { - saveVideo->setPath(KGlobalSettings::documentPath() ); +{ + saveVideo->setPath(KGlobalSettings::documentPath()); mShortcutEditor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/_test/videorecord_config.h b/effects/_test/videorecord_config.h index dd0468cbe..5563a42a7 100644 --- a/effects/_test/videorecord_config.h +++ b/effects/_test/videorecord_config.h @@ -30,21 +30,21 @@ namespace KWin { class VideoRecordEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit VideoRecordEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~VideoRecordEffectConfig(); +public: + explicit VideoRecordEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~VideoRecordEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - KShortcutsEditor* mShortcutEditor; - KUrlRequester *saveVideo; - }; +private: + KShortcutsEditor* mShortcutEditor; + KUrlRequester *saveVideo; +}; } // namespace diff --git a/effects/blur/blur.cpp b/effects/blur/blur.cpp index 5980ce7ad..931e2f935 100644 --- a/effects/blur/blur.cpp +++ b/effects/blur/blur.cpp @@ -119,7 +119,7 @@ void BlurEffect::propertyNotify(EffectWindow *w, long atom) bool BlurEffect::supported() { bool supported = GLRenderTarget::supported() && GLTexture::NPOTTextureSupported() && - (GLSLBlurShader::supported() || ARBBlurShader::supported()); + (GLSLBlurShader::supported() || ARBBlurShader::supported()); if (supported) { int maxTexSize; @@ -131,9 +131,9 @@ bool BlurEffect::supported() if (supported) { // check the blacklist - KSharedConfigPtr config = KSharedConfig::openConfig( "kwinrc" ); - KConfigGroup blacklist = config->group( "Blacklist" ).group( "Blur" ); - if (effects->checkDriverBlacklist( blacklist )) { + KSharedConfigPtr config = KSharedConfig::openConfig("kwinrc"); + KConfigGroup blacklist = config->group("Blacklist").group("Blur"); + if (effects->checkDriverBlacklist(blacklist)) { kDebug() << "Blur effect disabled by driver blacklist"; supported = false; } @@ -152,8 +152,8 @@ QRegion BlurEffect::expand(const QRegion ®ion) const QRegion expanded; if (region.rectCount() < 20) { - foreach (const QRect &rect, region.rects()) - expanded += expand(rect); + foreach (const QRect & rect, region.rects()) + expanded += expand(rect); } else expanded += expand(region.boundingRect()); @@ -172,7 +172,7 @@ QRegion BlurEffect::blurRegion(const EffectWindow *w) const region = w->shape(); region -= w->decorationInnerRect(); region |= appRegion.translated(w->contentsRect().topLeft()) & - w->contentsRect(); + w->contentsRect(); } else region = appRegion & w->contentsRect(); } else { @@ -197,7 +197,7 @@ void BlurEffect::drawRegion(const QRegion ®ion) vertices.resize(vertexCount); int i = 0; - foreach (const QRect &r, region.rects()) { + foreach (const QRect & r, region.rects()) { vertices[i++] = QVector2D(r.x() + r.width(), r.y()); vertices[i++] = QVector2D(r.x(), r.y()); vertices[i++] = QVector2D(r.x(), r.y() + r.height()); @@ -230,13 +230,12 @@ void BlurEffect::drawWindow(EffectWindow *w, int mask, QRegion region, WindowPai bool valid = target->valid() && shader->isValid(); QRegion shape; - const QVariant forceBlur = w->data( WindowForceBlurRole ); - if ((!effects->activeFullScreenEffect() || (forceBlur.isValid() && forceBlur.toBool() )) + const QVariant forceBlur = w->data(WindowForceBlurRole); + if ((!effects->activeFullScreenEffect() || (forceBlur.isValid() && forceBlur.toBool())) && hasAlpha && !w->isDesktop() && !transformed) shape = blurRegion(w).translated(w->geometry().topLeft()) & screen; - if (valid && !shape.isEmpty() && region.intersects(shape.boundingRect())) - { + if (valid && !shape.isEmpty() && region.intersects(shape.boundingRect())) { doBlur(shape, screen, data.opacity * data.contents_opacity); } @@ -248,7 +247,7 @@ void BlurEffect::paintEffectFrame(EffectFrame *frame, QRegion region, double opa { const QRect screen(0, 0, displayWidth(), displayHeight()); bool valid = target->valid() && shader->isValid(); - QRegion shape = frame->geometry().adjusted( -5, -5, 5, 5 ) & screen; + QRegion shape = frame->geometry().adjusted(-5, -5, 5, 5) & screen; if (valid && !shape.isEmpty() && region.intersects(shape.boundingRect())) { doBlur(shape, screen, opacity * frameOpacity); } diff --git a/effects/blur/blur.h b/effects/blur/blur.h index b202d9d27..e3f1cb247 100644 --- a/effects/blur/blur.h +++ b/effects/blur/blur.h @@ -18,7 +18,7 @@ */ #ifndef BLUR_H -#define BLUR_H +#define BLUR_H #include #include diff --git a/effects/blur/blurshader.cpp b/effects/blur/blurshader.cpp index 35d30ff28..516fece1d 100644 --- a/effects/blur/blurshader.cpp +++ b/effects/blur/blurshader.cpp @@ -68,7 +68,7 @@ void BlurShader::setDirection(Qt::Orientation direction) float BlurShader::gaussian(float x, float sigma) const { return (1.0 / std::sqrt(2.0 * M_PI) * sigma) - * std::exp(-((x * x) / (2.0 * sigma * sigma))); + * std::exp(-((x * x) / (2.0 * sigma * sigma))); } QVector BlurShader::gaussianKernel() const @@ -380,11 +380,10 @@ void ARBBlurShader::unbind() #ifndef KWIN_HAVE_OPENGLES int boundObject; glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_BINDING_ARB, &boundObject); - if( boundObject == program ) - { + if (boundObject == program) { glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, 0); glDisable(GL_FRAGMENT_PROGRAM_ARB); - } + } #endif } @@ -418,7 +417,7 @@ void ARBBlurShader::init() stream << "!!ARBfp1.0\n"; - // The kernel values are hardcoded into the program + // The kernel values are hardcoded into the program for (int i = 0; i <= center; i++) stream << "PARAM kernel" << i << " = " << kernel[center + i] << ";\n"; @@ -442,14 +441,14 @@ void ARBBlurShader::init() for (int i = 1; i < size; i++) stream << "TEX temp" << i << ", temp" << i << ", texture[0], 2D;\n"; - // Multiply the samples with the kernel values and compute the sum + // Multiply the samples with the kernel values and compute the sum stream << "MUL temp0, temp0, kernel0;\n"; for (int i = 0, j = 1; i < center; i++) { stream << "MAD temp0, temp" << j++ << ", kernel" << i + 1 << ", temp0;\n"; stream << "MAD temp0, temp" << j++ << ", kernel" << i + 1 << ", temp0;\n"; } - stream << "MOV result.color, temp0;\n"; // gl_FragColor = temp0 + stream << "MOV result.color, temp0;\n"; // gl_FragColor = temp0 stream << "END\n"; stream.flush(); diff --git a/effects/blur/blurshader.h b/effects/blur/blurshader.h index fe7360999..4308be9f5 100644 --- a/effects/blur/blurshader.h +++ b/effects/blur/blurshader.h @@ -35,15 +35,21 @@ public: static BlurShader *create(); - bool isValid() const { return mValid; } + bool isValid() const { + return mValid; + } // Sets the radius in pixels void setRadius(int radius); - int radius() const { return mRadius; } + int radius() const { + return mRadius; + } // Sets the blur direction void setDirection(Qt::Orientation direction); - Qt::Orientation direction() const { return mDirection; } + Qt::Orientation direction() const { + return mDirection; + } // Sets the distance between two pixels virtual void setPixelDistance(float val) = 0; @@ -55,7 +61,9 @@ public: protected: float gaussian(float x, float sigma) const; QVector gaussianKernel() const; - void setIsValid(bool value) { mValid = value; } + void setIsValid(bool value) { + mValid = value; + } virtual void init() = 0; virtual void reset() = 0; virtual int maxKernelSize() const = 0; diff --git a/effects/boxswitch/boxswitch.cpp b/effects/boxswitch/boxswitch.cpp index fc8f98b09..4b2a69d50 100644 --- a/effects/boxswitch/boxswitch.cpp +++ b/effects/boxswitch/boxswitch.cpp @@ -32,316 +32,265 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( boxswitch, BoxSwitchEffect ) +KWIN_EFFECT(boxswitch, BoxSwitchEffect) BoxSwitchEffect::BoxSwitchEffect() - : mActivated( 0 ) - , mMode( 0 ) - , thumbnailFrame( effects->effectFrame( EffectFrameStyled ) ) - , selected_window( 0 ) - , painting_desktop( 0 ) - , animation( false ) - , highlight_is_set( false ) - , primaryTabBox( true ) - , secondaryTabBox( false ) - , mProxy( this ) - , mProxyActivated( 0 ) - , mProxyAnimateSwitch( 0 ) - , mProxyShowText( 0 ) - , mPositioningFactor( 0.5f ) - { - text_font.setBold( true ); - text_font.setPointSize( 12 ); - thumbnailFrame->setFont( text_font ); - thumbnailFrame->setAlignment( Qt::AlignBottom | Qt::AlignHCenter ); + : mActivated(0) + , mMode(0) + , thumbnailFrame(effects->effectFrame(EffectFrameStyled)) + , selected_window(0) + , painting_desktop(0) + , animation(false) + , highlight_is_set(false) + , primaryTabBox(true) + , secondaryTabBox(false) + , mProxy(this) + , mProxyActivated(0) + , mProxyAnimateSwitch(0) + , mProxyShowText(0) + , mPositioningFactor(0.5f) +{ + text_font.setBold(true); + text_font.setPointSize(12); + thumbnailFrame->setFont(text_font); + thumbnailFrame->setAlignment(Qt::AlignBottom | Qt::AlignHCenter); highlight_margin = 10; - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} BoxSwitchEffect::~BoxSwitchEffect() - { +{ delete thumbnailFrame; - } +} -void BoxSwitchEffect::reconfigure( ReconfigureFlags ) - { - color_frame = KColorScheme( QPalette::Active, KColorScheme::Window ).background().color(); - color_frame.setAlphaF( 0.9 ); - color_highlight = KColorScheme( QPalette::Active, KColorScheme::Selection ).background().color(); - color_highlight.setAlphaF( 0.9 ); - activeTimeLine.setDuration( animationTime( 250 )); - activeTimeLine.setCurveShape( TimeLine::EaseInOutCurve ); - timeLine.setDuration( animationTime( 150 )); - timeLine.setCurveShape( TimeLine::EaseInOutCurve ); - KConfigGroup conf = effects->effectConfig( "BoxSwitch" ); +void BoxSwitchEffect::reconfigure(ReconfigureFlags) +{ + color_frame = KColorScheme(QPalette::Active, KColorScheme::Window).background().color(); + color_frame.setAlphaF(0.9); + color_highlight = KColorScheme(QPalette::Active, KColorScheme::Selection).background().color(); + color_highlight.setAlphaF(0.9); + activeTimeLine.setDuration(animationTime(250)); + activeTimeLine.setCurveShape(TimeLine::EaseInOutCurve); + timeLine.setDuration(animationTime(150)); + timeLine.setCurveShape(TimeLine::EaseInOutCurve); + KConfigGroup conf = effects->effectConfig("BoxSwitch"); - bg_opacity = conf.readEntry( "BackgroundOpacity", 25 ) / 100.0; - elevate_window = conf.readEntry( "ElevateSelected", true ); - mAnimateSwitch = conf.readEntry( "AnimateSwitch", false ); + bg_opacity = conf.readEntry("BackgroundOpacity", 25) / 100.0; + elevate_window = conf.readEntry("ElevateSelected", true); + mAnimateSwitch = conf.readEntry("AnimateSwitch", false); - primaryTabBox = conf.readEntry( "TabBox", true ); - secondaryTabBox = conf.readEntry( "TabBoxAlternative", false ); - } + primaryTabBox = conf.readEntry("TabBox", true); + secondaryTabBox = conf.readEntry("TabBoxAlternative", false); +} -void BoxSwitchEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( activeTimeLine.value() != 0.0 && !mProxyActivated ) - { - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { - if( windows.contains( w )) - { - if( w == selected_window ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP ); +void BoxSwitchEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (activeTimeLine.value() != 0.0 && !mProxyActivated) { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { + if (windows.contains(w)) { + if (w == selected_window) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP); else data.setTranslucent(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE | EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE | EffectWindow::PAINT_DISABLED_BY_DESKTOP); } - else - { - if( painting_desktop ) - { - if( w->isOnDesktop( painting_desktop )) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); + } else { + if (painting_desktop) { + if (w->isOnDesktop(painting_desktop)) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void BoxSwitchEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( mActivated ) - activeTimeLine.addTime( time ); - else - { - activeTimeLine.removeTime( time ); - if( activeTimeLine.value() == 0.0 ) - { // No longer need the window data - qDeleteAll( windows ); +void BoxSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (mActivated) + activeTimeLine.addTime(time); + else { + activeTimeLine.removeTime(time); + if (activeTimeLine.value() == 0.0) { + // No longer need the window data + qDeleteAll(windows); windows.clear(); - } } - if( mActivated && animation ) - { - timeLine.addTime( time ); - calculateItemSizes(); - } - effects->prePaintScreen( data, time ); } + if (mActivated && animation) { + timeLine.addTime(time); + calculateItemSizes(); + } + effects->prePaintScreen(data, time); +} -void BoxSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( mActivated && !mProxyActivated ) - { - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { +void BoxSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (mActivated && !mProxyActivated) { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { paintWindowsBox(region); - } - else - { - if( !painting_desktop ) - { - thumbnailFrame->setSelection( desktops[ selected_desktop ]->area ); - thumbnailFrame->render( region ); + } else { + if (!painting_desktop) { + thumbnailFrame->setSelection(desktops[ selected_desktop ]->area); + thumbnailFrame->render(region); QHash< int, ItemInfo* >::const_iterator i; - for( i = desktops.constBegin(); i != desktops.constEnd(); ++i ) - { + for (i = desktops.constBegin(); i != desktops.constEnd(); ++i) { painting_desktop = i.key(); - paintDesktopThumbnail( painting_desktop ); - } - painting_desktop = 0; + paintDesktopThumbnail(painting_desktop); } + painting_desktop = 0; } } } +} void BoxSwitchEffect::paintWindowsBox(const QRegion& region) - { - if( (mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch) ) - thumbnailFrame->setSelection( highlight_area ); +{ + if ((mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch)) + thumbnailFrame->setSelection(highlight_area); else - thumbnailFrame->setSelection( windows[ selected_window ]->area ); - thumbnailFrame->render( region ); + thumbnailFrame->setSelection(windows[ selected_window ]->area); + thumbnailFrame->render(region); - if( (mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch) ) - { + if ((mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch)) { // HACK: PaintClipper is used because window split is somehow wrong if the height is greater than width - PaintClipper::push( frame_area ); + PaintClipper::push(frame_area); QHash< EffectWindow*, ItemInfo* >::const_iterator i; - for( i = windows.constBegin(); i != windows.constEnd(); ++i ) - { - paintWindowThumbnail( i.key() ); - paintWindowIcon( i.key() ); - } - PaintClipper::pop( frame_area ); + for (i = windows.constBegin(); i != windows.constEnd(); ++i) { + paintWindowThumbnail(i.key()); + paintWindowIcon(i.key()); } - else - { + PaintClipper::pop(frame_area); + } else { QHash< EffectWindow*, ItemInfo* >::const_iterator i; - for( i = windows.constBegin(); i != windows.constEnd(); ++i ) - { - paintWindowThumbnail( i.key() ); - paintWindowIcon( i.key() ); - } + for (i = windows.constBegin(); i != windows.constEnd(); ++i) { + paintWindowThumbnail(i.key()); + paintWindowIcon(i.key()); } } +} void BoxSwitchEffect::postPaintScreen() - { - if( mActivated && activeTimeLine.value() != 1.0 ) +{ + if (mActivated && activeTimeLine.value() != 1.0) effects->addRepaintFull(); - if( !mActivated && activeTimeLine.value() != 0.0 ) + if (!mActivated && activeTimeLine.value() != 0.0) effects->addRepaintFull(); - if( mActivated && animation ) - { - if( timeLine.value() == 1.0 ) - { - timeLine.setProgress( 0.0 ); + if (mActivated && animation) { + if (timeLine.value() == 1.0) { + timeLine.setProgress(0.0); animation = false; - if( !scheduled_directions.isEmpty() ) - { + if (!scheduled_directions.isEmpty()) { direction = scheduled_directions.dequeue(); animation = true; - } } - QRect repaint = QRect( frame_area.x() - item_max_size.width()*0.5, - frame_area.y(), - frame_area.width() + item_max_size.width(), - frame_area.height() ); - effects->addRepaint( repaint ); } - effects->postPaintScreen(); + QRect repaint = QRect(frame_area.x() - item_max_size.width() * 0.5, + frame_area.y(), + frame_area.width() + item_max_size.width(), + frame_area.height()); + effects->addRepaint(repaint); } + effects->postPaintScreen(); +} -void BoxSwitchEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if((( mActivated && (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) ) - || ( !mActivated && activeTimeLine.value() != 0.0 )) && !mProxyActivated) - { - if( windows.contains( w ) && w != selected_window ) - { - if( w->isMinimized() || !w->isOnCurrentDesktop() ) +void BoxSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (((mActivated && (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode)) + || (!mActivated && activeTimeLine.value() != 0.0)) && !mProxyActivated) { + if (windows.contains(w) && w != selected_window) { + if (w->isMinimized() || !w->isOnCurrentDesktop()) // TODO: When deactivating minimized windows are not painted at all data.opacity *= activeTimeLine.value() * bg_opacity; else - data.opacity *= 1.0 - activeTimeLine.value() * ( 1.0 - bg_opacity ); - } + data.opacity *= 1.0 - activeTimeLine.value() * (1.0 - bg_opacity); } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void BoxSwitchEffect::windowInputMouseEvent( Window w, QEvent* e ) - { - assert( w == mInput ); - Q_UNUSED( w ); - if( e->type() != QEvent::MouseButtonPress ) +void BoxSwitchEffect::windowInputMouseEvent(Window w, QEvent* e) +{ + assert(w == mInput); + Q_UNUSED(w); + if (e->type() != QEvent::MouseButtonPress) return; - QPoint pos = static_cast< QMouseEvent* >( e )->pos(); + QPoint pos = static_cast< QMouseEvent* >(e)->pos(); pos += frame_area.topLeft(); // determine which item was clicked - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { QHash< EffectWindow*, ItemInfo* >::const_iterator i; - for( i = windows.constBegin(); i != windows.constEnd(); ++i ) - { - if( i.value()->clickable.contains( pos )) - { - effects->setTabBoxWindow( i.key() ); + for (i = windows.constBegin(); i != windows.constEnd(); ++i) { + if (i.value()->clickable.contains(pos)) { + effects->setTabBoxWindow(i.key()); break; - } } + } // special handling for second half of window in case of animation and even number of windows - if( mAnimateSwitch && ( windows.size() % 2 == 0 ) ) - { - QRect additionalRect = QRect( frame_area.x(), frame_area.y(), - item_max_size.width()*0.5, item_max_size.height()); - if( additionalRect.contains( pos )) - { - effects->setTabBoxWindow( right_window ); - } + if (mAnimateSwitch && (windows.size() % 2 == 0)) { + QRect additionalRect = QRect(frame_area.x(), frame_area.y(), + item_max_size.width() * 0.5, item_max_size.height()); + if (additionalRect.contains(pos)) { + effects->setTabBoxWindow(right_window); } } - else - { + } else { QHash< int, ItemInfo* >::const_iterator i; - for( i = desktops.constBegin(); i != desktops.constEnd(); ++i ) - { - if( i.value()->clickable.contains( pos )) - effects->setTabBoxDesktop( i.key() ); + for (i = desktops.constBegin(); i != desktops.constEnd(); ++i) { + if (i.value()->clickable.contains(pos)) + effects->setTabBoxDesktop(i.key()); + } + } +} + +void BoxSwitchEffect::windowDamaged(EffectWindow* w, const QRect& damage) +{ + Q_UNUSED(damage); + if (mActivated) { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { + if (windows.contains(w)) { + effects->addRepaint(frame_area); + } + } else { + if (w->isOnAllDesktops()) { + foreach (ItemInfo * info, desktops) + effects->addRepaint(info->area); + } else { + effects->addRepaint(desktops[ w->desktop()]->area); } } } +} -void BoxSwitchEffect::windowDamaged( EffectWindow* w, const QRect& damage ) - { - Q_UNUSED( damage ); - if( mActivated ) - { - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { - if( windows.contains( w )) - { - effects->addRepaint( frame_area ); - } +void BoxSwitchEffect::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + if (mActivated) { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { + if (windows.contains(w) && w->size() != old.size()) { + effects->addRepaint(windows[ w ]->area); } - else - { - if( w->isOnAllDesktops()) - { - foreach( ItemInfo* info, desktops ) - effects->addRepaint( info->area ); - } - else - { - effects->addRepaint( desktops[ w->desktop() ]->area ); - } + } else { + if (w->isOnAllDesktops()) { + foreach (ItemInfo * info, desktops) + effects->addRepaint(info->area); + } else { + effects->addRepaint(desktops[ w->desktop()]->area); } } } +} -void BoxSwitchEffect::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - if( mActivated ) - { - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { - if( windows.contains( w ) && w->size() != old.size()) - { - effects->addRepaint( windows[ w ]->area ); - } - } - else - { - if( w->isOnAllDesktops()) - { - foreach( ItemInfo* info, desktops ) - effects->addRepaint( info->area ); - } - else - { - effects->addRepaint( desktops[ w->desktop() ]->area ); - } - } - } - } - -void BoxSwitchEffect::tabBoxAdded( int mode ) - { - if( !mActivated ) - { - if( ( mode == TabBoxWindowsMode && primaryTabBox ) || - ( mode == TabBoxWindowsAlternativeMode && secondaryTabBox) ) - { - if( effects->currentTabBoxWindowList().count() > 0 ) - { +void BoxSwitchEffect::tabBoxAdded(int mode) +{ + if (!mActivated) { + if ((mode == TabBoxWindowsMode && primaryTabBox) || + (mode == TabBoxWindowsAlternativeMode && secondaryTabBox)) { + if (effects->currentTabBoxWindowList().count() > 0) { mMode = mode; effects->refTabBox(); highlight_is_set = false; @@ -349,709 +298,605 @@ void BoxSwitchEffect::tabBoxAdded( int mode ) scheduled_directions.clear(); right_window = 0; setActive(); - } } - else if( mode == TabBoxDesktopListMode || mode == TabBoxDesktopMode ) - { // DesktopMode - if( effects->currentTabBoxDesktopList().count() > 0 ) - { + } else if (mode == TabBoxDesktopListMode || mode == TabBoxDesktopMode) { + // DesktopMode + if (effects->currentTabBoxDesktopList().count() > 0) { mMode = mode; painting_desktop = 0; effects->refTabBox(); setActive(); - } } } } +} void BoxSwitchEffect::tabBoxClosed() - { - if( mActivated ) +{ + if (mActivated) setInactive(); - } +} void BoxSwitchEffect::tabBoxUpdated() - { - if( mActivated ) - { - if( (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) - && selected_window != effects->currentTabBoxWindow() ) - { - if( selected_window != NULL ) - { - if( (mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch) ) - { - int old_index = effects->currentTabBoxWindowList().indexOf( selected_window ); - int new_index = effects->currentTabBoxWindowList().indexOf( effects->currentTabBoxWindow() ); +{ + if (mActivated) { + if ((mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) + && selected_window != effects->currentTabBoxWindow()) { + if (selected_window != NULL) { + if ((mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch)) { + int old_index = effects->currentTabBoxWindowList().indexOf(selected_window); + int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); Direction new_direction; int distance = new_index - old_index; - if( distance > 0 ) + if (distance > 0) new_direction = Left; - if( distance < 0 ) + if (distance < 0) new_direction = Right; - if( distance != 0 ) - { - distance = abs( distance ); + if (distance != 0) { + distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; - if( tempDistance < abs( distance ) ) - { + if (tempDistance < abs(distance)) { distance = tempDistance; - if( new_direction == Left ) + if (new_direction == Left) new_direction = Right; else new_direction = Left; - } - if( !animation ) - { + } + if (!animation) { animation = true; direction = new_direction; distance--; - } - for( int i=0; icurrentTabBoxWindowList().count() ) + scheduled_directions.enqueue(new_direction); + if (scheduled_directions.count() == effects->currentTabBoxWindowList().count()) scheduled_directions.clear(); - } } } - if( windows.contains( selected_window )) - effects->addRepaint( windows.value( selected_window )->area ); - selected_window->addRepaintFull(); } - setSelectedWindow( effects->currentTabBoxWindow()); - if( windows.contains( selected_window )) - effects->addRepaint( windows.value( selected_window )->area ); - selected_window->addRepaintFull(); - effects->addRepaint( text_area ); + if (windows.contains(selected_window)) + effects->addRepaint(windows.value(selected_window)->area); + selected_window->addRepaintFull(); } - else if( mMode != TabBoxWindowsMode && mMode != TabBoxWindowsAlternativeMode ) - { // DesktopMode - if( desktops.contains( selected_desktop )) - effects->addRepaint( desktops.value( selected_desktop )->area ); + setSelectedWindow(effects->currentTabBoxWindow()); + if (windows.contains(selected_window)) + effects->addRepaint(windows.value(selected_window)->area); + selected_window->addRepaintFull(); + effects->addRepaint(text_area); + } else if (mMode != TabBoxWindowsMode && mMode != TabBoxWindowsAlternativeMode) { + // DesktopMode + if (desktops.contains(selected_desktop)) + effects->addRepaint(desktops.value(selected_desktop)->area); selected_desktop = effects->currentTabBoxDesktop(); - if( !mProxyActivated || mProxyShowText ) - thumbnailFrame->setText( effects->desktopName( selected_desktop )); - if( desktops.contains( selected_desktop )) - effects->addRepaint( desktops.value( selected_desktop )->area ); - effects->addRepaint( text_area ); - if( effects->currentTabBoxDesktopList() == original_desktops ) + if (!mProxyActivated || mProxyShowText) + thumbnailFrame->setText(effects->desktopName(selected_desktop)); + if (desktops.contains(selected_desktop)) + effects->addRepaint(desktops.value(selected_desktop)->area); + effects->addRepaint(text_area); + if (effects->currentTabBoxDesktopList() == original_desktops) return; original_desktops = effects->currentTabBoxDesktopList(); - } + } // for safety copy list each time tabbox is updated original_windows = effects->currentTabBoxWindowList(); - effects->addRepaint( frame_area ); + effects->addRepaint(frame_area); calculateFrameSize(); calculateItemSizes(); - moveResizeInputWindow( frame_area.x(), frame_area.y(), frame_area.width(), frame_area.height()); - effects->addRepaint( frame_area ); - } + moveResizeInputWindow(frame_area.x(), frame_area.y(), frame_area.width(), frame_area.height()); + effects->addRepaint(frame_area); } +} void BoxSwitchEffect::setActive() - { +{ mActivated = true; // Just in case we are activated again before the deactivation animation finished - qDeleteAll( windows ); + qDeleteAll(windows); windows.clear(); - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { original_windows = effects->currentTabBoxWindowList(); - setSelectedWindow( effects->currentTabBoxWindow()); - } - else - { + setSelectedWindow(effects->currentTabBoxWindow()); + } else { original_desktops = effects->currentTabBoxDesktopList(); selected_desktop = effects->currentTabBoxDesktop(); - if( !mProxyActivated || mProxyShowText ) - thumbnailFrame->setText( effects->desktopName( selected_desktop )); - } + if (!mProxyActivated || mProxyShowText) + thumbnailFrame->setText(effects->desktopName(selected_desktop)); + } calculateFrameSize(); calculateItemSizes(); - if( !mProxyActivated ) - { + if (!mProxyActivated) { // only create the input window when effect is not activated via the proxy - mInput = effects->createInputWindow( this, frame_area.x(), frame_area.y(), - frame_area.width(), frame_area.height(), Qt::ArrowCursor ); - } - effects->addRepaint( frame_area ); - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { + mInput = effects->createInputWindow(this, frame_area.x(), frame_area.y(), + frame_area.width(), frame_area.height(), Qt::ArrowCursor); + } + effects->addRepaint(frame_area); + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { QHash< EffectWindow*, ItemInfo* >::const_iterator i; - for( i = windows.constBegin(); i != windows.constEnd(); ++i ) - { + for (i = windows.constBegin(); i != windows.constEnd(); ++i) { i.key()->addRepaintFull(); - } } } +} void BoxSwitchEffect::setInactive() - { +{ mActivated = false; effects->unrefTabBox(); - if( !mProxyActivated && mInput != None ) - { - effects->destroyInputWindow( mInput ); + if (!mProxyActivated && mInput != None) { + effects->destroyInputWindow(mInput); mInput = None; - } + } mProxyActivated = false; mPositioningFactor = 0.5f; - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { QHash< EffectWindow*, ItemInfo* >::const_iterator i; - for( i = windows.constBegin(); i != windows.constEnd(); ++i ) - { - if( i.key() != selected_window ) + for (i = windows.constBegin(); i != windows.constEnd(); ++i) { + if (i.key() != selected_window) i.key()->addRepaintFull(); - } + } // We don't unset the selected window so we have correct fading // But we do need to remove elevation status - if( elevate_window && selected_window ) - effects->setElevatedWindow( selected_window, false ); + if (elevate_window && selected_window) + effects->setElevatedWindow(selected_window, false); - foreach( EffectWindow* w, referrencedWindows ) - { + foreach (EffectWindow * w, referrencedWindows) { w->unrefWindow(); - } + } referrencedWindows.clear(); - } - else - { // DesktopMode - qDeleteAll( windows ); + } else { + // DesktopMode + qDeleteAll(windows); desktops.clear(); - } + } thumbnailFrame->free(); - effects->addRepaint( frame_area ); + effects->addRepaint(frame_area); frame_area = QRect(); - } +} -void BoxSwitchEffect::setSelectedWindow( EffectWindow* w ) - { - if( elevate_window && selected_window ) - { - effects->setElevatedWindow( selected_window, false ); - } +void BoxSwitchEffect::setSelectedWindow(EffectWindow* w) +{ + if (elevate_window && selected_window) { + effects->setElevatedWindow(selected_window, false); + } selected_window = w; - if( selected_window && ( !mProxyActivated || mProxyShowText ) ) - thumbnailFrame->setText( selected_window->caption() ); - if( elevate_window && w ) - { - effects->setElevatedWindow( selected_window, true ); - } + if (selected_window && (!mProxyActivated || mProxyShowText)) + thumbnailFrame->setText(selected_window->caption()); + if (elevate_window && w) { + effects->setElevatedWindow(selected_window, true); } +} -void BoxSwitchEffect::windowClosed( EffectWindow* w ) - { - if( w == selected_window ) - { - setSelectedWindow( 0 ); - } - if( windows.contains( w ) ) - { +void BoxSwitchEffect::windowClosed(EffectWindow* w) +{ + if (w == selected_window) { + setSelectedWindow(0); + } + if (windows.contains(w)) { w->refWindow(); - referrencedWindows.append( w ); - original_windows.removeAll( w ); + referrencedWindows.append(w); + original_windows.removeAll(w); delete windows[ w ]; - windows.remove( w ); + windows.remove(w); effects->addRepaintFull(); - } } +} -void BoxSwitchEffect::moveResizeInputWindow( int x, int y, int width, int height ) - { - XMoveWindow( display(), mInput, x, y ); - XResizeWindow( display(), mInput, width, height ); - } +void BoxSwitchEffect::moveResizeInputWindow(int x, int y, int width, int height) +{ + XMoveWindow(display(), mInput, x, y); + XResizeWindow(display(), mInput, width, height); +} void BoxSwitchEffect::calculateFrameSize() - { +{ int itemcount; - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { itemcount = original_windows.count(); - item_max_size.setWidth( 200 ); - item_max_size.setHeight( 200 ); - } - else - { + item_max_size.setWidth(200); + item_max_size.setHeight(200); + } else { itemcount = original_desktops.count(); - item_max_size.setWidth( 200 ); - item_max_size.setHeight( 200 ); - } + item_max_size.setWidth(200); + item_max_size.setHeight(200); + } // How much height to reserve for a one-line text label - text_area.setHeight( QFontMetrics( text_font ).height() * 1.2 ); + text_area.setHeight(QFontMetrics(text_font).height() * 1.2); // Separator space between items and text const int separator_height = 6; // Shrink the size until all windows/desktops can fit onscreen - frame_area.setWidth( itemcount * item_max_size.width()); - QRect screenr = effects->clientArea( PlacementArea, effects->activeScreen(), effects->currentDesktop()); - while( frame_area.width() > screenr.width()) - { + frame_area.setWidth(itemcount * item_max_size.width()); + QRect screenr = effects->clientArea(PlacementArea, effects->activeScreen(), effects->currentDesktop()); + while (frame_area.width() > screenr.width()) { item_max_size /= 2; - frame_area.setWidth( itemcount * item_max_size.width()); - } - frame_area.setHeight( item_max_size.height() + - separator_height + text_area.height()); - if( mProxyActivated && !mProxyShowText ) - frame_area.setHeight( item_max_size.height() ); - text_area.setWidth( frame_area.width() ); - - frame_area.moveTo( screenr.x() + ( screenr.width() - frame_area.width()) / 2, - screenr.y() + ( screenr.height() - frame_area.height()) / 2 * mPositioningFactor * 2 ); - text_area.moveTo( frame_area.x(), - frame_area.y() + item_max_size.height() + separator_height); - - thumbnailFrame->setGeometry( frame_area ); + frame_area.setWidth(itemcount * item_max_size.width()); } + frame_area.setHeight(item_max_size.height() + + separator_height + text_area.height()); + if (mProxyActivated && !mProxyShowText) + frame_area.setHeight(item_max_size.height()); + text_area.setWidth(frame_area.width()); + + frame_area.moveTo(screenr.x() + (screenr.width() - frame_area.width()) / 2, + screenr.y() + (screenr.height() - frame_area.height()) / 2 * mPositioningFactor * 2); + text_area.moveTo(frame_area.x(), + frame_area.y() + item_max_size.height() + separator_height); + + thumbnailFrame->setGeometry(frame_area); +} void BoxSwitchEffect::calculateItemSizes() - { - if( mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode ) - { - qDeleteAll( windows ); +{ + if (mMode == TabBoxWindowsMode || mMode == TabBoxWindowsAlternativeMode) { + qDeleteAll(windows); windows.clear(); - if( (mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch) ) - { - int index = original_windows.indexOf( effects->currentTabBoxWindow() ); + if ((mAnimateSwitch && !mProxyActivated) || (mProxyActivated && mProxyAnimateSwitch)) { + int index = original_windows.indexOf(effects->currentTabBoxWindow()); int leftIndex = index; int rightIndex = index + 1; - if( rightIndex == original_windows.count() ) + if (rightIndex == original_windows.count()) rightIndex = 0; EffectWindowList ordered_windows; - int leftWindowCount = original_windows.count()/2; + int leftWindowCount = original_windows.count() / 2; int rightWindowCount = leftWindowCount; - if( original_windows.count()%2 == 1 ) + if (original_windows.count() % 2 == 1) leftWindowCount++; - for( int i=0; i < leftWindowCount; i++ ) - { - int tempIndex = ( leftIndex - i ); - if( tempIndex < 0 ) + for (int i = 0; i < leftWindowCount; i++) { + int tempIndex = (leftIndex - i); + if (tempIndex < 0) tempIndex = original_windows.count() + tempIndex; - ordered_windows.prepend( original_windows[ tempIndex ] ); - } - for( int i=0; i < rightWindowCount; i++ ) - { - int tempIndex = ( rightIndex + i ) % original_windows.count(); - ordered_windows.append( original_windows[ tempIndex ] ); - } + ordered_windows.prepend(original_windows[ tempIndex ]); + } + for (int i = 0; i < rightWindowCount; i++) { + int tempIndex = (rightIndex + i) % original_windows.count(); + ordered_windows.append(original_windows[ tempIndex ]); + } // move items cause of schedule - for( int i=0; i < scheduled_directions.count(); i++ ) - { + for (int i = 0; i < scheduled_directions.count(); i++) { Direction actual = scheduled_directions[ i ]; - if( actual == Left ) - { + if (actual == Left) { EffectWindow* w = ordered_windows.takeLast(); - ordered_windows.prepend( w ); - } - else - { + ordered_windows.prepend(w); + } else { EffectWindow* w = ordered_windows.takeFirst(); - ordered_windows.append( w ); - } + ordered_windows.append(w); } - if( animation && timeLine.value() < 0.5 ) - { - if( direction == Left ) - { + } + if (animation && timeLine.value() < 0.5) { + if (direction == Left) { EffectWindow* w = ordered_windows.takeLast(); edge_window = w; - ordered_windows.prepend( w ); - } - else - { + ordered_windows.prepend(w); + } else { EffectWindow* w = ordered_windows.takeFirst(); edge_window = w; - ordered_windows.append( w ); - } + ordered_windows.append(w); } - else if( animation && timeLine.value() >= 0.5 ) - { - if( animation && direction == Left ) + } else if (animation && timeLine.value() >= 0.5) { + if (animation && direction == Left) edge_window = ordered_windows.last(); - if( animation && direction == Right ) + if (animation && direction == Right) edge_window = ordered_windows.first(); - } + } int offset = 0; - if( animation ) - { - if( direction == Left ) - offset = (float)item_max_size.width()*(1.0-timeLine.value()); + if (animation) { + if (direction == Left) + offset = (float)item_max_size.width() * (1.0 - timeLine.value()); else - offset = -(float)item_max_size.width()*(1.0-timeLine.value()); - } - for( int i = 0; i < ordered_windows.count(); i++ ) - { - if( !ordered_windows.at( i ) ) + offset = -(float)item_max_size.width() * (1.0 - timeLine.value()); + } + for (int i = 0; i < ordered_windows.count(); i++) { + if (!ordered_windows.at(i)) continue; - EffectWindow* w = ordered_windows.at( i ); + EffectWindow* w = ordered_windows.at(i); windows[ w ] = new ItemInfo(); - windows[ w ]->iconFrame = effects->effectFrame( EffectFrameUnstyled, false ); - windows[ w ]->iconFrame->setAlignment( Qt::AlignTop | Qt::AlignLeft ); - windows[ w ]->iconFrame->setIcon( w->icon() ); + windows[ w ]->iconFrame = effects->effectFrame(EffectFrameUnstyled, false); + windows[ w ]->iconFrame->setAlignment(Qt::AlignTop | Qt::AlignLeft); + windows[ w ]->iconFrame->setIcon(w->icon()); float moveIndex = i; - if( animation && timeLine.value() < 0.5 ) - { - if( direction == Left ) + if (animation && timeLine.value() < 0.5) { + if (direction == Left) moveIndex--; else moveIndex++; - } - if( ordered_windows.count()%2 == 0 ) + } + if (ordered_windows.count() % 2 == 0) moveIndex += 0.5; - windows[ w ]->area = QRect( frame_area.x() + moveIndex * item_max_size.width() + offset, - frame_area.y(), - item_max_size.width(), item_max_size.height()); + windows[ w ]->area = QRect(frame_area.x() + moveIndex * item_max_size.width() + offset, + frame_area.y(), + item_max_size.width(), item_max_size.height()); windows[ w ]->clickable = windows[ w ]->area; - } - if( ordered_windows.count()%2 == 0 ) - { + } + if (ordered_windows.count() % 2 == 0) { right_window = ordered_windows.last(); - } - if( !highlight_is_set ) - { + } + if (!highlight_is_set) { highlight_area = windows[ selected_window ]->area; highlight_is_set = true; - } } - else - { - for( int i = 0; i < original_windows.count(); i++ ) - { - if( !original_windows.at( i ) ) + } else { + for (int i = 0; i < original_windows.count(); i++) { + if (!original_windows.at(i)) continue; - EffectWindow* w = original_windows.at( i ); + EffectWindow* w = original_windows.at(i); windows[ w ] = new ItemInfo(); - windows[ w ]->iconFrame = effects->effectFrame( EffectFrameUnstyled, false ); - windows[ w ]->iconFrame->setAlignment( Qt::AlignTop | Qt::AlignLeft ); - windows[ w ]->iconFrame->setIcon( w->icon() ); + windows[ w ]->iconFrame = effects->effectFrame(EffectFrameUnstyled, false); + windows[ w ]->iconFrame->setAlignment(Qt::AlignTop | Qt::AlignLeft); + windows[ w ]->iconFrame->setIcon(w->icon()); - windows[ w ]->area = QRect( frame_area.x() + i * item_max_size.width(), - frame_area.y(), - item_max_size.width(), item_max_size.height()); + windows[ w ]->area = QRect(frame_area.x() + i * item_max_size.width(), + frame_area.y(), + item_max_size.width(), item_max_size.height()); windows[ w ]->clickable = windows[ w ]->area; - } } } - else - { + } else { desktops.clear(); - for( int i = 0; i < original_desktops.count(); i++ ) - { - int it = original_desktops.at( i ); + for (int i = 0; i < original_desktops.count(); i++) { + int it = original_desktops.at(i); desktops[ it ] = new ItemInfo(); - desktops[ it ]->area = QRect( frame_area.x() + i * item_max_size.width(), - frame_area.y(), - item_max_size.width(), item_max_size.height()); + desktops[ it ]->area = QRect(frame_area.x() + i * item_max_size.width(), + frame_area.y(), + item_max_size.width(), item_max_size.height()); desktops[ it ]->clickable = desktops[ it ]->area; - } } } +} -void BoxSwitchEffect::paintWindowThumbnail( EffectWindow* w ) - { - if( !windows.contains( w )) +void BoxSwitchEffect::paintWindowThumbnail(EffectWindow* w) +{ + if (!windows.contains(w)) return; - WindowPaintData data( w ); + WindowPaintData data(w); - setPositionTransformations( data, - windows[ w ]->thumbnail, w, - windows[ w ]->area.adjusted( highlight_margin, highlight_margin, -highlight_margin, -highlight_margin ), - Qt::KeepAspectRatio ); + setPositionTransformations(data, + windows[ w ]->thumbnail, w, + windows[ w ]->area.adjusted(highlight_margin, highlight_margin, -highlight_margin, -highlight_margin), + Qt::KeepAspectRatio); - if( animation && ( w == edge_window ) && ( windows.size() % 2 == 1 ) ) - { + if (animation && (w == edge_window) && (windows.size() % 2 == 1)) { // in case of animation: // the window which has to change the side will be split and painted on both sides of the edge double splitPoint = 0.0; - if( direction == Left ) - { - splitPoint = w->geometry().width()*timeLine.value(); - } - else - { - splitPoint = w->geometry().width() - w->geometry().width()*timeLine.value(); - } - data.quads = data.quads.splitAtX( splitPoint ); + if (direction == Left) { + splitPoint = w->geometry().width() * timeLine.value(); + } else { + splitPoint = w->geometry().width() - w->geometry().width() * timeLine.value(); + } + data.quads = data.quads.splitAtX(splitPoint); WindowQuadList left_quads; WindowQuadList right_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.left() >= splitPoint ) + foreach (const WindowQuad & quad, data.quads) { + if (quad.left() >= splitPoint) left_quads << quad; - if( quad.right() <= splitPoint ) + if (quad.right() <= splitPoint) right_quads << quad; - } + } // the base position of the window is changed after half of the animation - if( timeLine.value() < 0.5 ) - { - if( direction == Left ) + if (timeLine.value() < 0.5) { + if (direction == Left) data.quads = left_quads; else data.quads = right_quads; - } - else - { - if( direction == Left ) + } else { + if (direction == Left) data.quads = right_quads; else data.quads = left_quads; - } + } // paint one part of the thumbnail - effects->paintWindow( w, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - windows[ w ]->thumbnail, data ); + effects->paintWindow(w, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + windows[ w ]->thumbnail, data); QRect secondThumbnail; - + // paint the second part of the thumbnail: // the other window quads are needed and a new rect for transformation has to be calculated - if( direction == Left ) - { - if( timeLine.value() < 0.5 ) - { + if (direction == Left) { + if (timeLine.value() < 0.5) { data.quads = right_quads; - secondThumbnail = QRect( frame_area.x() + frame_area.width() - - (float)item_max_size.width()*timeLine.value(), - frame_area.y(), item_max_size.width(), item_max_size.height()); - } - else - { + secondThumbnail = QRect(frame_area.x() + frame_area.width() - + (float)item_max_size.width() * timeLine.value(), + frame_area.y(), item_max_size.width(), item_max_size.height()); + } else { data.quads = left_quads; - secondThumbnail = QRect( frame_area.x() - (float)item_max_size.width()*timeLine.value(), - frame_area.y(), item_max_size.width(), item_max_size.height()); - if( right_window ) - secondThumbnail = QRect( frame_area.x() - - (float)item_max_size.width()*(timeLine.value()-0.5), - frame_area.y(), item_max_size.width(), item_max_size.height()); - } + secondThumbnail = QRect(frame_area.x() - (float)item_max_size.width() * timeLine.value(), + frame_area.y(), item_max_size.width(), item_max_size.height()); + if (right_window) + secondThumbnail = QRect(frame_area.x() - + (float)item_max_size.width() * (timeLine.value() - 0.5), + frame_area.y(), item_max_size.width(), item_max_size.height()); } - else - { - if( timeLine.value() < 0.5 ) - { + } else { + if (timeLine.value() < 0.5) { data.quads = left_quads; - secondThumbnail = QRect( frame_area.x() - - (float)item_max_size.width()*(1.0 - timeLine.value()), - frame_area.y(), item_max_size.width(), item_max_size.height()); - } - else - { + secondThumbnail = QRect(frame_area.x() - + (float)item_max_size.width() * (1.0 - timeLine.value()), + frame_area.y(), item_max_size.width(), item_max_size.height()); + } else { data.quads = right_quads; - secondThumbnail = QRect( frame_area.x() + frame_area.width() - - (float)item_max_size.width()*(1.0 - timeLine.value()), - frame_area.y(), item_max_size.width(), item_max_size.height()); - } + secondThumbnail = QRect(frame_area.x() + frame_area.width() - + (float)item_max_size.width() * (1.0 - timeLine.value()), + frame_area.y(), item_max_size.width(), item_max_size.height()); } - setPositionTransformations( data, - windows[ w ]->thumbnail, w, - secondThumbnail.adjusted( highlight_margin, highlight_margin, -highlight_margin, -highlight_margin ), - Qt::KeepAspectRatio ); - effects->paintWindow( w, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - windows[ w ]->thumbnail, data ); } - else if( ( windows.size() % 2 == 0 ) && ( w == right_window ) ) - { + setPositionTransformations(data, + windows[ w ]->thumbnail, w, + secondThumbnail.adjusted(highlight_margin, highlight_margin, -highlight_margin, -highlight_margin), + Qt::KeepAspectRatio); + effects->paintWindow(w, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + windows[ w ]->thumbnail, data); + } else if ((windows.size() % 2 == 0) && (w == right_window)) { // in case of even number of thumbnails: // the window on the right is painted one half on left and on half on the right side float animationOffset = 0.0f; - double splitPoint = w->geometry().width()*0.5; - if( animation && timeLine.value() <= 0.5 ) - { + double splitPoint = w->geometry().width() * 0.5; + if (animation && timeLine.value() <= 0.5) { // in case of animation the right window has only to be split during first half of animation - if( direction == Left ) - { - splitPoint += w->geometry().width()*timeLine.value(); - animationOffset = -(float)item_max_size.width()*timeLine.value(); - } - else - { - splitPoint -= w->geometry().width()*timeLine.value(); - animationOffset = (float)item_max_size.width()*timeLine.value(); - } + if (direction == Left) { + splitPoint += w->geometry().width() * timeLine.value(); + animationOffset = -(float)item_max_size.width() * timeLine.value(); + } else { + splitPoint -= w->geometry().width() * timeLine.value(); + animationOffset = (float)item_max_size.width() * timeLine.value(); } - if( animation && timeLine.value() > 0.5 ) - { + } + if (animation && timeLine.value() > 0.5) { // at half of animation a different window has become the right window // we have to adjust the splitting again - if( direction == Left ) - { - splitPoint -= w->geometry().width()*(1.0-timeLine.value()); - animationOffset = (float)item_max_size.width()*(1.0-timeLine.value()); - } - else - { - splitPoint += w->geometry().width()*(1.0-timeLine.value()); - animationOffset = -(float)item_max_size.width()*(1.0-timeLine.value()); - } + if (direction == Left) { + splitPoint -= w->geometry().width() * (1.0 - timeLine.value()); + animationOffset = (float)item_max_size.width() * (1.0 - timeLine.value()); + } else { + splitPoint += w->geometry().width() * (1.0 - timeLine.value()); + animationOffset = -(float)item_max_size.width() * (1.0 - timeLine.value()); } - data.quads = data.quads.splitAtX( splitPoint ); + } + data.quads = data.quads.splitAtX(splitPoint); WindowQuadList rightQuads; WindowQuadList leftQuads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() <= splitPoint ) + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() <= splitPoint) leftQuads << quad; else rightQuads << quad; - } + } // left quads are painted on right side of frame data.quads = leftQuads; - effects->drawWindow( w, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - windows[ w ]->thumbnail, data ); + effects->drawWindow(w, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + windows[ w ]->thumbnail, data); // right quads are painted on left side of frame data.quads = rightQuads; QRect secondThumbnail; - secondThumbnail = QRect( frame_area.x() - - (float)item_max_size.width()*0.5 + animationOffset, - frame_area.y(), item_max_size.width(), item_max_size.height()); - setPositionTransformations( data, - windows[ w ]->thumbnail, w, - secondThumbnail.adjusted( highlight_margin, highlight_margin, -highlight_margin, -highlight_margin ), - Qt::KeepAspectRatio ); - effects->drawWindow( w, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - windows[ w ]->thumbnail, data ); - } - else - { - effects->drawWindow( w, - PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - windows[ w ]->thumbnail, data ); - } + secondThumbnail = QRect(frame_area.x() - + (float)item_max_size.width() * 0.5 + animationOffset, + frame_area.y(), item_max_size.width(), item_max_size.height()); + setPositionTransformations(data, + windows[ w ]->thumbnail, w, + secondThumbnail.adjusted(highlight_margin, highlight_margin, -highlight_margin, -highlight_margin), + Qt::KeepAspectRatio); + effects->drawWindow(w, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + windows[ w ]->thumbnail, data); + } else { + effects->drawWindow(w, + PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + windows[ w ]->thumbnail, data); } +} -void BoxSwitchEffect::paintDesktopThumbnail( int iDesktop ) - { - if( !desktops.contains( iDesktop )) +void BoxSwitchEffect::paintDesktopThumbnail(int iDesktop) +{ + if (!desktops.contains(iDesktop)) return; ScreenPaintData data; QRect region; - QRect r = desktops[ iDesktop ]->area.adjusted( highlight_margin, highlight_margin, - -highlight_margin, -highlight_margin ); - QSize size = QSize( displayWidth(), displayHeight()); + QRect r = desktops[ iDesktop ]->area.adjusted(highlight_margin, highlight_margin, + -highlight_margin, -highlight_margin); + QSize size = QSize(displayWidth(), displayHeight()); - size.scale( r.size(), Qt::KeepAspectRatio ); - data.xScale = size.width() / double( displayWidth()); - data.yScale = size.height() / double( displayHeight()); - int width = int( displayWidth() * data.xScale ); - int height = int( displayHeight() * data.yScale ); - int x = r.x() + ( r.width() - width ) / 2; - int y = r.y() + ( r.height() - height ) / 2; - region = QRect( x, y, width, height ); + size.scale(r.size(), Qt::KeepAspectRatio); + data.xScale = size.width() / double(displayWidth()); + data.yScale = size.height() / double(displayHeight()); + int width = int(displayWidth() * data.xScale); + int height = int(displayHeight() * data.yScale); + int x = r.x() + (r.width() - width) / 2; + int y = r.y() + (r.height() - height) / 2; + region = QRect(x, y, width, height); data.xTranslate = x; data.yTranslate = y; - effects->paintScreen( PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST, - region, data ); - } + effects->paintScreen(PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST, + region, data); +} -void BoxSwitchEffect::paintWindowIcon( EffectWindow* w ) - { - if( !windows.contains( w )) +void BoxSwitchEffect::paintWindowIcon(EffectWindow* w) +{ + if (!windows.contains(w)) return; // Don't render null icons - if( w->icon().isNull() ) - { + if (w->icon().isNull()) { return; - } + } int width = w->icon().width(); int height = w->icon().height(); int x = windows[ w ]->area.x() + windows[ w ]->area.width() - width - highlight_margin; int y = windows[ w ]->area.y() + windows[ w ]->area.height() - height - highlight_margin; - if( ( windows.size() % 2 == 0 ) ) - { - if( w == right_window ) - { + if ((windows.size() % 2 == 0)) { + if (w == right_window) { // in case of right window the icon has to be painted on the left side of the frame - x = frame_area.x() + windows[ w ]->area.width()*0.5 - width - highlight_margin; - if( animation ) - { - if( timeLine.value() <= 0.5 ) - { - if( direction == Left ) - { - x -= windows[ w ]->area.width()*timeLine.value(); - x = qMax( x, frame_area.x() ); - } - else - x += windows[ w ]->area.width()*timeLine.value(); - } - else - { - if( direction == Left ) - x += windows[ w ]->area.width()*(1.0-timeLine.value()); - else - { - x -= windows[ w ]->area.width()*(1.0-timeLine.value()); - x = qMax( x, frame_area.x() ); - } + x = frame_area.x() + windows[ w ]->area.width() * 0.5 - width - highlight_margin; + if (animation) { + if (timeLine.value() <= 0.5) { + if (direction == Left) { + x -= windows[ w ]->area.width() * timeLine.value(); + x = qMax(x, frame_area.x()); + } else + x += windows[ w ]->area.width() * timeLine.value(); + } else { + if (direction == Left) + x += windows[ w ]->area.width() * (1.0 - timeLine.value()); + else { + x -= windows[ w ]->area.width() * (1.0 - timeLine.value()); + x = qMax(x, frame_area.x()); } } } } - else - { + } else { // during animation the icon of the edge window has to change position - if( animation && w == edge_window ) - { - if( timeLine.value() < 0.5 ) - { - if( direction == Left ) - x += windows[ w ]->area.width()*timeLine.value(); + if (animation && w == edge_window) { + if (timeLine.value() < 0.5) { + if (direction == Left) + x += windows[ w ]->area.width() * timeLine.value(); else - x -= windows[ w ]->area.width()*timeLine.value(); - } - else - { - if( direction == Left ) - x -= windows[ w ]->area.width()*(1.0 - timeLine.value()); + x -= windows[ w ]->area.width() * timeLine.value(); + } else { + if (direction == Left) + x -= windows[ w ]->area.width() * (1.0 - timeLine.value()); else - x += windows[ w ]->area.width()*(1.0 - timeLine.value()); - } + x += windows[ w ]->area.width() * (1.0 - timeLine.value()); } } - - windows[ w ]->iconFrame->setPosition( QPoint( x, y )); - windows[ w ]->iconFrame->render( infiniteRegion(), 1.0, 0.75 ); } + windows[ w ]->iconFrame->setPosition(QPoint(x, y)); + windows[ w ]->iconFrame->render(infiniteRegion(), 1.0, 0.75); +} + void* BoxSwitchEffect::proxy() - { +{ return &mProxy; - } +} -void BoxSwitchEffect::activateFromProxy( int mode, bool animate, bool showText, float positioningFactor ) - { - if( !mActivated ) - { +void BoxSwitchEffect::activateFromProxy(int mode, bool animate, bool showText, float positioningFactor) +{ + if (!mActivated) { mProxyActivated = true; mProxyAnimateSwitch = animate; mProxyShowText = showText; mPositioningFactor = positioningFactor; thumbnailFrame->setText(" "); - if( ( mode == TabBoxWindowsMode ) || ( mode == TabBoxWindowsAlternativeMode ) ) - { - if( effects->currentTabBoxWindowList().count() > 0 ) - { + if ((mode == TabBoxWindowsMode) || (mode == TabBoxWindowsAlternativeMode)) { + if (effects->currentTabBoxWindowList().count() > 0) { mMode = mode; effects->refTabBox(); highlight_is_set = false; @@ -1059,31 +904,29 @@ void BoxSwitchEffect::activateFromProxy( int mode, bool animate, bool showText, scheduled_directions.clear(); right_window = 0; setActive(); - } } - else if( mode == TabBoxDesktopListMode || mode == TabBoxDesktopMode ) - { // DesktopMode - if( effects->currentTabBoxDesktopList().count() > 0 ) - { + } else if (mode == TabBoxDesktopListMode || mode == TabBoxDesktopMode) { + // DesktopMode + if (effects->currentTabBoxDesktopList().count() > 0) { mMode = mode; painting_desktop = 0; effects->refTabBox(); setActive(); - } } - if( !mActivated ) - mProxyActivated = false; } + if (!mActivated) + mProxyActivated = false; } +} BoxSwitchEffect::ItemInfo::ItemInfo() - : iconFrame( NULL ) - { - } + : iconFrame(NULL) +{ +} BoxSwitchEffect::ItemInfo::~ItemInfo() - { +{ delete iconFrame; - } +} } // namespace diff --git a/effects/boxswitch/boxswitch.h b/effects/boxswitch/boxswitch.h index df214da1c..303a7bf41 100644 --- a/effects/boxswitch/boxswitch.h +++ b/effects/boxswitch/boxswitch.h @@ -40,103 +40,102 @@ namespace KWin class BoxSwitchEffect : public Effect - { - public: - BoxSwitchEffect(); - ~BoxSwitchEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); +{ +public: + BoxSwitchEffect(); + ~BoxSwitchEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); - virtual void windowInputMouseEvent( Window w, QEvent* e ); - virtual void windowDamaged( EffectWindow* w, const QRect& damage ); - virtual void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - virtual void tabBoxAdded( int mode ); - virtual void tabBoxClosed(); - virtual void tabBoxUpdated(); - virtual void windowClosed( EffectWindow* w ); - virtual void* proxy(); - void activateFromProxy( int mode, bool animate, bool showText, float positioningFactor ); - void paintWindowsBox( const QRegion& region ); - private: - class ItemInfo; - void setActive(); - void setInactive(); - void moveResizeInputWindow( int x, int y, int width, int height ); - void calculateFrameSize(); - void calculateItemSizes(); - void setSelectedWindow( EffectWindow* w ); + virtual void windowInputMouseEvent(Window w, QEvent* e); + virtual void windowDamaged(EffectWindow* w, const QRect& damage); + virtual void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + virtual void tabBoxAdded(int mode); + virtual void tabBoxClosed(); + virtual void tabBoxUpdated(); + virtual void windowClosed(EffectWindow* w); + virtual void* proxy(); + void activateFromProxy(int mode, bool animate, bool showText, float positioningFactor); + void paintWindowsBox(const QRegion& region); +private: + class ItemInfo; + void setActive(); + void setInactive(); + void moveResizeInputWindow(int x, int y, int width, int height); + void calculateFrameSize(); + void calculateItemSizes(); + void setSelectedWindow(EffectWindow* w); - void paintWindowThumbnail( EffectWindow* w ); - void paintDesktopThumbnail( int iDesktop ); - void paintWindowIcon( EffectWindow* w ); + void paintWindowThumbnail(EffectWindow* w); + void paintDesktopThumbnail(int iDesktop); + void paintWindowIcon(EffectWindow* w); - bool mActivated; - Window mInput; - int mMode; + bool mActivated; + Window mInput; + int mMode; - EffectFrame* thumbnailFrame; + EffectFrame* thumbnailFrame; - QRect frame_area; - int highlight_margin; - QSize item_max_size; // maximum item display size (including highlight) - QRect text_area; - QFont text_font; - QColor color_frame; - QColor color_highlight; + QRect frame_area; + int highlight_margin; + QSize item_max_size; // maximum item display size (including highlight) + QRect text_area; + QFont text_font; + QColor color_frame; + QColor color_highlight; - float bg_opacity; - bool elevate_window; + float bg_opacity; + bool elevate_window; - QHash< EffectWindow*, ItemInfo* > windows; - EffectWindowList original_windows; - EffectWindowList referrencedWindows; - EffectWindow* selected_window; - QHash< int, ItemInfo* > desktops; - QList< int > original_desktops; - int selected_desktop; + QHash< EffectWindow*, ItemInfo* > windows; + EffectWindowList original_windows; + EffectWindowList referrencedWindows; + EffectWindow* selected_window; + QHash< int, ItemInfo* > desktops; + QList< int > original_desktops; + int selected_desktop; - int painting_desktop; + int painting_desktop; - bool mAnimateSwitch; - TimeLine activeTimeLine; - TimeLine timeLine; - bool animation; - QRect highlight_area; - bool highlight_is_set; - enum Direction - { - Left, - Right - }; - Direction direction; - QQueue scheduled_directions; - EffectWindow* edge_window; - EffectWindow* right_window; - - bool primaryTabBox; - bool secondaryTabBox; - - BoxSwitchEffectProxy mProxy; - bool mProxyActivated; - bool mProxyAnimateSwitch; - bool mProxyShowText; - float mPositioningFactor; + bool mAnimateSwitch; + TimeLine activeTimeLine; + TimeLine timeLine; + bool animation; + QRect highlight_area; + bool highlight_is_set; + enum Direction { + Left, + Right }; + Direction direction; + QQueue scheduled_directions; + EffectWindow* edge_window; + EffectWindow* right_window; + + bool primaryTabBox; + bool secondaryTabBox; + + BoxSwitchEffectProxy mProxy; + bool mProxyActivated; + bool mProxyAnimateSwitch; + bool mProxyShowText; + float mPositioningFactor; +}; class BoxSwitchEffect::ItemInfo - { - public: - ItemInfo(); - ~ItemInfo(); - QRect area; // maximal painting area, including any frames/highlights/etc. - QRegion clickable; - QRect thumbnail; - EffectFrame* iconFrame; - }; +{ +public: + ItemInfo(); + ~ItemInfo(); + QRect area; // maximal painting area, including any frames/highlights/etc. + QRegion clickable; + QRect thumbnail; + EffectFrame* iconFrame; +}; } // namespace diff --git a/effects/boxswitch/boxswitch_config.cpp b/effects/boxswitch/boxswitch_config.cpp index ae4c0e15a..394ed1ac9 100644 --- a/effects/boxswitch/boxswitch_config.cpp +++ b/effects/boxswitch/boxswitch_config.cpp @@ -32,72 +32,72 @@ KWIN_EFFECT_CONFIG_FACTORY BoxSwitchEffectConfigForm::BoxSwitchEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } BoxSwitchEffectConfig::BoxSwitchEffectConfig(QWidget* parent, const QVariantList& args) - : KCModule( EffectFactory::componentData(), parent, args ) - { - m_ui = new BoxSwitchEffectConfigForm( this ); + : KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new BoxSwitchEffectConfigForm(this); - QVBoxLayout* layout = new QVBoxLayout( this ); + QVBoxLayout* layout = new QVBoxLayout(this); - layout->addWidget( m_ui ); + layout->addWidget(m_ui); - connect( m_ui->opacitySpin, SIGNAL( valueChanged(int) ), this, SLOT( changed() )); - connect( m_ui->elevateBox, SIGNAL( stateChanged(int) ), this, SLOT( changed() )); - connect( m_ui->animateBox, SIGNAL( stateChanged(int) ), this, SLOT( changed() )); + connect(m_ui->opacitySpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->elevateBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->animateBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); load(); - } +} BoxSwitchEffectConfig::~BoxSwitchEffectConfig() - { - } +{ +} void BoxSwitchEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "BoxSwitch" ); - - int opacity = conf.readEntry( "BackgroundOpacity", 25 ); - m_ui->opacitySpin->setValue( opacity ); + KConfigGroup conf = EffectsHandler::effectConfig("BoxSwitch"); - bool elevate = conf.readEntry( "ElevateSelected", true ); - m_ui->elevateBox->setChecked( elevate ); + int opacity = conf.readEntry("BackgroundOpacity", 25); + m_ui->opacitySpin->setValue(opacity); - bool animate = conf.readEntry( "AnimateSwitch", false ); - m_ui->animateBox->setChecked( animate ); + bool elevate = conf.readEntry("ElevateSelected", true); + m_ui->elevateBox->setChecked(elevate); + + bool animate = conf.readEntry("AnimateSwitch", false); + m_ui->animateBox->setChecked(animate); emit changed(false); - } +} void BoxSwitchEffectConfig::save() - { +{ KCModule::save(); - KConfigGroup conf = EffectsHandler::effectConfig( "BoxSwitch" ); + KConfigGroup conf = EffectsHandler::effectConfig("BoxSwitch"); - conf.writeEntry( "BackgroundOpacity", m_ui->opacitySpin->value() ); + conf.writeEntry("BackgroundOpacity", m_ui->opacitySpin->value()); - conf.writeEntry( "ElevateSelected", m_ui->elevateBox->isChecked() ); + conf.writeEntry("ElevateSelected", m_ui->elevateBox->isChecked()); - conf.writeEntry( "AnimateSwitch", m_ui->animateBox->isChecked() ); + conf.writeEntry("AnimateSwitch", m_ui->animateBox->isChecked()); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "boxswitch" ); - } + EffectsHandler::sendReloadMessage("boxswitch"); +} void BoxSwitchEffectConfig::defaults() - { - m_ui->opacitySpin->setValue( 25 ); - m_ui->elevateBox->setChecked( true ); - m_ui->animateBox->setChecked( false ); +{ + m_ui->opacitySpin->setValue(25); + m_ui->elevateBox->setChecked(true); + m_ui->animateBox->setChecked(false); emit changed(true); - } +} } // namespace diff --git a/effects/boxswitch/boxswitch_config.h b/effects/boxswitch/boxswitch_config.h index 2ec72203b..381a52502 100644 --- a/effects/boxswitch/boxswitch_config.h +++ b/effects/boxswitch/boxswitch_config.h @@ -31,25 +31,25 @@ namespace KWin class BoxSwitchEffectConfigForm : public QWidget, public Ui::BoxSwitchEffectConfigForm { Q_OBJECT - public: - explicit BoxSwitchEffectConfigForm(QWidget* parent); +public: + explicit BoxSwitchEffectConfigForm(QWidget* parent); }; class BoxSwitchEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit BoxSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~BoxSwitchEffectConfig(); +public: + explicit BoxSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~BoxSwitchEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - BoxSwitchEffectConfigForm* m_ui; - }; +private: + BoxSwitchEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/boxswitch/boxswitch_proxy.cpp b/effects/boxswitch/boxswitch_proxy.cpp index b9e2d56a5..b62b1c9cb 100644 --- a/effects/boxswitch/boxswitch_proxy.cpp +++ b/effects/boxswitch/boxswitch_proxy.cpp @@ -24,23 +24,23 @@ along with this program. If not, see . namespace KWin { -BoxSwitchEffectProxy::BoxSwitchEffectProxy( BoxSwitchEffect* effect ) - : m_effect( effect ) - { - } +BoxSwitchEffectProxy::BoxSwitchEffectProxy(BoxSwitchEffect* effect) + : m_effect(effect) +{ +} BoxSwitchEffectProxy::~BoxSwitchEffectProxy() - { - } +{ +} -void BoxSwitchEffectProxy::activate( int mode, bool animate, bool showText, float positioningFactor ) - { - m_effect->activateFromProxy( mode, animate, showText, positioningFactor ); - } +void BoxSwitchEffectProxy::activate(int mode, bool animate, bool showText, float positioningFactor) +{ + m_effect->activateFromProxy(mode, animate, showText, positioningFactor); +} -void BoxSwitchEffectProxy::paintWindowsBox( const QRegion& region ) - { - m_effect->paintWindowsBox( region ); - } +void BoxSwitchEffectProxy::paintWindowsBox(const QRegion& region) +{ + m_effect->paintWindowsBox(region); +} } // namespace diff --git a/effects/boxswitch/boxswitch_proxy.h b/effects/boxswitch/boxswitch_proxy.h index f1e908933..eab863c0f 100644 --- a/effects/boxswitch/boxswitch_proxy.h +++ b/effects/boxswitch/boxswitch_proxy.h @@ -30,22 +30,22 @@ class BoxSwitchEffect; class BoxSwitchEffectProxy { - public: - BoxSwitchEffectProxy( BoxSwitchEffect* effect ); - ~BoxSwitchEffectProxy(); +public: + BoxSwitchEffectProxy(BoxSwitchEffect* effect); + ~BoxSwitchEffectProxy(); - /** - * Activates the BoxSwitch Effect. It will get deactivated in tabBoxClosed() - * @param mode The TabBoxMode for which it should be activated. - * @param animate switch will be animated - * @param showText the caption of the window will be shown - * @param positioningFactor where to put the frame: 0.0 == top, 1.0 == bottom - */ - void activate( int mode, bool animate, bool showText, float positioningFactor ); - void paintWindowsBox( const QRegion& region); + /** + * Activates the BoxSwitch Effect. It will get deactivated in tabBoxClosed() + * @param mode The TabBoxMode for which it should be activated. + * @param animate switch will be animated + * @param showText the caption of the window will be shown + * @param positioningFactor where to put the frame: 0.0 == top, 1.0 == bottom + */ + void activate(int mode, bool animate, bool showText, float positioningFactor); + void paintWindowsBox(const QRegion& region); - private: - BoxSwitchEffect* m_effect; +private: + BoxSwitchEffect* m_effect; }; } // namespace diff --git a/effects/configs_builtins.cpp b/effects/configs_builtins.cpp index d80d3ad5a..6861d5c9c 100644 --- a/effects/configs_builtins.cpp +++ b/effects/configs_builtins.cpp @@ -56,33 +56,33 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT_CONFIG_MULTIPLE( builtins, - KWIN_EFFECT_CONFIG_SINGLE( boxswitch, BoxSwitchEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( dashboard, DashboardEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( desktopgrid, DesktopGridEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( diminactive, DimInactiveEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( magiclamp, MagicLampEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( presentwindows, PresentWindowsEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( resize, ResizeEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( showfps, ShowFpsEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( translucency, TranslucencyEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( thumbnailaside, ThumbnailAsideEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( zoom, ZoomEffectConfig ) +KWIN_EFFECT_CONFIG_MULTIPLE(builtins, + KWIN_EFFECT_CONFIG_SINGLE(boxswitch, BoxSwitchEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(dashboard, DashboardEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(desktopgrid, DesktopGridEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(diminactive, DimInactiveEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(magiclamp, MagicLampEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(presentwindows, PresentWindowsEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(resize, ResizeEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(showfps, ShowFpsEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(translucency, TranslucencyEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(thumbnailaside, ThumbnailAsideEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(zoom, ZoomEffectConfig) #ifdef KWIN_HAVE_OPENGL_COMPOSITING - KWIN_EFFECT_CONFIG_SINGLE( blur, BlurEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( coverswitch, CoverSwitchEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( cube, CubeEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( cubeslide, CubeSlideEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( flipswitch, FlipSwitchEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( glide, GlideEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( invert, InvertEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( lookingglass, LookingGlassEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( magnifier, MagnifierEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( mousemark, MouseMarkEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( trackmouse, TrackMouseEffectConfig ) - KWIN_EFFECT_CONFIG_SINGLE( wobblywindows, WobblyWindowsEffectConfig ) + KWIN_EFFECT_CONFIG_SINGLE(blur, BlurEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(coverswitch, CoverSwitchEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(cube, CubeEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(cubeslide, CubeSlideEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(flipswitch, FlipSwitchEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(glide, GlideEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(invert, InvertEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(lookingglass, LookingGlassEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(magnifier, MagnifierEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(mousemark, MouseMarkEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(trackmouse, TrackMouseEffectConfig) + KWIN_EFFECT_CONFIG_SINGLE(wobblywindows, WobblyWindowsEffectConfig) #endif - ) + ) } // namespace diff --git a/effects/coverswitch/coverswitch.cpp b/effects/coverswitch/coverswitch.cpp index 1c31c93ec..94b612f28 100644 --- a/effects/coverswitch/coverswitch.cpp +++ b/effects/coverswitch/coverswitch.cpp @@ -41,111 +41,107 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( coverswitch, CoverSwitchEffect ) -KWIN_EFFECT_SUPPORTED( coverswitch, CoverSwitchEffect::supported() ) +KWIN_EFFECT(coverswitch, CoverSwitchEffect) +KWIN_EFFECT_SUPPORTED(coverswitch, CoverSwitchEffect::supported()) CoverSwitchEffect::CoverSwitchEffect() - : mActivated( 0 ) - , angle( 60.0 ) - , animation( false ) - , start( false ) - , stop( false ) - , stopRequested( false ) - , startRequested( false ) - , zPosition( 900.0 ) - , scaleFactor( 0.0 ) - , direction( Left ) - , selected_window( 0 ) - , captionFrame( effects->effectFrame( EffectFrameStyled ) ) - , primaryTabBox( false ) - , secondaryTabBox( false ) - { - reconfigure( ReconfigureAll ); + : mActivated(0) + , angle(60.0) + , animation(false) + , start(false) + , stop(false) + , stopRequested(false) + , startRequested(false) + , zPosition(900.0) + , scaleFactor(0.0) + , direction(Left) + , selected_window(0) + , captionFrame(effects->effectFrame(EffectFrameStyled)) + , primaryTabBox(false) + , secondaryTabBox(false) +{ + reconfigure(ReconfigureAll); // Caption frame - captionFont.setBold( true ); - captionFont.setPointSize( captionFont.pointSize() * 2 ); - captionFrame->setFont( captionFont ); - captionFrame->enableCrossFade( true ); + captionFont.setBold(true); + captionFont.setPointSize(captionFont.pointSize() * 2); + captionFrame->setFont(captionFont); + captionFrame->enableCrossFade(true); const QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/coverswitch-reflection.glsl"); m_reflectionShader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, fragmentshader); - } +} CoverSwitchEffect::~CoverSwitchEffect() - { +{ delete captionFrame; delete m_reflectionShader; - } +} bool CoverSwitchEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void CoverSwitchEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "CoverSwitch" ); - animationDuration = animationTime( conf, "Duration", 200 ); - animateSwitch = conf.readEntry( "AnimateSwitch", true ); - animateStart = conf.readEntry( "AnimateStart", true ); - animateStop = conf.readEntry( "AnimateStop", true ); - reflection = conf.readEntry( "Reflection", true ); - windowTitle = conf.readEntry( "WindowTitle", true ); - zPosition = conf.readEntry( "ZPosition", 900.0 ); - thumbnails = conf.readEntry( "Thumbnails", true ); - dynamicThumbnails = conf.readEntry( "DynamicThumbnails", true ); - thumbnailWindows = conf.readEntry( "ThumbnailWindows", 8 ); - timeLine.setCurveShape( TimeLine::EaseInOutCurve ); - timeLine.setDuration( animationDuration ); - primaryTabBox = conf.readEntry( "TabBox", false ); - secondaryTabBox = conf.readEntry( "TabBoxAlternative", false ); - QColor tmp = conf.readEntry( "MirrorFrontColor", QColor(0,0,0) ); +void CoverSwitchEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("CoverSwitch"); + animationDuration = animationTime(conf, "Duration", 200); + animateSwitch = conf.readEntry("AnimateSwitch", true); + animateStart = conf.readEntry("AnimateStart", true); + animateStop = conf.readEntry("AnimateStop", true); + reflection = conf.readEntry("Reflection", true); + windowTitle = conf.readEntry("WindowTitle", true); + zPosition = conf.readEntry("ZPosition", 900.0); + thumbnails = conf.readEntry("Thumbnails", true); + dynamicThumbnails = conf.readEntry("DynamicThumbnails", true); + thumbnailWindows = conf.readEntry("ThumbnailWindows", 8); + timeLine.setCurveShape(TimeLine::EaseInOutCurve); + timeLine.setDuration(animationDuration); + primaryTabBox = conf.readEntry("TabBox", false); + secondaryTabBox = conf.readEntry("TabBoxAlternative", false); + QColor tmp = conf.readEntry("MirrorFrontColor", QColor(0, 0, 0)); mirrorColor[0][0] = tmp.redF(); mirrorColor[0][1] = tmp.greenF(); mirrorColor[0][2] = tmp.blueF(); mirrorColor[0][3] = 1.0; - tmp = conf.readEntry( "MirrorRearColor", QColor(0,0,0) ); + tmp = conf.readEntry("MirrorRearColor", QColor(0, 0, 0)); mirrorColor[1][0] = tmp.redF(); mirrorColor[1][1] = tmp.greenF(); mirrorColor[1][2] = tmp.blueF(); mirrorColor[1][3] = -1.0; - - } -void CoverSwitchEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( mActivated || stop || stopRequested ) - { +} + +void CoverSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (mActivated || stop || stopRequested) { data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - if( animation || start || stop ) - { - timeLine.addTime( (double)time ); - } - if( selected_window == NULL ) - abort(); + if (animation || start || stop) { + timeLine.addTime((double)time); } - effects->prePaintScreen(data, time); + if (selected_window == NULL) + abort(); } + effects->prePaintScreen(data, time); +} -void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); +void CoverSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); - if( mActivated || stop || stopRequested ) - { + if (mActivated || stop || stopRequested) { QMatrix4x4 origProjection; QMatrix4x4 origModelview; ShaderManager *shaderManager = ShaderManager::instance(); - if( effects->numScreens() > 1 ) - { + if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode - QRect fullRect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); + QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; - float ymax = zNear * tan( fovy * M_PI / 360.0f ); + float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; @@ -155,36 +151,32 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& float xmaxFactor = 1.0; float yminFactor = 1.0; float ymaxFactor = 1.0; - if( area.x() == 0 && area.width() != fullRect.width() ) - { + if (area.x() == 0 && area.width() != fullRect.width()) { // horizontal layout: left screen - xminFactor = (float)area.width()/(float)fullRect.width(); - xmaxFactor = ((float)fullRect.width()-(float)area.width()*0.5f)/((float)fullRect.width()*0.5f); - xTranslate = (float)fullRect.width()*0.5f-(float)area.width()*0.5f; - } - if( area.x() != 0 && area.width() != fullRect.width() ) - { + xminFactor = (float)area.width() / (float)fullRect.width(); + xmaxFactor = ((float)fullRect.width() - (float)area.width() * 0.5f) / ((float)fullRect.width() * 0.5f); + xTranslate = (float)fullRect.width() * 0.5f - (float)area.width() * 0.5f; + } + if (area.x() != 0 && area.width() != fullRect.width()) { // horizontal layout: right screen - xminFactor = ((float)fullRect.width()-(float)area.width()*0.5f)/((float)fullRect.width()*0.5f); - xmaxFactor = (float)area.width()/(float)fullRect.width(); - xTranslate = (float)fullRect.width()*0.5f-(float)area.width()*0.5f; - } - if( area.y() == 0 && area.height() != fullRect.height() ) - { + xminFactor = ((float)fullRect.width() - (float)area.width() * 0.5f) / ((float)fullRect.width() * 0.5f); + xmaxFactor = (float)area.width() / (float)fullRect.width(); + xTranslate = (float)fullRect.width() * 0.5f - (float)area.width() * 0.5f; + } + if (area.y() == 0 && area.height() != fullRect.height()) { // vertical layout: top screen - yminFactor = ((float)fullRect.height()-(float)area.height()*0.5f)/((float)fullRect.height()*0.5f); - ymaxFactor = (float)area.height()/(float)fullRect.height(); - yTranslate = (float)fullRect.height()*0.5f-(float)area.height()*0.5f; - } - if( area.y() != 0 && area.height() != fullRect.height() ) - { + yminFactor = ((float)fullRect.height() - (float)area.height() * 0.5f) / ((float)fullRect.height() * 0.5f); + ymaxFactor = (float)area.height() / (float)fullRect.height(); + yTranslate = (float)fullRect.height() * 0.5f - (float)area.height() * 0.5f; + } + if (area.y() != 0 && area.height() != fullRect.height()) { // vertical layout: bottom screen - yminFactor = (float)area.height()/(float)fullRect.height(); - ymaxFactor = ((float)fullRect.height()-(float)area.height()*0.5f)/((float)fullRect.height()*0.5f); - yTranslate = (float)fullRect.height()*0.5f-(float)area.height()*0.5f; - } + yminFactor = (float)area.height() / (float)fullRect.height(); + ymaxFactor = ((float)fullRect.height() - (float)area.height() * 0.5f) / ((float)fullRect.height() * 0.5f); + yTranslate = (float)fullRect.height() * 0.5f - (float)area.height() * 0.5f; + } QMatrix4x4 projection; - projection.frustum(xmin*xminFactor, xmax*xmaxFactor, ymin*yminFactor, ymax*ymaxFactor, zNear, zFar); + projection.frustum(xmin * xminFactor, xmax * xmaxFactor, ymin * yminFactor, ymax * ymaxFactor, zNear, zFar); QMatrix4x4 modelview; modelview.translate(xTranslate, yTranslate, 0.0); if (shaderManager->isShaderBound()) { @@ -192,7 +184,7 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& origProjection = shader->getUniformMatrix4x4("projection"); origModelview = shader->getUniformMatrix4x4("modelview"); shader->setUniform("projection", projection); - shader->setUniform("modelview", origModelview*modelview); + shader->setUniform("modelview", origModelview * modelview); shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES @@ -203,94 +195,89 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& pushMatrix(modelview); #endif } - } - + } + QList< EffectWindow* > tempList = currentWindowList; - int index = tempList.indexOf( selected_window ); - if( animation || start || stop ) - { - if( !start && !stop ) - { - if( direction == Right ) + int index = tempList.indexOf(selected_window); + if (animation || start || stop) { + if (!start && !stop) { + if (direction == Right) index++; else index--; - if( index < 0 ) + if (index < 0) index = tempList.count() + index; - if( index >= tempList.count() ) + if (index >= tempList.count()) index = index % tempList.count(); - } - foreach( Direction direction, scheduled_directions ) - { - if( direction == Right ) - index++; - else - index--; - if( index < 0 ) - index = tempList.count() + index; - if( index >= tempList.count() ) - index = index % tempList.count(); - } } - int leftIndex = index -1; - if( leftIndex < 0 ) - leftIndex = tempList.count() -1; - int rightIndex = index +1; - if( rightIndex == tempList.count() ) + foreach (Direction direction, scheduled_directions) { + if (direction == Right) + index++; + else + index--; + if (index < 0) + index = tempList.count() + index; + if (index >= tempList.count()) + index = index % tempList.count(); + } + } + int leftIndex = index - 1; + if (leftIndex < 0) + leftIndex = tempList.count() - 1; + int rightIndex = index + 1; + if (rightIndex == tempList.count()) rightIndex = 0; EffectWindow* frontWindow = tempList[ index ]; leftWindows.clear(); rightWindows.clear(); - bool evenWindows = ( tempList.count() % 2 == 0 ) ? true : false; + bool evenWindows = (tempList.count() % 2 == 0) ? true : false; int leftWindowCount = 0; - if( evenWindows ) - leftWindowCount = tempList.count()/2 - 1; + if (evenWindows) + leftWindowCount = tempList.count() / 2 - 1; else - leftWindowCount = ( tempList.count() - 1 )/2; - for( int i=0; i < leftWindowCount; i++ ) - { - int tempIndex = ( leftIndex - i ); - if( tempIndex < 0 ) + leftWindowCount = (tempList.count() - 1) / 2; + for (int i = 0; i < leftWindowCount; i++) { + int tempIndex = (leftIndex - i); + if (tempIndex < 0) tempIndex = tempList.count() + tempIndex; - leftWindows.prepend( tempList[ tempIndex ] ); - } + leftWindows.prepend(tempList[ tempIndex ]); + } int rightWindowCount = 0; - if( evenWindows ) - rightWindowCount = tempList.count()/2; + if (evenWindows) + rightWindowCount = tempList.count() / 2; else - rightWindowCount = ( tempList.count() - 1 )/2; - for( int i=0; i < rightWindowCount; i++ ) - { - int tempIndex = ( rightIndex + i ) % tempList.count(); - rightWindows.prepend( tempList[ tempIndex ] ); - } + rightWindowCount = (tempList.count() - 1) / 2; + for (int i = 0; i < rightWindowCount; i++) { + int tempIndex = (rightIndex + i) % tempList.count(); + rightWindows.prepend(tempList[ tempIndex ]); + } - if( reflection ) - { + if (reflection) { // restrict painting the reflections to the current screen - QRegion clip = QRegion( area ); - PaintClipper::push( clip ); + QRegion clip = QRegion(area); + PaintClipper::push(clip); // no reflections during start and stop animation // except when using a shader - if( (!start && !stop) || ShaderManager::instance()->isValid() ) - paintScene( frontWindow, leftWindows, rightWindows, true ); - PaintClipper::pop( clip ); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA ); + if ((!start && !stop) || ShaderManager::instance()->isValid()) + paintScene(frontWindow, leftWindows, rightWindows, true); + PaintClipper::pop(clip); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); #ifndef KWIN_HAVE_OPENGLES - glPolygonMode( GL_FRONT, GL_FILL ); + glPolygonMode(GL_FRONT, GL_FILL); #endif - QRect fullRect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); + QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); // we can use a huge scale factor (needed to calculate the rearground vertices) // as we restrict with a PaintClipper painting on the current screen - float reflectionScaleFactor = 100000 * tan( 60.0 * M_PI / 360.0f )/area.width(); + float reflectionScaleFactor = 100000 * tan(60.0 * M_PI / 360.0f) / area.width(); float vertices[] = { - -area.width()*0.5f, area.height(), 0.0, - area.width()*0.5f, area.height(), 0.0, + -area.width() * 0.5f, area.height(), 0.0, + area.width() * 0.5f, area.height(), 0.0, (float)area.width()*reflectionScaleFactor, area.height(), -5000, - -(float)area.width()*reflectionScaleFactor, area.height(), -5000 }; + -(float)area.width()*reflectionScaleFactor, area.height(), -5000 + }; // foreground if (start) { mirrorColor[0][3] = timeLine.value(); @@ -303,25 +290,23 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& int y = 0; // have to adjust the y values to fit OpenGL // in OpenGL y==0 is at bottom, in Qt at top - if( effects->numScreens() > 1 ) - { - QRect fullArea = effects->clientArea( FullArea, 0, 1 ); - if( fullArea.height() != area.height() ) - { - if( area.y() == 0 ) + if (effects->numScreens() > 1) { + QRect fullArea = effects->clientArea(FullArea, 0, 1); + if (fullArea.height() != area.height()) { + if (area.y() == 0) y = fullArea.height() - area.height(); else y = fullArea.height() - area.y() - area.height(); - } } + } // use scissor to restrict painting of the reflection plane to current screen - glScissor( area.x(), y, area.width(), area.height() ); - glEnable( GL_SCISSOR_TEST ); + glScissor(area.x(), y, area.width(), area.height()); + glEnable(GL_SCISSOR_TEST); if (shaderManager->isValid() && m_reflectionShader->isValid()) { shaderManager->pushShader(m_reflectionShader); QMatrix4x4 windowTransformation; - windowTransformation.translate(area.x() + area.width()*0.5f, 0.0, 0.0); + windowTransformation.translate(area.x() + area.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform("windowTransformation", windowTransformation); m_reflectionShader->setUniform("u_frontColor", QVector4D(mirrorColor[0][0], mirrorColor[0][1], mirrorColor[0][2], mirrorColor[0][3])); m_reflectionShader->setUniform("u_backColor", QVector4D(mirrorColor[1][0], mirrorColor[1][1], mirrorColor[1][2], mirrorColor[1][3])); @@ -351,32 +336,30 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& } else { #ifndef KWIN_HAVE_OPENGLES glPushMatrix(); - if( effects->numScreens() > 1 && area.x() != fullRect.x() ) - { + if (effects->numScreens() > 1 && area.x() != fullRect.x()) { // have to change the reflection area in horizontal layout and right screen - glTranslatef( -area.x(), 0.0, 0.0 ); - } - glTranslatef( area.x() + area.width()*0.5f, 0.0, 0.0 ); - glColor4fv( mirrorColor[0] ); - glBegin( GL_POLYGON ); - glVertex3f( vertices[0], vertices[1], vertices[2] ); - glVertex3f( vertices[3], vertices[4], vertices[5] ); + glTranslatef(-area.x(), 0.0, 0.0); + } + glTranslatef(area.x() + area.width() * 0.5f, 0.0, 0.0); + glColor4fv(mirrorColor[0]); + glBegin(GL_POLYGON); + glVertex3f(vertices[0], vertices[1], vertices[2]); + glVertex3f(vertices[3], vertices[4], vertices[5]); // rearground - glColor4fv( mirrorColor[1] ); - glVertex3f( vertices[6], vertices[7], vertices[8] ); - glVertex3f( vertices[9], vertices[10], vertices[11] ); + glColor4fv(mirrorColor[1]); + glVertex3f(vertices[6], vertices[7], vertices[8]); + glVertex3f(vertices[9], vertices[10], vertices[11]); glEnd(); glPopMatrix(); #endif } - glDisable( GL_SCISSOR_TEST ); - glDisable( GL_BLEND ); - } - paintScene( frontWindow, leftWindows, rightWindows ); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); + } + paintScene(frontWindow, leftWindows, rightWindows); - if( effects->numScreens() > 1 ) - { + if (effects->numScreens() > 1) { if (shaderManager->isShaderBound()) { GLShader *shader = shaderManager->pushShader(ShaderManager::GenericShader); shader->setUniform("projection", origProjection); @@ -391,90 +374,76 @@ void CoverSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& glMatrixMode(GL_MODELVIEW); #endif } - } + } // Render the caption frame - if (windowTitle) - { + if (windowTitle) { double opacity = 1.0; - if( start ) + if (start) opacity = timeLine.value(); - else if( stop ) + else if (stop) opacity = 1.0 - timeLine.value(); - if( animation ) - captionFrame->setCrossFadeProgress( timeLine.value() ); - captionFrame->render( region, opacity ); + if (animation) + captionFrame->setCrossFadeProgress(timeLine.value()); + captionFrame->render(region, opacity); } - if( ( thumbnails && (!dynamicThumbnails || - (dynamicThumbnails && currentWindowList.size() >= thumbnailWindows)) ) - && !( start || stop ) ) - { + if ((thumbnails && (!dynamicThumbnails || + (dynamicThumbnails && currentWindowList.size() >= thumbnailWindows))) + && !(start || stop)) { BoxSwitchEffectProxy *proxy = - static_cast( effects->getProxy( "boxswitch" ) ); - if( proxy ) - proxy->paintWindowsBox( region ); - } + static_cast(effects->getProxy("boxswitch")); + if (proxy) + proxy->paintWindowsBox(region); } } +} void CoverSwitchEffect::postPaintScreen() - { - if( ( mActivated && ( animation || start ) ) || stop || stopRequested ) - { - if( timeLine.value() == 1.0 ) - { +{ + if ((mActivated && (animation || start)) || stop || stopRequested) { + if (timeLine.value() == 1.0) { timeLine.setProgress(0.0); - if( stop ) - { + if (stop) { stop = false; - effects->setActiveFullScreenEffect( 0 ); - foreach( EffectWindow* window, referrencedWindows ) - { + effects->setActiveFullScreenEffect(0); + foreach (EffectWindow * window, referrencedWindows) { window->unrefWindow(); - } + } referrencedWindows.clear(); currentWindowList.clear(); - if( startRequested ) - { + if (startRequested) { startRequested = false; mActivated = true; effects->refTabBox(); currentWindowList = effects->currentTabBoxWindowList(); - if( animateStart ) - { + if (animateStart) { start = true; - } } } - else if( !scheduled_directions.isEmpty() ) - { + } else if (!scheduled_directions.isEmpty()) { direction = scheduled_directions.dequeue(); - if( start ) - { + if (start) { animation = true; start = false; - } } - else - { + } else { animation = false; start = false; - if( stopRequested ) - { + if (stopRequested) { stopRequested = false; stop = true; - } } } - effects->addRepaintFull(); } - effects->postPaintScreen(); + effects->addRepaintFull(); } + effects->postPaintScreen(); +} -void CoverSwitchEffect::paintScene( EffectWindow* frontWindow, const EffectWindowList& leftWindows, - const EffectWindowList& rightWindows, bool reflectedWindows ) - { +void CoverSwitchEffect::paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, + const EffectWindowList& rightWindows, bool reflectedWindows) +{ // LAYOUT // one window in the front. Other windows left and right rotated // for odd number of windows: left: (n-1)/2; front: 1; right: (n-1)/2 @@ -502,631 +471,526 @@ void CoverSwitchEffect::paintScene( EffectWindow* frontWindow, const EffectWindo // paint sequence no animation: left, right, front // paint sequence forward animation: right, front, left - if( !animation ) - { - paintWindows( leftWindows, true, reflectedWindows ); - paintWindows( rightWindows, false, reflectedWindows ); - paintFrontWindow( frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows ); - } - else - { - if( direction == Right ) - { - if( timeLine.value() < 0.5 ) - { + if (!animation) { + paintWindows(leftWindows, true, reflectedWindows); + paintWindows(rightWindows, false, reflectedWindows); + paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); + } else { + if (direction == Right) { + if (timeLine.value() < 0.5) { // paint in normal way - paintWindows( leftWindows, true, reflectedWindows ); - paintWindows( rightWindows, false, reflectedWindows ); - paintFrontWindow( frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows ); - } - else - { - paintWindows( rightWindows, false, reflectedWindows ); - paintFrontWindow( frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows ); - paintWindows( leftWindows, true, reflectedWindows, rightWindows.at( 0 ) ); - } + paintWindows(leftWindows, true, reflectedWindows); + paintWindows(rightWindows, false, reflectedWindows); + paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); + } else { + paintWindows(rightWindows, false, reflectedWindows); + paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); + paintWindows(leftWindows, true, reflectedWindows, rightWindows.at(0)); } - else - { - paintWindows( leftWindows, true, reflectedWindows ); - if( timeLine.value() < 0.5 ) - { - paintWindows( rightWindows, false, reflectedWindows ); - paintFrontWindow( frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows ); - } - else - { + } else { + paintWindows(leftWindows, true, reflectedWindows); + if (timeLine.value() < 0.5) { + paintWindows(rightWindows, false, reflectedWindows); + paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); + } else { EffectWindow* leftWindow; - if( leftWindowCount > 0) - { - leftWindow = leftWindows.at( 0 ); - paintFrontWindow( frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows ); - } - else + if (leftWindowCount > 0) { + leftWindow = leftWindows.at(0); + paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); + } else leftWindow = frontWindow; - paintWindows( rightWindows, false, reflectedWindows, leftWindow ); - } + paintWindows(rightWindows, false, reflectedWindows, leftWindow); } } } +} -void CoverSwitchEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( mActivated || stop || stopRequested ) - { - if( !( mask & PAINT_WINDOW_TRANSFORMED ) && !w->isDesktop() ) - { - if( ( start || stop ) && w->isDock() ) - { +void CoverSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (mActivated || stop || stopRequested) { + if (!(mask & PAINT_WINDOW_TRANSFORMED) && !w->isDesktop()) { + if ((start || stop) && w->isDock()) { data.opacity = 1.0 - timeLine.value(); - if( stop ) + if (stop) data.opacity = timeLine.value(); - } - else + } else return; - } } - if ( ( start || stop ) && (!w->isOnCurrentDesktop() || w->isMinimized() ) ) - { - if (stop) // Fade out windows not on the current desktop + } + if ((start || stop) && (!w->isOnCurrentDesktop() || w->isMinimized())) { + if (stop) // Fade out windows not on the current desktop data.opacity = (1.0 - timeLine.value()); else // Fade in Windows from other desktops when animation is started data.opacity = timeLine.value(); - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void CoverSwitchEffect::tabBoxAdded( int mode ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void CoverSwitchEffect::tabBoxAdded(int mode) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - if( !mActivated ) - { + if (!mActivated) { // only for windows mode - if( (( mode == TabBoxWindowsMode && primaryTabBox ) || - ( mode == TabBoxWindowsAlternativeMode && secondaryTabBox )) - && effects->currentTabBoxWindowList().count() > 0 ) - { - input = effects->createFullScreenInputWindow( this, Qt::ArrowCursor ); + if (((mode == TabBoxWindowsMode && primaryTabBox) || + (mode == TabBoxWindowsAlternativeMode && secondaryTabBox)) + && effects->currentTabBoxWindowList().count() > 0) { + input = effects->createFullScreenInputWindow(this, Qt::ArrowCursor); activeScreen = effects->activeScreen(); BoxSwitchEffectProxy *proxy = - static_cast( effects->getProxy( "boxswitch" ) ); - if( proxy ) - proxy->activate( mode, true, false, 0.05f ); - if( !stop && !stopRequested ) - { + static_cast(effects->getProxy("boxswitch")); + if (proxy) + proxy->activate(mode, true, false, 0.05f); + if (!stop && !stopRequested) { effects->refTabBox(); - effects->setActiveFullScreenEffect( this ); + effects->setActiveFullScreenEffect(this); scheduled_directions.clear(); selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); direction = Left; mActivated = true; - if( animateStart ) - { + if (animateStart) { start = true; - } + } // Calculation of correct area - area = effects->clientArea( FullScreenArea, activeScreen, effects->currentDesktop()); - scaleFactor = (zPosition+1100) * 2.0 * tan( 60.0 * M_PI / 360.0f )/displayWidth(); - if( displayWidth()-area.width() != 0 ) - { + area = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); + scaleFactor = (zPosition + 1100) * 2.0 * tan(60.0 * M_PI / 360.0f) / displayWidth(); + if (displayWidth() - area.width() != 0) { // one of the screens is smaller than the other (horizontal) - if( area.width() < displayWidth() - area.width() ) - scaleFactor *= (float)area.width()/(float)(displayWidth()-area.width()); - else if( area.width() != displayWidth() - area.width() ) - { + if (area.width() < displayWidth() - area.width()) + scaleFactor *= (float)area.width() / (float)(displayWidth() - area.width()); + else if (area.width() != displayWidth() - area.width()) { // vertical layout with different width // but we don't want to catch screens with same width and different height - if( displayHeight() != area.height() ) - scaleFactor *= (float)area.width()/(float)(displayWidth()); - } + if (displayHeight() != area.height()) + scaleFactor *= (float)area.width() / (float)(displayWidth()); } + } // Setup caption frame geometry - if (windowTitle) - { - QRect frameRect = QRect( area.width() * 0.25f + area.x(), - area.height() * 0.9f + area.y(), - area.width() * 0.5f, - QFontMetrics( captionFont ).height() ); - captionFrame->setGeometry( frameRect ); - captionFrame->setIconSize( QSize( frameRect.height(), frameRect.height() )); + if (windowTitle) { + QRect frameRect = QRect(area.width() * 0.25f + area.x(), + area.height() * 0.9f + area.y(), + area.width() * 0.5f, + QFontMetrics(captionFont).height()); + captionFrame->setGeometry(frameRect); + captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); // And initial contents - captionFrame->setText( selected_window->caption() ); - captionFrame->setIcon( selected_window->icon() ); + captionFrame->setText(selected_window->caption()); + captionFrame->setIcon(selected_window->icon()); } effects->addRepaintFull(); - } - else - { + } else { startRequested = true; - } } } } +} void CoverSwitchEffect::tabBoxClosed() - { - if( mActivated ) - { - if( animateStop ) - { - if( !animation && !start ) - { +{ + if (mActivated) { + if (animateStop) { + if (!animation && !start) { stop = true; - } - else if( start && scheduled_directions.isEmpty() ) - { + } else if (start && scheduled_directions.isEmpty()) { start = false; stop = true; - timeLine.setProgress( 1.0 - timeLine.value() ); - } - else - { + timeLine.setProgress(1.0 - timeLine.value()); + } else { stopRequested = true; - } } - else - effects->setActiveFullScreenEffect( 0 ); + } else + effects->setActiveFullScreenEffect(0); mActivated = false; effects->unrefTabBox(); - effects->destroyInputWindow( input ); + effects->destroyInputWindow(input); effects->addRepaintFull(); - } } +} void CoverSwitchEffect::tabBoxUpdated() - { - if( mActivated ) - { - if( animateSwitch && currentWindowList.count() > 1) - { +{ + if (mActivated) { + if (animateSwitch && currentWindowList.count() > 1) { // determine the switch direction - if( selected_window != effects->currentTabBoxWindow() ) - { - if( selected_window != NULL ) - { - int old_index = currentWindowList.indexOf( selected_window ); - int new_index = effects->currentTabBoxWindowList().indexOf( effects->currentTabBoxWindow() ); + if (selected_window != effects->currentTabBoxWindow()) { + if (selected_window != NULL) { + int old_index = currentWindowList.indexOf(selected_window); + int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); Direction new_direction; int distance = new_index - old_index; - if( distance > 0 ) + if (distance > 0) new_direction = Left; - if( distance < 0 ) + if (distance < 0) new_direction = Right; - if( effects->currentTabBoxWindowList().count() == 2 ) - { + if (effects->currentTabBoxWindowList().count() == 2) { new_direction = Left; distance = 1; - } - if( distance != 0 ) - { - distance = abs( distance ); + } + if (distance != 0) { + distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; - if( tempDistance < abs( distance ) ) - { + if (tempDistance < abs(distance)) { distance = tempDistance; - if( new_direction == Left ) + if (new_direction == Left) new_direction = Right; else new_direction = Left; - } - if( !animation && !start ) - { + } + if (!animation && !start) { animation = true; direction = new_direction; distance--; - } - for( int i=0; icurrentTabBoxWindowList().count() ) + scheduled_directions.enqueue(new_direction); + if (scheduled_directions.count() == effects->currentTabBoxWindowList().count()) scheduled_directions.clear(); - } } } + } selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); - captionFrame->setText( selected_window->caption() ); - captionFrame->setIcon( selected_window->icon() ); - } + captionFrame->setText(selected_window->caption()); + captionFrame->setIcon(selected_window->icon()); } - effects->addRepaintFull(); } + effects->addRepaintFull(); } +} -void CoverSwitchEffect::paintWindowCover( EffectWindow* w, bool reflectedWindow, WindowPaintData& data ) - { +void CoverSwitchEffect::paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data) +{ QRect windowRect = w->geometry(); data.yTranslate = area.height() - windowRect.y() - windowRect.height(); data.zTranslate = -zPosition; - if( start ) - { - if( w->isMinimized() ) - { + if (start) { + if (w->isMinimized()) { data.opacity *= timeLine.value(); - } - else - { + } else { data.xTranslate *= timeLine.value(); data.yTranslate *= timeLine.value(); - if( effects->numScreens() > 1) - { - QRect clientRect = effects->clientArea( FullScreenArea, w->screen(), effects->currentDesktop() ); - QRect fullRect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - if( w->screen() == activeScreen ) - { - if( clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x() ) - { - data.xTranslate -= clientRect.x()*(1.0f-timeLine.value()); - } - if( clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y() ) - { - data.yTranslate -= clientRect.y()*(1.0f-timeLine.value()); - } + if (effects->numScreens() > 1) { + QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); + QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + if (w->screen() == activeScreen) { + if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { + data.xTranslate -= clientRect.x() * (1.0f - timeLine.value()); } - else - { - if( clientRect.width() != fullRect.width() && clientRect.x() < area.x()) - { - data.xTranslate -= clientRect.width()*(1.0f-timeLine.value()); - } - if( clientRect.height() != fullRect.height() && clientRect.y() < area.y() ) - { - data.yTranslate -= clientRect.height()*(1.0f-timeLine.value()); - } + if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { + data.yTranslate -= clientRect.y() * (1.0f - timeLine.value()); + } + } else { + if (clientRect.width() != fullRect.width() && clientRect.x() < area.x()) { + data.xTranslate -= clientRect.width() * (1.0f - timeLine.value()); + } + if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { + data.yTranslate -= clientRect.height() * (1.0f - timeLine.value()); } } + } data.zTranslate *= timeLine.value(); - if( data.rotation ) + if (data.rotation) data.rotation->angle *= timeLine.value(); - } } - if( stop ) - { - if( w->isMinimized() && w != effects->activeWindow() ) - { + } + if (stop) { + if (w->isMinimized() && w != effects->activeWindow()) { data.opacity *= (1.0 - timeLine.value()); - } - else - { + } else { data.xTranslate *= (1.0 - timeLine.value()); data.yTranslate *= (1.0 - timeLine.value()); - if( effects->numScreens() > 1) - { - QRect clientRect = effects->clientArea( FullScreenArea, w->screen(), effects->currentDesktop() ); - QRect rect = effects->clientArea( FullScreenArea, activeScreen, effects->currentDesktop() ); - QRect fullRect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - if( w->screen() == activeScreen ) - { - if( clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x() ) - { - data.xTranslate -= clientRect.x()*timeLine.value(); - } - if( clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y() ) - { - data.yTranslate -= clientRect.y()*timeLine.value(); - } + if (effects->numScreens() > 1) { + QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); + QRect rect = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); + QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + if (w->screen() == activeScreen) { + if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { + data.xTranslate -= clientRect.x() * timeLine.value(); } - else - { - if( clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) - { - data.xTranslate -= clientRect.width()*timeLine.value(); - } - if( clientRect.height() != fullRect.height() && clientRect.y() < area.y() ) - { - data.yTranslate -= clientRect.height()*timeLine.value(); - } + if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { + data.yTranslate -= clientRect.y() * timeLine.value(); + } + } else { + if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { + data.xTranslate -= clientRect.width() * timeLine.value(); + } + if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { + data.yTranslate -= clientRect.height() * timeLine.value(); } } - data.zTranslate *= (1.0 - timeLine.value()); - if( data.rotation ) - data.rotation->angle *= (1.0 - timeLine.value()); } + data.zTranslate *= (1.0 - timeLine.value()); + if (data.rotation) + data.rotation->angle *= (1.0 - timeLine.value()); } + } QRect thumbnail = infiniteRegion(); - if( reflectedWindow ) - { + if (reflectedWindow) { if (ShaderManager::instance()->isValid()) { GLShader *shader = ShaderManager::instance()->pushShader(ShaderManager::GenericShader); QMatrix4x4 origMatrix = shader->getUniformMatrix4x4("screenTransformation"); QMatrix4x4 reflectionMatrix; reflectionMatrix.scale(1.0, -1.0, 1.0); - shader->setUniform("screenTransformation", origMatrix*reflectionMatrix); + shader->setUniform("screenTransformation", origMatrix * reflectionMatrix); data.yTranslate = - area.height() - windowRect.y() - windowRect.height(); if (start) { data.opacity *= timeLine.value(); } else if (stop) { data.opacity *= 1.0 - timeLine.value(); } - effects->paintWindow( w, - PAINT_WINDOW_TRANSFORMED, - infiniteRegion(), data ); + effects->paintWindow(w, + PAINT_WINDOW_TRANSFORMED, + infiniteRegion(), data); shader->setUniform("screenTransformation", origMatrix); ShaderManager::instance()->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES glPushMatrix(); - glScalef( 1.0, -1.0, 1.0 ); + glScalef(1.0, -1.0, 1.0); data.yTranslate = - area.height() - windowRect.y() - windowRect.height(); - effects->paintWindow( w, - PAINT_WINDOW_TRANSFORMED, - infiniteRegion(), data ); + effects->paintWindow(w, + PAINT_WINDOW_TRANSFORMED, + infiniteRegion(), data); glPopMatrix(); #endif } - } - else - { - effects->paintWindow( w, - PAINT_WINDOW_TRANSFORMED, - infiniteRegion(), data ); - } + } else { + effects->paintWindow(w, + PAINT_WINDOW_TRANSFORMED, + infiniteRegion(), data); } +} -void CoverSwitchEffect::paintFrontWindow( EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow ) - { - if( frontWindow == NULL ) +void CoverSwitchEffect::paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow) +{ + if (frontWindow == NULL) return; float distance = 0.0; bool specialHandlingForward = false; - WindowPaintData data( frontWindow ); - data.xTranslate = area.width()*0.5 - frontWindow->geometry().x() - frontWindow->geometry().width()*0.5; - if( leftWindows == 0 ) - { + WindowPaintData data(frontWindow); + data.xTranslate = area.width() * 0.5 - frontWindow->geometry().x() - frontWindow->geometry().width() * 0.5; + if (leftWindows == 0) { leftWindows = 1; - if( !start && !stop ) + if (!start && !stop) specialHandlingForward = true; - } - if( rightWindows == 0 ) - { + } + if (rightWindows == 0) { rightWindows = 1; - } - if( animation ) - { - if( direction == Right ) - { + } + if (animation) { + if (direction == Right) { // move to right - distance = -frontWindow->geometry().width()*0.5f + area.width()*0.5f + - (((float)displayWidth()*0.5*scaleFactor)-(float)area.width()*0.5f)/rightWindows; + distance = -frontWindow->geometry().width() * 0.5f + area.width() * 0.5f + + (((float)displayWidth() * 0.5 * scaleFactor) - (float)area.width() * 0.5f) / rightWindows; data.xTranslate += distance * timeLine.value(); RotationData rot; rot.axis = RotationData::YAxis; - rot.angle = -angle*timeLine.value(); + rot.angle = -angle * timeLine.value(); rot.xRotationPoint = frontWindow->geometry().width(); data.rotation = &rot; - } - else - { + } else { // move to left - distance = frontWindow->geometry().width()*0.5f - area.width()*0.5f + - ((float)width*0.5f-((float)displayWidth()*0.5*scaleFactor))/leftWindows; + distance = frontWindow->geometry().width() * 0.5f - area.width() * 0.5f + + ((float)width * 0.5f - ((float)displayWidth() * 0.5 * scaleFactor)) / leftWindows; float factor = 1.0; - if( specialHandlingForward ) + if (specialHandlingForward) factor = 2.0; data.xTranslate += distance * timeLine.value() * factor; RotationData rot; rot.axis = RotationData::YAxis; - rot.angle = angle*timeLine.value(); + rot.angle = angle * timeLine.value(); data.rotation = &rot; - } } - if( specialHandlingForward ) - { - data.opacity *= (1.0 - timeLine.value() * 2.0); - paintWindowCover( frontWindow, reflectedWindow, data ); - } - else - paintWindowCover( frontWindow, reflectedWindow, data ); } + if (specialHandlingForward) { + data.opacity *= (1.0 - timeLine.value() * 2.0); + paintWindowCover(frontWindow, reflectedWindow, data); + } else + paintWindowCover(frontWindow, reflectedWindow, data); +} -void CoverSwitchEffect::paintWindows( const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow ) - { +void CoverSwitchEffect::paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow) +{ int width = area.width(); int windowCount = windows.count(); EffectWindow* window; - - int rotateFactor = 1; - if( !left ) - { - rotateFactor = -1; - } - float xTranslate = -((float)(width)*0.5f-((float)displayWidth()*0.5*scaleFactor)); - if( !left ) - xTranslate = ((float)displayWidth()*0.5*scaleFactor)-(float)width*0.5f; + int rotateFactor = 1; + if (!left) { + rotateFactor = -1; + } + + float xTranslate = -((float)(width) * 0.5f - ((float)displayWidth() * 0.5 * scaleFactor)); + if (!left) + xTranslate = ((float)displayWidth() * 0.5 * scaleFactor) - (float)width * 0.5f; // handling for additional window from other side // has to appear on this side after half of the time - if( animation && timeLine.value() >= 0.5 && additionalWindow != NULL ) - { + if (animation && timeLine.value() >= 0.5 && additionalWindow != NULL) { RotationData rot; rot.axis = RotationData::YAxis; rot.angle = angle; - rot.angle = angle*rotateFactor; - WindowPaintData data( additionalWindow ); - if( left ) + rot.angle = angle * rotateFactor; + WindowPaintData data(additionalWindow); + if (left) data.xTranslate += -xTranslate - additionalWindow->geometry().x(); - else - { - data.xTranslate += xTranslate + area.width() - - additionalWindow->geometry().x() - additionalWindow->geometry().width(); + else { + data.xTranslate += xTranslate + area.width() - + additionalWindow->geometry().x() - additionalWindow->geometry().width(); rot.xRotationPoint = additionalWindow->geometry().width(); - } - data.rotation = &rot; - data.opacity *= ( timeLine.value() - 0.5 ) * 2.0; - paintWindowCover( additionalWindow, reflectedWindows, data ); } + data.rotation = &rot; + data.opacity *= (timeLine.value() - 0.5) * 2.0; + paintWindowCover(additionalWindow, reflectedWindows, data); + } RotationData rot; rot.axis = RotationData::YAxis; // normal behaviour - for( int i=0; i < windows.count(); i++) - { - window = windows.at( i ); - if( window == NULL || window->isDeleted() ) - { + for (int i = 0; i < windows.count(); i++) { + window = windows.at(i); + if (window == NULL || window->isDeleted()) { continue; - } - WindowPaintData data( window ); + } + WindowPaintData data(window); rot.angle = angle; - if( left ) - data.xTranslate += -xTranslate + xTranslate*i/windowCount - window->geometry().x(); + if (left) + data.xTranslate += -xTranslate + xTranslate * i / windowCount - window->geometry().x(); else - data.xTranslate += xTranslate + width - xTranslate*i/windowCount - window->geometry().x() - window->geometry().width(); - if( animation ) - { - if( direction == Right ) - { - if( ( i == windowCount - 1 ) && left ) - { + data.xTranslate += xTranslate + width - xTranslate * i / windowCount - window->geometry().x() - window->geometry().width(); + if (animation) { + if (direction == Right) { + if ((i == windowCount - 1) && left) { // right most window on left side -> move to front // have to move one window distance plus half the difference between the window and the desktop size - data.xTranslate += (xTranslate/windowCount + (width - window->geometry().width())*0.5f)*timeLine.value(); - rot.angle = ( angle - angle * timeLine.value() ); - } - // right most window does not have to be moved - else if( !left && ( i == 0 ) ); // do nothing - else - { - // all other windows - move to next position - data.xTranslate += xTranslate/windowCount * timeLine.value(); - } + data.xTranslate += (xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.value(); + rot.angle = (angle - angle * timeLine.value()); } - else - { - if( ( i == windowCount - 1 ) && !left ) - { - // left most window on right side -> move to front - data.xTranslate -= (xTranslate/windowCount + (width - window->geometry().width())*0.5f)*timeLine.value(); - rot.angle = ( angle - angle * timeLine.value() ); - } - // left most window does not have to be moved - else if( i==0 && left); // do nothing - else - { + // right most window does not have to be moved + else if (!left && (i == 0)); // do nothing + else { // all other windows - move to next position - data.xTranslate -= xTranslate/windowCount * timeLine.value(); - } + data.xTranslate += xTranslate / windowCount * timeLine.value(); + } + } else { + if ((i == windowCount - 1) && !left) { + // left most window on right side -> move to front + data.xTranslate -= (xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.value(); + rot.angle = (angle - angle * timeLine.value()); + } + // left most window does not have to be moved + else if (i == 0 && left); // do nothing + else { + // all other windows - move to next position + data.xTranslate -= xTranslate / windowCount * timeLine.value(); } } - if( left ) + } + if (left) rot.xRotationPoint = 0.0; else rot.xRotationPoint = window->geometry().width(); rot.angle *= rotateFactor; data.rotation = &rot; // make window most to edge transparent if animation - if( animation && i == 0 && ( ( direction == Left && left ) || ( direction == Right && !left ) ) ) - { + if (animation && i == 0 && ((direction == Left && left) || (direction == Right && !left))) { // only for the first half of the animation - if( timeLine.value() < 0.5 ) - { + if (timeLine.value() < 0.5) { data.opacity *= (1.0 - timeLine.value() * 2.0); - paintWindowCover( window, reflectedWindows, data ); - } - } - else - { - paintWindowCover( window, reflectedWindows, data ); + paintWindowCover(window, reflectedWindows, data); } + } else { + paintWindowCover(window, reflectedWindows, data); } } +} -void CoverSwitchEffect::windowInputMouseEvent( Window w, QEvent* e ) - { - assert( w == input ); - Q_UNUSED( w ); - if( e->type() != QEvent::MouseButtonPress ) +void CoverSwitchEffect::windowInputMouseEvent(Window w, QEvent* e) +{ + assert(w == input); + Q_UNUSED(w); + if (e->type() != QEvent::MouseButtonPress) return; // we don't want click events during animations - if( animation ) + if (animation) return; - QPoint pos = static_cast< QMouseEvent* >( e )->pos(); + QPoint pos = static_cast< QMouseEvent* >(e)->pos(); // determine if a window has been clicked // not interested in events above a fullscreen window (ignoring panel size) - if( pos.y() < (area.height()*scaleFactor - area.height())*0.5f*(1.0f/scaleFactor) ) + if (pos.y() < (area.height()*scaleFactor - area.height()) * 0.5f *(1.0f / scaleFactor)) return; // if there is no selected window (that is no window at all) we cannot click it - if( !selected_window ) + if (!selected_window) return; - if( pos.x() < (area.width()*scaleFactor - selected_window->width())*0.5f*(1.0f/scaleFactor) ) - { - float availableSize = (area.width()*scaleFactor - area.width())*0.5f*(1.0f/scaleFactor); - for( int i=0;iwidth()) * 0.5f *(1.0f / scaleFactor)) { + float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); + for (int i = 0; i < leftWindows.count(); i++) { + int windowPos = availableSize / leftWindows.count() * i; + if (pos.x() < windowPos) continue; - if( i+1 < leftWindows.count() ) - { - if( pos.x() > availableSize/leftWindows.count()*(i+1) ) + if (i + 1 < leftWindows.count()) { + if (pos.x() > availableSize / leftWindows.count()*(i + 1)) continue; - } - - effects->setTabBoxWindow( leftWindows[i] ); - return; } - } - if( pos.x() > area.width() - (area.width()*scaleFactor - selected_window->width())*0.5f*(1.0f/scaleFactor) ) - { - float availableSize = (area.width()*scaleFactor - area.width())*0.5f*(1.0f/scaleFactor); - for( int i=0;i windowPos ) - continue; - if( i+1 < rightWindows.count() ) - { - if( pos.x() < area.width() - availableSize/rightWindows.count()*(i+1) ) - continue; - } - - effects->setTabBoxWindow( rightWindows[i] ); + effects->setTabBoxWindow(leftWindows[i]); return; - } } } + if (pos.x() > area.width() - (area.width()*scaleFactor - selected_window->width()) * 0.5f *(1.0f / scaleFactor)) { + float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); + for (int i = 0; i < rightWindows.count(); i++) { + int windowPos = area.width() - availableSize / rightWindows.count() * i; + if (pos.x() > windowPos) + continue; + if (i + 1 < rightWindows.count()) { + if (pos.x() < area.width() - availableSize / rightWindows.count()*(i + 1)) + continue; + } + + effects->setTabBoxWindow(rightWindows[i]); + return; + } + } +} + void CoverSwitchEffect::abort() - { +{ // it's possible that abort is called after tabbox has been closed // in this case the cleanup is already done (see bug 207554) - if( mActivated ) - { + if (mActivated) { effects->unrefTabBox(); - effects->destroyInputWindow( input ); - } - effects->setActiveFullScreenEffect( 0 ); + effects->destroyInputWindow(input); + } + effects->setActiveFullScreenEffect(0); mActivated = false; stop = false; stopRequested = false; effects->addRepaintFull(); captionFrame->free(); - } +} -void CoverSwitchEffect::windowClosed( EffectWindow* c ) - { +void CoverSwitchEffect::windowClosed(EffectWindow* c) +{ // if the list is not empty, the effect is active - if( !currentWindowList.isEmpty() ) - { + if (!currentWindowList.isEmpty()) { c->refWindow(); - referrencedWindows.append( c ); - currentWindowList.removeAll( c ); - leftWindows.removeAll( c ); - rightWindows.removeAll( c ); - } + referrencedWindows.append(c); + currentWindowList.removeAll(c); + leftWindows.removeAll(c); + rightWindows.removeAll(c); } +} } // namespace diff --git a/effects/coverswitch/coverswitch.h b/effects/coverswitch/coverswitch.h index e6311af07..f820d3201 100644 --- a/effects/coverswitch/coverswitch.h +++ b/effects/coverswitch/coverswitch.h @@ -35,76 +35,75 @@ namespace KWin class CoverSwitchEffect : public Effect - { - public: - CoverSwitchEffect(); - ~CoverSwitchEffect(); +{ +public: + CoverSwitchEffect(); + ~CoverSwitchEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void tabBoxAdded( int mode ); - virtual void tabBoxClosed(); - virtual void tabBoxUpdated(); - virtual void windowInputMouseEvent( Window w, QEvent* e ); - virtual void windowClosed( EffectWindow* c ); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void tabBoxAdded(int mode); + virtual void tabBoxClosed(); + virtual void tabBoxUpdated(); + virtual void windowInputMouseEvent(Window w, QEvent* e); + virtual void windowClosed(EffectWindow* c); - static bool supported(); - private: - void paintScene( EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, - bool reflectedWindows = false ); - void paintWindowCover( EffectWindow* w, bool reflectedWindow, WindowPaintData& data ); - void paintFrontWindow( EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow ); - void paintWindows( const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow = NULL ); - void abort(); + static bool supported(); +private: + void paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, + bool reflectedWindows = false); + void paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data); + void paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow); + void paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow = NULL); + void abort(); - bool mActivated; - float angle; - bool animateSwitch; - bool animateStart; - bool animateStop; - bool animation; - bool start; - bool stop; - bool reflection; - float mirrorColor[2][4]; - bool windowTitle; - int animationDuration; - bool stopRequested; - bool startRequested; - TimeLine timeLine; - QRect area; - Window input; - float zPosition; - float scaleFactor; - enum Direction - { - Left, - Right - }; - Direction direction; - QQueue scheduled_directions; - EffectWindow* selected_window; - int activeScreen; - QList< EffectWindow* > leftWindows; - QList< EffectWindow* > rightWindows; - EffectWindowList currentWindowList; - EffectWindowList referrencedWindows; - - EffectFrame* captionFrame; - QFont captionFont; - - bool thumbnails; - bool dynamicThumbnails; - int thumbnailWindows; - - bool primaryTabBox; - bool secondaryTabBox; - - GLShader *m_reflectionShader; + bool mActivated; + float angle; + bool animateSwitch; + bool animateStart; + bool animateStop; + bool animation; + bool start; + bool stop; + bool reflection; + float mirrorColor[2][4]; + bool windowTitle; + int animationDuration; + bool stopRequested; + bool startRequested; + TimeLine timeLine; + QRect area; + Window input; + float zPosition; + float scaleFactor; + enum Direction { + Left, + Right }; + Direction direction; + QQueue scheduled_directions; + EffectWindow* selected_window; + int activeScreen; + QList< EffectWindow* > leftWindows; + QList< EffectWindow* > rightWindows; + EffectWindowList currentWindowList; + EffectWindowList referrencedWindows; + + EffectFrame* captionFrame; + QFont captionFont; + + bool thumbnails; + bool dynamicThumbnails; + int thumbnailWindows; + + bool primaryTabBox; + bool secondaryTabBox; + + GLShader *m_reflectionShader; +}; } // namespace diff --git a/effects/coverswitch/coverswitch_config.cpp b/effects/coverswitch/coverswitch_config.cpp index 913295682..61df4f46a 100644 --- a/effects/coverswitch/coverswitch_config.cpp +++ b/effects/coverswitch/coverswitch_config.cpp @@ -31,12 +31,12 @@ KWIN_EFFECT_CONFIG_FACTORY CoverSwitchEffectConfigForm::CoverSwitchEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } CoverSwitchEffectConfig::CoverSwitchEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new CoverSwitchEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -60,80 +60,80 @@ CoverSwitchEffectConfig::CoverSwitchEffectConfig(QWidget* parent, const QVariant connect(m_ui->checkDynamicThumbnails, SIGNAL(stateChanged(int)), this, SLOT(thumbnailsChanged())); load(); - } +} void CoverSwitchEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "CoverSwitch" ); + KConfigGroup conf = EffectsHandler::effectConfig("CoverSwitch"); - m_ui->spinDuration->setValue( conf.readEntry( "Duration", 0 ) ); - m_ui->spinDuration->setSuffix( ki18np( " millisecond", " milliseconds" ) ); - m_ui->checkAnimateSwitch->setChecked( conf.readEntry( "AnimateSwitch", true )); - m_ui->checkAnimateStart->setChecked( conf.readEntry( "AnimateStart", true )); - m_ui->checkAnimateStop->setChecked( conf.readEntry( "AnimateStop", true )); - m_ui->checkReflection->setChecked( conf.readEntry( "Reflection", true )); - m_ui->colorFront->setColor( conf.readEntry( "MirrorFrontColor", QColor(0,0,0) )); - m_ui->colorRear->setColor( conf.readEntry( "MirrorRearColor", QColor(0,0,0) )); - m_ui->checkWindowTitle->setChecked( conf.readEntry( "WindowTitle", true )); - m_ui->checkThumbnails->setChecked( conf.readEntry( "Thumbnails", true )); - m_ui->checkDynamicThumbnails->setChecked( conf.readEntry( "DynamicThumbnails", true )); - m_ui->spinThumbnailWindows->setValue( conf.readEntry( "ThumbnailWindows", 8 )); - m_ui->zPositionSlider->setValue( conf.readEntry( "ZPosition", 900 )); + m_ui->spinDuration->setValue(conf.readEntry("Duration", 0)); + m_ui->spinDuration->setSuffix(ki18np(" millisecond", " milliseconds")); + m_ui->checkAnimateSwitch->setChecked(conf.readEntry("AnimateSwitch", true)); + m_ui->checkAnimateStart->setChecked(conf.readEntry("AnimateStart", true)); + m_ui->checkAnimateStop->setChecked(conf.readEntry("AnimateStop", true)); + m_ui->checkReflection->setChecked(conf.readEntry("Reflection", true)); + m_ui->colorFront->setColor(conf.readEntry("MirrorFrontColor", QColor(0, 0, 0))); + m_ui->colorRear->setColor(conf.readEntry("MirrorRearColor", QColor(0, 0, 0))); + m_ui->checkWindowTitle->setChecked(conf.readEntry("WindowTitle", true)); + m_ui->checkThumbnails->setChecked(conf.readEntry("Thumbnails", true)); + m_ui->checkDynamicThumbnails->setChecked(conf.readEntry("DynamicThumbnails", true)); + m_ui->spinThumbnailWindows->setValue(conf.readEntry("ThumbnailWindows", 8)); + m_ui->zPositionSlider->setValue(conf.readEntry("ZPosition", 900)); thumbnailsChanged(); emit changed(false); - } +} void CoverSwitchEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "CoverSwitch" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("CoverSwitch"); - conf.writeEntry( "Duration", m_ui->spinDuration->value() ); - conf.writeEntry( "AnimateSwitch", m_ui->checkAnimateSwitch->isChecked() ); - conf.writeEntry( "AnimateStart", m_ui->checkAnimateStart->isChecked() ); - conf.writeEntry( "AnimateStop", m_ui->checkAnimateStop->isChecked() ); - conf.writeEntry( "Reflection", m_ui->checkReflection->isChecked() ); - conf.writeEntry( "MirrorFrontColor", m_ui->colorFront->color() ); - conf.writeEntry( "MirrorRearColor", m_ui->colorRear->color() ); - conf.writeEntry( "WindowTitle", m_ui->checkWindowTitle->isChecked() ); - conf.writeEntry( "Thumbnails", m_ui->checkThumbnails->isChecked() ); - conf.writeEntry( "DynamicThumbnails", m_ui->checkDynamicThumbnails->isChecked() ); - conf.writeEntry( "ThumbnailWindows", m_ui->spinThumbnailWindows->value() ); - conf.writeEntry( "ZPosition", m_ui->zPositionSlider->value() ); + conf.writeEntry("Duration", m_ui->spinDuration->value()); + conf.writeEntry("AnimateSwitch", m_ui->checkAnimateSwitch->isChecked()); + conf.writeEntry("AnimateStart", m_ui->checkAnimateStart->isChecked()); + conf.writeEntry("AnimateStop", m_ui->checkAnimateStop->isChecked()); + conf.writeEntry("Reflection", m_ui->checkReflection->isChecked()); + conf.writeEntry("MirrorFrontColor", m_ui->colorFront->color()); + conf.writeEntry("MirrorRearColor", m_ui->colorRear->color()); + conf.writeEntry("WindowTitle", m_ui->checkWindowTitle->isChecked()); + conf.writeEntry("Thumbnails", m_ui->checkThumbnails->isChecked()); + conf.writeEntry("DynamicThumbnails", m_ui->checkDynamicThumbnails->isChecked()); + conf.writeEntry("ThumbnailWindows", m_ui->spinThumbnailWindows->value()); + conf.writeEntry("ZPosition", m_ui->zPositionSlider->value()); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "coverswitch" ); - } + EffectsHandler::sendReloadMessage("coverswitch"); +} void CoverSwitchEffectConfig::defaults() - { - m_ui->spinDuration->setValue( 0 ); - m_ui->checkAnimateSwitch->setCheckState( Qt::Checked ); - m_ui->checkAnimateStart->setCheckState( Qt::Checked ); - m_ui->checkAnimateStop->setCheckState( Qt::Checked ); - m_ui->checkReflection->setCheckState( Qt::Checked ); - m_ui->colorFront->setColor( QColor(0,0,0) ); - m_ui->colorRear->setColor( QColor(0,0,0) ); - m_ui->checkWindowTitle->setCheckState( Qt::Checked ); - m_ui->checkThumbnails->setCheckState( Qt::Checked ); - m_ui->checkDynamicThumbnails->setCheckState( Qt::Checked ); - m_ui->spinThumbnailWindows->setValue( 8 ); - m_ui->zPositionSlider->setValue( 900 ); +{ + m_ui->spinDuration->setValue(0); + m_ui->checkAnimateSwitch->setCheckState(Qt::Checked); + m_ui->checkAnimateStart->setCheckState(Qt::Checked); + m_ui->checkAnimateStop->setCheckState(Qt::Checked); + m_ui->checkReflection->setCheckState(Qt::Checked); + m_ui->colorFront->setColor(QColor(0, 0, 0)); + m_ui->colorRear->setColor(QColor(0, 0, 0)); + m_ui->checkWindowTitle->setCheckState(Qt::Checked); + m_ui->checkThumbnails->setCheckState(Qt::Checked); + m_ui->checkDynamicThumbnails->setCheckState(Qt::Checked); + m_ui->spinThumbnailWindows->setValue(8); + m_ui->zPositionSlider->setValue(900); emit changed(true); - } +} void CoverSwitchEffectConfig::thumbnailsChanged() - { +{ bool enabled = m_ui->checkThumbnails->isChecked() && m_ui->checkDynamicThumbnails->isChecked(); - m_ui->checkDynamicThumbnails->setEnabled( m_ui->checkThumbnails->isChecked() ); - m_ui->spinThumbnailWindows->setEnabled( enabled ); - m_ui->labelThumbnailWindows->setEnabled( enabled ); - } + m_ui->checkDynamicThumbnails->setEnabled(m_ui->checkThumbnails->isChecked()); + m_ui->spinThumbnailWindows->setEnabled(enabled); + m_ui->labelThumbnailWindows->setEnabled(enabled); +} } // namespace diff --git a/effects/coverswitch/coverswitch_config.h b/effects/coverswitch/coverswitch_config.h index 59ffe970c..72a91693d 100644 --- a/effects/coverswitch/coverswitch_config.h +++ b/effects/coverswitch/coverswitch_config.h @@ -32,27 +32,27 @@ namespace KWin class CoverSwitchEffectConfigForm : public QWidget, public Ui::CoverSwitchEffectConfigForm { Q_OBJECT - public: - explicit CoverSwitchEffectConfigForm(QWidget* parent); +public: + explicit CoverSwitchEffectConfigForm(QWidget* parent); }; class CoverSwitchEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit CoverSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit CoverSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private slots: - void thumbnailsChanged(); +private slots: + void thumbnailsChanged(); - private: - CoverSwitchEffectConfigForm* m_ui; - }; +private: + CoverSwitchEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/cube/cube.cpp b/effects/cube/cube.cpp index fd78bb9e5..9fd912cd7 100644 --- a/effects/cube/cube.cpp +++ b/effects/cube/cube.cpp @@ -43,58 +43,58 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( cube, CubeEffect ) -KWIN_EFFECT_SUPPORTED( cube, CubeEffect::supported() ) +KWIN_EFFECT(cube, CubeEffect) +KWIN_EFFECT_SUPPORTED(cube, CubeEffect::supported()) CubeEffect::CubeEffect() - : activated( false ) - , mousePolling( false ) - , cube_painting( false ) - , keyboard_grab( false ) - , schedule_close( false ) - , painting_desktop( 1 ) - , frontDesktop( 0 ) - , cubeOpacity( 1.0 ) - , opacityDesktopOnly( true ) - , displayDesktopName( false ) - , desktopNameFrame( effects->effectFrame( EffectFrameStyled ) ) - , reflection( true ) - , rotating( false ) - , desktopChangedWhileRotating( false ) - , paintCaps( true ) - , rotationDirection( Left ) - , verticalRotationDirection( Upwards ) - , verticalPosition( Normal ) - , wallpaper( NULL ) - , texturedCaps( true ) - , capTexture( NULL ) - , manualAngle( 0.0 ) - , manualVerticalAngle( 0.0 ) - , currentShape( TimeLine::EaseInOutCurve ) - , start( false ) - , stop( false ) - , reflectionPainting( false ) - , activeScreen( 0 ) - , bottomCap( false ) - , closeOnMouseRelease( false ) - , zoom( 0.0 ) - , zPosition( 0.0 ) - , useForTabBox( false ) - , tabBoxMode( false ) - , shortcutsRegistered( false ) - , mode( Cube ) - , useShaders( false ) - , cylinderShader( 0 ) - , sphereShader( 0 ) - , zOrderingFactor( 0.0f ) - , mAddedHeightCoeff1( 0.0f ) - , mAddedHeightCoeff2( 0.0f ) - , m_cubeCapBuffer( NULL ) - , m_proxy( this ) - { - desktopNameFont.setBold( true ); - desktopNameFont.setPointSize( 14 ); - desktopNameFrame->setFont( desktopNameFont ); + : activated(false) + , mousePolling(false) + , cube_painting(false) + , keyboard_grab(false) + , schedule_close(false) + , painting_desktop(1) + , frontDesktop(0) + , cubeOpacity(1.0) + , opacityDesktopOnly(true) + , displayDesktopName(false) + , desktopNameFrame(effects->effectFrame(EffectFrameStyled)) + , reflection(true) + , rotating(false) + , desktopChangedWhileRotating(false) + , paintCaps(true) + , rotationDirection(Left) + , verticalRotationDirection(Upwards) + , verticalPosition(Normal) + , wallpaper(NULL) + , texturedCaps(true) + , capTexture(NULL) + , manualAngle(0.0) + , manualVerticalAngle(0.0) + , currentShape(TimeLine::EaseInOutCurve) + , start(false) + , stop(false) + , reflectionPainting(false) + , activeScreen(0) + , bottomCap(false) + , closeOnMouseRelease(false) + , zoom(0.0) + , zPosition(0.0) + , useForTabBox(false) + , tabBoxMode(false) + , shortcutsRegistered(false) + , mode(Cube) + , useShaders(false) + , cylinderShader(0) + , sphereShader(0) + , zOrderingFactor(0.0f) + , mAddedHeightCoeff1(0.0f) + , mAddedHeightCoeff2(0.0f) + , m_cubeCapBuffer(NULL) + , m_proxy(this) +{ + desktopNameFont.setBold(true); + desktopNameFont.setPointSize(14); + desktopNameFrame->setFont(desktopNameFont); const QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/cube-reflection.glsl"); m_reflectionShader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, fragmentshader); @@ -103,140 +103,129 @@ CubeEffect::CubeEffect() m_textureMirrorMatrix.scale(1.0, -1.0, 1.0); m_textureMirrorMatrix.translate(0.0, -1.0, 0.0); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} bool CubeEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void CubeEffect::reconfigure( ReconfigureFlags ) - { - loadConfig( "Cube" ); - } +void CubeEffect::reconfigure(ReconfigureFlags) +{ + loadConfig("Cube"); +} -void CubeEffect::loadConfig( QString config ) - { - KConfigGroup conf = effects->effectConfig( config ); - foreach( ElectricBorder border, borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, borderActivateCylinder ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, borderActivateSphere ) - { - effects->unreserveElectricBorder( border ); - } +void CubeEffect::loadConfig(QString config) +{ + KConfigGroup conf = effects->effectConfig(config); + foreach (ElectricBorder border, borderActivate) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, borderActivateCylinder) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, borderActivateSphere) { + effects->unreserveElectricBorder(border); + } borderActivate.clear(); borderActivateCylinder.clear(); borderActivateSphere.clear(); QList borderList = QList(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivate", borderList ); - foreach( int i, borderList ) - { - borderActivate.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivate", borderList); + foreach (int i, borderList) { + borderActivate.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); + } borderList.clear(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivateCylinder", borderList ); - foreach( int i, borderList ) - { - borderActivateCylinder.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivateCylinder", borderList); + foreach (int i, borderList) { + borderActivateCylinder.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); + } borderList.clear(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivateSphere", borderList ); - foreach( int i, borderList ) - { - borderActivateSphere.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivateSphere", borderList); + foreach (int i, borderList) { + borderActivateSphere.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); + } - cubeOpacity = (float)conf.readEntry( "Opacity", 80 )/100.0f; - opacityDesktopOnly = conf.readEntry( "OpacityDesktopOnly", false ); - displayDesktopName = conf.readEntry( "DisplayDesktopName", true ); - reflection = conf.readEntry( "Reflection", true ); - rotationDuration = animationTime( conf, "RotationDuration", 500 ); - backgroundColor = conf.readEntry( "BackgroundColor", QColor( Qt::black ) ); - capColor = conf.readEntry( "CapColor", KColorScheme( QPalette::Active, KColorScheme::Window ).background().color() ); - paintCaps = conf.readEntry( "Caps", true ); - closeOnMouseRelease = conf.readEntry( "CloseOnMouseRelease", false ); + cubeOpacity = (float)conf.readEntry("Opacity", 80) / 100.0f; + opacityDesktopOnly = conf.readEntry("OpacityDesktopOnly", false); + displayDesktopName = conf.readEntry("DisplayDesktopName", true); + reflection = conf.readEntry("Reflection", true); + rotationDuration = animationTime(conf, "RotationDuration", 500); + backgroundColor = conf.readEntry("BackgroundColor", QColor(Qt::black)); + capColor = conf.readEntry("CapColor", KColorScheme(QPalette::Active, KColorScheme::Window).background().color()); + paintCaps = conf.readEntry("Caps", true); + closeOnMouseRelease = conf.readEntry("CloseOnMouseRelease", false); float defaultZPosition = 100.0f; - if( config == "Sphere" ) + if (config == "Sphere") defaultZPosition = 450.0f; - zPosition = conf.readEntry( "ZPosition", defaultZPosition ); - useForTabBox = conf.readEntry( "TabBox", false ); - invertKeys = conf.readEntry( "InvertKeys", false ); - invertMouse = conf.readEntry( "InvertMouse", false ); - capDeformationFactor = conf.readEntry( "CapDeformation", 0 )/100.0f; - useZOrdering = conf.readEntry( "ZOrdering", false ); - QString file = conf.readEntry( "Wallpaper", QString("") ); - if( wallpaper ) + zPosition = conf.readEntry("ZPosition", defaultZPosition); + useForTabBox = conf.readEntry("TabBox", false); + invertKeys = conf.readEntry("InvertKeys", false); + invertMouse = conf.readEntry("InvertMouse", false); + capDeformationFactor = conf.readEntry("CapDeformation", 0) / 100.0f; + useZOrdering = conf.readEntry("ZOrdering", false); + QString file = conf.readEntry("Wallpaper", QString("")); + if (wallpaper) wallpaper->discard(); delete wallpaper; wallpaper = NULL; - if( !file.isEmpty() ) - { - QImage img = QImage( file ); - if( !img.isNull() ) - { - wallpaper = new GLTexture( img ); - } + if (!file.isEmpty()) { + QImage img = QImage(file); + if (!img.isNull()) { + wallpaper = new GLTexture(img); } + } delete capTexture; capTexture = NULL; - texturedCaps = conf.readEntry( "TexturedCaps", true ); - if( texturedCaps ) - { - QString capPath = conf.readEntry( "CapPath", KGlobal::dirs()->findResource( "appdata", "cubecap.png" ) ); - QImage img = QImage( capPath ); - if( !img.isNull() ) - { - capTexture = new GLTexture( img ); - capTexture->setFilter( GL_LINEAR ); + texturedCaps = conf.readEntry("TexturedCaps", true); + if (texturedCaps) { + QString capPath = conf.readEntry("CapPath", KGlobal::dirs()->findResource("appdata", "cubecap.png")); + QImage img = QImage(capPath); + if (!img.isNull()) { + capTexture = new GLTexture(img); + capTexture->setFilter(GL_LINEAR); #ifndef KWIN_HAVE_OPENGLES - capTexture->setWrapMode( GL_CLAMP_TO_BORDER ); + capTexture->setWrapMode(GL_CLAMP_TO_BORDER); #endif - } } + } - timeLine.setCurveShape( TimeLine::EaseInOutCurve ); - timeLine.setDuration( rotationDuration ); + timeLine.setCurveShape(TimeLine::EaseInOutCurve); + timeLine.setDuration(rotationDuration); - verticalTimeLine.setCurveShape( TimeLine::EaseInOutCurve ); - verticalTimeLine.setDuration( rotationDuration ); + verticalTimeLine.setCurveShape(TimeLine::EaseInOutCurve); + verticalTimeLine.setDuration(rotationDuration); // do not connect the shortcut if we use cylinder or sphere - if( !shortcutsRegistered ) - { - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* cubeAction = static_cast< KAction* >( actionCollection->addAction( "Cube" )); - cubeAction->setText( i18n("Desktop Cube" )); - cubeAction->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F11 )); + if (!shortcutsRegistered) { + KActionCollection* actionCollection = new KActionCollection(this); + KAction* cubeAction = static_cast< KAction* >(actionCollection->addAction("Cube")); + cubeAction->setText(i18n("Desktop Cube")); + cubeAction->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F11)); cubeShortcut = cubeAction->globalShortcut(); - KAction* cylinderAction = static_cast< KAction* >( actionCollection->addAction( "Cylinder" )); - cylinderAction->setText( i18n("Desktop Cylinder" )); - cylinderAction->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut); + KAction* cylinderAction = static_cast< KAction* >(actionCollection->addAction("Cylinder")); + cylinderAction->setText(i18n("Desktop Cylinder")); + cylinderAction->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); cylinderShortcut = cylinderAction->globalShortcut(); - KAction* sphereAction = static_cast< KAction* >( actionCollection->addAction( "Sphere" )); - sphereAction->setText( i18n("Desktop Sphere" )); - sphereAction->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut); + KAction* sphereAction = static_cast< KAction* >(actionCollection->addAction("Sphere")); + sphereAction->setText(i18n("Desktop Sphere")); + sphereAction->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); sphereShortcut = sphereAction->globalShortcut(); - connect( cubeAction, SIGNAL( triggered( bool )), this, SLOT( toggleCube())); - connect( cylinderAction, SIGNAL( triggered( bool )), this, SLOT( toggleCylinder())); - connect( sphereAction, SIGNAL( triggered( bool )), this, SLOT( toggleSphere())); - connect( cubeAction, SIGNAL( globalShortcutChanged( QKeySequence )), this, SLOT( cubeShortcutChanged(QKeySequence))); - connect( cylinderAction, SIGNAL( globalShortcutChanged( QKeySequence )), this, SLOT( cylinderShortcutChanged(QKeySequence))); - connect( sphereAction, SIGNAL( globalShortcutChanged( QKeySequence )), this, SLOT( sphereShortcutChanged(QKeySequence))); + connect(cubeAction, SIGNAL(triggered(bool)), this, SLOT(toggleCube())); + connect(cylinderAction, SIGNAL(triggered(bool)), this, SLOT(toggleCylinder())); + connect(sphereAction, SIGNAL(triggered(bool)), this, SLOT(toggleSphere())); + connect(cubeAction, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(cubeShortcutChanged(QKeySequence))); + connect(cylinderAction, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(cylinderShortcutChanged(QKeySequence))); + connect(sphereAction, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(sphereShortcutChanged(QKeySequence))); shortcutsRegistered = true; - } + } // set the cap color on the shader if (ShaderManager::instance()->isValid() && m_capShader->isValid()) { @@ -244,22 +233,19 @@ void CubeEffect::loadConfig( QString config ) m_capShader->setUniform("u_capColor", capColor); ShaderManager::instance()->popShader(); } - } +} CubeEffect::~CubeEffect() - { - foreach( ElectricBorder border, borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, borderActivateCylinder ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, borderActivateSphere ) - { - effects->unreserveElectricBorder( border ); - } +{ + foreach (ElectricBorder border, borderActivate) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, borderActivateCylinder) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, borderActivateSphere) { + effects->unreserveElectricBorder(border); + } delete wallpaper; delete capTexture; delete cylinderShader; @@ -268,34 +254,30 @@ CubeEffect::~CubeEffect() delete m_reflectionShader; delete m_capShader; delete m_cubeCapBuffer; - } +} bool CubeEffect::loadShader() - { - if( !(GLShader::fragmentShaderSupported() && +{ + if (!(GLShader::fragmentShaderSupported() && (effects->compositingType() == OpenGLCompositing))) return false; - QString fragmentshader = KGlobal::dirs()->findResource( "data", "kwin/cylinder.frag" ); - QString cylinderVertexshader = KGlobal::dirs()->findResource( "data", "kwin/cylinder.vert" ); - QString sphereVertexshader = KGlobal::dirs()->findResource( "data", "kwin/sphere.vert" ); - if( fragmentshader.isEmpty() || cylinderVertexshader.isEmpty() || sphereVertexshader.isEmpty() ) - { + QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/cylinder.frag"); + QString cylinderVertexshader = KGlobal::dirs()->findResource("data", "kwin/cylinder.vert"); + QString sphereVertexshader = KGlobal::dirs()->findResource("data", "kwin/sphere.vert"); + if (fragmentshader.isEmpty() || cylinderVertexshader.isEmpty() || sphereVertexshader.isEmpty()) { kError(1212) << "Couldn't locate shader files" << endl; return false; - } + } ShaderManager *shaderManager = ShaderManager::instance(); // TODO: use generic shader - currently it is failing in alpha/brightness manipulation cylinderShader = new GLShader(cylinderVertexshader, fragmentshader); - if( !cylinderShader->isValid() ) - { + if (!cylinderShader->isValid()) { kError(1212) << "The cylinder shader failed to load!" << endl; return false; - } - else - { + } else { shaderManager->pushShader(cylinderShader); - cylinderShader->setUniform( "sample", 0 ); + cylinderShader->setUniform("sample", 0); QMatrix4x4 projection; float fovy = 60.0f; float aspect = 1.0f; @@ -308,28 +290,25 @@ bool CubeEffect::loadShader() projection.frustum(xmin, xmax, ymin, ymax, zNear, zFar); cylinderShader->setUniform("projection", projection); QMatrix4x4 modelview; - float scaleFactor = 1.1 * tan( fovy * M_PI / 360.0f )/ymax; - modelview.translate(xmin*scaleFactor, ymax*scaleFactor, -1.1); - modelview.scale((xmax-xmin)*scaleFactor/displayWidth(), -(ymax-ymin)*scaleFactor/displayHeight(), 0.001); + float scaleFactor = 1.1 * tan(fovy * M_PI / 360.0f) / ymax; + modelview.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); + modelview.scale((xmax - xmin)*scaleFactor / displayWidth(), -(ymax - ymin)*scaleFactor / displayHeight(), 0.001); cylinderShader->setUniform("modelview", modelview); const QMatrix4x4 identity; cylinderShader->setUniform("screenTransformation", identity); cylinderShader->setUniform("windowTransformation", identity); - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - cylinderShader->setUniform( "width", (float)rect.width()*0.5f ); + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + cylinderShader->setUniform("width", (float)rect.width() * 0.5f); shaderManager->popShader(); - } + } // TODO: use generic shader - currently it is failing in alpha/brightness manipulation sphereShader = new GLShader(sphereVertexshader, fragmentshader); - if( !sphereShader->isValid() ) - { + if (!sphereShader->isValid()) { kError(1212) << "The sphere shader failed to load!" << endl; return false; - } - else - { + } else { shaderManager->pushShader(sphereShader); - sphereShader->setUniform( "sample", 0 ); + sphereShader->setUniform("sample", 0); QMatrix4x4 projection; float fovy = 60.0f; float aspect = 1.0f; @@ -342,162 +321,153 @@ bool CubeEffect::loadShader() projection.frustum(xmin, xmax, ymin, ymax, zNear, zFar); sphereShader->setUniform("projection", projection); QMatrix4x4 modelview; - float scaleFactor = 1.1 * tan( fovy * M_PI / 360.0f )/ymax; - modelview.translate(xmin*scaleFactor, ymax*scaleFactor, -1.1); - modelview.scale((xmax-xmin)*scaleFactor/displayWidth(), -(ymax-ymin)*scaleFactor/displayHeight(), 0.001); + float scaleFactor = 1.1 * tan(fovy * M_PI / 360.0f) / ymax; + modelview.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); + modelview.scale((xmax - xmin)*scaleFactor / displayWidth(), -(ymax - ymin)*scaleFactor / displayHeight(), 0.001); sphereShader->setUniform("modelview", modelview); const QMatrix4x4 identity; sphereShader->setUniform("screenTransformation", identity); sphereShader->setUniform("windowTransformation", identity); - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - sphereShader->setUniform( "width", (float)rect.width()*0.5f ); - sphereShader->setUniform( "height", (float)rect.height()*0.5f ); - sphereShader->setUniform( "u_offset", QVector2D(0, 0)); + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + sphereShader->setUniform("width", (float)rect.width() * 0.5f); + sphereShader->setUniform("height", (float)rect.height() * 0.5f); + sphereShader->setUniform("u_offset", QVector2D(0, 0)); shaderManager->popShader(); checkGLError("Loading Sphere Shader"); - } - return true; } + return true; +} -void CubeEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( activated ) - { +void CubeEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (activated) { data.mask |= PAINT_SCREEN_TRANSFORMED | Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS | PAINT_SCREEN_BACKGROUND_FIRST; - if( rotating || start || stop ) - { - timeLine.addTime( time ); + if (rotating || start || stop) { + timeLine.addTime(time); + rotateCube(); + } + if (verticalRotating) { + verticalTimeLine.addTime(time); rotateCube(); - } - if( verticalRotating ) - { - verticalTimeLine.addTime( time ); - rotateCube(); - } } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void CubeEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( activated ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); +void CubeEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (activated) { + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); // background float clearColor[4]; - glGetFloatv( GL_COLOR_CLEAR_VALUE, clearColor ); - glClearColor( backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), 1.0 ); - glClear( GL_COLOR_BUFFER_BIT ); - glClearColor( clearColor[0], clearColor[1], clearColor[2], clearColor[3] ); + glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor); + glClearColor(backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), 1.0); + glClear(GL_COLOR_BUFFER_BIT); + glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); // wallpaper - if( wallpaper ) - { + if (wallpaper) { wallpaper->bind(); - wallpaper->render( region, rect ); + wallpaper->render(region, rect); wallpaper->unbind(); - } + } #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // some veriables needed for painting the caps - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float point = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); float zTranslate = zPosition + zoom; - if( start ) + if (start) zTranslate *= timeLine.value(); - if( stop ) - zTranslate *= ( 1.0 - timeLine.value() ); + if (stop) + zTranslate *= (1.0 - timeLine.value()); // reflection - if( reflection && mode != Sphere ) - { + if (reflection && mode != Sphere) { // restrict painting the reflections to the current screen - PaintClipper::push( QRegion( rect )); + PaintClipper::push(QRegion(rect)); // we can use a huge scale factor (needed to calculate the rearground vertices) // as we restrict with a PaintClipper painting on the current screen - float scaleFactor = 1000000 * tan( 60.0 * M_PI / 360.0f )/rect.height(); + float scaleFactor = 1000000 * tan(60.0 * M_PI / 360.0f) / rect.height(); m_reflectionMatrix.setToIdentity(); m_reflectionMatrix.scale(1.0, -1.0, 1.0); // TODO reflection is not correct when mixing manual (mouse) rotating with rotation by cursor keys // there's also a small bug when zooming - float addedHeight1 = -sin( asin( float( rect.height() ) / mAddedHeightCoeff1 ) + fabs( manualVerticalAngle ) * M_PI / 180.0f ) * mAddedHeightCoeff1; - float addedHeight2 = -sin( asin( float( rect.height() ) / mAddedHeightCoeff2 ) + fabs( manualVerticalAngle ) * M_PI / 180.0f ) * mAddedHeightCoeff2 - addedHeight1; - if( manualVerticalAngle > 0.0f && effects->numberOfDesktops() & 1 ) - { - m_reflectionMatrix.translate(0.0, cos( fabs( manualAngle ) * M_PI / 360.0f * float( effects->numberOfDesktops() ) ) * addedHeight2 + addedHeight1 - float( rect.height() ), 0.0); - } - else - { - m_reflectionMatrix.translate(0.0, sin( fabs( manualAngle ) * M_PI / 360.0f * float( effects->numberOfDesktops() ) ) * addedHeight2 + addedHeight1 - float( rect.height() ), 0.0); - } + float addedHeight1 = -sin(asin(float(rect.height()) / mAddedHeightCoeff1) + fabs(manualVerticalAngle) * M_PI / 180.0f) * mAddedHeightCoeff1; + float addedHeight2 = -sin(asin(float(rect.height()) / mAddedHeightCoeff2) + fabs(manualVerticalAngle) * M_PI / 180.0f) * mAddedHeightCoeff2 - addedHeight1; + if (manualVerticalAngle > 0.0f && effects->numberOfDesktops() & 1) { + m_reflectionMatrix.translate(0.0, cos(fabs(manualAngle) * M_PI / 360.0f * float(effects->numberOfDesktops())) * addedHeight2 + addedHeight1 - float(rect.height()), 0.0); + } else { + m_reflectionMatrix.translate(0.0, sin(fabs(manualAngle) * M_PI / 360.0f * float(effects->numberOfDesktops())) * addedHeight2 + addedHeight1 - float(rect.height()), 0.0); + } pushMatrix(m_reflectionMatrix); #ifndef KWIN_HAVE_OPENGLES // TODO: find a solution for GLES - glEnable( GL_CLIP_PLANE0 ); + glEnable(GL_CLIP_PLANE0); #endif reflectionPainting = true; - glEnable( GL_CULL_FACE ); - paintCap(true, -point-zTranslate); + glEnable(GL_CULL_FACE); + paintCap(true, -point - zTranslate); // cube - glCullFace( GL_BACK ); + glCullFace(GL_BACK); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); // call the inside cube effects #ifndef KWIN_HAVE_OPENGLES - foreach( CubeInsideEffect* inside, m_cubeInsideEffects ) - { + foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { pushMatrix(m_rotationMatrix); - glTranslatef( rect.width()/2, rect.height()/2, -point-zTranslate ); - glRotatef( (1-frontDesktop)*360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0 ); + glTranslatef(rect.width() / 2, rect.height() / 2, -point - zTranslate); + glRotatef((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); inside->paint(); popMatrix(); - } + } #endif - glCullFace( GL_FRONT ); + glCullFace(GL_FRONT); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); - paintCap(false, -point-zTranslate); - glDisable( GL_CULL_FACE ); + paintCap(false, -point - zTranslate); + glDisable(GL_CULL_FACE); reflectionPainting = false; #ifndef KWIN_HAVE_OPENGLES // TODO: find a solution for GLES - glDisable( GL_CLIP_PLANE0 ); + glDisable(GL_CLIP_PLANE0); #endif popMatrix(); float vertices[] = { - -rect.width()*0.5f, rect.height(), 0.0, - rect.width()*0.5f, rect.height(), 0.0, + -rect.width() * 0.5f, rect.height(), 0.0, + rect.width() * 0.5f, rect.height(), 0.0, (float)rect.width()*scaleFactor, rect.height(), -5000, - -(float)rect.width()*scaleFactor, rect.height(), -5000 }; + -(float)rect.width()*scaleFactor, rect.height(), -5000 + }; // foreground float alpha = 0.7; - if( start ) + if (start) alpha = 0.3 + 0.4 * timeLine.value(); - if( stop ) - alpha = 0.3 + 0.4 * ( 1.0 - timeLine.value() ); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + if (stop) + alpha = 0.3 + 0.4 * (1.0 - timeLine.value()); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); ShaderManager *shaderManager = ShaderManager::instance(); if (shaderManager->isValid() && m_reflectionShader->isValid()) { // ensure blending is enabled - no attribute stack shaderManager->pushShader(m_reflectionShader); QMatrix4x4 windowTransformation; - windowTransformation.translate(rect.x() + rect.width()*0.5f, 0.0, 0.0); + windowTransformation.translate(rect.x() + rect.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform("windowTransformation", windowTransformation); m_reflectionShader->setUniform("u_alpha", alpha); QVector verts; @@ -524,30 +494,30 @@ void CubeEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES - glColor4f( 0.0, 0.0, 0.0, alpha ); + glColor4f(0.0, 0.0, 0.0, alpha); glPushMatrix(); - glTranslatef( rect.x() + rect.width()*0.5f, 0.0, 0.0 ); - glBegin( GL_POLYGON ); - glVertex3f( vertices[0], vertices[1], vertices[2] ); - glVertex3f( vertices[3], vertices[4], vertices[5] ); + glTranslatef(rect.x() + rect.width() * 0.5f, 0.0, 0.0); + glBegin(GL_POLYGON); + glVertex3f(vertices[0], vertices[1], vertices[2]); + glVertex3f(vertices[3], vertices[4], vertices[5]); // rearground alpha = -1.0; - glColor4f( 0.0, 0.0, 0.0, alpha ); - glVertex3f( vertices[6], vertices[7], vertices[8] ); - glVertex3f( vertices[9], vertices[10], vertices[11] ); + glColor4f(0.0, 0.0, 0.0, alpha); + glVertex3f(vertices[6], vertices[7], vertices[8]); + glVertex3f(vertices[9], vertices[10], vertices[11]); glEnd(); glPopMatrix(); #endif } - glDisable( GL_BLEND ); - PaintClipper::pop( QRegion( rect )); - } - glEnable( GL_CULL_FACE ); + glDisable(GL_BLEND); + PaintClipper::pop(QRegion(rect)); + } + glEnable(GL_CULL_FACE); // caps - paintCap(false, -point-zTranslate); + paintCap(false, -point - zTranslate); // cube - glCullFace( GL_FRONT ); + glCullFace(GL_FRONT); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); @@ -555,222 +525,196 @@ void CubeEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) // call the inside cube effects #ifndef KWIN_HAVE_OPENGLES - foreach( CubeInsideEffect* inside, m_cubeInsideEffects ) - { + foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { pushMatrix(m_rotationMatrix); - glTranslatef( rect.width()/2, rect.height()/2, -point-zTranslate ); - glRotatef( (1-frontDesktop)*360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0 ); + glTranslatef(rect.width() / 2, rect.height() / 2, -point - zTranslate); + glRotatef((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); inside->paint(); popMatrix(); - } + } #endif - glCullFace( GL_BACK ); + glCullFace(GL_BACK); pushMatrix(m_rotationMatrix); paintCube(mask, region, data); popMatrix(); // cap - paintCap(true, -point-zTranslate); - glDisable( GL_CULL_FACE ); + paintCap(true, -point - zTranslate); + glDisable(GL_CULL_FACE); - glDisable( GL_BLEND ); + glDisable(GL_BLEND); #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif // desktop name box - inspired from coverswitch - if( displayDesktopName ) - { + if (displayDesktopName) { double opacity = 1.0; - if( start ) + if (start) opacity = timeLine.value(); - if( stop ) + if (stop) opacity = 1.0 - timeLine.value(); - QRect screenRect = effects->clientArea( ScreenArea, activeScreen, frontDesktop ); - QRect frameRect = QRect( screenRect.width() * 0.33f + screenRect.x(), screenRect.height() * 0.95f + screenRect.y(), - screenRect.width() * 0.34f, QFontMetrics( desktopNameFont ).height() ); - desktopNameFrame->setGeometry( frameRect ); - desktopNameFrame->setText( effects->desktopName( frontDesktop ) ); - desktopNameFrame->render( region, opacity ); - } - } - else - { - effects->paintScreen( mask, region, data ); + QRect screenRect = effects->clientArea(ScreenArea, activeScreen, frontDesktop); + QRect frameRect = QRect(screenRect.width() * 0.33f + screenRect.x(), screenRect.height() * 0.95f + screenRect.y(), + screenRect.width() * 0.34f, QFontMetrics(desktopNameFont).height()); + desktopNameFrame->setGeometry(frameRect); + desktopNameFrame->setText(effects->desktopName(frontDesktop)); + desktopNameFrame->render(region, opacity); } + } else { + effects->paintScreen(mask, region, data); } +} void CubeEffect::rotateCube() - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); +{ + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); m_rotationMatrix.setToIdentity(); float internalCubeAngle = 360.0f / effects->numberOfDesktops(); float zTranslate = zPosition + zoom; - if( start ) + if (start) zTranslate *= timeLine.value(); - if( stop ) - zTranslate *= ( 1.0 - timeLine.value() ); + if (stop) + zTranslate *= (1.0 - timeLine.value()); // Rotation of the cube - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float point = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); - if( verticalRotating || verticalPosition != Normal || manualVerticalAngle != 0.0 ) - { + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); + if (verticalRotating || verticalPosition != Normal || manualVerticalAngle != 0.0) { // change the verticalPosition if manualVerticalAngle > 90 or < -90 degrees - if( manualVerticalAngle <= -90.0 ) - { + if (manualVerticalAngle <= -90.0) { manualVerticalAngle += 90.0; - if( verticalPosition == Normal ) + if (verticalPosition == Normal) verticalPosition = Down; - if( verticalPosition == Up ) + if (verticalPosition == Up) verticalPosition = Normal; - } - if( manualVerticalAngle >= 90.0 ) - { - manualVerticalAngle -= 90.0; - if( verticalPosition == Normal ) - verticalPosition = Up; - if( verticalPosition == Down ) - verticalPosition = Normal; - } - float angle = 0.0; - if( verticalPosition == Up ) - { - angle = 90.0; - if( !verticalRotating) - { - if( manualVerticalAngle < 0.0 ) - angle += manualVerticalAngle; - else - manualVerticalAngle = 0.0; - } - } - else if( verticalPosition == Down ) - { - angle = -90.0; - if( !verticalRotating) - { - if( manualVerticalAngle > 0.0 ) - angle += manualVerticalAngle; - else - manualVerticalAngle = 0.0; - } - } - else - { - angle = manualVerticalAngle; - } - if( verticalRotating ) - { - angle *= verticalTimeLine.value(); - if( verticalPosition == Normal && verticalRotationDirection == Upwards ) - angle = -90.0 + 90*verticalTimeLine.value(); - if( verticalPosition == Normal && verticalRotationDirection == Downwards ) - angle = 90.0 - 90*verticalTimeLine.value(); - angle += manualVerticalAngle * (1.0-verticalTimeLine.value()); - } - if( stop ) - angle *= (1.0 - timeLine.value()); - m_rotationMatrix.translate(rect.width()/2, rect.height()/2, -point-zTranslate); - m_rotationMatrix.rotate(angle, 1.0, 0.0, 0.0); - m_rotationMatrix.translate(-rect.width()/2, -rect.height()/2, point+zTranslate); } - if( rotating || (manualAngle != 0.0) ) - { + if (manualVerticalAngle >= 90.0) { + manualVerticalAngle -= 90.0; + if (verticalPosition == Normal) + verticalPosition = Up; + if (verticalPosition == Down) + verticalPosition = Normal; + } + float angle = 0.0; + if (verticalPosition == Up) { + angle = 90.0; + if (!verticalRotating) { + if (manualVerticalAngle < 0.0) + angle += manualVerticalAngle; + else + manualVerticalAngle = 0.0; + } + } else if (verticalPosition == Down) { + angle = -90.0; + if (!verticalRotating) { + if (manualVerticalAngle > 0.0) + angle += manualVerticalAngle; + else + manualVerticalAngle = 0.0; + } + } else { + angle = manualVerticalAngle; + } + if (verticalRotating) { + angle *= verticalTimeLine.value(); + if (verticalPosition == Normal && verticalRotationDirection == Upwards) + angle = -90.0 + 90 * verticalTimeLine.value(); + if (verticalPosition == Normal && verticalRotationDirection == Downwards) + angle = 90.0 - 90 * verticalTimeLine.value(); + angle += manualVerticalAngle * (1.0 - verticalTimeLine.value()); + } + if (stop) + angle *= (1.0 - timeLine.value()); + m_rotationMatrix.translate(rect.width() / 2, rect.height() / 2, -point - zTranslate); + m_rotationMatrix.rotate(angle, 1.0, 0.0, 0.0); + m_rotationMatrix.translate(-rect.width() / 2, -rect.height() / 2, point + zTranslate); + } + if (rotating || (manualAngle != 0.0)) { int tempFrontDesktop = frontDesktop; - if( manualAngle > internalCubeAngle * 0.5f ) - { + if (manualAngle > internalCubeAngle * 0.5f) { manualAngle -= internalCubeAngle; tempFrontDesktop--; - if( tempFrontDesktop == 0 ) + if (tempFrontDesktop == 0) tempFrontDesktop = effects->numberOfDesktops(); - } - if( manualAngle < -internalCubeAngle * 0.5f ) - { + } + if (manualAngle < -internalCubeAngle * 0.5f) { manualAngle += internalCubeAngle; tempFrontDesktop++; - if( tempFrontDesktop > effects->numberOfDesktops() ) + if (tempFrontDesktop > effects->numberOfDesktops()) tempFrontDesktop = 1; - } + } float rotationAngle = internalCubeAngle * timeLine.value(); - if( rotationAngle > internalCubeAngle * 0.5f ) - { + if (rotationAngle > internalCubeAngle * 0.5f) { rotationAngle -= internalCubeAngle; - if( !desktopChangedWhileRotating ) - { + if (!desktopChangedWhileRotating) { desktopChangedWhileRotating = true; - if( rotationDirection == Left ) - { + if (rotationDirection == Left) { tempFrontDesktop++; - } - else if( rotationDirection == Right ) - { + } else if (rotationDirection == Right) { tempFrontDesktop--; - } - if( tempFrontDesktop > effects->numberOfDesktops() ) - tempFrontDesktop = 1; - else if( tempFrontDesktop == 0 ) - tempFrontDesktop = effects->numberOfDesktops(); } + if (tempFrontDesktop > effects->numberOfDesktops()) + tempFrontDesktop = 1; + else if (tempFrontDesktop == 0) + tempFrontDesktop = effects->numberOfDesktops(); } + } // don't change front desktop during stop animation as this would break some logic - if( !stop ) + if (!stop) frontDesktop = tempFrontDesktop; - if( rotationDirection == Left ) - { + if (rotationDirection == Left) { rotationAngle *= -1; - } - if( stop ) + } + if (stop) rotationAngle = manualAngle * (1.0 - timeLine.value()); else rotationAngle += manualAngle * (1.0 - timeLine.value()); - m_rotationMatrix.translate(rect.width()/2, rect.height()/2, -point-zTranslate); + m_rotationMatrix.translate(rect.width() / 2, rect.height() / 2, -point - zTranslate); m_rotationMatrix.rotate(rotationAngle, 0.0, 1.0, 0.0); - m_rotationMatrix.translate(-rect.width()/2, -rect.height()/2, point+zTranslate); - } + m_rotationMatrix.translate(-rect.width() / 2, -rect.height() / 2, point + zTranslate); } +} -void CubeEffect::paintCube( int mask, QRegion region, ScreenPaintData& data ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); +void CubeEffect::paintCube(int mask, QRegion region, ScreenPaintData& data) +{ + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float internalCubeAngle = 360.0f / effects->numberOfDesktops(); cube_painting = true; float zTranslate = zPosition + zoom; - if( start ) + if (start) zTranslate *= timeLine.value(); - if( stop ) - zTranslate *= ( 1.0 - timeLine.value() ); + if (stop) + zTranslate *= (1.0 - timeLine.value()); // Rotation of the cube - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float point = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); - for( int i=0; inumberOfDesktops(); i++ ) - { + for (int i = 0; i < effects->numberOfDesktops(); i++) { // start painting the cube - painting_desktop = (i + frontDesktop )%effects->numberOfDesktops(); - if( painting_desktop == 0 ) - { + painting_desktop = (i + frontDesktop) % effects->numberOfDesktops(); + if (painting_desktop == 0) { painting_desktop = effects->numberOfDesktops(); - } + } ScreenPaintData newData = data; RotationData rot = RotationData(); rot.axis = RotationData::YAxis; rot.angle = internalCubeAngle * i; - rot.xRotationPoint = rect.width()/2; + rot.xRotationPoint = rect.width() / 2; rot.zRotationPoint = -point; newData.rotation = &rot; newData.zTranslate = -zTranslate; - effects->paintScreen( mask, region, newData ); - } + effects->paintScreen(mask, region, newData); + } cube_painting = false; painting_desktop = effects->currentDesktop(); - } +} void CubeEffect::paintCap(bool frontFirst, float zOffset) - { - if( ( !paintCaps ) || effects->numberOfDesktops() <= 2 ) +{ + if ((!paintCaps) || effects->numberOfDesktops() <= 2) return; GLenum firstCull = frontFirst ? GL_FRONT : GL_BACK; GLenum secondCull = frontFirst ? GL_BACK : GL_FRONT; @@ -778,7 +722,7 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) // create the VBO if not yet created if (!m_cubeCapBuffer) { - switch (mode) { + switch(mode) { case Cube: paintCubeCap(); break; @@ -795,8 +739,8 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) } QMatrix4x4 capMatrix; - capMatrix.translate(rect.width()/2, 0.0, zOffset); - capMatrix.rotate((1-frontDesktop)*360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); + capMatrix.translate(rect.width() / 2, 0.0, zOffset); + capMatrix.rotate((1 - frontDesktop) * 360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); capMatrix.translate(0.0, rect.height(), 0.0); if (mode == Sphere) { capMatrix.scale(1.0, -1.0, 1.0); @@ -815,7 +759,7 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) m_capShader->setUniform("u_opacity", opacity); m_capShader->setUniform("u_mirror", 1); if (reflectionPainting) { - m_capShader->setUniform("screenTransformation", m_reflectionMatrix*m_rotationMatrix); + m_capShader->setUniform("screenTransformation", m_reflectionMatrix * m_rotationMatrix); } else { m_capShader->setUniform("screenTransformation", m_rotationMatrix); } @@ -824,41 +768,40 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) capTexture->bind(); } } else { - pushMatrix(m_rotationMatrix*capMatrix); + pushMatrix(m_rotationMatrix * capMatrix); #ifndef KWIN_HAVE_OPENGLES - glMatrixMode( GL_TEXTURE ); + glMatrixMode(GL_TEXTURE); #endif pushMatrix(); loadMatrix(m_textureMirrorMatrix); #ifndef KWIN_HAVE_OPENGLES - glMatrixMode( GL_MODELVIEW ); + glMatrixMode(GL_MODELVIEW); - glColor4f( capColor.redF(), capColor.greenF(), capColor.blueF(), cubeOpacity ); - if( texturedCaps && effects->numberOfDesktops() > 3 && capTexture ) - { + glColor4f(capColor.redF(), capColor.greenF(), capColor.blueF(), cubeOpacity); + if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { // modulate the cap texture: cap color should be background for translucent pixels // cube opacity should be used for all pixels // blend with cap color float color[4] = { capColor.redF(), capColor.greenF(), capColor.blueF(), cubeOpacity }; - glActiveTexture( GL_TEXTURE0 ); + glActiveTexture(GL_TEXTURE0); capTexture->bind(); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); - glColor4fv( color ); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); + glColor4fv(color); // set Opacity to cube opacity // TODO: change opacity during start/stop animation - glActiveTexture( GL_TEXTURE1 ); + glActiveTexture(GL_TEXTURE1); capTexture->bind(); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE ); - glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE ); - glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS ); - glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); - glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_CONSTANT ); - glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color ); - glActiveTexture( GL_TEXTURE0 ); - glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color ); - } + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_CONSTANT); + glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color); + glActiveTexture(GL_TEXTURE0); + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color); + } #endif } @@ -875,12 +818,12 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) m_capShader->setUniform("u_mirror", 0); } else { #ifndef KWIN_HAVE_OPENGLES - glMatrixMode( GL_TEXTURE ); + glMatrixMode(GL_TEXTURE); popMatrix(); - glMatrixMode( GL_MODELVIEW ); + glMatrixMode(GL_MODELVIEW); #endif popMatrix(); - pushMatrix(m_rotationMatrix*capMatrix); + pushMatrix(m_rotationMatrix * capMatrix); } glCullFace(secondCull); m_cubeCapBuffer->render(GL_TRIANGLES); @@ -893,60 +836,55 @@ void CubeEffect::paintCap(bool frontFirst, float zOffset) } } else { popMatrix(); - if( texturedCaps && effects->numberOfDesktops() > 3 && capTexture ) - { + if (texturedCaps && effects->numberOfDesktops() > 3 && capTexture) { #ifndef KWIN_HAVE_OPENGLES - glActiveTexture( GL_TEXTURE1 ); - glDisable( capTexture->target() ); - glActiveTexture( GL_TEXTURE0 ); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); - glColor4f( 0.0f, 0.0f, 0.0f, 0.0f ); + glActiveTexture(GL_TEXTURE1); + glDisable(capTexture->target()); + glActiveTexture(GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glColor4f(0.0f, 0.0f, 0.0f, 0.0f); capTexture->unbind(); #endif - } - } + } } +} void CubeEffect::paintCubeCap() - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float z = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); - float zTexture = rect.width()/2*tan(45.0f*M_PI/180.0f); - float angle = 360.0f/effects->numberOfDesktops(); +{ + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float z = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); + float zTexture = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); + float angle = 360.0f / effects->numberOfDesktops(); bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; - for( int i=0; inumberOfDesktops(); i++ ) - { - int triangleRows = effects->numberOfDesktops()*5; - float zTriangleDistance = z/(float)triangleRows; - float widthTriangle = tan( angle*0.5 * M_PI/180.0 ) * zTriangleDistance; + for (int i = 0; i < effects->numberOfDesktops(); i++) { + int triangleRows = effects->numberOfDesktops() * 5; + float zTriangleDistance = z / (float)triangleRows; + float widthTriangle = tan(angle * 0.5 * M_PI / 180.0) * zTriangleDistance; float currentWidth = 0.0; - float cosValue = cos( i*angle * M_PI/180.0 ); - float sinValue = sin( i*angle * M_PI/180.0 ); - for( int j=0; jsetData(verts.count()/3, 3, verts.constData(), texture ? texCoords.constData() : NULL); - } + m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); +} void CubeEffect::paintCylinderCap() - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); +{ + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); - float radian = (cubeAngle*0.5)*M_PI/180; - float radius = (rect.width()*0.5)*tan(radian); - float segment = radius/30.0f; + float radian = (cubeAngle * 0.5) * M_PI / 180; + float radius = (rect.width() * 0.5) * tan(radian); + float segment = radius / 30.0f; bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; - for( int i=1; i<=30; i++ ) - { + for (int i = 1; i <= 30; i++) { int steps = 72; - for( int j=0; j<=steps; j++ ) - { - const float azimuthAngle = (j*(360.0f/steps))*M_PI/180.0f; - const float azimuthAngle2 = ((j+1)*(360.0f/steps))*M_PI/180.0f; - const float x1 = segment*(i-1) * sin( azimuthAngle ); - const float x2 = segment*i * sin( azimuthAngle ); - const float x3 = segment*(i-1) * sin( azimuthAngle2 ); - const float x4 = segment*i * sin( azimuthAngle2 ); - const float z1 = segment*(i-1) * cos( azimuthAngle ); - const float z2 = segment*i * cos( azimuthAngle ); - const float z3 = segment*(i-1) * cos( azimuthAngle2 ); - const float z4 = segment*i * cos( azimuthAngle2 ); - if (texture) { - texCoords << (radius+x1)/(radius*2.0f) << 1.0f - (z1+radius)/(radius*2.0f); - texCoords << (radius+x2)/(radius*2.0f) << 1.0f - (z2+radius)/(radius*2.0f); - texCoords << (radius+x3)/(radius*2.0f) << 1.0f - (z3+radius)/(radius*2.0f); - texCoords << (radius+x4)/(radius*2.0f) << 1.0f - (z4+radius)/(radius*2.0f); - texCoords << (radius+x3)/(radius*2.0f) << 1.0f - (z3+radius)/(radius*2.0f); - texCoords << (radius+x2)/(radius*2.0f) << 1.0f - (z2+radius)/(radius*2.0f); + for (int j = 0; j <= steps; j++) { + const float azimuthAngle = (j * (360.0f / steps)) * M_PI / 180.0f; + const float azimuthAngle2 = ((j + 1) * (360.0f / steps)) * M_PI / 180.0f; + const float x1 = segment * (i - 1) * sin(azimuthAngle); + const float x2 = segment * i * sin(azimuthAngle); + const float x3 = segment * (i - 1) * sin(azimuthAngle2); + const float x4 = segment * i * sin(azimuthAngle2); + const float z1 = segment * (i - 1) * cos(azimuthAngle); + const float z2 = segment * i * cos(azimuthAngle); + const float z3 = segment * (i - 1) * cos(azimuthAngle2); + const float z4 = segment * i * cos(azimuthAngle2); + if (texture) { + texCoords << (radius + x1) / (radius * 2.0f) << 1.0f - (z1 + radius) / (radius * 2.0f); + texCoords << (radius + x2) / (radius * 2.0f) << 1.0f - (z2 + radius) / (radius * 2.0f); + texCoords << (radius + x3) / (radius * 2.0f) << 1.0f - (z3 + radius) / (radius * 2.0f); + texCoords << (radius + x4) / (radius * 2.0f) << 1.0f - (z4 + radius) / (radius * 2.0f); + texCoords << (radius + x3) / (radius * 2.0f) << 1.0f - (z3 + radius) / (radius * 2.0f); + texCoords << (radius + x2) / (radius * 2.0f) << 1.0f - (z2 + radius) / (radius * 2.0f); } verts << x1 << 0.0 << z1; verts << x2 << 0.0 << z2; @@ -1059,49 +990,47 @@ void CubeEffect::paintCylinderCap() verts << x4 << 0.0 << z4; verts << x3 << 0.0 << z3; verts << x2 << 0.0 << z2; - } } + } delete m_cubeCapBuffer; m_cubeCapBuffer = new GLVertexBuffer(GLVertexBuffer::Static); - m_cubeCapBuffer->setData(verts.count()/3, 3, verts.constData(), texture ? texCoords.constData() : NULL); - } + m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); +} void CubeEffect::paintSphereCap() - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float zTexture = rect.width()/2*tan(45.0f*M_PI/180.0f); - float radius = (rect.width()*0.5)/cos(cubeAngle*0.5*M_PI/180.0); - float angle = acos( (rect.height()*0.5)/radius )*180.0/M_PI; +{ + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float zTexture = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); + float radius = (rect.width() * 0.5) / cos(cubeAngle * 0.5 * M_PI / 180.0); + float angle = acos((rect.height() * 0.5) / radius) * 180.0 / M_PI; angle /= 30; bool texture = texturedCaps && effects->numberOfDesktops() > 3 && capTexture; QVector verts; QVector texCoords; - for( int i=0; i<30; i++ ) - { - float topAngle = angle*i*M_PI/180.0; - float bottomAngle = angle*(i+1)*M_PI/180.0; - float yTop = rect.height()*0.5 - radius * cos( topAngle ); - yTop -= (yTop-rect.height()*0.5)*capDeformationFactor; - float yBottom = rect.height()*0.5 -radius * cos( bottomAngle ); - yBottom -= (yBottom-rect.height()*0.5)*capDeformationFactor; - for( int j=0; j<36; j++ ) - { - const float x1 = radius * sin( topAngle ) * sin( (90.0+j*10.0)*M_PI/180.0 ); - const float z1 = radius * sin( topAngle ) * cos( (90.0+j*10.0)*M_PI/180.0 ); - const float x2 = radius * sin( bottomAngle ) * sin( (90.0+j*10.0)*M_PI/180.00 ); - const float z2 = radius * sin( bottomAngle ) * cos( (90.0+j*10.0)*M_PI/180.0 ); - const float x3 = radius * sin( bottomAngle ) * sin( (90.0+(j+1)*10.0)*M_PI/180.0 ); - const float z3 = radius * sin( bottomAngle ) * cos( (90.0+(j+1)*10.0)*M_PI/180.0 ); - const float x4 = radius * sin( topAngle ) * sin( (90.0+(j+1)*10.0)*M_PI/180.0 ); - const float z4 = radius * sin( topAngle ) * cos( (90.0+(j+1)*10.0)*M_PI/180.0 ); + for (int i = 0; i < 30; i++) { + float topAngle = angle * i * M_PI / 180.0; + float bottomAngle = angle * (i + 1) * M_PI / 180.0; + float yTop = rect.height() * 0.5 - radius * cos(topAngle); + yTop -= (yTop - rect.height() * 0.5) * capDeformationFactor; + float yBottom = rect.height() * 0.5 - radius * cos(bottomAngle); + yBottom -= (yBottom - rect.height() * 0.5) * capDeformationFactor; + for (int j = 0; j < 36; j++) { + const float x1 = radius * sin(topAngle) * sin((90.0 + j * 10.0) * M_PI / 180.0); + const float z1 = radius * sin(topAngle) * cos((90.0 + j * 10.0) * M_PI / 180.0); + const float x2 = radius * sin(bottomAngle) * sin((90.0 + j * 10.0) * M_PI / 180.00); + const float z2 = radius * sin(bottomAngle) * cos((90.0 + j * 10.0) * M_PI / 180.0); + const float x3 = radius * sin(bottomAngle) * sin((90.0 + (j + 1) * 10.0) * M_PI / 180.0); + const float z3 = radius * sin(bottomAngle) * cos((90.0 + (j + 1) * 10.0) * M_PI / 180.0); + const float x4 = radius * sin(topAngle) * sin((90.0 + (j + 1) * 10.0) * M_PI / 180.0); + const float z4 = radius * sin(topAngle) * cos((90.0 + (j + 1) * 10.0) * M_PI / 180.0); if (texture) { - texCoords << x4/(rect.width())+0.5 << 0.5 - z4/zTexture * 0.5; - texCoords << x1/(rect.width())+0.5 << 0.5 - z1/zTexture * 0.5; - texCoords << x2/(rect.width())+0.5 << 0.5 - z2/zTexture * 0.5; - texCoords << x2/(rect.width())+0.5 << 0.5 - z2/zTexture * 0.5; - texCoords << x3/(rect.width())+0.5 << 0.5 - z3/zTexture * 0.5; - texCoords << x4/(rect.width())+0.5 << 0.5 - z4/zTexture * 0.5; + texCoords << x4 / (rect.width()) + 0.5 << 0.5 - z4 / zTexture * 0.5; + texCoords << x1 / (rect.width()) + 0.5 << 0.5 - z1 / zTexture * 0.5; + texCoords << x2 / (rect.width()) + 0.5 << 0.5 - z2 / zTexture * 0.5; + texCoords << x2 / (rect.width()) + 0.5 << 0.5 - z2 / zTexture * 0.5; + texCoords << x3 / (rect.width()) + 0.5 << 0.5 - z3 / zTexture * 0.5; + texCoords << x4 / (rect.width()) + 0.5 << 0.5 - z4 / zTexture * 0.5; } verts << x4 << yTop << z4; verts << x1 << yTop << z1; @@ -1109,325 +1038,271 @@ void CubeEffect::paintSphereCap() verts << x2 << yBottom << z2; verts << x3 << yBottom << z3; verts << x4 << yTop << z4; - } } + } delete m_cubeCapBuffer; m_cubeCapBuffer = new GLVertexBuffer(GLVertexBuffer::Static); - m_cubeCapBuffer->setData(verts.count()/3, 3, verts.constData(), texture ? texCoords.constData() : NULL); - } + m_cubeCapBuffer->setData(verts.count() / 3, 3, verts.constData(), texture ? texCoords.constData() : NULL); +} void CubeEffect::postPaintScreen() - { +{ effects->postPaintScreen(); - if( activated ) - { - if( start ) - { - if( timeLine.value() == 1.0 ) - { + if (activated) { + if (start) { + if (timeLine.value() == 1.0) { start = false; timeLine.setProgress(0.0); // more rotations? - if( !rotations.empty() ) - { + if (!rotations.empty()) { rotationDirection = rotations.dequeue(); rotating = true; // change the curve shape if current shape is not easeInOut - if( currentShape != TimeLine::EaseInOutCurve ) - { + if (currentShape != TimeLine::EaseInOutCurve) { // more rotations follow -> linear curve - if( !rotations.empty() ) - { + if (!rotations.empty()) { currentShape = TimeLine::LinearCurve; - } - // last rotation step -> easeOut curve - else - { - currentShape = TimeLine::EaseOutCurve; - } - timeLine.setCurveShape( currentShape ); } - else - { + // last rotation step -> easeOut curve + else { + currentShape = TimeLine::EaseOutCurve; + } + timeLine.setCurveShape(currentShape); + } else { // if there is at least one more rotation, we can change to easeIn - if( !rotations.empty() ) - { + if (!rotations.empty()) { currentShape = TimeLine::EaseInCurve; - timeLine.setCurveShape( currentShape ); - } + timeLine.setCurveShape(currentShape); } } } + } effects->addRepaintFull(); return; // schedule_close could have been called, start has to finish first - } - if( stop ) - { - if( timeLine.value() == 1.0 ) - { - effects->setCurrentDesktop( frontDesktop ); + } + if (stop) { + if (timeLine.value() == 1.0) { + effects->setCurrentDesktop(frontDesktop); stop = false; timeLine.setProgress(0.0); activated = false; // set the new desktop - if( keyboard_grab ) + if (keyboard_grab) effects->ungrabKeyboard(); keyboard_grab = false; - effects->destroyInputWindow( input ); + effects->destroyInputWindow(input); - effects->setActiveFullScreenEffect( 0 ); + effects->setActiveFullScreenEffect(0); delete m_cubeCapBuffer; m_cubeCapBuffer = NULL; desktopNameFrame->free(); - } - effects->addRepaintFull(); } - if( rotating || verticalRotating ) - { - if( rotating && timeLine.value() == 1.0 ) - { + effects->addRepaintFull(); + } + if (rotating || verticalRotating) { + if (rotating && timeLine.value() == 1.0) { timeLine.setProgress(0.0); rotating = false; desktopChangedWhileRotating = false; manualAngle = 0.0; // more rotations? - if( !rotations.empty() ) - { + if (!rotations.empty()) { rotationDirection = rotations.dequeue(); rotating = true; // change the curve shape if current shape is not easeInOut - if( currentShape != TimeLine::EaseInOutCurve ) - { + if (currentShape != TimeLine::EaseInOutCurve) { // more rotations follow -> linear curve - if( !rotations.empty() ) - { + if (!rotations.empty()) { currentShape = TimeLine::LinearCurve; - } - // last rotation step -> easeOut curve - else - { - currentShape = TimeLine::EaseOutCurve; - } - timeLine.setCurveShape( currentShape ); } - else - { + // last rotation step -> easeOut curve + else { + currentShape = TimeLine::EaseOutCurve; + } + timeLine.setCurveShape(currentShape); + } else { // if there is at least one more rotation, we can change to easeIn - if( !rotations.empty() ) - { + if (!rotations.empty()) { currentShape = TimeLine::EaseInCurve; - timeLine.setCurveShape( currentShape ); - } + timeLine.setCurveShape(currentShape); } } - else - { + } else { // reset curve shape if there are no more rotations - if( currentShape != TimeLine::EaseInOutCurve ) - { + if (currentShape != TimeLine::EaseInOutCurve) { currentShape = TimeLine::EaseInOutCurve; - timeLine.setCurveShape( currentShape ); - } + timeLine.setCurveShape(currentShape); } } - if( verticalRotating && verticalTimeLine.value() == 1.0 ) - { + } + if (verticalRotating && verticalTimeLine.value() == 1.0) { verticalTimeLine.setProgress(0.0); verticalRotating = false; manualVerticalAngle = 0.0; // more rotations? - if( !verticalRotations.empty() ) - { + if (!verticalRotations.empty()) { verticalRotationDirection = verticalRotations.dequeue(); verticalRotating = true; - if( verticalRotationDirection == Upwards ) - { - if( verticalPosition == Normal ) + if (verticalRotationDirection == Upwards) { + if (verticalPosition == Normal) verticalPosition = Up; - if( verticalPosition == Down ) + if (verticalPosition == Down) verticalPosition = Normal; - } - if( verticalRotationDirection == Downwards ) - { - if( verticalPosition == Normal ) + } + if (verticalRotationDirection == Downwards) { + if (verticalPosition == Normal) verticalPosition = Down; - if( verticalPosition == Up ) + if (verticalPosition == Up) verticalPosition = Normal; - } } } + } effects->addRepaintFull(); return; // rotation has to end before cube is closed - } - if( schedule_close ) - { + } + if (schedule_close) { schedule_close = false; stop = true; effects->addRepaintFull(); - } } } +} -void CubeEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( activated ) - { - if( cube_painting ) - { - if( mode == Cylinder || mode == Sphere ) - { - int leftDesktop = frontDesktop -1; +void CubeEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (activated) { + if (cube_painting) { + if (mode == Cylinder || mode == Sphere) { + int leftDesktop = frontDesktop - 1; int rightDesktop = frontDesktop + 1; - if( leftDesktop == 0 ) + if (leftDesktop == 0) leftDesktop = effects->numberOfDesktops(); - if( rightDesktop > effects->numberOfDesktops() ) + if (rightDesktop > effects->numberOfDesktops()) rightDesktop = 1; - if( painting_desktop == frontDesktop ) - data.quads = data.quads.makeGrid( 40 ); - else if( painting_desktop == leftDesktop || painting_desktop == rightDesktop ) - data.quads = data.quads.makeGrid( 100 ); + if (painting_desktop == frontDesktop) + data.quads = data.quads.makeGrid(40); + else if (painting_desktop == leftDesktop || painting_desktop == rightDesktop) + data.quads = data.quads.makeGrid(100); else - data.quads = data.quads.makeGrid( 250 ); + data.quads = data.quads.makeGrid(250); + } + if (w->isOnDesktop(painting_desktop)) { + QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); + if (w->x() < rect.x()) { + data.quads = data.quads.splitAtX(-w->x()); } - if( w->isOnDesktop( painting_desktop )) - { - QRect rect = effects->clientArea( FullArea, activeScreen, painting_desktop ); - if( w->x() < rect.x() ) - { - data.quads = data.quads.splitAtX( -w->x() ); - } - if( w->x() + w->width() > rect.x() + rect.width() ) - { - data.quads = data.quads.splitAtX( rect.width() - w->x() ); - } - if( w->y() < rect.y() ) - { - data.quads = data.quads.splitAtY( -w->y() ); - } - if( w->y() + w->height() > rect.y() + rect.height() ) - { - data.quads = data.quads.splitAtY( rect.height() - w->y() ); - } - if( useZOrdering && !w->isDesktop() && !w->isDock() && !w->isOnAllDesktops() ) + if (w->x() + w->width() > rect.x() + rect.width()) { + data.quads = data.quads.splitAtX(rect.width() - w->x()); + } + if (w->y() < rect.y()) { + data.quads = data.quads.splitAtY(-w->y()); + } + if (w->y() + w->height() > rect.y() + rect.height()) { + data.quads = data.quads.splitAtY(rect.height() - w->y()); + } + if (useZOrdering && !w->isDesktop() && !w->isDock() && !w->isOnAllDesktops()) data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - else - { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else { // check for windows belonging to the previous desktop - int prev_desktop = painting_desktop -1; - if( prev_desktop == 0 ) + int prev_desktop = painting_desktop - 1; + if (prev_desktop == 0) prev_desktop = effects->numberOfDesktops(); - if( w->isOnDesktop( prev_desktop ) && mode == Cube && !useZOrdering ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, prev_desktop); - if( w->x()+w->width() > rect.x() + rect.width() ) - { - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - data.quads = data.quads.splitAtX( rect.width() - w->x() ); - if( w->y() < rect.y() ) - { - data.quads = data.quads.splitAtY( -w->y() ); - } - if( w->y() + w->height() > rect.y() + rect.height() ) - { - data.quads = data.quads.splitAtY( rect.height() - w->y() ); - } - data.setTransformed(); - effects->prePaintWindow( w, data, time ); - return; + if (w->isOnDesktop(prev_desktop) && mode == Cube && !useZOrdering) { + QRect rect = effects->clientArea(FullArea, activeScreen, prev_desktop); + if (w->x() + w->width() > rect.x() + rect.width()) { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + data.quads = data.quads.splitAtX(rect.width() - w->x()); + if (w->y() < rect.y()) { + data.quads = data.quads.splitAtY(-w->y()); } - } - // check for windows belonging to the next desktop - int next_desktop = painting_desktop +1; - if( next_desktop > effects->numberOfDesktops() ) - next_desktop = 1; - if( w->isOnDesktop( next_desktop ) && mode == Cube && !useZOrdering ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, next_desktop); - if( w->x() < rect.x() ) - { - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - data.quads = data.quads.splitAtX( -w->x() ); - if( w->y() < rect.y() ) - { - data.quads = data.quads.splitAtY( -w->y() ); - } - if( w->y() + w->height() > rect.y() + rect.height() ) - { - data.quads = data.quads.splitAtY( rect.height() - w->y() ); - } - data.setTransformed(); - effects->prePaintWindow( w, data, time ); - return; + if (w->y() + w->height() > rect.y() + rect.height()) { + data.quads = data.quads.splitAtY(rect.height() - w->y()); } + data.setTransformed(); + effects->prePaintWindow(w, data, time); + return; } - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); } + // check for windows belonging to the next desktop + int next_desktop = painting_desktop + 1; + if (next_desktop > effects->numberOfDesktops()) + next_desktop = 1; + if (w->isOnDesktop(next_desktop) && mode == Cube && !useZOrdering) { + QRect rect = effects->clientArea(FullArea, activeScreen, next_desktop); + if (w->x() < rect.x()) { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + data.quads = data.quads.splitAtX(-w->x()); + if (w->y() < rect.y()) { + data.quads = data.quads.splitAtY(-w->y()); + } + if (w->y() + w->height() > rect.y() + rect.height()) { + data.quads = data.quads.splitAtY(rect.height() - w->y()); + } + data.setTransformed(); + effects->prePaintWindow(w, data, time); + return; + } + } + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void CubeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void CubeEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ ShaderManager *shaderManager = ShaderManager::instance(); GLShader *shader = shaderManager->pushShader(ShaderManager::GenericShader); QMatrix4x4 origMatrix; - if( activated && cube_painting ) - { + if (activated && cube_painting) { //kDebug(1212) << w->caption(); float opacity = cubeOpacity; - if( start ) - { - opacity = 1.0 - (1.0 - opacity)*timeLine.value(); - if( reflectionPainting ) - opacity = 0.5 + ( cubeOpacity - 0.5 )*timeLine.value(); + if (start) { + opacity = 1.0 - (1.0 - opacity) * timeLine.value(); + if (reflectionPainting) + opacity = 0.5 + (cubeOpacity - 0.5) * timeLine.value(); // fade in windows belonging to different desktops - if( painting_desktop == effects->currentDesktop() && (!w->isOnDesktop( painting_desktop )) ) + if (painting_desktop == effects->currentDesktop() && (!w->isOnDesktop(painting_desktop))) opacity = timeLine.value() * cubeOpacity; - } - if( stop ) - { - opacity = 1.0 - (1.0 - opacity)*( 1.0 - timeLine.value() ); - if( reflectionPainting ) - opacity = 0.5 + ( cubeOpacity - 0.5 )*( 1.0 - timeLine.value() ); + } + if (stop) { + opacity = 1.0 - (1.0 - opacity) * (1.0 - timeLine.value()); + if (reflectionPainting) + opacity = 0.5 + (cubeOpacity - 0.5) * (1.0 - timeLine.value()); // fade out windows belonging to different desktops - if( painting_desktop == effects->currentDesktop() && (!w->isOnDesktop( painting_desktop )) ) + if (painting_desktop == effects->currentDesktop() && (!w->isOnDesktop(painting_desktop))) opacity = cubeOpacity * (1.0 - timeLine.value()); - } + } // z-Ordering - if( !w->isDesktop() && !w->isDock() && useZOrdering && !w->isOnAllDesktops() ) - { - float zOrdering = (effects->stackingOrder().indexOf( w )+1)*zOrderingFactor; - if( start ) + if (!w->isDesktop() && !w->isDock() && useZOrdering && !w->isOnAllDesktops()) { + float zOrdering = (effects->stackingOrder().indexOf(w) + 1) * zOrderingFactor; + if (start) zOrdering *= timeLine.value(); - if( stop ) + if (stop) zOrdering *= (1.0 - timeLine.value()); data.zTranslate += zOrdering; - } + } // check for windows belonging to the previous desktop - int prev_desktop = painting_desktop -1; - if( prev_desktop == 0 ) + int prev_desktop = painting_desktop - 1; + if (prev_desktop == 0) prev_desktop = effects->numberOfDesktops(); - int next_desktop = painting_desktop +1; - if( next_desktop > effects->numberOfDesktops() ) + int next_desktop = painting_desktop + 1; + if (next_desktop > effects->numberOfDesktops()) next_desktop = 1; if (!shader) { pushMatrix(); } - if( w->isOnDesktop( prev_desktop ) && ( mask & PAINT_WINDOW_TRANSFORMED ) ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, prev_desktop); + if (w->isOnDesktop(prev_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { + QRect rect = effects->clientArea(FullArea, activeScreen, prev_desktop); WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() > rect.width() - w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() > rect.width() - w->x()) { + new_quads.append(quad); } + } data.quads = new_quads; if (shader) { data.xTranslate = -rect.width(); @@ -1437,26 +1312,23 @@ void CubeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowP rot.xRotationPoint = rect.width() - w->x(); rot.angle = 360.0f / effects->numberOfDesktops(); data.rotation = &rot; - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float point = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); QMatrix4x4 matrix; - matrix.translate(rect.width()/2, 0.0, -point); + matrix.translate(rect.width() / 2, 0.0, -point); matrix.rotate(-360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); - matrix.translate(-rect.width()/2, 0.0, point); + matrix.translate(-rect.width() / 2, 0.0, point); multiplyMatrix(matrix); } - } - if( w->isOnDesktop( next_desktop ) && ( mask & PAINT_WINDOW_TRANSFORMED ) ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, next_desktop); + } + if (w->isOnDesktop(next_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { + QRect rect = effects->clientArea(FullArea, activeScreen, next_desktop); WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( w->x() + quad.right() <= rect.x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (w->x() + quad.right() <= rect.x()) { + new_quads.append(quad); } + } data.quads = new_quads; if (shader) { data.xTranslate = rect.width(); @@ -1466,127 +1338,111 @@ void CubeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowP rot.xRotationPoint = -w->x(); rot.angle = -360.0f / effects->numberOfDesktops(); data.rotation = &rot; - float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 180.0f); - float point = rect.width()/2*tan(cubeAngle*0.5f*M_PI/180.0f); + float cubeAngle = (float)((float)(effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 180.0f); + float point = rect.width() / 2 * tan(cubeAngle * 0.5f * M_PI / 180.0f); QMatrix4x4 matrix; - matrix.translate(rect.width()/2, 0.0, -point); + matrix.translate(rect.width() / 2, 0.0, -point); matrix.rotate(360.0f / effects->numberOfDesktops(), 0.0, 1.0, 0.0); - matrix.translate(-rect.width()/2, 0.0, point); + matrix.translate(-rect.width() / 2, 0.0, point); multiplyMatrix(matrix); } - } - QRect rect = effects->clientArea( FullArea, activeScreen, painting_desktop ); + } + QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); - if( start || stop ) - { + if (start || stop) { // we have to change opacity values for fade in/out of windows which are shown on front-desktop - if( prev_desktop == effects->currentDesktop() && w->x() < rect.x() ) - { - if( start ) + if (prev_desktop == effects->currentDesktop() && w->x() < rect.x()) { + if (start) opacity = timeLine.value() * cubeOpacity; - if( stop ) + if (stop) opacity = cubeOpacity * (1.0 - timeLine.value()); - } - if( next_desktop == effects->currentDesktop() && w->x() + w->width() > rect.x() + rect.width() ) - { - if( start ) - opacity = timeLine.value() * cubeOpacity; - if( stop ) - opacity = cubeOpacity * (1.0 - timeLine.value()); - } } + if (next_desktop == effects->currentDesktop() && w->x() + w->width() > rect.x() + rect.width()) { + if (start) + opacity = timeLine.value() * cubeOpacity; + if (stop) + opacity = cubeOpacity * (1.0 - timeLine.value()); + } + } // HACK set opacity to 0.99 in case of fully opaque to ensure that windows are painted in correct sequence // bug #173214 - if( opacity > 0.99f ) + if (opacity > 0.99f) opacity = 0.99f; - if( opacityDesktopOnly && !w->isDesktop() ) + if (opacityDesktopOnly && !w->isDesktop()) opacity = 0.99f; data.opacity *= opacity; - if( w->isOnDesktop(painting_desktop) && w->x() < rect.x() ) - { + if (w->isOnDesktop(painting_desktop) && w->x() < rect.x()) { WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() > -w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() > -w->x()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->isOnDesktop(painting_desktop) && w->x() + w->width() > rect.x() + rect.width() ) - { + data.quads = new_quads; + } + if (w->isOnDesktop(painting_desktop) && w->x() + w->width() > rect.x() + rect.width()) { WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() <= rect.width() - w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() <= rect.width() - w->x()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->y() < rect.y() ) - { + data.quads = new_quads; + } + if (w->y() < rect.y()) { WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() > -w->y() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() > -w->y()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->y() + w->height() > rect.y() + rect.height() ) - { + data.quads = new_quads; + } + if (w->y() + w->height() > rect.y() + rect.height()) { WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() <= rect.height() - w->y() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() <= rect.height() - w->y()) { + new_quads.append(quad); } - data.quads = new_quads; } + data.quads = new_quads; + } if (shader) { origMatrix = shader->getUniformMatrix4x4("screenTransformation"); if (mode == Cylinder) { shaderManager->pushShader(cylinderShader); - cylinderShader->setUniform( "xCoord", (float)w->x() ); - cylinderShader->setUniform( "cubeAngle", (effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 90.0f ); + cylinderShader->setUniform("xCoord", (float)w->x()); + cylinderShader->setUniform("cubeAngle", (effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 90.0f); float factor = 0.0f; - if( start ) + if (start) factor = 1.0f - timeLine.value(); - if( stop ) + if (stop) factor = timeLine.value(); - cylinderShader->setUniform( "timeLine", factor ); + cylinderShader->setUniform("timeLine", factor); data.shader = cylinderShader; } if (mode == Sphere) { shaderManager->pushShader(sphereShader); - sphereShader->setUniform( "u_offset", QVector2D(w->x(), w->y())); - sphereShader->setUniform( "cubeAngle", (effects->numberOfDesktops() - 2 )/(float)effects->numberOfDesktops() * 90.0f ); + sphereShader->setUniform("u_offset", QVector2D(w->x(), w->y())); + sphereShader->setUniform("cubeAngle", (effects->numberOfDesktops() - 2) / (float)effects->numberOfDesktops() * 90.0f); float factor = 0.0f; - if( start ) + if (start) factor = 1.0f - timeLine.value(); - if( stop ) + if (stop) factor = timeLine.value(); - sphereShader->setUniform( "timeLine", factor ); + sphereShader->setUniform("timeLine", factor); data.shader = sphereShader; } if (reflectionPainting) { - shader->setUniform("screenTransformation", m_reflectionMatrix*m_rotationMatrix*origMatrix); + shader->setUniform("screenTransformation", m_reflectionMatrix * m_rotationMatrix * origMatrix); } else { - shader->setUniform("screenTransformation", m_rotationMatrix*origMatrix); + shader->setUniform("screenTransformation", m_rotationMatrix * origMatrix); } } - } - effects->paintWindow( w, mask, region, data ); - if( activated && cube_painting ) - { + } + effects->paintWindow(w, mask, region, data); + if (activated && cube_painting) { if (shader) { if (mode == Cylinder || mode == Sphere) { shaderManager->popShader(); @@ -1595,679 +1451,582 @@ void CubeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowP } shaderManager->popShader(); } - if( w->isDesktop() && effects->numScreens() > 1 && paintCaps ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, painting_desktop ); - QRegion paint = QRegion( rect ); - for( int i=0; inumScreens(); i++ ) - { - if( i == w->screen() ) + if (w->isDesktop() && effects->numScreens() > 1 && paintCaps) { + QRect rect = effects->clientArea(FullArea, activeScreen, painting_desktop); + QRegion paint = QRegion(rect); + for (int i = 0; i < effects->numScreens(); i++) { + if (i == w->screen()) continue; - paint = paint.subtracted( QRegion( effects->clientArea( ScreenArea, i, painting_desktop ))); - } - paint = paint.subtracted( QRegion( w->geometry())); + paint = paint.subtracted(QRegion(effects->clientArea(ScreenArea, i, painting_desktop))); + } + paint = paint.subtracted(QRegion(w->geometry())); // in case of free area in multiscreen setup fill it with cap color - if( !paint.isEmpty() ) - { + if (!paint.isEmpty()) { #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); QVector verts; float quadSize = 0.0f; - int leftDesktop = frontDesktop -1; + int leftDesktop = frontDesktop - 1; int rightDesktop = frontDesktop + 1; - if( leftDesktop == 0 ) + if (leftDesktop == 0) leftDesktop = effects->numberOfDesktops(); - if( rightDesktop > effects->numberOfDesktops() ) + if (rightDesktop > effects->numberOfDesktops()) rightDesktop = 1; - if( painting_desktop == frontDesktop ) + if (painting_desktop == frontDesktop) quadSize = 100.0f; - else if( painting_desktop == leftDesktop || painting_desktop == rightDesktop ) + else if (painting_desktop == leftDesktop || painting_desktop == rightDesktop) quadSize = 150.0f; else quadSize = 250.0f; - foreach( const QRect &paintRect, paint.rects() ) - { - for( int i=0; i<=(paintRect.height()/quadSize); i++ ) - { - for( int j=0; j<=(paintRect.width()/quadSize); j++ ) - { - verts << qMin( paintRect.x()+(j+1)*quadSize, (float)paintRect.x() + paintRect.width() ) << paintRect.y()+i*quadSize; - verts << paintRect.x()+j*quadSize << paintRect.y()+i*quadSize; - verts << paintRect.x()+j*quadSize << qMin( paintRect.y() + (i+1)*quadSize, (float)paintRect.y() + paintRect.height() ); - verts << paintRect.x()+j*quadSize << qMin( paintRect.y() + (i+1)*quadSize, (float)paintRect.y() + paintRect.height() ); - verts << qMin( paintRect.x()+(j+1)*quadSize, (float)paintRect.x() + paintRect.width() ) << qMin( paintRect.y() + (i+1)*quadSize, (float)paintRect.y() + paintRect.height() ); - verts << qMin( paintRect.x()+(j+1)*quadSize, (float)paintRect.x() + paintRect.width() ) << paintRect.y()+i*quadSize; - } + foreach (const QRect & paintRect, paint.rects()) { + for (int i = 0; i <= (paintRect.height() / quadSize); i++) { + for (int j = 0; j <= (paintRect.width() / quadSize); j++) { + verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << paintRect.y() + i*quadSize; + verts << paintRect.x() + j*quadSize << paintRect.y() + i*quadSize; + verts << paintRect.x() + j*quadSize << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); + verts << paintRect.x() + j*quadSize << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); + verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << qMin(paintRect.y() + (i + 1)*quadSize, (float)paintRect.y() + paintRect.height()); + verts << qMin(paintRect.x() + (j + 1)*quadSize, (float)paintRect.x() + paintRect.width()) << paintRect.y() + i*quadSize; } } + } GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); QColor color = capColor; capColor.setAlphaF(cubeOpacity); // TODO: use sphere and cylinder shaders vbo->setColor(color); - vbo->setData(verts.size()/2, 2, verts.constData(), NULL); + vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_TRIANGLES); - glDisable( GL_BLEND ); + glDisable(GL_BLEND); #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif - } } + } if (!shader) { popMatrix(); } - } } +} -bool CubeEffect::borderActivated( ElectricBorder border ) - { - if( !borderActivate.contains( border ) && - !borderActivateCylinder.contains( border ) && - !borderActivateSphere.contains( border ) ) +bool CubeEffect::borderActivated(ElectricBorder border) +{ + if (!borderActivate.contains(border) && + !borderActivateCylinder.contains(border) && + !borderActivateSphere.contains(border)) return false; - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return false; - if( borderActivate.contains( border ) ) - { - if( !activated || ( activated && mode == Cube ) ) + if (borderActivate.contains(border)) { + if (!activated || (activated && mode == Cube)) toggleCube(); else return false; - } - if( borderActivateCylinder.contains( border ) ) - { - if( !activated || ( activated && mode == Cylinder ) ) + } + if (borderActivateCylinder.contains(border)) { + if (!activated || (activated && mode == Cylinder)) toggleCylinder(); else return false; - } - if( borderActivateSphere.contains( border ) ) - { - if( !activated || ( activated && mode == Sphere ) ) + } + if (borderActivateSphere.contains(border)) { + if (!activated || (activated && mode == Sphere)) toggleSphere(); else return false; - } - return true; } + return true; +} void CubeEffect::toggleCube() - { +{ kDebug(1212) << "toggle cube"; - toggle( Cube ); - } + toggle(Cube); +} void CubeEffect::toggleCylinder() - { +{ kDebug(1212) << "toggle cylinder"; - if( !useShaders ) + if (!useShaders) useShaders = loadShader(); - if( useShaders ) - toggle( Cylinder ); + if (useShaders) + toggle(Cylinder); else - kError( 1212 ) << "Sorry shaders are not available - cannot activate Cylinder"; - } + kError(1212) << "Sorry shaders are not available - cannot activate Cylinder"; +} void CubeEffect::toggleSphere() - { +{ kDebug(1212) << "toggle sphere"; - if( !useShaders ) + if (!useShaders) useShaders = loadShader(); - if( useShaders ) - toggle( Sphere ); + if (useShaders) + toggle(Sphere); else - kError( 1212 ) << "Sorry shaders are not available - cannot activate Sphere"; - } + kError(1212) << "Sorry shaders are not available - cannot activate Sphere"; +} -void CubeEffect::toggle( CubeMode newMode ) - { - if( ( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) || - effects->numberOfDesktops() < 2 ) +void CubeEffect::toggle(CubeMode newMode) +{ + if ((effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) || + effects->numberOfDesktops() < 2) return; - if( !activated ) - { + if (!activated) { mode = newMode; - setActive( true ); - } - else - { - setActive( false ); - } + setActive(true); + } else { + setActive(false); } +} -void CubeEffect::grabbedKeyboardEvent( QKeyEvent* e ) - { - if( stop ) +void CubeEffect::grabbedKeyboardEvent(QKeyEvent* e) +{ + if (stop) return; // taken from desktopgrid.cpp - if( e->type() == QEvent::KeyPress ) - { + if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) - if( mode == Cube && cubeShortcut.contains( e->key() + e->modifiers() ) ) - { + if (mode == Cube && cubeShortcut.contains(e->key() + e->modifiers())) { toggleCube(); return; - } - if( mode == Cylinder && cylinderShortcut.contains( e->key() + e->modifiers() ) ) - { + } + if (mode == Cylinder && cylinderShortcut.contains(e->key() + e->modifiers())) { toggleCylinder(); return; - } - if( mode == Sphere && sphereShortcut.contains( e->key() + e->modifiers() ) ) - { + } + if (mode == Sphere && sphereShortcut.contains(e->key() + e->modifiers())) { toggleSphere(); return; - } + } int desktop = -1; // switch by F or just - if( e->key() >= Qt::Key_F1 && e->key() <= Qt::Key_F35 ) + if (e->key() >= Qt::Key_F1 && e->key() <= Qt::Key_F35) desktop = e->key() - Qt::Key_F1 + 1; - else if( e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9 ) + else if (e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9) desktop = e->key() == Qt::Key_0 ? 10 : e->key() - Qt::Key_0; - if( desktop != -1 ) - { - if( desktop <= effects->numberOfDesktops()) - { + if (desktop != -1) { + if (desktop <= effects->numberOfDesktops()) { // we have to rotate to chosen desktop // and end effect when rotation finished - rotateToDesktop( desktop ); - setActive( false ); - } + rotateToDesktop(desktop); + setActive(false); + } return; - } - switch( e->key()) - { // wrap only on autorepeat - case Qt::Key_Left: - // rotate to previous desktop - kDebug(1212) << "left"; - if( !rotating && !start ) - { - rotating = true; - if( invertKeys ) - rotationDirection = Right; - else - rotationDirection = Left; - } - else - { - if( rotations.count() < effects->numberOfDesktops() ) - { - if( invertKeys ) - rotations.enqueue( Right ); - else - rotations.enqueue( Left ); - } - } - break; - case Qt::Key_Right: - // rotate to next desktop - kDebug(1212) << "right"; - if( !rotating && !start ) - { - rotating = true; - if( invertKeys ) - rotationDirection = Left; - else - rotationDirection = Right; - } - else - { - if( rotations.count() < effects->numberOfDesktops() ) - { - if( invertKeys ) - rotations.enqueue( Left ); - else - rotations.enqueue( Right ); - } - } - break; - case Qt::Key_Up: - kDebug(1212) << "up"; - if( invertKeys ) - { - if( verticalPosition != Down ) - { - if( !verticalRotating ) - { - verticalRotating = true; - verticalRotationDirection = Downwards; - if( verticalPosition == Normal ) - verticalPosition = Down; - if( verticalPosition == Up ) - verticalPosition = Normal; - } - else - { - verticalRotations.enqueue( Downwards ); - } - } - else if( manualVerticalAngle > 0.0 && !verticalRotating ) - { - // rotate to down position from the manual position - verticalRotating = true; - verticalRotationDirection = Downwards; - verticalPosition = Down; - manualVerticalAngle -= 90.0; - } - } - else - { - if( verticalPosition != Up ) - { - if( !verticalRotating ) - { - verticalRotating = true; - verticalRotationDirection = Upwards; - if( verticalPosition == Normal ) - verticalPosition = Up; - if( verticalPosition == Down ) - verticalPosition = Normal; - } - else - { - verticalRotations.enqueue( Upwards ); - } - } - else if( manualVerticalAngle < 0.0 && !verticalRotating ) - { - // rotate to up position from the manual position - verticalRotating = true; - verticalRotationDirection = Upwards; - verticalPosition = Up; - manualVerticalAngle += 90.0; - } - } - break; - case Qt::Key_Down: - kDebug(1212) << "down"; - if( invertKeys ) - { - if( verticalPosition != Up ) - { - if( !verticalRotating ) - { - verticalRotating = true; - verticalRotationDirection = Upwards; - if( verticalPosition == Normal ) - verticalPosition = Up; - if( verticalPosition == Down ) - verticalPosition = Normal; - } - else - { - verticalRotations.enqueue( Upwards ); - } - } - else if( manualVerticalAngle < 0.0 && !verticalRotating ) - { - // rotate to up position from the manual position - verticalRotating = true; - verticalRotationDirection = Upwards; - verticalPosition = Up; - manualVerticalAngle += 90.0; - } - } - else - { - if( verticalPosition != Down ) - { - if( !verticalRotating ) - { - verticalRotating = true; - verticalRotationDirection = Downwards; - if( verticalPosition == Normal ) - verticalPosition = Down; - if( verticalPosition == Up ) - verticalPosition = Normal; - } - else - { - verticalRotations.enqueue( Downwards ); - } - } - else if( manualVerticalAngle > 0.0 && !verticalRotating ) - { - // rotate to down position from the manual position - verticalRotating = true; - verticalRotationDirection = Downwards; - verticalPosition = Down; - manualVerticalAngle -= 90.0; - } - } - break; - case Qt::Key_Escape: - rotateToDesktop( effects->currentDesktop() ); - setActive( false ); - return; - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_Space: - setActive( false ); - return; - case Qt::Key_Plus: - zoom -= 10.0; - zoom = qMax( -zPosition, zoom ); - rotateCube(); - break; - case Qt::Key_Minus: - zoom += 10.0f; - rotateCube(); - break; - default: - break; - } - effects->addRepaintFull(); } + switch(e->key()) { + // wrap only on autorepeat + case Qt::Key_Left: + // rotate to previous desktop + kDebug(1212) << "left"; + if (!rotating && !start) { + rotating = true; + if (invertKeys) + rotationDirection = Right; + else + rotationDirection = Left; + } else { + if (rotations.count() < effects->numberOfDesktops()) { + if (invertKeys) + rotations.enqueue(Right); + else + rotations.enqueue(Left); + } + } + break; + case Qt::Key_Right: + // rotate to next desktop + kDebug(1212) << "right"; + if (!rotating && !start) { + rotating = true; + if (invertKeys) + rotationDirection = Left; + else + rotationDirection = Right; + } else { + if (rotations.count() < effects->numberOfDesktops()) { + if (invertKeys) + rotations.enqueue(Left); + else + rotations.enqueue(Right); + } + } + break; + case Qt::Key_Up: + kDebug(1212) << "up"; + if (invertKeys) { + if (verticalPosition != Down) { + if (!verticalRotating) { + verticalRotating = true; + verticalRotationDirection = Downwards; + if (verticalPosition == Normal) + verticalPosition = Down; + if (verticalPosition == Up) + verticalPosition = Normal; + } else { + verticalRotations.enqueue(Downwards); + } + } else if (manualVerticalAngle > 0.0 && !verticalRotating) { + // rotate to down position from the manual position + verticalRotating = true; + verticalRotationDirection = Downwards; + verticalPosition = Down; + manualVerticalAngle -= 90.0; + } + } else { + if (verticalPosition != Up) { + if (!verticalRotating) { + verticalRotating = true; + verticalRotationDirection = Upwards; + if (verticalPosition == Normal) + verticalPosition = Up; + if (verticalPosition == Down) + verticalPosition = Normal; + } else { + verticalRotations.enqueue(Upwards); + } + } else if (manualVerticalAngle < 0.0 && !verticalRotating) { + // rotate to up position from the manual position + verticalRotating = true; + verticalRotationDirection = Upwards; + verticalPosition = Up; + manualVerticalAngle += 90.0; + } + } + break; + case Qt::Key_Down: + kDebug(1212) << "down"; + if (invertKeys) { + if (verticalPosition != Up) { + if (!verticalRotating) { + verticalRotating = true; + verticalRotationDirection = Upwards; + if (verticalPosition == Normal) + verticalPosition = Up; + if (verticalPosition == Down) + verticalPosition = Normal; + } else { + verticalRotations.enqueue(Upwards); + } + } else if (manualVerticalAngle < 0.0 && !verticalRotating) { + // rotate to up position from the manual position + verticalRotating = true; + verticalRotationDirection = Upwards; + verticalPosition = Up; + manualVerticalAngle += 90.0; + } + } else { + if (verticalPosition != Down) { + if (!verticalRotating) { + verticalRotating = true; + verticalRotationDirection = Downwards; + if (verticalPosition == Normal) + verticalPosition = Down; + if (verticalPosition == Up) + verticalPosition = Normal; + } else { + verticalRotations.enqueue(Downwards); + } + } else if (manualVerticalAngle > 0.0 && !verticalRotating) { + // rotate to down position from the manual position + verticalRotating = true; + verticalRotationDirection = Downwards; + verticalPosition = Down; + manualVerticalAngle -= 90.0; + } + } + break; + case Qt::Key_Escape: + rotateToDesktop(effects->currentDesktop()); + setActive(false); + return; + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Space: + setActive(false); + return; + case Qt::Key_Plus: + zoom -= 10.0; + zoom = qMax(-zPosition, zoom); + rotateCube(); + break; + case Qt::Key_Minus: + zoom += 10.0f; + rotateCube(); + break; + default: + break; + } + effects->addRepaintFull(); } +} -void CubeEffect::rotateToDesktop( int desktop ) - { +void CubeEffect::rotateToDesktop(int desktop) +{ int tempFrontDesktop = frontDesktop; - if( !rotations.empty() ) - { + if (!rotations.empty()) { // all scheduled rotations will be removed as a speed up rotations.clear(); - } - if( rotating && !desktopChangedWhileRotating ) - { + } + if (rotating && !desktopChangedWhileRotating) { // front desktop will change during the actual rotation - this has to be considered - if( rotationDirection == Left ) - { + if (rotationDirection == Left) { tempFrontDesktop++; - } - else if( rotationDirection == Right ) - { + } else if (rotationDirection == Right) { tempFrontDesktop--; - } - if( tempFrontDesktop > effects->numberOfDesktops() ) - tempFrontDesktop = 1; - else if( tempFrontDesktop == 0 ) - tempFrontDesktop = effects->numberOfDesktops(); } + if (tempFrontDesktop > effects->numberOfDesktops()) + tempFrontDesktop = 1; + else if (tempFrontDesktop == 0) + tempFrontDesktop = effects->numberOfDesktops(); + } // find the fastest rotation path from tempFrontDesktop to desktop int rightRotations = tempFrontDesktop - desktop; - if( rightRotations < 0 ) + if (rightRotations < 0) rightRotations += effects->numberOfDesktops(); int leftRotations = desktop - tempFrontDesktop; - if( leftRotations < 0 ) + if (leftRotations < 0) leftRotations += effects->numberOfDesktops(); - if( leftRotations <= rightRotations ) - { - for( int i=0; isetActive( true ); - } - if( active ) - { - if( !mousePolling ) - { +void CubeEffect::setActive(bool active) +{ + foreach (CubeInsideEffect * inside, m_cubeInsideEffects) { + inside->setActive(true); + } + if (active) { + if (!mousePolling) { effects->startMousePolling(); mousePolling = true; - } + } activated = true; activeScreen = effects->activeScreen(); - keyboard_grab = effects->grabKeyboard( this ); - input = effects->createInputWindow( this, 0, 0, displayWidth(), displayHeight(), - Qt::OpenHandCursor ); + keyboard_grab = effects->grabKeyboard(this); + input = effects->createInputWindow(this, 0, 0, displayWidth(), displayHeight(), + Qt::OpenHandCursor); frontDesktop = effects->currentDesktop(); zoom = 0.0; - zOrderingFactor = zPosition / ( effects->stackingOrder().count() - 1 ); + zOrderingFactor = zPosition / (effects->stackingOrder().count() - 1); start = true; - effects->setActiveFullScreenEffect( this ); + effects->setActiveFullScreenEffect(this); kDebug(1212) << "Cube is activated"; verticalPosition = Normal; verticalRotating = false; manualAngle = 0.0; manualVerticalAngle = 0.0; - if( reflection ) - { - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop()); + if (reflection) { + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); #ifndef KWIN_HAVE_OPENGLES // clip parts above the reflection area double eqn[4] = {0.0, 1.0, 0.0, 0.0}; glPushMatrix(); - glTranslatef( 0.0, rect.height(), 0.0 ); - glClipPlane( GL_CLIP_PLANE0, eqn ); + glTranslatef(0.0, rect.height(), 0.0); + glClipPlane(GL_CLIP_PLANE0, eqn); glPopMatrix(); #endif - float temporaryCoeff = float( rect.width() ) / tan( M_PI / float( effects->numberOfDesktops() ) ); - mAddedHeightCoeff1 = sqrt( float( rect.height() ) * float( rect.height() ) + temporaryCoeff * temporaryCoeff ); - mAddedHeightCoeff2 = sqrt( float( rect.height() ) * float( rect.height() ) + float( rect.width() ) * float( rect.width() ) + temporaryCoeff * temporaryCoeff ); - } + float temporaryCoeff = float(rect.width()) / tan(M_PI / float(effects->numberOfDesktops())); + mAddedHeightCoeff1 = sqrt(float(rect.height()) * float(rect.height()) + temporaryCoeff * temporaryCoeff); + mAddedHeightCoeff2 = sqrt(float(rect.height()) * float(rect.height()) + float(rect.width()) * float(rect.width()) + temporaryCoeff * temporaryCoeff); + } m_rotationMatrix.setToIdentity(); effects->addRepaintFull(); - } - else - { - if( mousePolling ) - { + } else { + if (mousePolling) { effects->stopMousePolling(); mousePolling = false; - } + } schedule_close = true; // we have to add a repaint, to start the deactivating effects->addRepaintFull(); - } } +} -void CubeEffect::mouseChanged( const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, - Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers, Qt::KeyboardModifiers ) - { - if( !activated ) +void CubeEffect::mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, + Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers, Qt::KeyboardModifiers) +{ + if (!activated) return; - if( tabBoxMode ) + if (tabBoxMode) return; - if( stop ) + if (stop) return; - QRect rect = effects->clientArea( FullArea, activeScreen, effects->currentDesktop() ); - if( buttons.testFlag( Qt::LeftButton ) ) - { + QRect rect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); + if (buttons.testFlag(Qt::LeftButton)) { bool repaint = false; // vertical movement only if there is not a rotation - if( !verticalRotating ) - { + if (!verticalRotating) { // display height corresponds to 180* int deltaY = pos.y() - oldpos.y(); - float deltaVerticalDegrees = (float)deltaY/rect.height()*180.0f; - if( invertMouse ) + float deltaVerticalDegrees = (float)deltaY / rect.height() * 180.0f; + if (invertMouse) manualVerticalAngle += deltaVerticalDegrees; else manualVerticalAngle -= deltaVerticalDegrees; - if( deltaVerticalDegrees != 0.0 ) + if (deltaVerticalDegrees != 0.0) repaint = true; - } + } // horizontal movement only if there is not a rotation - if( !rotating ) - { + if (!rotating) { // display width corresponds to sum of angles of the polyhedron int deltaX = oldpos.x() - pos.x(); - float deltaDegrees = (float)deltaX/rect.width() * 360.0f; - if( deltaX == 0 ) - { - if( pos.x() == 0 ) + float deltaDegrees = (float)deltaX / rect.width() * 360.0f; + if (deltaX == 0) { + if (pos.x() == 0) deltaDegrees = 5.0f; - if( pos.x() == displayWidth() -1 ) + if (pos.x() == displayWidth() - 1) deltaDegrees = -5.0f; - } - if( invertMouse ) + } + if (invertMouse) manualAngle += deltaDegrees; else manualAngle -= deltaDegrees; - if( deltaDegrees != 0.0 ) + if (deltaDegrees != 0.0) repaint = true; - } - if( repaint ) - { + } + if (repaint) { rotateCube(); effects->addRepaintFull(); - } } - if( !oldbuttons.testFlag( Qt::LeftButton ) && buttons.testFlag( Qt::LeftButton ) ) - { - XDefineCursor( display(), input, QCursor( Qt::ClosedHandCursor).handle() ); - } - if( oldbuttons.testFlag( Qt::LeftButton) && !buttons.testFlag( Qt::LeftButton ) ) - { - XDefineCursor( display(), input, QCursor( Qt::OpenHandCursor).handle() ); - if( closeOnMouseRelease ) - setActive( false ); - } - if( oldbuttons.testFlag( Qt::RightButton) && !buttons.testFlag( Qt::RightButton ) ) - { + } + if (!oldbuttons.testFlag(Qt::LeftButton) && buttons.testFlag(Qt::LeftButton)) { + XDefineCursor(display(), input, QCursor(Qt::ClosedHandCursor).handle()); + } + if (oldbuttons.testFlag(Qt::LeftButton) && !buttons.testFlag(Qt::LeftButton)) { + XDefineCursor(display(), input, QCursor(Qt::OpenHandCursor).handle()); + if (closeOnMouseRelease) + setActive(false); + } + if (oldbuttons.testFlag(Qt::RightButton) && !buttons.testFlag(Qt::RightButton)) { // end effect on right mouse button - setActive( false ); - } + setActive(false); } +} -void CubeEffect::windowInputMouseEvent( Window w, QEvent* e ) - { - assert( w == input ); - Q_UNUSED( w ); - QMouseEvent *mouse = dynamic_cast< QMouseEvent* >( e ); - if( mouse && mouse->type() == QEvent::MouseButtonRelease ) - { - if( mouse->button() == Qt::XButton1 ) - { - if( !rotating && !start ) - { +void CubeEffect::windowInputMouseEvent(Window w, QEvent* e) +{ + assert(w == input); + Q_UNUSED(w); + QMouseEvent *mouse = dynamic_cast< QMouseEvent* >(e); + if (mouse && mouse->type() == QEvent::MouseButtonRelease) { + if (mouse->button() == Qt::XButton1) { + if (!rotating && !start) { rotating = true; - if( invertMouse ) + if (invertMouse) rotationDirection = Right; else rotationDirection = Left; - } - else - { - if( rotations.count() < effects->numberOfDesktops() ) - { - if( invertMouse ) - rotations.enqueue( Right ); + } else { + if (rotations.count() < effects->numberOfDesktops()) { + if (invertMouse) + rotations.enqueue(Right); else - rotations.enqueue( Left ); - } + rotations.enqueue(Left); } - effects->addRepaintFull(); } - if( mouse->button() == Qt::XButton2 ) - { - if( !rotating && !start ) - { + effects->addRepaintFull(); + } + if (mouse->button() == Qt::XButton2) { + if (!rotating && !start) { rotating = true; - if( invertMouse ) + if (invertMouse) rotationDirection = Left; else rotationDirection = Right; - } - else - { - if( rotations.count() < effects->numberOfDesktops() ) - { - if( invertMouse ) - rotations.enqueue( Left ); + } else { + if (rotations.count() < effects->numberOfDesktops()) { + if (invertMouse) + rotations.enqueue(Left); else - rotations.enqueue( Right ); - } + rotations.enqueue(Right); } - effects->addRepaintFull(); } + effects->addRepaintFull(); } } +} -void CubeEffect::tabBoxAdded( int mode ) - { - if( activated ) +void CubeEffect::tabBoxAdded(int mode) +{ + if (activated) return; - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - if( useForTabBox && mode == TabBoxDesktopListMode ) - { + if (useForTabBox && mode == TabBoxDesktopListMode) { effects->refTabBox(); tabBoxMode = true; - setActive( true ); - rotateToDesktop( effects->currentTabBoxDesktop() ); - } + setActive(true); + rotateToDesktop(effects->currentTabBoxDesktop()); } +} void CubeEffect::tabBoxUpdated() - { - if( activated ) - { - rotateToDesktop( effects->currentTabBoxDesktop() ); +{ + if (activated) { + rotateToDesktop(effects->currentTabBoxDesktop()); effects->addRepaintFull(); - } } +} void CubeEffect::tabBoxClosed() - { - if( activated ) - { +{ + if (activated) { effects->unrefTabBox(); tabBoxMode = false; - setActive( false ); - } + setActive(false); } +} -void CubeEffect::cubeShortcutChanged( const QKeySequence& seq ) - { - cubeShortcut = KShortcut( seq ); - } +void CubeEffect::cubeShortcutChanged(const QKeySequence& seq) +{ + cubeShortcut = KShortcut(seq); +} -void CubeEffect::cylinderShortcutChanged( const QKeySequence& seq ) - { - cylinderShortcut = KShortcut( seq ); - } +void CubeEffect::cylinderShortcutChanged(const QKeySequence& seq) +{ + cylinderShortcut = KShortcut(seq); +} -void CubeEffect::sphereShortcutChanged( const QKeySequence& seq ) - { - sphereShortcut = KShortcut( seq ); - } +void CubeEffect::sphereShortcutChanged(const QKeySequence& seq) +{ + sphereShortcut = KShortcut(seq); +} void* CubeEffect::proxy() - { +{ return &m_proxy; - } +} void CubeEffect::registerCubeInsideEffect(CubeInsideEffect* effect) - { - m_cubeInsideEffects.append( effect ); - } +{ + m_cubeInsideEffects.append(effect); +} void CubeEffect::unregisterCubeInsideEffect(CubeInsideEffect* effect) - { - m_cubeInsideEffects.removeAll( effect ); - } +{ + m_cubeInsideEffects.removeAll(effect); +} } // namespace diff --git a/effects/cube/cube.h b/effects/cube/cube.h index 71c4bc321..a89764980 100644 --- a/effects/cube/cube.h +++ b/effects/cube/cube.h @@ -35,150 +35,147 @@ namespace KWin class CubeEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - CubeEffect(); - ~CubeEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual bool borderActivated( ElectricBorder border ); - virtual void grabbedKeyboardEvent( QKeyEvent* e ); - virtual void mouseChanged( const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, - Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - virtual void windowInputMouseEvent( Window w, QEvent* e ); - virtual void tabBoxAdded( int mode ); - virtual void tabBoxUpdated(); - virtual void tabBoxClosed(); +public: + CubeEffect(); + ~CubeEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual bool borderActivated(ElectricBorder border); + virtual void grabbedKeyboardEvent(QKeyEvent* e); + virtual void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, + Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); + virtual void windowInputMouseEvent(Window w, QEvent* e); + virtual void tabBoxAdded(int mode); + virtual void tabBoxUpdated(); + virtual void tabBoxClosed(); - // proxy functions - virtual void* proxy(); - void registerCubeInsideEffect( CubeInsideEffect* effect ); - void unregisterCubeInsideEffect( CubeInsideEffect* effect ); + // proxy functions + virtual void* proxy(); + void registerCubeInsideEffect(CubeInsideEffect* effect); + void unregisterCubeInsideEffect(CubeInsideEffect* effect); - static bool supported(); - private slots: - void toggleCube(); - void toggleCylinder(); - void toggleSphere(); - // slots for global shortcut changed - // needed to toggle the effect - void cubeShortcutChanged( const QKeySequence& seq ); - void cylinderShortcutChanged( const QKeySequence& seq ); - void sphereShortcutChanged( const QKeySequence& seq ); - private: - enum RotationDirection - { - Left, - Right, - Upwards, - Downwards - }; - enum VerticalRotationPosition - { - Up, - Normal, - Down - }; - enum CubeMode - { - Cube, - Cylinder, - Sphere - }; - void toggle( CubeMode newMode = Cube ); - void paintCube( int mask, QRegion region, ScreenPaintData& data ); - void paintCap(bool frontFirst, float zOffset); - void paintCubeCap(); - void paintCylinderCap(); - void paintSphereCap(); - bool loadShader(); - void loadConfig( QString config ); - void rotateCube(); - void rotateToDesktop( int desktop ); - void setActive( bool active ); - bool activated; - bool mousePolling; - bool cube_painting; - bool keyboard_grab; - bool schedule_close; - QList borderActivate; - QList borderActivateCylinder; - QList borderActivateSphere; - int painting_desktop; - Window input; - int frontDesktop; - float cubeOpacity; - bool opacityDesktopOnly; - bool displayDesktopName; - EffectFrame* desktopNameFrame; - QFont desktopNameFont; - bool reflection; - bool rotating; - bool verticalRotating; - bool desktopChangedWhileRotating; - bool paintCaps; - TimeLine timeLine; - TimeLine verticalTimeLine; - RotationDirection rotationDirection; - RotationDirection verticalRotationDirection; - VerticalRotationPosition verticalPosition; - QQueue rotations; - QQueue verticalRotations; - QColor backgroundColor; - QColor capColor; - GLTexture* wallpaper; - bool texturedCaps; - GLTexture* capTexture; - float manualAngle; - float manualVerticalAngle; - TimeLine::CurveShape currentShape; - bool start; - bool stop; - bool reflectionPainting; - int rotationDuration; - int activeScreen; - bool bottomCap; - bool closeOnMouseRelease; - float zoom; - float zPosition; - bool useForTabBox; - bool invertKeys; - bool invertMouse; - bool tabBoxMode; - bool shortcutsRegistered; - CubeMode mode; - bool useShaders; - GLShader* cylinderShader; - GLShader* sphereShader; - GLShader* m_reflectionShader; - GLShader* m_capShader; - float capDeformationFactor; - bool useZOrdering; - float zOrderingFactor; - bool useList; - // needed for reflection - float mAddedHeightCoeff1; - float mAddedHeightCoeff2; - - QMatrix4x4 m_rotationMatrix; - QMatrix4x4 m_reflectionMatrix; - QMatrix4x4 m_textureMirrorMatrix; - GLVertexBuffer *m_cubeCapBuffer; - - // Shortcuts - needed to toggle the effect - KShortcut cubeShortcut; - KShortcut cylinderShortcut; - KShortcut sphereShortcut; - - // proxy - CubeEffectProxy m_proxy; - QList< CubeInsideEffect* > m_cubeInsideEffects; + static bool supported(); +private slots: + void toggleCube(); + void toggleCylinder(); + void toggleSphere(); + // slots for global shortcut changed + // needed to toggle the effect + void cubeShortcutChanged(const QKeySequence& seq); + void cylinderShortcutChanged(const QKeySequence& seq); + void sphereShortcutChanged(const QKeySequence& seq); +private: + enum RotationDirection { + Left, + Right, + Upwards, + Downwards }; + enum VerticalRotationPosition { + Up, + Normal, + Down + }; + enum CubeMode { + Cube, + Cylinder, + Sphere + }; + void toggle(CubeMode newMode = Cube); + void paintCube(int mask, QRegion region, ScreenPaintData& data); + void paintCap(bool frontFirst, float zOffset); + void paintCubeCap(); + void paintCylinderCap(); + void paintSphereCap(); + bool loadShader(); + void loadConfig(QString config); + void rotateCube(); + void rotateToDesktop(int desktop); + void setActive(bool active); + bool activated; + bool mousePolling; + bool cube_painting; + bool keyboard_grab; + bool schedule_close; + QList borderActivate; + QList borderActivateCylinder; + QList borderActivateSphere; + int painting_desktop; + Window input; + int frontDesktop; + float cubeOpacity; + bool opacityDesktopOnly; + bool displayDesktopName; + EffectFrame* desktopNameFrame; + QFont desktopNameFont; + bool reflection; + bool rotating; + bool verticalRotating; + bool desktopChangedWhileRotating; + bool paintCaps; + TimeLine timeLine; + TimeLine verticalTimeLine; + RotationDirection rotationDirection; + RotationDirection verticalRotationDirection; + VerticalRotationPosition verticalPosition; + QQueue rotations; + QQueue verticalRotations; + QColor backgroundColor; + QColor capColor; + GLTexture* wallpaper; + bool texturedCaps; + GLTexture* capTexture; + float manualAngle; + float manualVerticalAngle; + TimeLine::CurveShape currentShape; + bool start; + bool stop; + bool reflectionPainting; + int rotationDuration; + int activeScreen; + bool bottomCap; + bool closeOnMouseRelease; + float zoom; + float zPosition; + bool useForTabBox; + bool invertKeys; + bool invertMouse; + bool tabBoxMode; + bool shortcutsRegistered; + CubeMode mode; + bool useShaders; + GLShader* cylinderShader; + GLShader* sphereShader; + GLShader* m_reflectionShader; + GLShader* m_capShader; + float capDeformationFactor; + bool useZOrdering; + float zOrderingFactor; + bool useList; + // needed for reflection + float mAddedHeightCoeff1; + float mAddedHeightCoeff2; + + QMatrix4x4 m_rotationMatrix; + QMatrix4x4 m_reflectionMatrix; + QMatrix4x4 m_textureMirrorMatrix; + GLVertexBuffer *m_cubeCapBuffer; + + // Shortcuts - needed to toggle the effect + KShortcut cubeShortcut; + KShortcut cylinderShortcut; + KShortcut sphereShortcut; + + // proxy + CubeEffectProxy m_proxy; + QList< CubeInsideEffect* > m_cubeInsideEffects; +}; } // namespace diff --git a/effects/cube/cube_config.cpp b/effects/cube/cube_config.cpp index 4ee2e4886..9b6b803b4 100644 --- a/effects/cube/cube_config.cpp +++ b/effects/cube/cube_config.cpp @@ -35,39 +35,39 @@ KWIN_EFFECT_CONFIG_FACTORY CubeEffectConfigForm::CubeEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } CubeEffectConfig::CubeEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new CubeEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(m_ui); - m_ui->tabWidget->setTabText( 0, i18nc("@title:tab Basic Settings", "Basic") ); - m_ui->tabWidget->setTabText( 1, i18nc("@title:tab Advanced Settings", "Advanced") ); + m_ui->tabWidget->setTabText(0, i18nc("@title:tab Basic Settings", "Basic")); + m_ui->tabWidget->setTabText(1, i18nc("@title:tab Advanced Settings", "Advanced")); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); - m_actionCollection->setConfigGroup( "Cube" ); + m_actionCollection->setConfigGroup("Cube"); m_actionCollection->setConfigGlobal(true); - KAction* cubeAction = (KAction*) m_actionCollection->addAction( "Cube" ); - cubeAction->setText( i18n("Desktop Cube" )); + KAction* cubeAction = (KAction*) m_actionCollection->addAction("Cube"); + cubeAction->setText(i18n("Desktop Cube")); cubeAction->setProperty("isConfigurationAction", true); - cubeAction->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F11 )); - KAction* cylinderAction = (KAction*) m_actionCollection->addAction( "Cylinder" ); - cylinderAction->setText( i18n("Desktop Cylinder" )); + cubeAction->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F11)); + KAction* cylinderAction = (KAction*) m_actionCollection->addAction("Cylinder"); + cylinderAction->setText(i18n("Desktop Cylinder")); cylinderAction->setProperty("isConfigurationAction", true); - cylinderAction->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut); - KAction* sphereAction = (KAction*) m_actionCollection->addAction( "Sphere" ); - sphereAction->setText( i18n("Desktop Sphere" )); + cylinderAction->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); + KAction* sphereAction = (KAction*) m_actionCollection->addAction("Sphere"); + sphereAction->setText(i18n("Desktop Sphere")); sphereAction->setProperty("isConfigurationAction", true); - sphereAction->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut); + sphereAction->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); m_ui->editor->addCollection(m_actionCollection); @@ -94,166 +94,145 @@ CubeEffectConfig::CubeEffectConfig(QWidget* parent, const QVariantList& args) : connect(m_ui->zOrderingBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); load(); - } +} void CubeEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "Cube" ); + KConfigGroup conf = EffectsHandler::effectConfig("Cube"); - int duration = conf.readEntry( "RotationDuration", 0 ); - float opacity = conf.readEntry( "Opacity", 80 ); - bool desktopOpacityOnly = conf.readEntry( "OpacityDesktopOnly", false ); - bool desktopName = conf.readEntry( "DisplayDesktopName", true ); - bool reflection = conf.readEntry( "Reflection", true ); - QColor background = conf.readEntry( "BackgroundColor", QColor( Qt::black ) ); - QColor capColor = conf.readEntry( "CapColor", KColorScheme( QPalette::Active, KColorScheme::Window ).background().color() ); - bool texturedCaps = conf.readEntry( "TexturedCaps", true ); - bool caps = conf.readEntry( "Caps", true ); - bool closeOnMouseRelease = conf.readEntry( "CloseOnMouseRelease", false ); - bool walkThroughDesktop = conf.readEntry( "TabBox", false ); - m_ui->zPositionSlider->setValue( conf.readEntry( "ZPosition", 100 ) ); - m_ui->wallpaperRequester->setUrl( KUrl( conf.readEntry( "Wallpaper", "" ) )); - bool invertKeys = conf.readEntry( "InvertKeys", false ); - bool invertMouse = conf.readEntry( "InvertMouse", false ); - m_ui->capDeformationSlider->setValue( conf.readEntry( "CapDeformation", 0 ) ); - bool zOrdering = conf.readEntry( "ZOrdering", false ); + int duration = conf.readEntry("RotationDuration", 0); + float opacity = conf.readEntry("Opacity", 80); + bool desktopOpacityOnly = conf.readEntry("OpacityDesktopOnly", false); + bool desktopName = conf.readEntry("DisplayDesktopName", true); + bool reflection = conf.readEntry("Reflection", true); + QColor background = conf.readEntry("BackgroundColor", QColor(Qt::black)); + QColor capColor = conf.readEntry("CapColor", KColorScheme(QPalette::Active, KColorScheme::Window).background().color()); + bool texturedCaps = conf.readEntry("TexturedCaps", true); + bool caps = conf.readEntry("Caps", true); + bool closeOnMouseRelease = conf.readEntry("CloseOnMouseRelease", false); + bool walkThroughDesktop = conf.readEntry("TabBox", false); + m_ui->zPositionSlider->setValue(conf.readEntry("ZPosition", 100)); + m_ui->wallpaperRequester->setUrl(KUrl(conf.readEntry("Wallpaper", ""))); + bool invertKeys = conf.readEntry("InvertKeys", false); + bool invertMouse = conf.readEntry("InvertMouse", false); + m_ui->capDeformationSlider->setValue(conf.readEntry("CapDeformation", 0)); + bool zOrdering = conf.readEntry("ZOrdering", false); - m_ui->rotationDurationSpin->setValue( duration ); - m_ui->rotationDurationSpin->setSuffix( ki18np( " millisecond", " milliseconds" ) ); - m_ui->cubeOpacitySlider->setValue( opacity ); - m_ui->cubeOpacitySpin->setValue( opacity ); - m_ui->desktopOpacityOnlyBox->setChecked( desktopOpacityOnly ); - if( desktopName ) - { - m_ui->displayDesktopNameBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->displayDesktopNameBox->setCheckState( Qt::Unchecked ); - } - if( reflection ) - { - m_ui->reflectionBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->reflectionBox->setCheckState( Qt::Unchecked ); - } - if( caps ) - { - m_ui->cubeCapsBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->cubeCapsBox->setCheckState( Qt::Unchecked ); - } - if( texturedCaps ) - { - m_ui->capsImageBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->capsImageBox->setCheckState( Qt::Unchecked ); - } - if( closeOnMouseRelease ) - { - m_ui->closeOnMouseReleaseBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->closeOnMouseReleaseBox->setCheckState( Qt::Unchecked ); - } - if( walkThroughDesktop ) - { - m_ui->walkThroughDesktopBox->setCheckState( Qt::Checked ); - } - else - { - m_ui->walkThroughDesktopBox->setCheckState( Qt::Unchecked ); - } - m_ui->backgroundColorButton->setColor( background ); - m_ui->capColorButton->setColor( capColor ); - m_ui->invertKeysBox->setChecked( invertKeys ); - m_ui->invertMouseBox->setChecked( invertMouse ); - m_ui->zOrderingBox->setChecked( zOrdering ); + m_ui->rotationDurationSpin->setValue(duration); + m_ui->rotationDurationSpin->setSuffix(ki18np(" millisecond", " milliseconds")); + m_ui->cubeOpacitySlider->setValue(opacity); + m_ui->cubeOpacitySpin->setValue(opacity); + m_ui->desktopOpacityOnlyBox->setChecked(desktopOpacityOnly); + if (desktopName) { + m_ui->displayDesktopNameBox->setCheckState(Qt::Checked); + } else { + m_ui->displayDesktopNameBox->setCheckState(Qt::Unchecked); + } + if (reflection) { + m_ui->reflectionBox->setCheckState(Qt::Checked); + } else { + m_ui->reflectionBox->setCheckState(Qt::Unchecked); + } + if (caps) { + m_ui->cubeCapsBox->setCheckState(Qt::Checked); + } else { + m_ui->cubeCapsBox->setCheckState(Qt::Unchecked); + } + if (texturedCaps) { + m_ui->capsImageBox->setCheckState(Qt::Checked); + } else { + m_ui->capsImageBox->setCheckState(Qt::Unchecked); + } + if (closeOnMouseRelease) { + m_ui->closeOnMouseReleaseBox->setCheckState(Qt::Checked); + } else { + m_ui->closeOnMouseReleaseBox->setCheckState(Qt::Unchecked); + } + if (walkThroughDesktop) { + m_ui->walkThroughDesktopBox->setCheckState(Qt::Checked); + } else { + m_ui->walkThroughDesktopBox->setCheckState(Qt::Unchecked); + } + m_ui->backgroundColorButton->setColor(background); + m_ui->capColorButton->setColor(capColor); + m_ui->invertKeysBox->setChecked(invertKeys); + m_ui->invertMouseBox->setChecked(invertMouse); + m_ui->zOrderingBox->setChecked(zOrdering); capsSelectionChanged(); emit changed(false); - } +} void CubeEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "Cube" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("Cube"); - conf.writeEntry( "RotationDuration", m_ui->rotationDurationSpin->value() ); - conf.writeEntry( "DisplayDesktopName", m_ui->displayDesktopNameBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "Reflection", m_ui->reflectionBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "Opacity", m_ui->cubeOpacitySpin->value() ); - conf.writeEntry( "OpacityDesktopOnly", m_ui->desktopOpacityOnlyBox->isChecked() ); - conf.writeEntry( "BackgroundColor", m_ui->backgroundColorButton->color() ); - conf.writeEntry( "Caps", m_ui->cubeCapsBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "CapColor", m_ui->capColorButton->color() ); - conf.writeEntry( "TexturedCaps", m_ui->capsImageBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "CloseOnMouseRelease", m_ui->closeOnMouseReleaseBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "Wallpaper", m_ui->wallpaperRequester->url().path() ); - conf.writeEntry( "ZPosition", m_ui->zPositionSlider->value() ); - conf.writeEntry( "TabBox", m_ui->walkThroughDesktopBox->checkState() == Qt::Checked ? true : false ); - conf.writeEntry( "InvertKeys", m_ui->invertKeysBox->isChecked() ); - conf.writeEntry( "InvertMouse", m_ui->invertMouseBox->isChecked() ); - conf.writeEntry( "CapDeformation", m_ui->capDeformationSlider->value() ); - conf.writeEntry( "ZOrdering", m_ui->zOrderingBox->isChecked() ); + conf.writeEntry("RotationDuration", m_ui->rotationDurationSpin->value()); + conf.writeEntry("DisplayDesktopName", m_ui->displayDesktopNameBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("Reflection", m_ui->reflectionBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("Opacity", m_ui->cubeOpacitySpin->value()); + conf.writeEntry("OpacityDesktopOnly", m_ui->desktopOpacityOnlyBox->isChecked()); + conf.writeEntry("BackgroundColor", m_ui->backgroundColorButton->color()); + conf.writeEntry("Caps", m_ui->cubeCapsBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("CapColor", m_ui->capColorButton->color()); + conf.writeEntry("TexturedCaps", m_ui->capsImageBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("CloseOnMouseRelease", m_ui->closeOnMouseReleaseBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("Wallpaper", m_ui->wallpaperRequester->url().path()); + conf.writeEntry("ZPosition", m_ui->zPositionSlider->value()); + conf.writeEntry("TabBox", m_ui->walkThroughDesktopBox->checkState() == Qt::Checked ? true : false); + conf.writeEntry("InvertKeys", m_ui->invertKeysBox->isChecked()); + conf.writeEntry("InvertMouse", m_ui->invertMouseBox->isChecked()); + conf.writeEntry("CapDeformation", m_ui->capDeformationSlider->value()); + conf.writeEntry("ZOrdering", m_ui->zOrderingBox->isChecked()); m_ui->editor->save(); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "cube" ); - } + EffectsHandler::sendReloadMessage("cube"); +} void CubeEffectConfig::defaults() - { - m_ui->rotationDurationSpin->setValue( 0 ); - m_ui->displayDesktopNameBox->setCheckState( Qt::Checked ); - m_ui->reflectionBox->setCheckState( Qt::Checked ); - m_ui->cubeOpacitySpin->setValue( 80 ); - m_ui->cubeOpacitySlider->setValue( 80 ); - m_ui->desktopOpacityOnlyBox->setChecked( false ); - m_ui->backgroundColorButton->setColor( QColor( Qt::black ) ); - m_ui->cubeCapsBox->setCheckState( Qt::Checked ); - m_ui->capColorButton->setColor( KColorScheme( QPalette::Active, KColorScheme::Window ).background().color() ); - m_ui->capsImageBox->setCheckState( Qt::Checked ); - m_ui->closeOnMouseReleaseBox->setCheckState( Qt::Unchecked ); - m_ui->wallpaperRequester->setUrl( KUrl( "" )); - m_ui->zPositionSlider->setValue( 100 ); - m_ui->walkThroughDesktopBox->setCheckState( Qt::Unchecked ); - m_ui->invertKeysBox->setChecked( false ); - m_ui->invertMouseBox->setChecked( false ); - m_ui->capDeformationSlider->setValue( 0 ); - m_ui->zOrderingBox->setChecked( false ); +{ + m_ui->rotationDurationSpin->setValue(0); + m_ui->displayDesktopNameBox->setCheckState(Qt::Checked); + m_ui->reflectionBox->setCheckState(Qt::Checked); + m_ui->cubeOpacitySpin->setValue(80); + m_ui->cubeOpacitySlider->setValue(80); + m_ui->desktopOpacityOnlyBox->setChecked(false); + m_ui->backgroundColorButton->setColor(QColor(Qt::black)); + m_ui->cubeCapsBox->setCheckState(Qt::Checked); + m_ui->capColorButton->setColor(KColorScheme(QPalette::Active, KColorScheme::Window).background().color()); + m_ui->capsImageBox->setCheckState(Qt::Checked); + m_ui->closeOnMouseReleaseBox->setCheckState(Qt::Unchecked); + m_ui->wallpaperRequester->setUrl(KUrl("")); + m_ui->zPositionSlider->setValue(100); + m_ui->walkThroughDesktopBox->setCheckState(Qt::Unchecked); + m_ui->invertKeysBox->setChecked(false); + m_ui->invertMouseBox->setChecked(false); + m_ui->capDeformationSlider->setValue(0); + m_ui->zOrderingBox->setChecked(false); m_ui->editor->allDefault(); emit changed(true); - } +} void CubeEffectConfig::capsSelectionChanged() - { - if( m_ui->cubeCapsBox->checkState() == Qt::Checked ) - { +{ + if (m_ui->cubeCapsBox->checkState() == Qt::Checked) { // activate cap color - m_ui->capColorButton->setEnabled( true ); - m_ui->capColorLabel->setEnabled( true ); - m_ui->capsImageBox->setEnabled( true ); - } - else - { + m_ui->capColorButton->setEnabled(true); + m_ui->capColorLabel->setEnabled(true); + m_ui->capsImageBox->setEnabled(true); + } else { // deactivate cap color - m_ui->capColorButton->setEnabled( false ); - m_ui->capColorLabel->setEnabled( false ); - m_ui->capsImageBox->setEnabled( false ); - } - } + m_ui->capColorButton->setEnabled(false); + m_ui->capColorLabel->setEnabled(false); + m_ui->capsImageBox->setEnabled(false); + } +} } // namespace diff --git a/effects/cube/cube_config.h b/effects/cube/cube_config.h index 1beaea90a..8281f9a3f 100644 --- a/effects/cube/cube_config.h +++ b/effects/cube/cube_config.h @@ -32,27 +32,27 @@ namespace KWin class CubeEffectConfigForm : public QWidget, public Ui::CubeEffectConfigForm { Q_OBJECT - public: - explicit CubeEffectConfigForm(QWidget* parent); +public: + explicit CubeEffectConfigForm(QWidget* parent); }; class CubeEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit CubeEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit CubeEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private slots: - void capsSelectionChanged(); - private: - CubeEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private slots: + void capsSelectionChanged(); +private: + CubeEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/cube/cube_inside.h b/effects/cube/cube_inside.h index 9ab44b505..b3e4d906f 100644 --- a/effects/cube/cube_inside.h +++ b/effects/cube/cube_inside.h @@ -27,12 +27,12 @@ namespace KWin class CubeInsideEffect : public Effect { - public: - CubeInsideEffect() {} - virtual ~CubeInsideEffect() {} +public: + CubeInsideEffect() {} + virtual ~CubeInsideEffect() {} - virtual void paint() = 0; - virtual void setActive( bool active ) = 0; + virtual void paint() = 0; + virtual void setActive(bool active) = 0; }; } // namespace diff --git a/effects/cube/cube_proxy.cpp b/effects/cube/cube_proxy.cpp index 73f30deae..e573d5b31 100644 --- a/effects/cube/cube_proxy.cpp +++ b/effects/cube/cube_proxy.cpp @@ -25,23 +25,23 @@ along with this program. If not, see . namespace KWin { -CubeEffectProxy::CubeEffectProxy( CubeEffect* effect ) - : m_effect( effect ) - { - } +CubeEffectProxy::CubeEffectProxy(CubeEffect* effect) + : m_effect(effect) +{ +} CubeEffectProxy::~CubeEffectProxy() - { - } +{ +} -void CubeEffectProxy::registerCubeInsideEffect( CubeInsideEffect* effect ) - { - m_effect->registerCubeInsideEffect( effect ); - } +void CubeEffectProxy::registerCubeInsideEffect(CubeInsideEffect* effect) +{ + m_effect->registerCubeInsideEffect(effect); +} -void CubeEffectProxy::unregisterCubeInsideEffect( CubeInsideEffect* effect ) - { - m_effect->unregisterCubeInsideEffect( effect ); - } +void CubeEffectProxy::unregisterCubeInsideEffect(CubeInsideEffect* effect) +{ + m_effect->unregisterCubeInsideEffect(effect); +} } // namespace diff --git a/effects/cube/cube_proxy.h b/effects/cube/cube_proxy.h index e5ef09868..f28b9a41e 100644 --- a/effects/cube/cube_proxy.h +++ b/effects/cube/cube_proxy.h @@ -29,15 +29,15 @@ class CubeInsideEffect; class CubeEffectProxy { - public: - CubeEffectProxy( CubeEffect* effect ); - ~CubeEffectProxy(); +public: + CubeEffectProxy(CubeEffect* effect); + ~CubeEffectProxy(); - void registerCubeInsideEffect( CubeInsideEffect* effect ); - void unregisterCubeInsideEffect( CubeInsideEffect* effect ); + void registerCubeInsideEffect(CubeInsideEffect* effect); + void unregisterCubeInsideEffect(CubeInsideEffect* effect); - private: - CubeEffect* m_effect; +private: + CubeEffect* m_effect; }; } // namespace diff --git a/effects/cube/cubeslide.cpp b/effects/cube/cubeslide.cpp index ba1603cdd..b23c7a5b0 100644 --- a/effects/cube/cubeslide.cpp +++ b/effects/cube/cubeslide.cpp @@ -30,102 +30,96 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( cubeslide, CubeSlideEffect ) -KWIN_EFFECT_SUPPORTED( cubeslide, CubeSlideEffect::supported() ) +KWIN_EFFECT(cubeslide, CubeSlideEffect) +KWIN_EFFECT_SUPPORTED(cubeslide, CubeSlideEffect::supported()) CubeSlideEffect::CubeSlideEffect() - : windowMoving( false ) - , desktopChangedWhileMoving( false ) - , progressRestriction( 0.0f ) - { - reconfigure( ReconfigureAll ); - } + : windowMoving(false) + , desktopChangedWhileMoving(false) + , progressRestriction(0.0f) +{ + reconfigure(ReconfigureAll); +} CubeSlideEffect::~CubeSlideEffect() - { - } +{ +} bool CubeSlideEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void CubeSlideEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "CubeSlide" ); - rotationDuration = animationTime( conf, "RotationDuration", 500 ); - timeLine.setCurveShape( TimeLine::EaseInOutCurve ); - timeLine.setDuration( rotationDuration ); - dontSlidePanels = conf.readEntry( "DontSlidePanels", true ); - dontSlideStickyWindows = conf.readEntry( "DontSlideStickyWindows", false ); - usePagerLayout = conf.readEntry( "UsePagerLayout", true ); - useWindowMoving = conf.readEntry( "UseWindowMoving", false ); - } +void CubeSlideEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("CubeSlide"); + rotationDuration = animationTime(conf, "RotationDuration", 500); + timeLine.setCurveShape(TimeLine::EaseInOutCurve); + timeLine.setDuration(rotationDuration); + dontSlidePanels = conf.readEntry("DontSlidePanels", true); + dontSlideStickyWindows = conf.readEntry("DontSlideStickyWindows", false); + usePagerLayout = conf.readEntry("UsePagerLayout", true); + useWindowMoving = conf.readEntry("UseWindowMoving", false); +} -void CubeSlideEffect::prePaintScreen( ScreenPrePaintData& data, int time) - { - if( !slideRotations.empty() ) - { +void CubeSlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!slideRotations.empty()) { data.mask |= PAINT_SCREEN_TRANSFORMED | Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS | PAINT_SCREEN_BACKGROUND_FIRST; - timeLine.addTime( time ); - if( windowMoving && timeLine.progress() > progressRestriction ) - timeLine.setProgress( progressRestriction ); - if( dontSlidePanels ) + timeLine.addTime(time); + if (windowMoving && timeLine.progress() > progressRestriction) + timeLine.setProgress(progressRestriction); + if (dontSlidePanels) panels.clear(); stickyWindows.clear(); - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void CubeSlideEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data) - { - if( !slideRotations.empty() ) - { +void CubeSlideEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (!slideRotations.empty()) { #ifdef KWIN_HAVE_OPENGLES - glEnable( GL_CULL_FACE ); - glCullFace( GL_FRONT ); - paintSlideCube( mask, region, data ); - glCullFace( GL_BACK ); - paintSlideCube( mask, region, data ); - glDisable( GL_CULL_FACE ); + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); + paintSlideCube(mask, region, data); + glCullFace(GL_BACK); + paintSlideCube(mask, region, data); + glDisable(GL_CULL_FACE); #else - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); - glEnable( GL_CULL_FACE ); - glCullFace( GL_FRONT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); glPushMatrix(); - paintSlideCube( mask, region, data ); + paintSlideCube(mask, region, data); glPopMatrix(); - glCullFace( GL_BACK ); + glCullFace(GL_BACK); glPushMatrix(); - paintSlideCube( mask, region, data ); + paintSlideCube(mask, region, data); glPopMatrix(); - glDisable( GL_CULL_FACE ); + glDisable(GL_CULL_FACE); glPopAttrib(); #endif - if( dontSlidePanels ) - { - foreach( EffectWindow* w, panels ) - { - WindowPaintData wData( w ); - effects->paintWindow( w, 0, QRegion( w->x(), w->y(), w->width(), w->height() ), wData ); - } - } - foreach( EffectWindow* w, stickyWindows ) - { - WindowPaintData wData( w ); - effects->paintWindow( w, 0, QRegion( w->x(), w->y(), w->width(), w->height() ), wData ); + if (dontSlidePanels) { + foreach (EffectWindow * w, panels) { + WindowPaintData wData(w); + effects->paintWindow(w, 0, QRegion(w->x(), w->y(), w->width(), w->height()), wData); } } - else - effects->paintScreen( mask, region, data ); - } + foreach (EffectWindow * w, stickyWindows) { + WindowPaintData wData(w); + effects->paintWindow(w, 0, QRegion(w->x(), w->y(), w->width(), w->height()), wData); + } + } else + effects->paintScreen(mask, region, data); +} void CubeSlideEffect::paintSlideCube(int mask, QRegion region, ScreenPaintData& data) - { +{ // slide cube only paints to desktops at a time // first the horizontal rotations followed by vertical rotations - QRect rect = effects->clientArea( FullArea, effects->activeScreen(), effects->currentDesktop() ); - float point = rect.width()/2*tan(45.0f*M_PI/180.0f); + QRect rect = effects->clientArea(FullArea, effects->activeScreen(), effects->currentDesktop()); + float point = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); cube_painting = true; painting_desktop = front_desktop; @@ -135,578 +129,484 @@ void CubeSlideEffect::paintSlideCube(int mask, QRegion region, ScreenPaintData& RotationData secondFaceRot = RotationData(); RotationDirection direction = slideRotations.head(); int secondDesktop; - switch ( direction ) - { - case Left: - firstFaceRot.axis = RotationData::YAxis; - secondFaceRot.axis = RotationData::YAxis; - if( usePagerLayout ) - secondDesktop = effects->desktopToLeft( front_desktop, true ); - else - { - secondDesktop = front_desktop - 1; - if( secondDesktop == 0 ) - secondDesktop = effects->numberOfDesktops(); - } - firstFaceRot.angle = 90.0f*timeLine.value(); - secondFaceRot.angle = -90.0f*(1.0f - timeLine.value()); - break; - case Right: - firstFaceRot.axis = RotationData::YAxis; - secondFaceRot.axis = RotationData::YAxis; - if( usePagerLayout ) - secondDesktop = effects->desktopToRight( front_desktop, true ); - else - { - secondDesktop = front_desktop + 1; - if( secondDesktop > effects->numberOfDesktops() ) - secondDesktop = 1; - } - firstFaceRot.angle = -90.0f*timeLine.value(); - secondFaceRot.angle = 90.0f*(1.0f - timeLine.value()); - break; - case Upwards: - firstFaceRot.axis = RotationData::XAxis; - secondFaceRot.axis = RotationData::XAxis; - secondDesktop = effects->desktopAbove( front_desktop, true); - firstFaceRot.angle = -90.0f*timeLine.value(); - secondFaceRot.angle = 90.0f*(1.0f - timeLine.value()); - point = rect.height()/2*tan(45.0f*M_PI/180.0f); - break; - case Downwards: - firstFaceRot.axis = RotationData::XAxis; - secondFaceRot.axis = RotationData::XAxis; - secondDesktop = effects->desktopBelow( front_desktop, true ); - firstFaceRot.angle = 90.0f*timeLine.value(); - secondFaceRot.angle = -90.0f*(1.0f - timeLine.value()); - point = rect.height()/2*tan(45.0f*M_PI/180.0f); - break; - default: - // totally impossible - return; + switch(direction) { + case Left: + firstFaceRot.axis = RotationData::YAxis; + secondFaceRot.axis = RotationData::YAxis; + if (usePagerLayout) + secondDesktop = effects->desktopToLeft(front_desktop, true); + else { + secondDesktop = front_desktop - 1; + if (secondDesktop == 0) + secondDesktop = effects->numberOfDesktops(); } + firstFaceRot.angle = 90.0f * timeLine.value(); + secondFaceRot.angle = -90.0f * (1.0f - timeLine.value()); + break; + case Right: + firstFaceRot.axis = RotationData::YAxis; + secondFaceRot.axis = RotationData::YAxis; + if (usePagerLayout) + secondDesktop = effects->desktopToRight(front_desktop, true); + else { + secondDesktop = front_desktop + 1; + if (secondDesktop > effects->numberOfDesktops()) + secondDesktop = 1; + } + firstFaceRot.angle = -90.0f * timeLine.value(); + secondFaceRot.angle = 90.0f * (1.0f - timeLine.value()); + break; + case Upwards: + firstFaceRot.axis = RotationData::XAxis; + secondFaceRot.axis = RotationData::XAxis; + secondDesktop = effects->desktopAbove(front_desktop, true); + firstFaceRot.angle = -90.0f * timeLine.value(); + secondFaceRot.angle = 90.0f * (1.0f - timeLine.value()); + point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); + break; + case Downwards: + firstFaceRot.axis = RotationData::XAxis; + secondFaceRot.axis = RotationData::XAxis; + secondDesktop = effects->desktopBelow(front_desktop, true); + firstFaceRot.angle = 90.0f * timeLine.value(); + secondFaceRot.angle = -90.0f * (1.0f - timeLine.value()); + point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); + break; + default: + // totally impossible + return; + } // front desktop - firstFaceRot.xRotationPoint = rect.width()/2; - firstFaceRot.yRotationPoint = rect.height()/2; + firstFaceRot.xRotationPoint = rect.width() / 2; + firstFaceRot.yRotationPoint = rect.height() / 2; firstFaceRot.zRotationPoint = -point; firstFaceData.rotation = &firstFaceRot; other_desktop = secondDesktop; firstDesktop = true; - effects->paintScreen( mask, region, firstFaceData ); + effects->paintScreen(mask, region, firstFaceData); // second desktop other_desktop = painting_desktop; painting_desktop = secondDesktop; firstDesktop = false; - secondFaceRot.xRotationPoint = rect.width()/2; - secondFaceRot.yRotationPoint = rect.height()/2; + secondFaceRot.xRotationPoint = rect.width() / 2; + secondFaceRot.yRotationPoint = rect.height() / 2; secondFaceRot.zRotationPoint = -point; secondFaceData.rotation = &secondFaceRot; - effects->paintScreen( mask, region, secondFaceData ); + effects->paintScreen(mask, region, secondFaceData); cube_painting = false; painting_desktop = effects->currentDesktop(); - } +} -void CubeSlideEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time) - { - if( !slideRotations.empty() && cube_painting ) - { - QRect rect = effects->clientArea( FullArea, effects->activeScreen(), painting_desktop ); - if( dontSlidePanels && w->isDock()) - { - w->setData( WindowForceBlurRole, QVariant( true ) ); - panels.insert( w ); +void CubeSlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (!slideRotations.empty() && cube_painting) { + QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); + if (dontSlidePanels && w->isDock()) { + w->setData(WindowForceBlurRole, QVariant(true)); + panels.insert(w); + } + if (!w->isManaged()) { + w->setData(WindowForceBlurRole, QVariant(true)); + stickyWindows.insert(w); + } else if (dontSlideStickyWindows && !w->isDock() && + !w->isDesktop() && w->isOnAllDesktops()) { + w->setData(WindowForceBlurRole, QVariant(true)); + stickyWindows.insert(w); + } + if (w->isOnDesktop(painting_desktop)) { + if (w->x() < rect.x()) { + data.quads = data.quads.splitAtX(-w->x()); } - if( !w->isManaged() ) - { - w->setData( WindowForceBlurRole, QVariant( true ) ); - stickyWindows.insert( w ); + if (w->x() + w->width() > rect.x() + rect.width()) { + data.quads = data.quads.splitAtX(rect.width() - w->x()); } - else if( dontSlideStickyWindows && !w->isDock() && - !w->isDesktop() && w->isOnAllDesktops()) - { - w->setData( WindowForceBlurRole, QVariant( true ) ); - stickyWindows.insert( w ); + if (w->y() < rect.y()) { + data.quads = data.quads.splitAtY(-w->y()); } - if( w->isOnDesktop( painting_desktop ) ) - { - if( w->x() < rect.x() ) - { - data.quads = data.quads.splitAtX( -w->x() ); - } - if( w->x() + w->width() > rect.x() + rect.width() ) - { - data.quads = data.quads.splitAtX( rect.width() - w->x() ); - } - if( w->y() < rect.y() ) - { - data.quads = data.quads.splitAtY( -w->y() ); - } - if( w->y() + w->height() > rect.y() + rect.height() ) - { - data.quads = data.quads.splitAtY( rect.height() - w->y() ); - } - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); + if (w->y() + w->height() > rect.y() + rect.height()) { + data.quads = data.quads.splitAtY(rect.height() - w->y()); } - else if( w->isOnDesktop( other_desktop ) ) - { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else if (w->isOnDesktop(other_desktop)) { RotationDirection direction = slideRotations.head(); bool enable = false; - if( w->x() < rect.x() && - ( direction == Left || direction == Right ) ) - { - data.quads = data.quads.splitAtX( -w->x() ); + if (w->x() < rect.x() && + (direction == Left || direction == Right)) { + data.quads = data.quads.splitAtX(-w->x()); enable = true; - } - if( w->x() + w->width() > rect.x() + rect.width() && - ( direction == Left || direction == Right ) ) - { - data.quads = data.quads.splitAtX( rect.width() - w->x() ); + } + if (w->x() + w->width() > rect.x() + rect.width() && + (direction == Left || direction == Right)) { + data.quads = data.quads.splitAtX(rect.width() - w->x()); enable = true; - } - if( w->y() < rect.y() && - ( direction == Upwards || direction == Downwards ) ) - { - data.quads = data.quads.splitAtY( -w->y() ); + } + if (w->y() < rect.y() && + (direction == Upwards || direction == Downwards)) { + data.quads = data.quads.splitAtY(-w->y()); enable = true; - } - if( w->y() + w->height() > rect.y() + rect.height() && - ( direction == Upwards || direction == Downwards ) ) - { - data.quads = data.quads.splitAtY( rect.height() - w->y() ); + } + if (w->y() + w->height() > rect.y() + rect.height() && + (direction == Upwards || direction == Downwards)) { + data.quads = data.quads.splitAtY(rect.height() - w->y()); enable = true; - } - if( enable ) - { + } + if (enable) { data.setTransformed(); data.setTranslucent(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - effects->prePaintWindow( w, data, time ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } + effects->prePaintWindow(w, data, time); +} -void CubeSlideEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data) - { - if( !slideRotations.empty() && cube_painting ) - { - if( dontSlidePanels && w->isDock() ) +void CubeSlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (!slideRotations.empty() && cube_painting) { + if (dontSlidePanels && w->isDock()) return; - if( stickyWindows.contains( w ) ) + if (stickyWindows.contains(w)) return; // filter out quads overlapping the edges - QRect rect = effects->clientArea( FullArea, effects->activeScreen(), painting_desktop ); - if( w->isOnDesktop( painting_desktop ) ) - { - if( w->x() < rect.x() ) - { + QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); + if (w->isOnDesktop(painting_desktop)) { + if (w->x() < rect.x()) { WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() > -w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() > -w->x()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->x() + w->width() > rect.x() + rect.width() ) - { - WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() <= rect.width() - w->x() ) - { - new_quads.append( quad ); - } - } data.quads = new_quads; - } - if( w->y() < rect.y() ) - { - WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() > -w->y() ) - { - new_quads.append( quad ); - } - } - data.quads = new_quads; - } - if( w->y() + w->height() > rect.y() + rect.height() ) - { - WindowQuadList new_quads; - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() <= rect.height() - w->y() ) - { - new_quads.append( quad ); - } - } - data.quads = new_quads; - } } + if (w->x() + w->width() > rect.x() + rect.width()) { + WindowQuadList new_quads; + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() <= rect.width() - w->x()) { + new_quads.append(quad); + } + } + data.quads = new_quads; + } + if (w->y() < rect.y()) { + WindowQuadList new_quads; + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() > -w->y()) { + new_quads.append(quad); + } + } + data.quads = new_quads; + } + if (w->y() + w->height() > rect.y() + rect.height()) { + WindowQuadList new_quads; + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() <= rect.height() - w->y()) { + new_quads.append(quad); + } + } + data.quads = new_quads; + } + } // paint windows overlapping edges from other desktop - if( w->isOnDesktop( other_desktop ) && ( mask & PAINT_WINDOW_TRANSFORMED ) ) - { + if (w->isOnDesktop(other_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { RotationDirection direction = slideRotations.head(); - if( w->x() < rect.x() && - ( direction == Left || direction == Right ) ) - { + if (w->x() < rect.x() && + (direction == Left || direction == Right)) { WindowQuadList new_quads; data.xTranslate = rect.width(); - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() <= -w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() <= -w->x()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->x() + w->width() > rect.x() + rect.width() && - ( direction == Left || direction == Right ) ) - { + data.quads = new_quads; + } + if (w->x() + w->width() > rect.x() + rect.width() && + (direction == Left || direction == Right)) { WindowQuadList new_quads; data.xTranslate = -rect.width(); - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.right() > rect.width() - w->x() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.right() > rect.width() - w->x()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->y() < rect.y() && - ( direction == Upwards || direction == Downwards ) ) - { + data.quads = new_quads; + } + if (w->y() < rect.y() && + (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.yTranslate = rect.height(); - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() <= -w->y() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() <= -w->y()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( w->y() + w->height() > rect.y() + rect.height() && - ( direction == Upwards || direction == Downwards ) ) - { + data.quads = new_quads; + } + if (w->y() + w->height() > rect.y() + rect.height() && + (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.yTranslate = -rect.height(); - foreach( const WindowQuad &quad, data.quads ) - { - if( quad.bottom() > rect.height() - w->y() ) - { - new_quads.append( quad ); - } + foreach (const WindowQuad & quad, data.quads) { + if (quad.bottom() > rect.height() - w->y()) { + new_quads.append(quad); } - data.quads = new_quads; } - if( firstDesktop ) + data.quads = new_quads; + } + if (firstDesktop) data.opacity *= timeLine.value(); else - data.opacity *= ( 1.0 - timeLine.value() ); - } + data.opacity *= (1.0 - timeLine.value()); } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} void CubeSlideEffect::postPaintScreen() - { +{ effects->postPaintScreen(); - if( !slideRotations.empty() ) - { - if( timeLine.value() == 1.0 ) - { + if (!slideRotations.empty()) { + if (timeLine.value() == 1.0) { RotationDirection direction = slideRotations.dequeue(); - switch (direction) - { - case Left: - if( usePagerLayout ) - front_desktop = effects->desktopToLeft( front_desktop, true ); - else - { - front_desktop--; - if( front_desktop == 0 ) - front_desktop = effects->numberOfDesktops(); - } - break; - case Right: - if( usePagerLayout ) - front_desktop = effects->desktopToRight( front_desktop, true ); - else - { - front_desktop++; - if( front_desktop > effects->numberOfDesktops() ) - front_desktop = 1; - } - break; - case Upwards: - front_desktop = effects->desktopAbove( front_desktop, true ); - break; - case Downwards: - front_desktop = effects->desktopBelow( front_desktop, true ); - break; + switch(direction) { + case Left: + if (usePagerLayout) + front_desktop = effects->desktopToLeft(front_desktop, true); + else { + front_desktop--; + if (front_desktop == 0) + front_desktop = effects->numberOfDesktops(); } - timeLine.setProgress( 0.0 ); - if( slideRotations.count() == 1 ) - timeLine.setCurveShape( TimeLine::EaseOutCurve ); + break; + case Right: + if (usePagerLayout) + front_desktop = effects->desktopToRight(front_desktop, true); + else { + front_desktop++; + if (front_desktop > effects->numberOfDesktops()) + front_desktop = 1; + } + break; + case Upwards: + front_desktop = effects->desktopAbove(front_desktop, true); + break; + case Downwards: + front_desktop = effects->desktopBelow(front_desktop, true); + break; + } + timeLine.setProgress(0.0); + if (slideRotations.count() == 1) + timeLine.setCurveShape(TimeLine::EaseOutCurve); else - timeLine.setCurveShape( TimeLine::LinearCurve ); - if( slideRotations.empty() ) - { - foreach( EffectWindow* w, panels ) - w->setData( WindowForceBlurRole, QVariant( false ) ); - foreach( EffectWindow* w, stickyWindows ) - w->setData( WindowForceBlurRole, QVariant( false ) ); + timeLine.setCurveShape(TimeLine::LinearCurve); + if (slideRotations.empty()) { + foreach (EffectWindow * w, panels) + w->setData(WindowForceBlurRole, QVariant(false)); + foreach (EffectWindow * w, stickyWindows) + w->setData(WindowForceBlurRole, QVariant(false)); stickyWindows.clear(); panels.clear(); - effects->setActiveFullScreenEffect( 0 ); - } + effects->setActiveFullScreenEffect(0); } - effects->addRepaintFull(); } + effects->addRepaintFull(); } +} -void CubeSlideEffect::desktopChanged( int old ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void CubeSlideEffect::desktopChanged(int old) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - if( old > effects->numberOfDesktops() ) - { + if (old > effects->numberOfDesktops()) { // number of desktops has been reduced -> no animation return; - } - if( windowMoving ) - { + } + if (windowMoving) { desktopChangedWhileMoving = true; progressRestriction = 1.0 - progressRestriction; effects->addRepaintFull(); return; - } + } bool activate = true; - if( !slideRotations.empty() ) - { + if (!slideRotations.empty()) { // last slide still in progress activate = false; RotationDirection direction = slideRotations.dequeue(); slideRotations.clear(); - slideRotations.enqueue( direction ); - switch (direction) - { - case Left: - if( usePagerLayout ) - old = effects->desktopToLeft( front_desktop, true ); - else - { - old = front_desktop - 1; - if( old == 0 ) - old = effects->numberOfDesktops(); - } - break; - case Right: - if( usePagerLayout ) - old = effects->desktopToRight( front_desktop, true ); - else - { - old = front_desktop + 1; - if( old > effects->numberOfDesktops() ) - old = 1; - } - break; - case Upwards: - old = effects->desktopAbove( front_desktop, true ); - break; - case Downwards: - old = effects->desktopBelow( front_desktop, true ); - break; + slideRotations.enqueue(direction); + switch(direction) { + case Left: + if (usePagerLayout) + old = effects->desktopToLeft(front_desktop, true); + else { + old = front_desktop - 1; + if (old == 0) + old = effects->numberOfDesktops(); } - } - if( usePagerLayout ) - { - // calculate distance in respect to pager - QPoint diff = effects->desktopGridCoords( effects->currentDesktop() ) - effects->desktopGridCoords( old ); - if( qAbs( diff.x() ) > effects->desktopGridWidth()/2 ) - { - int sign = -1 * (diff.x()/qAbs( diff.x() )); - diff.setX( sign * ( effects->desktopGridWidth() - qAbs( diff.x() ))); + break; + case Right: + if (usePagerLayout) + old = effects->desktopToRight(front_desktop, true); + else { + old = front_desktop + 1; + if (old > effects->numberOfDesktops()) + old = 1; } - if( diff.x() > 0 ) - { - for( int i=0; i effects->desktopGridHeight()/2 ) - { - int sign = -1 * (diff.y()/qAbs( diff.y() )); - diff.setY( sign * ( effects->desktopGridHeight() - qAbs( diff.y() ))); - } - if( diff.y() > 0 ) - { - for( int i=0; icurrentDesktop(); - if( left < 0 ) - left = effects->numberOfDesktops() + left; - int right = effects->currentDesktop() - old; - if( right < 0 ) - right = effects->numberOfDesktops() + right; - if( left < right ) - { - for( int i=0; isetActiveFullScreenEffect( this ); - timeLine.setProgress( 0.0 ); - front_desktop = old; - effects->addRepaintFull(); + break; + case Upwards: + old = effects->desktopAbove(front_desktop, true); + break; + case Downwards: + old = effects->desktopBelow(front_desktop, true); + break; } } + if (usePagerLayout) { + // calculate distance in respect to pager + QPoint diff = effects->desktopGridCoords(effects->currentDesktop()) - effects->desktopGridCoords(old); + if (qAbs(diff.x()) > effects->desktopGridWidth() / 2) { + int sign = -1 * (diff.x() / qAbs(diff.x())); + diff.setX(sign *(effects->desktopGridWidth() - qAbs(diff.x()))); + } + if (diff.x() > 0) { + for (int i = 0; i < diff.x(); i++) { + slideRotations.enqueue(Right); + } + } else if (diff.x() < 0) { + diff.setX(-diff.x()); + for (int i = 0; i < diff.x(); i++) { + slideRotations.enqueue(Left); + } + } + if (qAbs(diff.y()) > effects->desktopGridHeight() / 2) { + int sign = -1 * (diff.y() / qAbs(diff.y())); + diff.setY(sign *(effects->desktopGridHeight() - qAbs(diff.y()))); + } + if (diff.y() > 0) { + for (int i = 0; i < diff.y(); i++) { + slideRotations.enqueue(Downwards); + } + } + if (diff.y() < 0) { + diff.setY(-diff.y()); + for (int i = 0; i < diff.y(); i++) { + slideRotations.enqueue(Upwards); + } + } + } else { + // ignore pager layout + int left = old - effects->currentDesktop(); + if (left < 0) + left = effects->numberOfDesktops() + left; + int right = effects->currentDesktop() - old; + if (right < 0) + right = effects->numberOfDesktops() + right; + if (left < right) { + for (int i = 0; i < left; i++) { + slideRotations.enqueue(Left); + } + } else { + for (int i = 0; i < right; i++) { + slideRotations.enqueue(Right); + } + } + } + timeLine.setDuration((float)rotationDuration / (float)slideRotations.count()); + if (activate) { + if (slideRotations.count() == 1) + timeLine.setCurveShape(TimeLine::EaseInOutCurve); + else + timeLine.setCurveShape(TimeLine::EaseInCurve); + effects->setActiveFullScreenEffect(this); + timeLine.setProgress(0.0); + front_desktop = old; + effects->addRepaintFull(); + } +} -void CubeSlideEffect::windowUserMovedResized( EffectWindow* c, bool first, bool last ) - { - if( !useWindowMoving ) +void CubeSlideEffect::windowUserMovedResized(EffectWindow* c, bool first, bool last) +{ + if (!useWindowMoving) return; - if( (first && last) || c->isUserResize() ) + if ((first && last) || c->isUserResize()) return; - if( last ) - { - if( !desktopChangedWhileMoving ) - { - if( slideRotations.isEmpty() ) + if (last) { + if (!desktopChangedWhileMoving) { + if (slideRotations.isEmpty()) return; const RotationDirection direction = slideRotations.dequeue(); - switch( direction ) - { - case Left: - slideRotations.enqueue( Right ); - break; - case Right: - slideRotations.enqueue( Left ); - break; - case Upwards: - slideRotations.enqueue( Downwards ); - break; - case Downwards: - slideRotations.enqueue( Upwards ); - break; - default: - break; // impossible - } - timeLine.setProgress( 1.0 - timeLine.progress() ); + switch(direction) { + case Left: + slideRotations.enqueue(Right); + break; + case Right: + slideRotations.enqueue(Left); + break; + case Upwards: + slideRotations.enqueue(Downwards); + break; + case Downwards: + slideRotations.enqueue(Upwards); + break; + default: + break; // impossible } + timeLine.setProgress(1.0 - timeLine.progress()); + } desktopChangedWhileMoving = false; windowMoving = false; effects->addRepaintFull(); return; - } + } const QPoint cursor = effects->cursorPos(); - const int horizontal = displayWidth()*0.1; - const int vertical = displayHeight()*0.1; - const QRect leftRect( 0, displayHeight()*0.1, horizontal, displayHeight()*0.8 ); - const QRect rightRect( displayWidth() - horizontal, displayHeight()*0.1, horizontal, displayHeight()*0.8 ); - const QRect topRect( horizontal, 0, displayWidth()*0.8, vertical ); - const QRect bottomRect( horizontal, displayHeight() - vertical, displayWidth() - horizontal*2, vertical ); - if( leftRect.contains( cursor ) ) - { - if( effects->desktopToLeft(effects->currentDesktop()) != effects->currentDesktop() ) - windowMovingChanged( 0.3 * (float)(horizontal - cursor.x())/(float)horizontal, Left ); - } - else if( rightRect.contains( cursor ) ) - { - if( effects->desktopToRight(effects->currentDesktop()) != effects->currentDesktop() ) - windowMovingChanged( 0.3 * (float)(cursor.x() - displayWidth() + horizontal)/(float)horizontal, Right ); - } - else if( topRect.contains( cursor ) ) - { - if( effects->desktopAbove(effects->currentDesktop()) != effects->currentDesktop() ) - windowMovingChanged( 0.3 * (float)(vertical - cursor.y())/(float)vertical, Upwards); - } - else if( bottomRect.contains( cursor ) ) - { - if( effects->desktopBelow(effects->currentDesktop()) != effects->currentDesktop() ) - windowMovingChanged( 0.3 * (float)(cursor.y() - displayHeight() + vertical)/(float)vertical, Downwards ); - } - else - { + const int horizontal = displayWidth() * 0.1; + const int vertical = displayHeight() * 0.1; + const QRect leftRect(0, displayHeight() * 0.1, horizontal, displayHeight() * 0.8); + const QRect rightRect(displayWidth() - horizontal, displayHeight() * 0.1, horizontal, displayHeight() * 0.8); + const QRect topRect(horizontal, 0, displayWidth() * 0.8, vertical); + const QRect bottomRect(horizontal, displayHeight() - vertical, displayWidth() - horizontal * 2, vertical); + if (leftRect.contains(cursor)) { + if (effects->desktopToLeft(effects->currentDesktop()) != effects->currentDesktop()) + windowMovingChanged(0.3 *(float)(horizontal - cursor.x()) / (float)horizontal, Left); + } else if (rightRect.contains(cursor)) { + if (effects->desktopToRight(effects->currentDesktop()) != effects->currentDesktop()) + windowMovingChanged(0.3 *(float)(cursor.x() - displayWidth() + horizontal) / (float)horizontal, Right); + } else if (topRect.contains(cursor)) { + if (effects->desktopAbove(effects->currentDesktop()) != effects->currentDesktop()) + windowMovingChanged(0.3 *(float)(vertical - cursor.y()) / (float)vertical, Upwards); + } else if (bottomRect.contains(cursor)) { + if (effects->desktopBelow(effects->currentDesktop()) != effects->currentDesktop()) + windowMovingChanged(0.3 *(float)(cursor.y() - displayHeight() + vertical) / (float)vertical, Downwards); + } else { // not in one of the areas windowMoving = false; desktopChangedWhileMoving = false; - timeLine.setProgress( 0.0 ); - if( !slideRotations.isEmpty() ) + timeLine.setProgress(0.0); + if (!slideRotations.isEmpty()) slideRotations.clear(); - effects->setActiveFullScreenEffect( 0 ); + effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); - } } +} -void CubeSlideEffect::windowMovingChanged( float progress, RotationDirection direction ) - { - if( desktopChangedWhileMoving ) +void CubeSlideEffect::windowMovingChanged(float progress, RotationDirection direction) +{ + if (desktopChangedWhileMoving) progressRestriction = 1.0 - progress; else progressRestriction = progress; front_desktop = effects->currentDesktop(); - if( slideRotations.isEmpty() ) - { - slideRotations.enqueue( direction ); - timeLine.setCurveShape( TimeLine::EaseInOutCurve ); + if (slideRotations.isEmpty()) { + slideRotations.enqueue(direction); + timeLine.setCurveShape(TimeLine::EaseInOutCurve); windowMoving = true; - effects->setActiveFullScreenEffect( this ); - } - effects->addRepaintFull(); + effects->setActiveFullScreenEffect(this); } + effects->addRepaintFull(); +} } // namespace diff --git a/effects/cube/cubeslide.h b/effects/cube/cubeslide.h index 31ee28728..a61c16693 100644 --- a/effects/cube/cubeslide.h +++ b/effects/cube/cubeslide.h @@ -30,48 +30,47 @@ namespace KWin { class CubeSlideEffect : public Effect - { - public: - CubeSlideEffect(); - ~CubeSlideEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void desktopChanged( int old ); - virtual void windowUserMovedResized( EffectWindow* c, bool first, bool last ); +{ +public: + CubeSlideEffect(); + ~CubeSlideEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void desktopChanged(int old); + virtual void windowUserMovedResized(EffectWindow* c, bool first, bool last); - static bool supported(); - private: - enum RotationDirection - { - Left, - Right, - Upwards, - Downwards - }; - void paintSlideCube( int mask, QRegion region, ScreenPaintData& data ); - void windowMovingChanged( float progress, RotationDirection direction ); - bool cube_painting; - int front_desktop; - int painting_desktop; - int other_desktop; - bool firstDesktop; - TimeLine timeLine; - QQueue slideRotations; - QSet panels; - QSet stickyWindows; - bool dontSlidePanels; - bool dontSlideStickyWindows; - bool usePagerLayout; - int rotationDuration; - bool useWindowMoving; - bool windowMoving; - bool desktopChangedWhileMoving; - double progressRestriction; + static bool supported(); +private: + enum RotationDirection { + Left, + Right, + Upwards, + Downwards }; + void paintSlideCube(int mask, QRegion region, ScreenPaintData& data); + void windowMovingChanged(float progress, RotationDirection direction); + bool cube_painting; + int front_desktop; + int painting_desktop; + int other_desktop; + bool firstDesktop; + TimeLine timeLine; + QQueue slideRotations; + QSet panels; + QSet stickyWindows; + bool dontSlidePanels; + bool dontSlideStickyWindows; + bool usePagerLayout; + int rotationDuration; + bool useWindowMoving; + bool windowMoving; + bool desktopChangedWhileMoving; + double progressRestriction; +}; } #endif diff --git a/effects/cube/cubeslide_config.cpp b/effects/cube/cubeslide_config.cpp index 15fda9869..6fe19834d 100644 --- a/effects/cube/cubeslide_config.cpp +++ b/effects/cube/cubeslide_config.cpp @@ -30,12 +30,12 @@ KWIN_EFFECT_CONFIG_FACTORY CubeSlideEffectConfigForm::CubeSlideEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } CubeSlideEffectConfig::CubeSlideEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new CubeSlideEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -49,53 +49,53 @@ CubeSlideEffectConfig::CubeSlideEffectConfig(QWidget* parent, const QVariantList connect(m_ui->windowsMovingBox, SIGNAL(stateChanged(int)), SLOT(changed())); load(); - } +} void CubeSlideEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "CubeSlide" ); + KConfigGroup conf = EffectsHandler::effectConfig("CubeSlide"); - int duration = conf.readEntry( "RotationDuration", 0 ); - bool dontSlidePanels = conf.readEntry( "DontSlidePanels", true ); - bool dontSlideStickyWindows = conf.readEntry( "DontSlideStickyWindows", false ); - bool usePager = conf.readEntry( "UsePagerLayout", true ); + int duration = conf.readEntry("RotationDuration", 0); + bool dontSlidePanels = conf.readEntry("DontSlidePanels", true); + bool dontSlideStickyWindows = conf.readEntry("DontSlideStickyWindows", false); + bool usePager = conf.readEntry("UsePagerLayout", true); - m_ui->rotationDurationSpin->setValue( duration ); - m_ui->dontSlidePanelsBox->setChecked( dontSlidePanels ); - m_ui->dontSlideStickyWindowsBox->setChecked( dontSlideStickyWindows ); - m_ui->usePagerBox->setChecked( usePager ); - m_ui->windowsMovingBox->setChecked( conf.readEntry( "UseWindowMoving", false ) ); + m_ui->rotationDurationSpin->setValue(duration); + m_ui->dontSlidePanelsBox->setChecked(dontSlidePanels); + m_ui->dontSlideStickyWindowsBox->setChecked(dontSlideStickyWindows); + m_ui->usePagerBox->setChecked(usePager); + m_ui->windowsMovingBox->setChecked(conf.readEntry("UseWindowMoving", false)); emit changed(false); - } +} void CubeSlideEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "CubeSlide" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("CubeSlide"); - conf.writeEntry( "RotationDuration", m_ui->rotationDurationSpin->value() ); - conf.writeEntry( "DontSlidePanels", m_ui->dontSlidePanelsBox->isChecked() ); - conf.writeEntry( "DontSlideStickyWindows", m_ui->dontSlideStickyWindowsBox->isChecked() ); - conf.writeEntry( "UsePagerLayout", m_ui->usePagerBox->isChecked() ); - conf.writeEntry( "UseWindowMoving", m_ui->windowsMovingBox->isChecked() ); + conf.writeEntry("RotationDuration", m_ui->rotationDurationSpin->value()); + conf.writeEntry("DontSlidePanels", m_ui->dontSlidePanelsBox->isChecked()); + conf.writeEntry("DontSlideStickyWindows", m_ui->dontSlideStickyWindowsBox->isChecked()); + conf.writeEntry("UsePagerLayout", m_ui->usePagerBox->isChecked()); + conf.writeEntry("UseWindowMoving", m_ui->windowsMovingBox->isChecked()); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "cubeslide" ); - } + EffectsHandler::sendReloadMessage("cubeslide"); +} void CubeSlideEffectConfig::defaults() - { - m_ui->rotationDurationSpin->setValue( 0 ); - m_ui->dontSlidePanelsBox->setChecked( true ); - m_ui->dontSlideStickyWindowsBox->setChecked( false ); - m_ui->usePagerBox->setChecked( true ); - m_ui->windowsMovingBox->setChecked( false ); +{ + m_ui->rotationDurationSpin->setValue(0); + m_ui->dontSlidePanelsBox->setChecked(true); + m_ui->dontSlideStickyWindowsBox->setChecked(false); + m_ui->usePagerBox->setChecked(true); + m_ui->windowsMovingBox->setChecked(false); emit changed(true); - } +} } // namespace diff --git a/effects/cube/cubeslide_config.h b/effects/cube/cubeslide_config.h index 84fe2d4d8..4cfc76d88 100644 --- a/effects/cube/cubeslide_config.h +++ b/effects/cube/cubeslide_config.h @@ -32,23 +32,23 @@ namespace KWin class CubeSlideEffectConfigForm : public QWidget, public Ui::CubeSlideEffectConfigForm { Q_OBJECT - public: - explicit CubeSlideEffectConfigForm(QWidget* parent); +public: + explicit CubeSlideEffectConfigForm(QWidget* parent); }; class CubeSlideEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit CubeSlideEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit CubeSlideEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); - private: - CubeSlideEffectConfigForm* m_ui; - }; +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); +private: + CubeSlideEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/dashboard/dashboard.cpp b/effects/dashboard/dashboard.cpp index 8ce38579b..7053443f3 100644 --- a/effects/dashboard/dashboard.cpp +++ b/effects/dashboard/dashboard.cpp @@ -25,41 +25,41 @@ namespace KWin KWIN_EFFECT(dashboard, DashboardEffect) DashboardEffect::DashboardEffect() - : transformWindow( false ) - , activateAnimation( false ) - , deactivateAnimation( false ) - { + : transformWindow(false) + , activateAnimation(false) + , deactivateAnimation(false) +{ // propagate that the effect is loaded propagate(); // read settings reconfigure(ReconfigureAll); - } +} DashboardEffect::~DashboardEffect() - { +{ unpropagate(); - } +} void DashboardEffect::propagate() - { +{ // TODO: better namespacing for atoms - atom = XInternAtom( display(), "_WM_EFFECT_KDE_DASHBOARD", false ); - effects->registerPropertyType( atom, true ); + atom = XInternAtom(display(), "_WM_EFFECT_KDE_DASHBOARD", false); + effects->registerPropertyType(atom, true); // TODO: maybe not the best way to propagate the loaded effect unsigned char dummy = 0; - XChangeProperty( display(), rootWindow(), atom, atom, 8, PropModeReplace, &dummy, 1 ); - } + XChangeProperty(display(), rootWindow(), atom, atom, 8, PropModeReplace, &dummy, 1); +} void DashboardEffect::unpropagate() - { +{ effects->registerPropertyType(atom, false); XDeleteProperty(display(), rootWindow(), atom); - } +} -void DashboardEffect::reconfigure( ReconfigureFlags ) - { +void DashboardEffect::reconfigure(ReconfigureFlags) +{ // read settings again KConfigGroup config = EffectsHandler::effectConfig("Dashboard"); @@ -69,153 +69,132 @@ void DashboardEffect::reconfigure( ReconfigureFlags ) blur = config.readEntry("Blur", false); - timeline.setDuration( animationTime( duration.toInt() ) ); - } + timeline.setDuration(animationTime(duration.toInt())); +} -void DashboardEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( transformWindow && ( w != window ) && w->isManaged() && !isDashboard( w ) ) - { +void DashboardEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (transformWindow && (w != window) && w->isManaged() && !isDashboard(w)) { brightnessDelta = (1 - (brightness.toDouble() / 100)); saturationDelta = (1 - (saturation.toDouble() / 100)); // dashboard active, transform other windows data.brightness *= (1 - (brightnessDelta * timeline.value())); data.saturation *= (1 - (saturationDelta * timeline.value())); - } + } - else if( transformWindow && ( w == window ) && w->isManaged() ) - { + else if (transformWindow && (w == window) && w->isManaged()) { // transform dashboard - if ((timeline.value() * 2) <= 1) - { + if ((timeline.value() * 2) <= 1) { data.opacity *= timeline.value() * 2; - } - else - { + } else { data.opacity *= 1; - } } - - effects->paintWindow( w, mask, region, data ); } -void DashboardEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( transformWindow ) - { - if( activateAnimation ) - timeline.addTime( time ); - if( deactivateAnimation ) - timeline.removeTime( time ); - } + effects->paintWindow(w, mask, region, data); +} + +void DashboardEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (transformWindow) { + if (activateAnimation) + timeline.addTime(time); + if (deactivateAnimation) + timeline.removeTime(time); + } effects->prePaintScreen(data, time); - } +} void DashboardEffect::postPaintScreen() - { - if( transformWindow ) - { - if( retransformWindow ) - { +{ + if (transformWindow) { + if (retransformWindow) { retransformWindow = false; transformWindow = false; effects->addRepaintFull(); - effects->setActiveFullScreenEffect( 0 ); - } + effects->setActiveFullScreenEffect(0); + } - if( activateAnimation ) - { - if( timeline.value() == 1.0 ) + if (activateAnimation) { + if (timeline.value() == 1.0) activateAnimation = false; effects->addRepaintFull(); - } + } - if( deactivateAnimation ) - { - if( timeline.value() == 0.0 ) - { + if (deactivateAnimation) { + if (timeline.value() == 0.0) { deactivateAnimation = false; transformWindow = false; - effects->setActiveFullScreenEffect( 0 ); - } + effects->setActiveFullScreenEffect(0); + } effects->addRepaintFull(); - } } + } effects->postPaintScreen(); - } +} -bool DashboardEffect::isDashboard ( EffectWindow *w ) - { - if( w->windowClass() == "dashboard dashboard") - { +bool DashboardEffect::isDashboard(EffectWindow *w) +{ + if (w->windowClass() == "dashboard dashboard") { return true; - } - else - { + } else { return false; - } } +} -void DashboardEffect::windowActivated( EffectWindow *w ) - { - if( !w ) +void DashboardEffect::windowActivated(EffectWindow *w) +{ + if (!w) return; // apply effect on dashboard activation - if( isDashboard( w ) ) - { - effects->setActiveFullScreenEffect( this ); + if (isDashboard(w)) { + effects->setActiveFullScreenEffect(this); transformWindow = true; window = w; - if ( blur ) - { - w->setData( WindowBlurBehindRole, w->geometry() ); - } + if (blur) { + w->setData(WindowBlurBehindRole, w->geometry()); + } effects->addRepaintFull(); - } - else - { - if( transformWindow) - { + } else { + if (transformWindow) { retransformWindow = true; effects->addRepaintFull(); - } } - } + } +} -void DashboardEffect::windowAdded( EffectWindow* w ) - { - propertyNotify( w, atom ); +void DashboardEffect::windowAdded(EffectWindow* w) +{ + propertyNotify(w, atom); - if( isDashboard( w ) ) - { + if (isDashboard(w)) { // Tell other windowAdded() effects to ignore this window - w->setData( WindowAddedGrabRole, QVariant::fromValue( static_cast( this ))); + w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); activateAnimation = true; deactivateAnimation = false; - timeline.setProgress( 0.0 ); + timeline.setProgress(0.0); w->addRepaintFull(); - } } +} -void DashboardEffect::windowClosed( EffectWindow* w ) - { - propertyNotify( w, atom ); +void DashboardEffect::windowClosed(EffectWindow* w) +{ + propertyNotify(w, atom); - if( isDashboard( w ) ) - { + if (isDashboard(w)) { // Tell other windowClosed() effects to ignore this window - w->setData( WindowClosedGrabRole, QVariant::fromValue( static_cast( this ))); + w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); w->addRepaintFull(); - } } +} } // namespace diff --git a/effects/dashboard/dashboard.h b/effects/dashboard/dashboard.h index 52b922afe..ee6be61d7 100644 --- a/effects/dashboard/dashboard.h +++ b/effects/dashboard/dashboard.h @@ -31,35 +31,35 @@ namespace KWin class DashboardEffect : public KWin::Effect - { - public: - DashboardEffect(); - ~DashboardEffect(); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); - virtual void propagate(); - virtual void reconfigure( ReconfigureFlags ); - virtual void unpropagate(); - virtual void windowActivated( EffectWindow *w ); - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - private: - bool blur; - bool isDashboard( EffectWindow* w ); - bool transformWindow; - bool retransformWindow; - bool activateAnimation; - bool deactivateAnimation; - TimeLine timeline; - long atom; - QString brightness; - double brightnessDelta; - QString saturation; - double saturationDelta; - QString duration; - EffectWindow* window; - }; +{ +public: + DashboardEffect(); + ~DashboardEffect(); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); + virtual void propagate(); + virtual void reconfigure(ReconfigureFlags); + virtual void unpropagate(); + virtual void windowActivated(EffectWindow *w); + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); +private: + bool blur; + bool isDashboard(EffectWindow* w); + bool transformWindow; + bool retransformWindow; + bool activateAnimation; + bool deactivateAnimation; + TimeLine timeline; + long atom; + QString brightness; + double brightnessDelta; + QString saturation; + double saturationDelta; + QString duration; + EffectWindow* window; +}; } // namespace diff --git a/effects/dashboard/dashboard_config.h b/effects/dashboard/dashboard_config.h index 60151694f..40a064270 100644 --- a/effects/dashboard/dashboard_config.h +++ b/effects/dashboard/dashboard_config.h @@ -39,7 +39,7 @@ public: void defaults(); private: - bool isBlurEffectAvailable (); + bool isBlurEffectAvailable(); long net_wm_dashboard; ::Ui::DashboardEffectConfig ui; diff --git a/effects/desktopgrid/desktopgrid.cpp b/effects/desktopgrid/desktopgrid.cpp index 37b1058ac..866e6458d 100644 --- a/effects/desktopgrid/desktopgrid.cpp +++ b/effects/desktopgrid/desktopgrid.cpp @@ -45,1588 +45,1397 @@ namespace KWin // WARNING, TODO: This effect relies on the desktop layout being EWMH-compliant. -KWIN_EFFECT( desktopgrid, DesktopGridEffect ) +KWIN_EFFECT(desktopgrid, DesktopGridEffect) DesktopGridEffect::DesktopGridEffect() - : activated( false ) + : activated(false) , timeline() - , keyboardGrab( false ) - , wasWindowMove( false ) - , wasDesktopMove( false ) - , windowMove( NULL ) + , keyboardGrab(false) + , wasWindowMove(false) + , wasDesktopMove(false) + , windowMove(NULL) , windowMoveDiff() , gridSize() - , orientation( Qt::Horizontal ) - , activeCell( 1, 1 ) + , orientation(Qt::Horizontal) + , activeCell(1, 1) , scale() , unscaledBorder() , scaledSize() , scaledOffset() - , m_proxy( 0 ) - { + , m_proxy(0) +{ // Load shortcuts - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = (KAction*) actionCollection->addAction( "ShowDesktopGrid" ); - a->setText( i18n( "Show Desktop Grid" )); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F8 )); + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = (KAction*) actionCollection->addAction("ShowDesktopGrid"); + a->setText(i18n("Show Desktop Grid")); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F8)); shortcut = a->globalShortcut(); - connect( a, SIGNAL( triggered( bool )), this, SLOT( toggle() )); - connect( a, SIGNAL( globalShortcutChanged( QKeySequence )), this, SLOT( globalShortcutChanged(QKeySequence))); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggle())); + connect(a, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChanged(QKeySequence))); // Load all other configuration details - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} DesktopGridEffect::~DesktopGridEffect() - { - foreach( ElectricBorder border, borderActivate ) - { - effects->unreserveElectricBorder( border ); - } +{ + foreach (ElectricBorder border, borderActivate) { + effects->unreserveElectricBorder(border); } +} -void DesktopGridEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "DesktopGrid" ); +void DesktopGridEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("DesktopGrid"); - foreach( ElectricBorder border, borderActivate ) - { - effects->unreserveElectricBorder( border ); - } + foreach (ElectricBorder border, borderActivate) { + effects->unreserveElectricBorder(border); + } borderActivate.clear(); QList borderList = QList(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivate", borderList ); - foreach( int i, borderList ) - { - borderActivate.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } - - zoomDuration = animationTime( conf, "ZoomDuration", 300 ); - timeline.setCurveShape( TimeLine::EaseInOutCurve ); - timeline.setDuration( zoomDuration ); - - border = conf.readEntry( "BorderWidth", 10 ); - desktopNameAlignment = Qt::Alignment( conf.readEntry( "DesktopNameAlignment", 0 )); - layoutMode = conf.readEntry( "LayoutMode", int( LayoutPager )); - customLayoutRows = conf.readEntry( "CustomLayoutRows", 2 ); - m_usePresentWindows = conf.readEntry( "PresentWindows", true ); + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivate", borderList); + foreach (int i, borderList) { + borderActivate.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); } + zoomDuration = animationTime(conf, "ZoomDuration", 300); + timeline.setCurveShape(TimeLine::EaseInOutCurve); + timeline.setDuration(zoomDuration); + + border = conf.readEntry("BorderWidth", 10); + desktopNameAlignment = Qt::Alignment(conf.readEntry("DesktopNameAlignment", 0)); + layoutMode = conf.readEntry("LayoutMode", int(LayoutPager)); + customLayoutRows = conf.readEntry("CustomLayoutRows", 2); + m_usePresentWindows = conf.readEntry("PresentWindows", true); +} + //----------------------------------------------------------------------------- // Screen painting -void DesktopGridEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( timeline.value() != 0 || activated || (isUsingPresentWindows() && isMotionManagerMovingWindows()) ) - { - if( activated ) +void DesktopGridEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (timeline.value() != 0 || activated || (isUsingPresentWindows() && isMotionManagerMovingWindows())) { + if (activated) timeline.addTime(time); else timeline.removeTime(time); - for( int i = 0; i < effects->numberOfDesktops(); i++ ) - { - if( i == highlightedDesktop - 1 ) + for (int i = 0; i < effects->numberOfDesktops(); i++) { + if (i == highlightedDesktop - 1) hoverTimeline[i].addTime(time); else hoverTimeline[i].removeTime(time); - } - if( isUsingPresentWindows() ) - { + } + if (isUsingPresentWindows()) { QList::iterator i; - for( i = m_managers.begin(); i != m_managers.end(); ++i ) - (*i).calculate( time ); - } + for (i = m_managers.begin(); i != m_managers.end(); ++i) + (*i).calculate(time); + } // PAINT_SCREEN_BACKGROUND_FIRST is needed because screen will be actually painted more than once, // so with normal screen painting second screen paint would erase parts of the first paint - if( timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows()) ) + if (timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows())) data.mask |= PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST; - if( !activated && timeline.value() == 0 && !(isUsingPresentWindows() && isMotionManagerMovingWindows()) ) + if (!activated && timeline.value() == 0 && !(isUsingPresentWindows() && isMotionManagerMovingWindows())) finish(); - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void DesktopGridEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( timeline.value() == 0 && !isUsingPresentWindows() ) - { - effects->paintScreen( mask, region, data ); +void DesktopGridEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (timeline.value() == 0 && !isUsingPresentWindows()) { + effects->paintScreen(mask, region, data); return; - } - for( int desktop = 1; desktop <= effects->numberOfDesktops(); desktop++ ) - { + } + for (int desktop = 1; desktop <= effects->numberOfDesktops(); desktop++) { ScreenPaintData d = data; paintingDesktop = desktop; - effects->paintScreen( mask, region, d ); - } + effects->paintScreen(mask, region, d); + } // paint the add desktop button - for( QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - if( !it.value() ) - { - EffectWindow *view = effects->findWindow( it.key()->winId() ); - if( view ) - { - view->setData( WindowForceBlurRole, QVariant( true ) ); + for (QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + if (!it.value()) { + EffectWindow *view = effects->findWindow(it.key()->winId()); + if (view) { + view->setData(WindowForceBlurRole, QVariant(true)); it.value() = view; - } - } - if( it.value() ) - { - WindowPaintData d( it.value() ); - d.opacity *= timeline.value(); - effects->drawWindow( it.value(), PAINT_WINDOW_TRANSLUCENT, - infiniteRegion(), d ); } } + if (it.value()) { + WindowPaintData d(it.value()); + d.opacity *= timeline.value(); + effects->drawWindow(it.value(), PAINT_WINDOW_TRANSLUCENT, + infiniteRegion(), d); + } + } - if( isUsingPresentWindows() && windowMove && wasWindowMove ) - { + if (isUsingPresentWindows() && windowMove && wasWindowMove) { // the moving window has to be painted on top of all desktops QPoint diff = cursorPos() - m_windowMoveStartPoint; - QRect geo = m_windowMoveGeometry.translated( diff ); - WindowPaintData d( windowMove ); - d.xScale *= (float)geo.width()/(float)windowMove->width(); - d.yScale *= (float)geo.height()/(float)windowMove->height(); - d.xTranslate += qRound( geo.left() - windowMove->x() ); - d.yTranslate += qRound( geo.top() - windowMove->y() ); - effects->drawWindow( windowMove, PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, infiniteRegion(), d ); - } + QRect geo = m_windowMoveGeometry.translated(diff); + WindowPaintData d(windowMove); + d.xScale *= (float)geo.width() / (float)windowMove->width(); + d.yScale *= (float)geo.height() / (float)windowMove->height(); + d.xTranslate += qRound(geo.left() - windowMove->x()); + d.yTranslate += qRound(geo.top() - windowMove->y()); + effects->drawWindow(windowMove, PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, infiniteRegion(), d); + } - if( desktopNameAlignment ) - { - for( int screen = 0; screen < effects->numScreens(); screen++ ) - { - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); - PaintClipper pc( screenGeom ); // TODO: Doesn't work in XRender for some reason? + if (desktopNameAlignment) { + for (int screen = 0; screen < effects->numScreens(); screen++) { + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); + PaintClipper pc(screenGeom); // TODO: Doesn't work in XRender for some reason? int desktop = 1; - foreach( EffectFrame* frame, desktopNames ) - { - QPointF posTL( scalePos( screenGeom.topLeft(), desktop, screen )); - QPointF posBR( scalePos( screenGeom.bottomRight(), desktop, screen )); - QRect textArea( posTL.x(), posTL.y(), posBR.x() - posTL.x(), posBR.y() - posTL.y() ); - textArea.adjust( textArea.width() / 10, textArea.height() / 10, - -textArea.width() / 10, -textArea.height() / 10 ); + foreach (EffectFrame * frame, desktopNames) { + QPointF posTL(scalePos(screenGeom.topLeft(), desktop, screen)); + QPointF posBR(scalePos(screenGeom.bottomRight(), desktop, screen)); + QRect textArea(posTL.x(), posTL.y(), posBR.x() - posTL.x(), posBR.y() - posTL.y()); + textArea.adjust(textArea.width() / 10, textArea.height() / 10, + -textArea.width() / 10, -textArea.height() / 10); int x, y; - if( desktopNameAlignment & Qt::AlignLeft ) + if (desktopNameAlignment & Qt::AlignLeft) x = textArea.x(); - else if( desktopNameAlignment & Qt::AlignRight ) + else if (desktopNameAlignment & Qt::AlignRight) x = textArea.right(); else x = textArea.center().x(); - if( desktopNameAlignment & Qt::AlignTop ) + if (desktopNameAlignment & Qt::AlignTop) y = textArea.y(); - else if( desktopNameAlignment & Qt::AlignBottom ) + else if (desktopNameAlignment & Qt::AlignBottom) y = textArea.bottom(); else y = textArea.center().y(); - frame->setPosition( QPoint( x, y )); - frame->render( region, timeline.value(), 0.7 ); + frame->setPosition(QPoint(x, y)); + frame->render(region, timeline.value(), 0.7); ++desktop; - } } } } +} void DesktopGridEffect::postPaintScreen() - { - if( activated ? timeline.value() != 1 : timeline.value() != 0 ) +{ + if (activated ? timeline.value() != 1 : timeline.value() != 0) effects->addRepaintFull(); // Repaint during zoom - if( isUsingPresentWindows() && isMotionManagerMovingWindows() ) + if (isUsingPresentWindows() && isMotionManagerMovingWindows()) effects->addRepaintFull(); - if( activated ) - { - for( int i = 0; i < effects->numberOfDesktops(); i++ ) - { - if( hoverTimeline[i].value() != 0.0 && hoverTimeline[i].value() != 1.0 ) - { // Repaint during soft highlighting + if (activated) { + for (int i = 0; i < effects->numberOfDesktops(); i++) { + if (hoverTimeline[i].value() != 0.0 && hoverTimeline[i].value() != 1.0) { + // Repaint during soft highlighting effects->addRepaintFull(); break; - } } } - effects->postPaintScreen(); } + effects->postPaintScreen(); +} //----------------------------------------------------------------------------- // Window painting -void DesktopGridEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows()) ) - { - if( w->isOnDesktop( paintingDesktop )) - { - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - if( w->isMinimized() && isUsingPresentWindows() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); +void DesktopGridEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows())) { + if (w->isOnDesktop(paintingDesktop)) { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + if (w->isMinimized() && isUsingPresentWindows()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); data.mask |= PAINT_WINDOW_TRANSFORMED; // Split windows at screen edges - for( int screen = 0; screen < effects->numScreens(); screen++ ) - { - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); - if( w->x() < screenGeom.x() ) - data.quads = data.quads.splitAtX( screenGeom.x() - w->x() ); - if( w->x() + w->width() > screenGeom.x() + screenGeom.width() ) - data.quads = data.quads.splitAtX( screenGeom.x() + screenGeom.width() - w->x() ); - if( w->y() < screenGeom.y() ) - data.quads = data.quads.splitAtY( screenGeom.y() - w->y() ); - if( w->y() + w->height() > screenGeom.y() + screenGeom.height() ) - data.quads = data.quads.splitAtY( screenGeom.y() + screenGeom.height() - w->y() ); - } - if( windowMove && wasWindowMove && windowMove->findModal() == w ) - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); + for (int screen = 0; screen < effects->numScreens(); screen++) { + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); + if (w->x() < screenGeom.x()) + data.quads = data.quads.splitAtX(screenGeom.x() - w->x()); + if (w->x() + w->width() > screenGeom.x() + screenGeom.width()) + data.quads = data.quads.splitAtX(screenGeom.x() + screenGeom.width() - w->x()); + if (w->y() < screenGeom.y()) + data.quads = data.quads.splitAtY(screenGeom.y() - w->y()); + if (w->y() + w->height() > screenGeom.y() + screenGeom.height()) + data.quads = data.quads.splitAtY(screenGeom.y() + screenGeom.height() - w->y()); } - else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - effects->prePaintWindow( w, data, time ); + if (windowMove && wasWindowMove && windowMove->findModal() == w) + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } + effects->prePaintWindow(w, data, time); +} -void DesktopGridEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows()) ) - { - if( isUsingPresentWindows() && w == windowMove && wasWindowMove ) - { +void DesktopGridEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (timeline.value() != 0 || (isUsingPresentWindows() && isMotionManagerMovingWindows())) { + if (isUsingPresentWindows() && w == windowMove && wasWindowMove) { return; // will be painted on top of all other windows - } - if( m_desktopButtonsViews.values().contains( w ) ) + } + if (m_desktopButtonsViews.values().contains(w)) return; // will be painted on top of all other windows double xScale = data.xScale; double yScale = data.yScale; // Don't change brightness of windows on all desktops as this causes flickering - if( !w->isOnAllDesktops() || w->isDesktop() ) - data.brightness *= 1.0 - ( 0.3 * ( 1.0 - hoverTimeline[paintingDesktop - 1].value() )); + if (!w->isOnAllDesktops() || w->isDesktop()) + data.brightness *= 1.0 - (0.3 * (1.0 - hoverTimeline[paintingDesktop - 1].value())); - for( int screen = 0; screen < effects->numScreens(); screen++ ) - { + for (int screen = 0; screen < effects->numScreens(); screen++) { // Assume desktop windows can never be on two screens at once (Plasma makes one window per screen) - if( w->isDesktop() ) + if (w->isDesktop()) screen = w->screen(); - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); QRectF transformedGeo = w->geometry(); // Display all quads on the same screen on the same pass WindowQuadList screenQuads; bool quadsAdded = false; - if( isUsingPresentWindows() ) - { - WindowMotionManager& manager = m_managers[ (paintingDesktop-1)*(effects->numScreens())+screen ]; - if( manager.isManaging( w ) ) - { - foreach( const WindowQuad &quad, data.quads ) - screenQuads.append( quad ); - transformedGeo = manager.transformedGeometry( w ); + if (isUsingPresentWindows()) { + WindowMotionManager& manager = m_managers[(paintingDesktop-1)*(effects->numScreens())+screen ]; + if (manager.isManaging(w)) { + foreach (const WindowQuad & quad, data.quads) + screenQuads.append(quad); + transformedGeo = manager.transformedGeometry(w); quadsAdded = true; - if( !manager.areWindowsMoving() ) + if (!manager.areWindowsMoving()) mask |= PAINT_WINDOW_LANCZOS; - } - else if( w->screen() != screen ) + } else if (w->screen() != screen) quadsAdded = true; // we don't want parts of overlapping windows on the other screen - } - if( !quadsAdded ) - { - foreach( const WindowQuad &quad, data.quads ) - { + } + if (!quadsAdded) { + foreach (const WindowQuad & quad, data.quads) { QRect quadRect( w->x() + quad.left(), w->y() + quad.top(), quad.right() - quad.left(), quad.bottom() - quad.top() - ); - if( quadRect.intersects( screenGeom ) ) - screenQuads.append( quad ); - } + ); + if (quadRect.intersects(screenGeom)) + screenQuads.append(quad); } - if( screenQuads.isEmpty() ) + } + if (screenQuads.isEmpty()) continue; // Nothing is being displayed, don't bother WindowPaintData d = data; d.quads = screenQuads; - QPointF newPos = scalePos( transformedGeo.topLeft().toPoint(), paintingDesktop, screen); + QPointF newPos = scalePos(transformedGeo.topLeft().toPoint(), paintingDesktop, screen); double progress = timeline.value(); - d.xScale = interpolate( 1, xScale * scale[screen] * (float)transformedGeo.width()/(float)w->geometry().width(), progress); - d.yScale = interpolate( 1, yScale * scale[screen] * (float)transformedGeo.height()/(float)w->geometry().height(), progress); - d.xTranslate += qRound( newPos.x() - w->x() ); - d.yTranslate += qRound( newPos.y() - w->y() ); + d.xScale = interpolate(1, xScale * scale[screen] * (float)transformedGeo.width() / (float)w->geometry().width(), progress); + d.yScale = interpolate(1, yScale * scale[screen] * (float)transformedGeo.height() / (float)w->geometry().height(), progress); + d.xTranslate += qRound(newPos.x() - w->x()); + d.yTranslate += qRound(newPos.y() - w->y()); - if( isUsingPresentWindows() && ( w->isDock() || w->isSkipSwitcher() ) ) - { + if (isUsingPresentWindows() && (w->isDock() || w->isSkipSwitcher())) { // fade out panels if present windows is used - d.opacity *= ( 1.0 - timeline.value() ); - } - if( isUsingPresentWindows() && w->isMinimized() ) - { + d.opacity *= (1.0 - timeline.value()); + } + if (isUsingPresentWindows() && w->isMinimized()) { d.opacity *= timeline.value(); - } + } - if( effects->compositingType() == XRenderCompositing ) - { // More exact clipping as XRender displays the entire window instead of just the quad - QPointF screenPosF = scalePos( screenGeom.topLeft(), paintingDesktop ).toPoint(); + if (effects->compositingType() == XRenderCompositing) { + // More exact clipping as XRender displays the entire window instead of just the quad + QPointF screenPosF = scalePos(screenGeom.topLeft(), paintingDesktop).toPoint(); QPoint screenPos( - qRound( screenPosF.x() ), - qRound( screenPosF.y() ) - ); + qRound(screenPosF.x()), + qRound(screenPosF.y()) + ); QSize screenSize( - qRound( interpolate( screenGeom.width(), scaledSize[screen].width(), progress )), - qRound( interpolate( screenGeom.height(), scaledSize[screen].height(), progress )) - ); - PaintClipper pc( effects->clientArea( ScreenArea, screen, 0 ) & QRect( screenPos, screenSize )); - effects->paintWindow( w, mask, region, d ); - } - else - { - PaintClipper pc( effects->clientArea( ScreenArea, screen, 0 )); - if( w->isDesktop() && timeline.value() == 1.0 ) - { + qRound(interpolate(screenGeom.width(), scaledSize[screen].width(), progress)), + qRound(interpolate(screenGeom.height(), scaledSize[screen].height(), progress)) + ); + PaintClipper pc(effects->clientArea(ScreenArea, screen, 0) & QRect(screenPos, screenSize)); + effects->paintWindow(w, mask, region, d); + } else { + PaintClipper pc(effects->clientArea(ScreenArea, screen, 0)); + if (w->isDesktop() && timeline.value() == 1.0) { // desktop windows are not in a motion manager and can always be rendered with // lanczos sampling except for animations mask |= PAINT_WINDOW_LANCZOS; - } - effects->paintWindow( w, mask, region, d ); } - // Assume desktop windows can never be on two screens at once (Plasma makes one window per screen) - if( w->isDesktop() ) - break; + effects->paintWindow(w, mask, region, d); } + // Assume desktop windows can never be on two screens at once (Plasma makes one window per screen) + if (w->isDesktop()) + break; } - else - effects->paintWindow( w, mask, region, data ); - } + } else + effects->paintWindow(w, mask, region, data); +} //----------------------------------------------------------------------------- // User interaction -void DesktopGridEffect::windowAdded( EffectWindow* w ) - { - if( !activated ) +void DesktopGridEffect::windowAdded(EffectWindow* w) +{ + if (!activated) return; - if( isUsingPresentWindows() ) - { - if( w->isDesktop() || w->isDock() || !w->visibleInClientGroup() ) + if (isUsingPresentWindows()) { + if (w->isDesktop() || w->isDock() || !w->visibleInClientGroup()) return; // don't add - if( w->isOnAllDesktops() ) - { - for( int i=0; inumberOfDesktops(); i++ ) - { - WindowMotionManager& manager = m_managers[ i*effects->numScreens()+w->screen() ]; - manager.manage( w ); - m_proxy->calculateWindowTransformations( manager.managedWindows(), w->screen(), manager ); - } - } - else - { - WindowMotionManager& manager = m_managers[ (w->desktop()-1)*effects->numScreens()+w->screen() ]; - manager.manage( w ); - m_proxy->calculateWindowTransformations( manager.managedWindows(), w->screen(), manager ); + if (w->isOnAllDesktops()) { + for (int i = 0; i < effects->numberOfDesktops(); i++) { + WindowMotionManager& manager = m_managers[ i*effects->numScreens()+w->screen()]; + manager.manage(w); + m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); } + } else { + WindowMotionManager& manager = m_managers[(w->desktop()-1)*effects->numScreens()+w->screen()]; + manager.manage(w); + m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); } - effects->addRepaintFull(); } + effects->addRepaintFull(); +} -void DesktopGridEffect::windowClosed( EffectWindow* w ) - { - if ( !activated && timeline.value() == 0 ) +void DesktopGridEffect::windowClosed(EffectWindow* w) +{ + if (!activated && timeline.value() == 0) return; - if( w == windowMove ) - { - effects->setElevatedWindow( windowMove, false ); + if (w == windowMove) { + effects->setElevatedWindow(windowMove, false); windowMove = NULL; - } - if( isUsingPresentWindows() ) - { - if( w->isOnAllDesktops() ) - { - for( int i=0; inumberOfDesktops(); i++ ) - { + } + if (isUsingPresentWindows()) { + if (w->isOnAllDesktops()) { + for (int i = 0; i < effects->numberOfDesktops(); i++) { WindowMotionManager& manager = m_managers[i*effects->numScreens()+w->screen()]; manager.unmanage(w); m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); - } } - else - { - if( w->desktop() <= effects->numberOfDesktops() ) - { + } else { + if (w->desktop() <= effects->numberOfDesktops()) { WindowMotionManager& manager = m_managers[(w->desktop()-1)*effects->numScreens()+w->screen()]; manager.unmanage(w); m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); - } } } - for( QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - if( it.value() && it.value() == w ) - { + } + for (QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + if (it.value() && it.value() == w) { w->refWindow(); break; - } } + } effects->addRepaintFull(); - } +} -void DesktopGridEffect::windowDeleted( EffectWindow* w ) - { - for( QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - if( it.value() && it.value() == w ) - { +void DesktopGridEffect::windowDeleted(EffectWindow* w) +{ + for (QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + if (it.value() && it.value() == w) { it.key()->deleteLater(); - m_desktopButtonsViews.erase( it ); + m_desktopButtonsViews.erase(it); break; - } } } +} -void DesktopGridEffect::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - Q_UNUSED( old ) - if( !activated ) +void DesktopGridEffect::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + Q_UNUSED(old) + if (!activated) return; - if( w == windowMove && wasWindowMove ) + if (w == windowMove && wasWindowMove) return; - if( isUsingPresentWindows() ) - { - if( w->isOnAllDesktops() ) - { - for( int i=0; inumberOfDesktops(); i++ ) - { + if (isUsingPresentWindows()) { + if (w->isOnAllDesktops()) { + for (int i = 0; i < effects->numberOfDesktops(); i++) { WindowMotionManager& manager = m_managers[i*effects->numScreens()+w->screen()]; m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); - } } - else - { + } else { WindowMotionManager& manager = m_managers[(w->desktop()-1)*effects->numScreens()+w->screen()]; m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); - } + } + } +} + +void DesktopGridEffect::windowInputMouseEvent(Window, QEvent* e) +{ + if ((e->type() != QEvent::MouseMove + && e->type() != QEvent::MouseButtonPress + && e->type() != QEvent::MouseButtonRelease) + || timeline.value() != 1) // Block user input during animations + return; + QMouseEvent* me = static_cast< QMouseEvent* >(e); + for (QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + DesktopButtonsView* view = it.key(); + if (!wasWindowMove && !wasDesktopMove && view->geometry().contains(me->pos())) { + const QPoint widgetPos = view->mapFromGlobal(me->pos()); + const QPointF scenePos = view->mapToScene(widgetPos); + QMouseEvent event(me->type(), widgetPos, me->pos(), me->button(), me->buttons(), me->modifiers()); + view->windowInputMouseEvent(&event); + return; } } -void DesktopGridEffect::windowInputMouseEvent( Window, QEvent* e ) - { - if(( e->type() != QEvent::MouseMove - && e->type() != QEvent::MouseButtonPress - && e->type() != QEvent::MouseButtonRelease ) - || timeline.value() != 1 ) // Block user input during animations - return; - QMouseEvent* me = static_cast< QMouseEvent* >( e ); - for( QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - DesktopButtonsView* view = it.key(); - if( !wasWindowMove && !wasDesktopMove && view->geometry().contains( me->pos() ) ) - { - const QPoint widgetPos = view->mapFromGlobal( me->pos() ); - const QPointF scenePos = view->mapToScene( widgetPos ); - QMouseEvent event( me->type(), widgetPos, me->pos(), me->button(), me->buttons(), me->modifiers() ); - view->windowInputMouseEvent( &event ); - return; - } - } - - if( e->type() == QEvent::MouseMove ) - { - int d = posToDesktop( me->pos()); - if( windowMove != NULL && - (me->pos() - dragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay() ) - { // Handle window moving - if( !wasWindowMove ) // Activate on move - { - if( isUsingPresentWindows() && windowMove->isOnAllDesktops() ) - { - for( int i=0; inumberOfDesktops(); ++i ) - { - WindowMotionManager& manager = m_managers[ (i)*(effects->numScreens()) + windowMove->screen() ]; - if( (i+1) == d ) - { - const QRectF transformedGeo = manager.transformedGeometry( windowMove ); - const QPointF pos = scalePos( transformedGeo.topLeft().toPoint(), d, windowMove->screen() ); - const QSize size( scale[windowMove->screen()] * (float)transformedGeo.width(), - scale[windowMove->screen()] * (float)transformedGeo.height() ); - m_windowMoveGeometry = QRect( pos.toPoint(), size ); + if (e->type() == QEvent::MouseMove) { + int d = posToDesktop(me->pos()); + if (windowMove != NULL && + (me->pos() - dragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay()) { + // Handle window moving + if (!wasWindowMove) { // Activate on move + if (isUsingPresentWindows() && windowMove->isOnAllDesktops()) { + for (int i = 0; i < effects->numberOfDesktops(); ++i) { + WindowMotionManager& manager = m_managers[(i)*(effects->numScreens()) + windowMove->screen()]; + if ((i + 1) == d) { + const QRectF transformedGeo = manager.transformedGeometry(windowMove); + const QPointF pos = scalePos(transformedGeo.topLeft().toPoint(), d, windowMove->screen()); + const QSize size(scale[windowMove->screen()] *(float)transformedGeo.width(), + scale[windowMove->screen()] *(float)transformedGeo.height()); + m_windowMoveGeometry = QRect(pos.toPoint(), size); m_windowMoveStartPoint = me->pos(); - } - manager.unmanage( windowMove ); - if( EffectWindow* modal = windowMove->findModal() ) - { - if( manager.isManaging( modal ) ) - manager.unmanage( modal ); - } - m_proxy->calculateWindowTransformations( manager.managedWindows(), windowMove->screen(), manager ); } + manager.unmanage(windowMove); + if (EffectWindow* modal = windowMove->findModal()) { + if (manager.isManaging(modal)) + manager.unmanage(modal); + } + m_proxy->calculateWindowTransformations(manager.managedWindows(), windowMove->screen(), manager); } - else if( isUsingPresentWindows() ) - { - WindowMotionManager& manager = m_managers[ (windowMove->desktop()-1)*(effects->numScreens()) + windowMove->screen() ]; - const QRectF transformedGeo = manager.transformedGeometry( windowMove ); - const QPointF pos = scalePos( transformedGeo.topLeft().toPoint(), windowMove->desktop(), windowMove->screen() ); - const QSize size( scale[windowMove->screen()] * (float)transformedGeo.width(), - scale[windowMove->screen()] * (float)transformedGeo.height() ); - m_windowMoveGeometry = QRect( pos.toPoint(), size ); + } else if (isUsingPresentWindows()) { + WindowMotionManager& manager = m_managers[(windowMove->desktop()-1)*(effects->numScreens()) + windowMove->screen()]; + const QRectF transformedGeo = manager.transformedGeometry(windowMove); + const QPointF pos = scalePos(transformedGeo.topLeft().toPoint(), windowMove->desktop(), windowMove->screen()); + const QSize size(scale[windowMove->screen()] *(float)transformedGeo.width(), + scale[windowMove->screen()] *(float)transformedGeo.height()); + m_windowMoveGeometry = QRect(pos.toPoint(), size); m_windowMoveStartPoint = me->pos(); - manager.unmanage( windowMove ); - if( EffectWindow* modal = windowMove->findModal() ) - { - if( manager.isManaging( modal ) ) - manager.unmanage( modal ); - } - m_proxy->calculateWindowTransformations( manager.managedWindows(), windowMove->screen(), manager ); + manager.unmanage(windowMove); + if (EffectWindow* modal = windowMove->findModal()) { + if (manager.isManaging(modal)) + manager.unmanage(modal); } - XDefineCursor( display(), input, QCursor( Qt::ClosedHandCursor ).handle() ); + m_proxy->calculateWindowTransformations(manager.managedWindows(), windowMove->screen(), manager); } + XDefineCursor(display(), input, QCursor(Qt::ClosedHandCursor).handle()); + } wasWindowMove = true; - if( windowMove->isMovable() && !isUsingPresentWindows() ) - { - int screen = effects->screenNumber( me->pos() ); - effects->moveWindow( windowMove, unscalePos( me->pos(), NULL ) + windowMoveDiff, true, 1.0 / scale[screen] ); - } - if( d != highlightedDesktop ) - { - if( !windowMove->isOnAllDesktops() ) - effects->windowToDesktop( windowMove, d ); // Not true all desktop move - const int screen = effects->screenNumber( me->pos() ); - if( screen != windowMove->screen() ) - effects->windowToScreen( windowMove, screen ); - } + if (windowMove->isMovable() && !isUsingPresentWindows()) { + int screen = effects->screenNumber(me->pos()); + effects->moveWindow(windowMove, unscalePos(me->pos(), NULL) + windowMoveDiff, true, 1.0 / scale[screen]); + } + if (d != highlightedDesktop) { + if (!windowMove->isOnAllDesktops()) + effects->windowToDesktop(windowMove, d); // Not true all desktop move + const int screen = effects->screenNumber(me->pos()); + if (screen != windowMove->screen()) + effects->windowToScreen(windowMove, screen); + } effects->addRepaintFull(); - } - else if( (me->buttons() & Qt::LeftButton) && !wasDesktopMove && - (me->pos() - dragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay()) - { + } else if ((me->buttons() & Qt::LeftButton) && !wasDesktopMove && + (me->pos() - dragStartPos).manhattanLength() > KGlobalSettings::dndEventDelay()) { wasDesktopMove = true; - XDefineCursor( display(), input, QCursor( Qt::ClosedHandCursor ).handle() ); - } - if( d != highlightedDesktop ) // Highlight desktop - { - if ( (me->buttons() & Qt::LeftButton) && !wasWindowMove && d <= effects->numberOfDesktops() ) - { + XDefineCursor(display(), input, QCursor(Qt::ClosedHandCursor).handle()); + } + if (d != highlightedDesktop) { // Highlight desktop + if ((me->buttons() & Qt::LeftButton) && !wasWindowMove && d <= effects->numberOfDesktops()) { EffectWindowList windows = effects->stackingOrder(); EffectWindowList stack; - foreach( EffectWindow* w, windows ) - { - if( w->isOnAllDesktops() ) + foreach (EffectWindow * w, windows) { + if (w->isOnAllDesktops()) continue; - if( w->isOnDesktop( highlightedDesktop ) ) - { - effects->windowToDesktop( w, d ); - if( isUsingPresentWindows() ) - { - m_managers[ (d-1)*(effects->numScreens()) + w->screen() ].manage( w ); - m_managers[ (highlightedDesktop-1)*(effects->numScreens()) + w->screen() ].unmanage( w ); - } + if (w->isOnDesktop(highlightedDesktop)) { + effects->windowToDesktop(w, d); + if (isUsingPresentWindows()) { + m_managers[(d-1)*(effects->numScreens()) + w->screen()].manage(w); + m_managers[(highlightedDesktop-1)*(effects->numScreens()) + w->screen()].unmanage(w); } - else if( w->isOnDesktop( d ) ) + } else if (w->isOnDesktop(d)) stack << w; - } - foreach( EffectWindow* w, stack ) - { - effects->windowToDesktop( w, highlightedDesktop ); - if( isUsingPresentWindows() ) - { - m_managers[ (d-1)*(effects->numScreens()) + w->screen() ].unmanage( w ); - m_managers[ (highlightedDesktop-1)*(effects->numScreens()) + w->screen() ].manage( w ); - } - } - if( isUsingPresentWindows() ) - { - for( int i=0; inumScreens(); i++ ) - { - WindowMotionManager& manager = m_managers[ (d-1)*(effects->numScreens()) + i ]; - WindowMotionManager& manager2 = m_managers[ (highlightedDesktop-1)*(effects->numScreens()) + i ]; - m_proxy->calculateWindowTransformations( manager.managedWindows(), i, manager ); - m_proxy->calculateWindowTransformations( manager2.managedWindows(), i, manager2 ); - } - effects->addRepaintFull(); + } + foreach (EffectWindow * w, stack) { + effects->windowToDesktop(w, highlightedDesktop); + if (isUsingPresentWindows()) { + m_managers[(d-1)*(effects->numScreens()) + w->screen()].unmanage(w); + m_managers[(highlightedDesktop-1)*(effects->numScreens()) + w->screen()].manage(w); } } - setHighlightedDesktop( d ); + if (isUsingPresentWindows()) { + for (int i = 0; i < effects->numScreens(); i++) { + WindowMotionManager& manager = m_managers[(d-1)*(effects->numScreens()) + i ]; + WindowMotionManager& manager2 = m_managers[(highlightedDesktop-1)*(effects->numScreens()) + i ]; + m_proxy->calculateWindowTransformations(manager.managedWindows(), i, manager); + m_proxy->calculateWindowTransformations(manager2.managedWindows(), i, manager2); + } + effects->addRepaintFull(); + } } + setHighlightedDesktop(d); } - if( e->type() == QEvent::MouseButtonPress ) - { - if( me->buttons() == Qt::LeftButton ) - { + } + if (e->type() == QEvent::MouseButtonPress) { + if (me->buttons() == Qt::LeftButton) { // QRect rect; dragStartPos = me->pos(); bool isDesktop = (me->modifiers() & Qt::ControlModifier); - EffectWindow* w = isDesktop ? NULL : windowAt( me->pos()); - if ( w != NULL ) + EffectWindow* w = isDesktop ? NULL : windowAt(me->pos()); + if (w != NULL) isDesktop = w->isDesktop(); - if( w != NULL && !w->isDesktop() && ( w->isMovable() || w->isMovableAcrossScreens() || isUsingPresentWindows() )) - { // Prepare it for moving - windowMoveDiff = w->pos() - unscalePos( me->pos(), NULL ); + if (w != NULL && !w->isDesktop() && (w->isMovable() || w->isMovableAcrossScreens() || isUsingPresentWindows())) { + // Prepare it for moving + windowMoveDiff = w->pos() - unscalePos(me->pos(), NULL); windowMove = w; - effects->setElevatedWindow( windowMove, true ); - } + effects->setElevatedWindow(windowMove, true); } - else if(( me->buttons() == Qt::MidButton || me->buttons() == Qt::RightButton ) && windowMove == NULL ) - { - EffectWindow* w = windowAt( me->pos()); - if( w != NULL ) - { - if( w->isOnAllDesktops()) - { - const int desktop = posToDesktop( me->pos() ); - effects->windowToDesktop( w, desktop ); - if( isUsingPresentWindows() ) - { - for( int i=0; inumberOfDesktops(); i++ ) - { - if( i != desktop - 1 ) - { - WindowMotionManager& manager = m_managers[ i*effects->numScreens() + w->screen() ]; - manager.unmanage( w ); - m_proxy->calculateWindowTransformations( manager.managedWindows(), w->screen(), manager ); - } + } else if ((me->buttons() == Qt::MidButton || me->buttons() == Qt::RightButton) && windowMove == NULL) { + EffectWindow* w = windowAt(me->pos()); + if (w != NULL) { + if (w->isOnAllDesktops()) { + const int desktop = posToDesktop(me->pos()); + effects->windowToDesktop(w, desktop); + if (isUsingPresentWindows()) { + for (int i = 0; i < effects->numberOfDesktops(); i++) { + if (i != desktop - 1) { + WindowMotionManager& manager = m_managers[ i*effects->numScreens() + w->screen()]; + manager.unmanage(w); + m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); } } } - else - { - if( isUsingPresentWindows() ) - { + } else { + if (isUsingPresentWindows()) { const int desktop = w->desktop(); - for( int i=0; inumberOfDesktops(); i++ ) - { - if( i != desktop - 1 ) - { - WindowMotionManager& manager = m_managers[ i*effects->numScreens() + w->screen() ]; - manager.manage( w ); - m_proxy->calculateWindowTransformations( manager.managedWindows(), w->screen(), manager ); - } + for (int i = 0; i < effects->numberOfDesktops(); i++) { + if (i != desktop - 1) { + WindowMotionManager& manager = m_managers[ i*effects->numScreens() + w->screen()]; + manager.manage(w); + m_proxy->calculateWindowTransformations(manager.managedWindows(), w->screen(), manager); } } - effects->windowToDesktop( w, NET::OnAllDesktops ); } + effects->windowToDesktop(w, NET::OnAllDesktops); + } effects->addRepaintFull(); - } } } - if( e->type() == QEvent::MouseButtonRelease && me->button() == Qt::LeftButton ) - { - if( !wasWindowMove && !wasDesktopMove ) - { - setCurrentDesktop( posToDesktop( me->pos() )); - if( windowMove ) - effects->activateWindow( windowMove ); - setActive( false ); - } - if( windowMove ) - { - if( wasWindowMove ) - { - if( isUsingPresentWindows() ) - { - if( windowMove->isOnAllDesktops() ) - { - const int targetDesktop = posToDesktop( cursorPos() ); - for( int i=0; inumberOfDesktops(); ++i ) - { - WindowMotionManager& manager = m_managers[ (i)*(effects->numScreens()) + windowMove->screen() ]; - manager.manage( windowMove ); - if( EffectWindow* modal = windowMove->findModal() ) - manager.manage( modal ); - if( i+1 == targetDesktop ) - { - // for the desktop the window is dropped on, we use the current geometry - manager.setTransformedGeometry( windowMove, moveGeometryToDesktop( targetDesktop ) ); - } - m_proxy->calculateWindowTransformations( manager.managedWindows(), windowMove->screen(), manager ); - } - } - else - { - WindowMotionManager& manager = m_managers[ (windowMove->desktop()-1)*(effects->numScreens()) + windowMove->screen() ]; - manager.manage( windowMove ); - if( EffectWindow* modal = windowMove->findModal() ) - manager.manage( modal ); - manager.setTransformedGeometry( windowMove, moveGeometryToDesktop( windowMove->desktop() ) ); - m_proxy->calculateWindowTransformations( manager.managedWindows(), windowMove->screen(), manager ); - } - effects->addRepaintFull(); - } - } - effects->setElevatedWindow( windowMove, false ); - windowMove = NULL; - XDefineCursor( display(), input, QCursor( Qt::PointingHandCursor ).handle() ); - } - else if ( wasDesktopMove ) - XDefineCursor( display(), input, QCursor( Qt::PointingHandCursor ).handle() ); - wasWindowMove = false; - wasDesktopMove = false; - } } + if (e->type() == QEvent::MouseButtonRelease && me->button() == Qt::LeftButton) { + if (!wasWindowMove && !wasDesktopMove) { + setCurrentDesktop(posToDesktop(me->pos())); + if (windowMove) + effects->activateWindow(windowMove); + setActive(false); + } + if (windowMove) { + if (wasWindowMove) { + if (isUsingPresentWindows()) { + if (windowMove->isOnAllDesktops()) { + const int targetDesktop = posToDesktop(cursorPos()); + for (int i = 0; i < effects->numberOfDesktops(); ++i) { + WindowMotionManager& manager = m_managers[(i)*(effects->numScreens()) + windowMove->screen()]; + manager.manage(windowMove); + if (EffectWindow* modal = windowMove->findModal()) + manager.manage(modal); + if (i + 1 == targetDesktop) { + // for the desktop the window is dropped on, we use the current geometry + manager.setTransformedGeometry(windowMove, moveGeometryToDesktop(targetDesktop)); + } + m_proxy->calculateWindowTransformations(manager.managedWindows(), windowMove->screen(), manager); + } + } else { + WindowMotionManager& manager = m_managers[(windowMove->desktop()-1)*(effects->numScreens()) + windowMove->screen()]; + manager.manage(windowMove); + if (EffectWindow* modal = windowMove->findModal()) + manager.manage(modal); + manager.setTransformedGeometry(windowMove, moveGeometryToDesktop(windowMove->desktop())); + m_proxy->calculateWindowTransformations(manager.managedWindows(), windowMove->screen(), manager); + } + effects->addRepaintFull(); + } + } + effects->setElevatedWindow(windowMove, false); + windowMove = NULL; + XDefineCursor(display(), input, QCursor(Qt::PointingHandCursor).handle()); + } else if (wasDesktopMove) + XDefineCursor(display(), input, QCursor(Qt::PointingHandCursor).handle()); + wasWindowMove = false; + wasDesktopMove = false; + } +} -void DesktopGridEffect::grabbedKeyboardEvent( QKeyEvent* e ) - { - if( timeline.value() != 1 ) // Block user input during animations +void DesktopGridEffect::grabbedKeyboardEvent(QKeyEvent* e) +{ + if (timeline.value() != 1) // Block user input during animations return; - if( windowMove != NULL ) + if (windowMove != NULL) return; - if( e->type() == QEvent::KeyPress ) - { + if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) - if( shortcut.contains( e->key() + e->modifiers() ) ) - { + if (shortcut.contains(e->key() + e->modifiers())) { toggle(); return; - } + } int desktop = -1; // switch by F or just - if( e->key() >= Qt::Key_F1 && e->key() <= Qt::Key_F35 ) + if (e->key() >= Qt::Key_F1 && e->key() <= Qt::Key_F35) desktop = e->key() - Qt::Key_F1 + 1; - else if( e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9 ) + else if (e->key() >= Qt::Key_0 && e->key() <= Qt::Key_9) desktop = e->key() == Qt::Key_0 ? 10 : e->key() - Qt::Key_0; - if( desktop != -1 ) - { - if( desktop <= effects->numberOfDesktops()) - { - setHighlightedDesktop( desktop ); - setCurrentDesktop( desktop ); - setActive( false ); - } + if (desktop != -1) { + if (desktop <= effects->numberOfDesktops()) { + setHighlightedDesktop(desktop); + setCurrentDesktop(desktop); + setActive(false); + } return; - } - switch( e->key()) - { // Wrap only on autorepeat - case Qt::Key_Left: - setHighlightedDesktop( desktopToLeft( highlightedDesktop, !e->isAutoRepeat())); - break; - case Qt::Key_Right: - setHighlightedDesktop( desktopToRight( highlightedDesktop, !e->isAutoRepeat())); - break; - case Qt::Key_Up: - setHighlightedDesktop( desktopUp( highlightedDesktop, !e->isAutoRepeat())); - break; - case Qt::Key_Down: - setHighlightedDesktop( desktopDown( highlightedDesktop, !e->isAutoRepeat())); - break; - case Qt::Key_Escape: - setActive( false ); - return; - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_Space: - setCurrentDesktop( highlightedDesktop ); - setActive( false ); - return; - case Qt::Key_Plus: - slotAddDesktop(); - break; - case Qt::Key_Minus: - slotRemoveDesktop(); - break; - default: - break; - } + } + switch(e->key()) { + // Wrap only on autorepeat + case Qt::Key_Left: + setHighlightedDesktop(desktopToLeft(highlightedDesktop, !e->isAutoRepeat())); + break; + case Qt::Key_Right: + setHighlightedDesktop(desktopToRight(highlightedDesktop, !e->isAutoRepeat())); + break; + case Qt::Key_Up: + setHighlightedDesktop(desktopUp(highlightedDesktop, !e->isAutoRepeat())); + break; + case Qt::Key_Down: + setHighlightedDesktop(desktopDown(highlightedDesktop, !e->isAutoRepeat())); + break; + case Qt::Key_Escape: + setActive(false); + return; + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Space: + setCurrentDesktop(highlightedDesktop); + setActive(false); + return; + case Qt::Key_Plus: + slotAddDesktop(); + break; + case Qt::Key_Minus: + slotRemoveDesktop(); + break; + default: + break; } } +} -bool DesktopGridEffect::borderActivated( ElectricBorder border ) - { - if( !borderActivate.contains( border ) ) +bool DesktopGridEffect::borderActivated(ElectricBorder border) +{ + if (!borderActivate.contains(border)) return false; - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return true; toggle(); return true; - } +} //----------------------------------------------------------------------------- // Helper functions // Transform a point to its position on the scaled grid -QPointF DesktopGridEffect::scalePos( const QPoint& pos, int desktop, int screen ) const - { - if( screen == -1 ) - screen = effects->screenNumber( pos ); - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); +QPointF DesktopGridEffect::scalePos(const QPoint& pos, int desktop, int screen) const +{ + if (screen == -1) + screen = effects->screenNumber(pos); + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); QPoint desktopCell; - if( orientation == Qt::Horizontal ) - { - desktopCell.setX(( desktop - 1 ) % gridSize.width() + 1 ); - desktopCell.setY(( desktop - 1 ) / gridSize.width() + 1 ); - } - else - { - desktopCell.setX(( desktop - 1 ) / gridSize.height() + 1 ); - desktopCell.setY(( desktop - 1 ) % gridSize.height() + 1 ); - } + if (orientation == Qt::Horizontal) { + desktopCell.setX((desktop - 1) % gridSize.width() + 1); + desktopCell.setY((desktop - 1) / gridSize.width() + 1); + } else { + desktopCell.setX((desktop - 1) / gridSize.height() + 1); + desktopCell.setY((desktop - 1) % gridSize.height() + 1); + } double progress = timeline.value(); QPointF point( interpolate( ( - ( screenGeom.width() + unscaledBorder[screen] ) * ( desktopCell.x() - 1 ) - - ( screenGeom.width() + unscaledBorder[screen] ) * ( activeCell.x() - 1 ) + (screenGeom.width() + unscaledBorder[screen]) *(desktopCell.x() - 1) + - (screenGeom.width() + unscaledBorder[screen]) *(activeCell.x() - 1) ) + pos.x(), ( - ( scaledSize[screen].width() + border ) * ( desktopCell.x() - 1 ) + (scaledSize[screen].width() + border) *(desktopCell.x() - 1) + scaledOffset[screen].x() - + ( pos.x() - screenGeom.x() ) * scale[screen] + + (pos.x() - screenGeom.x()) * scale[screen] ), - progress ), + progress), interpolate( ( - ( screenGeom.height() + unscaledBorder[screen] ) * ( desktopCell.y() - 1 ) - - ( screenGeom.height() + unscaledBorder[screen] ) * ( activeCell.y() - 1 ) + (screenGeom.height() + unscaledBorder[screen]) *(desktopCell.y() - 1) + - (screenGeom.height() + unscaledBorder[screen]) *(activeCell.y() - 1) ) + pos.y(), ( - ( scaledSize[screen].height() + border ) * ( desktopCell.y() - 1 ) + (scaledSize[screen].height() + border) *(desktopCell.y() - 1) + scaledOffset[screen].y() - + ( pos.y() - screenGeom.y() ) * scale[screen] + + (pos.y() - screenGeom.y()) * scale[screen] ), - progress ) - ); + progress) + ); return point; - } +} // Detransform a point to its position on the full grid // TODO: Doesn't correctly interpolate (Final position is correct though), don't forget to copy to posToDesktop() -QPoint DesktopGridEffect::unscalePos( const QPoint& pos, int* desktop ) const - { - int screen = effects->screenNumber( pos ); - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); - +QPoint DesktopGridEffect::unscalePos(const QPoint& pos, int* desktop) const +{ + int screen = effects->screenNumber(pos); + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); + //double progress = timeline.value(); double scaledX = /*interpolate( ( pos.x() - screenGeom.x() + unscaledBorder[screen] / 2.0 ) / ( screenGeom.width() + unscaledBorder[screen] ) + activeCell.x() - 1,*/ - ( pos.x() - scaledOffset[screen].x() + double( border ) / 2.0 ) / ( scaledSize[screen].width() + border )/*, + (pos.x() - scaledOffset[screen].x() + double(border) / 2.0) / (scaledSize[screen].width() + border)/*, progress )*/; double scaledY = /*interpolate( ( pos.y() - screenGeom.y() + unscaledBorder[screen] / 2.0 ) / ( screenGeom.height() + unscaledBorder[screen] ) + activeCell.y() - 1,*/ - ( pos.y() - scaledOffset[screen].y() + double( border ) / 2.0 ) / ( scaledSize[screen].height() + border )/*, + (pos.y() - scaledOffset[screen].y() + double(border) / 2.0) / (scaledSize[screen].height() + border)/*, progress )*/; - int gx = qBound( 0, int( scaledX ), gridSize.width() - 1 ); // Zero-based - int gy = qBound( 0, int( scaledY ), gridSize.height() - 1 ); + int gx = qBound(0, int(scaledX), gridSize.width() - 1); // Zero-based + int gy = qBound(0, int(scaledY), gridSize.height() - 1); scaledX -= gx; scaledY -= gy; - if( desktop != NULL ) - { - if( orientation == Qt::Horizontal ) + if (desktop != NULL) { + if (orientation == Qt::Horizontal) *desktop = gy * gridSize.width() + gx + 1; else *desktop = gx * gridSize.height() + gy + 1; - } - - return QPoint( - qBound( - screenGeom.x(), - qRound( - scaledX * ( screenGeom.width() + unscaledBorder[screen] ) - - unscaledBorder[screen] / 2.0 - + screenGeom.x() - ), - screenGeom.right() - ), - qBound( - screenGeom.y(), - qRound( - scaledY * ( screenGeom.height() + unscaledBorder[screen] ) - - unscaledBorder[screen] / 2.0 - + screenGeom.y() - ), - screenGeom.bottom() - ) - ); } -int DesktopGridEffect::posToDesktop( const QPoint& pos ) const - { // Copied from unscalePos() - int screen = effects->screenNumber( pos ); - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); - + return QPoint( + qBound( + screenGeom.x(), + qRound( + scaledX * (screenGeom.width() + unscaledBorder[screen]) + - unscaledBorder[screen] / 2.0 + + screenGeom.x() + ), + screenGeom.right() + ), + qBound( + screenGeom.y(), + qRound( + scaledY * (screenGeom.height() + unscaledBorder[screen]) + - unscaledBorder[screen] / 2.0 + + screenGeom.y() + ), + screenGeom.bottom() + ) + ); +} + +int DesktopGridEffect::posToDesktop(const QPoint& pos) const +{ + // Copied from unscalePos() + int screen = effects->screenNumber(pos); + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); + //double progress = timeline.value(); double scaledX = /*interpolate( ( pos.x() - screenGeom.x() + unscaledBorder[screen] / 2.0 ) / ( screenGeom.width() + unscaledBorder[screen] ) + activeCell.x() - 1,*/ - ( pos.x() - scaledOffset[screen].x() + double( border ) / 2.0 ) / ( scaledSize[screen].width() + border )/*, + (pos.x() - scaledOffset[screen].x() + double(border) / 2.0) / (scaledSize[screen].width() + border)/*, progress )*/; double scaledY = /*interpolate( ( pos.y() - screenGeom.y() + unscaledBorder[screen] / 2.0 ) / ( screenGeom.height() + unscaledBorder[screen] ) + activeCell.y() - 1,*/ - ( pos.y() - scaledOffset[screen].y() + double( border ) / 2.0 ) / ( scaledSize[screen].height() + border )/*, + (pos.y() - scaledOffset[screen].y() + double(border) / 2.0) / (scaledSize[screen].height() + border)/*, progress )*/; - int gx = qBound( 0, int( scaledX ), gridSize.width() - 1 ); // Zero-based - int gy = qBound( 0, int( scaledY ), gridSize.height() - 1 ); + int gx = qBound(0, int(scaledX), gridSize.width() - 1); // Zero-based + int gy = qBound(0, int(scaledY), gridSize.height() - 1); scaledX -= gx; scaledY -= gy; - if( orientation == Qt::Horizontal ) + if (orientation == Qt::Horizontal) return gy * gridSize.width() + gx + 1; return gx * gridSize.height() + gy + 1; - } +} -EffectWindow* DesktopGridEffect::windowAt( QPoint pos ) const - { +EffectWindow* DesktopGridEffect::windowAt(QPoint pos) const +{ // Get stacking order top first EffectWindowList windows = effects->stackingOrder(); EffectWindowList::Iterator begin = windows.begin(); EffectWindowList::Iterator end = windows.end(); --end; - while( begin < end ) - qSwap( *begin++, *end-- ); + while (begin < end) + qSwap(*begin++, *end--); int desktop; - pos = unscalePos( pos, &desktop ); - if( desktop > effects->numberOfDesktops() ) + pos = unscalePos(pos, &desktop); + if (desktop > effects->numberOfDesktops()) return NULL; - if( isUsingPresentWindows() ) - { - const int screen = effects->screenNumber( pos ); + if (isUsingPresentWindows()) { + const int screen = effects->screenNumber(pos); EffectWindow *w = - m_managers.at((desktop-1)*(effects->numScreens())+screen).windowAtPoint( pos, false ); - if( w ) + m_managers.at((desktop - 1) * (effects->numScreens()) + screen).windowAtPoint(pos, false); + if (w) return w; - foreach( EffectWindow* w, windows ) - { - if( w->isOnDesktop( desktop ) && w->isDesktop() && w->geometry().contains( pos )) + foreach (EffectWindow * w, windows) { + if (w->isOnDesktop(desktop) && w->isDesktop() && w->geometry().contains(pos)) return w; - } } - else - { - foreach( EffectWindow* w, windows ) - { - if( w->isOnDesktop( desktop ) && !w->isMinimized() && w->geometry().contains( pos )) + } else { + foreach (EffectWindow * w, windows) { + if (w->isOnDesktop(desktop) && !w->isMinimized() && w->geometry().contains(pos)) return w; - } } + } return NULL; - } +} -void DesktopGridEffect::setCurrentDesktop( int desktop ) - { - if( orientation == Qt::Horizontal ) - { - activeCell.setX(( desktop - 1 ) % gridSize.width() + 1 ); - activeCell.setY(( desktop - 1 ) / gridSize.width() + 1 ); - } - else - { - activeCell.setX(( desktop - 1 ) / gridSize.height() + 1 ); - activeCell.setY(( desktop - 1 ) % gridSize.height() + 1 ); - } - if( effects->currentDesktop() != desktop ) - effects->setCurrentDesktop( desktop ); +void DesktopGridEffect::setCurrentDesktop(int desktop) +{ + if (orientation == Qt::Horizontal) { + activeCell.setX((desktop - 1) % gridSize.width() + 1); + activeCell.setY((desktop - 1) / gridSize.width() + 1); + } else { + activeCell.setX((desktop - 1) / gridSize.height() + 1); + activeCell.setY((desktop - 1) % gridSize.height() + 1); } + if (effects->currentDesktop() != desktop) + effects->setCurrentDesktop(desktop); +} -void DesktopGridEffect::setHighlightedDesktop( int d ) - { - if( d == highlightedDesktop || d <= 0 || d > effects->numberOfDesktops() ) +void DesktopGridEffect::setHighlightedDesktop(int d) +{ + if (d == highlightedDesktop || d <= 0 || d > effects->numberOfDesktops()) return; highlightedDesktop = d; effects->addRepaintFull(); - } +} -int DesktopGridEffect::desktopToRight( int desktop, bool wrap ) const - { // Copied from Workspace::desktopToRight() +int DesktopGridEffect::desktopToRight(int desktop, bool wrap) const +{ + // Copied from Workspace::desktopToRight() int dt = desktop - 1; - if( orientation == Qt::Vertical ) - { + if (orientation == Qt::Vertical) { dt += gridSize.height(); - if( dt >= effects->numberOfDesktops() ) - { - if( wrap ) + if (dt >= effects->numberOfDesktops()) { + if (wrap) dt -= effects->numberOfDesktops(); else return desktop; - } } - else - { - int d = ( dt % gridSize.width() ) + 1; - if( d >= gridSize.width() ) - { - if( wrap ) + } else { + int d = (dt % gridSize.width()) + 1; + if (d >= gridSize.width()) { + if (wrap) d -= gridSize.width(); else return desktop; - } - dt = dt - ( dt % gridSize.width() ) + d; } - return dt + 1; + dt = dt - (dt % gridSize.width()) + d; } + return dt + 1; +} -int DesktopGridEffect::desktopToLeft( int desktop, bool wrap ) const - { // Copied from Workspace::desktopToLeft() +int DesktopGridEffect::desktopToLeft(int desktop, bool wrap) const +{ + // Copied from Workspace::desktopToLeft() int dt = desktop - 1; - if( orientation == Qt::Vertical ) - { + if (orientation == Qt::Vertical) { dt -= gridSize.height(); - if( dt < 0 ) - { - if( wrap ) + if (dt < 0) { + if (wrap) dt += effects->numberOfDesktops(); else return desktop; - } } - else - { - int d = ( dt % gridSize.width() ) - 1; - if( d < 0 ) - { - if( wrap ) + } else { + int d = (dt % gridSize.width()) - 1; + if (d < 0) { + if (wrap) d += gridSize.width(); else return desktop; - } - dt = dt - ( dt % gridSize.width() ) + d; } - return dt + 1; + dt = dt - (dt % gridSize.width()) + d; } + return dt + 1; +} -int DesktopGridEffect::desktopUp( int desktop, bool wrap ) const - { // Copied from Workspace::desktopUp() +int DesktopGridEffect::desktopUp(int desktop, bool wrap) const +{ + // Copied from Workspace::desktopUp() int dt = desktop - 1; - if( orientation == Qt::Horizontal ) - { + if (orientation == Qt::Horizontal) { dt -= gridSize.width(); - if( dt < 0 ) - { - if( wrap ) + if (dt < 0) { + if (wrap) dt += effects->numberOfDesktops(); else return desktop; - } } - else - { - int d = ( dt % gridSize.height() ) - 1; - if( d < 0 ) - { - if( wrap ) + } else { + int d = (dt % gridSize.height()) - 1; + if (d < 0) { + if (wrap) d += gridSize.height(); else return desktop; - } - dt = dt - ( dt % gridSize.height() ) + d; } - return dt + 1; + dt = dt - (dt % gridSize.height()) + d; } + return dt + 1; +} -int DesktopGridEffect::desktopDown( int desktop, bool wrap ) const - { // Copied from Workspace::desktopDown() +int DesktopGridEffect::desktopDown(int desktop, bool wrap) const +{ + // Copied from Workspace::desktopDown() int dt = desktop - 1; - if( orientation == Qt::Horizontal ) - { + if (orientation == Qt::Horizontal) { dt += gridSize.width(); - if( dt >= effects->numberOfDesktops() ) - { - if( wrap ) + if (dt >= effects->numberOfDesktops()) { + if (wrap) dt -= effects->numberOfDesktops(); else return desktop; - } } - else - { - int d = ( dt % gridSize.height() ) + 1; - if( d >= gridSize.height() ) - { - if( wrap ) + } else { + int d = (dt % gridSize.height()) + 1; + if (d >= gridSize.height()) { + if (wrap) d -= gridSize.height(); else return desktop; - } - dt = dt - ( dt % gridSize.height() ) + d; } - return dt + 1; + dt = dt - (dt % gridSize.height()) + d; } + return dt + 1; +} //----------------------------------------------------------------------------- // Activation void DesktopGridEffect::toggle() - { - setActive( !activated ); - } +{ + setActive(!activated); +} -void DesktopGridEffect::setActive( bool active ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void DesktopGridEffect::setActive(bool active) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; // Only one fullscreen effect at a time thanks - if( active && isMotionManagerMovingWindows() ) + if (active && isMotionManagerMovingWindows()) return; // Still moving windows from last usage - don't activate - if( activated == active ) + if (activated == active) return; // Already in that state activated = active; - if( activated && timeline.value() == 0 ) + if (activated && timeline.value() == 0) setup(); - if( !activated ) - { - if( isUsingPresentWindows() ) - { + if (!activated) { + if (isUsingPresentWindows()) { QList::iterator it; - for( it = m_managers.begin(); it != m_managers.end(); ++it ) - { - foreach( EffectWindow* w, (*it).managedWindows() ) - { - (*it).moveWindow( w, w->geometry() ); - } + for (it = m_managers.begin(); it != m_managers.end(); ++it) { + foreach (EffectWindow * w, (*it).managedWindows()) { + (*it).moveWindow(w, w->geometry()); } } - setHighlightedDesktop( effects->currentDesktop() ); // Ensure selected desktop is highlighted - for( QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - it.key()->hide(); - } } - effects->addRepaintFull(); + setHighlightedDesktop(effects->currentDesktop()); // Ensure selected desktop is highlighted + for (QHash< DesktopButtonsView*, EffectWindow*>::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + it.key()->hide(); + } } + effects->addRepaintFull(); +} void DesktopGridEffect::setup() - { - keyboardGrab = effects->grabKeyboard( this ); - input = effects->createInputWindow( this, 0, 0, displayWidth(), displayHeight(), - Qt::PointingHandCursor ); - effects->setActiveFullScreenEffect( this ); - setHighlightedDesktop( effects->currentDesktop() ); +{ + keyboardGrab = effects->grabKeyboard(this); + input = effects->createInputWindow(this, 0, 0, displayWidth(), displayHeight(), + Qt::PointingHandCursor); + effects->setActiveFullScreenEffect(this); + setHighlightedDesktop(effects->currentDesktop()); // Soft highlighting hoverTimeline.clear(); - for( int i = 0; i < effects->numberOfDesktops(); i++ ) - { - TimeLine newTimeline( animationTime( zoomDuration )); - newTimeline.setCurveShape( TimeLine::EaseInOutCurve ); - hoverTimeline.append( newTimeline ); - } - hoverTimeline[effects->currentDesktop() - 1].setProgress( 1.0 ); + for (int i = 0; i < effects->numberOfDesktops(); i++) { + TimeLine newTimeline(animationTime(zoomDuration)); + newTimeline.setCurveShape(TimeLine::EaseInOutCurve); + hoverTimeline.append(newTimeline); + } + hoverTimeline[effects->currentDesktop() - 1].setProgress(1.0); // Create desktop name textures if enabled - if( desktopNameAlignment ) - { + if (desktopNameAlignment) { QFont font; - font.setBold( true ); - font.setPointSize( 12 ); - for( int i = 0; i < effects->numberOfDesktops(); i++ ) - { - EffectFrame* frame = effects->effectFrame( EffectFrameUnstyled, false ); - frame->setFont( font ); - frame->setText( effects->desktopName( i+1 )); - frame->setAlignment( desktopNameAlignment ); - desktopNames.append( frame ); - } - } - setupGrid(); - setCurrentDesktop( effects->currentDesktop() ); - - // setup the motion managers - if( m_usePresentWindows ) - m_proxy = static_cast( effects->getProxy( "presentwindows" ) ); - if( isUsingPresentWindows() ) - { - for( int i=1; i<=effects->numberOfDesktops(); i++ ) - { - for( int j=0; jnumScreens(); j++ ) - { - WindowMotionManager manager; - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( w->isOnDesktop( i ) && w->screen() == j && !w->isDesktop() && !w->isDock() && - w->visibleInClientGroup() && !w->isSkipSwitcher() ) - { - manager.manage( w ); - } - } - m_proxy->calculateWindowTransformations(manager.managedWindows(), j, manager); - m_managers.append(manager); - } - } - } - bool enableAdd = effects->numberOfDesktops() < 20; - bool enableRemove = effects->numberOfDesktops() > 1; - for( int i=0; inumScreens(); ++i ) - { - DesktopButtonsView* view = new DesktopButtonsView(); - view->setAddDesktopEnabled( enableAdd ); - view->setRemoveDesktopEnabled( enableRemove ); - connect( view, SIGNAL(addDesktop()), SLOT(slotAddDesktop())); - connect( view, SIGNAL(removeDesktop()), SLOT(slotRemoveDesktop())); - const QRect screenRect = effects->clientArea( FullScreenArea, i, 1 ); - view->setGeometry( screenRect.right() + 1 - view->sceneRect().width(), - screenRect.bottom() + 1 - view->sceneRect().height(), - view->sceneRect().width(), view->sceneRect().height() ); - view->show(); - m_desktopButtonsViews.insert( view, NULL ); + font.setBold(true); + font.setPointSize(12); + for (int i = 0; i < effects->numberOfDesktops(); i++) { + EffectFrame* frame = effects->effectFrame(EffectFrameUnstyled, false); + frame->setFont(font); + frame->setText(effects->desktopName(i + 1)); + frame->setAlignment(desktopNameAlignment); + desktopNames.append(frame); } } + setupGrid(); + setCurrentDesktop(effects->currentDesktop()); + + // setup the motion managers + if (m_usePresentWindows) + m_proxy = static_cast(effects->getProxy("presentwindows")); + if (isUsingPresentWindows()) { + for (int i = 1; i <= effects->numberOfDesktops(); i++) { + for (int j = 0; j < effects->numScreens(); j++) { + WindowMotionManager manager; + foreach (EffectWindow * w, effects->stackingOrder()) { + if (w->isOnDesktop(i) && w->screen() == j && !w->isDesktop() && !w->isDock() && + w->visibleInClientGroup() && !w->isSkipSwitcher()) { + manager.manage(w); + } + } + m_proxy->calculateWindowTransformations(manager.managedWindows(), j, manager); + m_managers.append(manager); + } + } + } + bool enableAdd = effects->numberOfDesktops() < 20; + bool enableRemove = effects->numberOfDesktops() > 1; + for (int i = 0; i < effects->numScreens(); ++i) { + DesktopButtonsView* view = new DesktopButtonsView(); + view->setAddDesktopEnabled(enableAdd); + view->setRemoveDesktopEnabled(enableRemove); + connect(view, SIGNAL(addDesktop()), SLOT(slotAddDesktop())); + connect(view, SIGNAL(removeDesktop()), SLOT(slotRemoveDesktop())); + const QRect screenRect = effects->clientArea(FullScreenArea, i, 1); + view->setGeometry(screenRect.right() + 1 - view->sceneRect().width(), + screenRect.bottom() + 1 - view->sceneRect().height(), + view->sceneRect().width(), view->sceneRect().height()); + view->show(); + m_desktopButtonsViews.insert(view, NULL); + } +} void DesktopGridEffect::setupGrid() - { +{ // We need these variables for every paint so lets cache them int x, y; int numDesktops = effects->numberOfDesktops(); - switch( layoutMode ) - { - default: - case LayoutPager: - orientation = Qt::Horizontal; - gridSize = effects->desktopGridSize(); - // sanity check: pager may report incorrect size in case of one desktop - if( numDesktops == 1 ) - { - gridSize = QSize( 1, 1 ); - } - break; - case LayoutAutomatic: - y = sqrt( float( numDesktops ) ) + 0.5; - x = float( numDesktops ) / float( y ) + 0.5; - if( x * y < numDesktops ) - x++; - orientation = Qt::Horizontal; - gridSize.setWidth( x ); - gridSize.setHeight( y ); - break; - case LayoutCustom: - orientation = Qt::Horizontal; - gridSize.setWidth( ceil( effects->numberOfDesktops() / double( customLayoutRows ))); - gridSize.setHeight( customLayoutRows ); - break; + switch(layoutMode) { + default: + case LayoutPager: + orientation = Qt::Horizontal; + gridSize = effects->desktopGridSize(); + // sanity check: pager may report incorrect size in case of one desktop + if (numDesktops == 1) { + gridSize = QSize(1, 1); } + break; + case LayoutAutomatic: + y = sqrt(float(numDesktops)) + 0.5; + x = float(numDesktops) / float(y) + 0.5; + if (x * y < numDesktops) + x++; + orientation = Qt::Horizontal; + gridSize.setWidth(x); + gridSize.setHeight(y); + break; + case LayoutCustom: + orientation = Qt::Horizontal; + gridSize.setWidth(ceil(effects->numberOfDesktops() / double(customLayoutRows))); + gridSize.setHeight(customLayoutRows); + break; + } scale.clear(); unscaledBorder.clear(); scaledSize.clear(); scaledOffset.clear(); - for( int i = 0; i < effects->numScreens(); i++ ) - { - QRect geom = effects->clientArea( ScreenArea, i, 0 ); + for (int i = 0; i < effects->numScreens(); i++) { + QRect geom = effects->clientArea(ScreenArea, i, 0); double sScale; - if( gridSize.width() > gridSize.height() ) - sScale = ( geom.width() - border * ( gridSize.width() + 1 )) / double( geom.width() * gridSize.width() ); + if (gridSize.width() > gridSize.height()) + sScale = (geom.width() - border * (gridSize.width() + 1)) / double(geom.width() * gridSize.width()); else - sScale = ( geom.height() - border * ( gridSize.height() + 1 )) / double( geom.height() * gridSize.height() ); + sScale = (geom.height() - border * (gridSize.height() + 1)) / double(geom.height() * gridSize.height()); double sBorder = border / sScale; QSizeF size( - double( geom.width() ) * sScale, - double( geom.height() ) * sScale - ); + double(geom.width()) * sScale, + double(geom.height()) * sScale + ); QPointF offset( - geom.x() + ( geom.width() - size.width() * gridSize.width() - border * ( gridSize.width() - 1 )) / 2.0, - geom.y() + ( geom.height() - size.height() * gridSize.height() - border * ( gridSize.height() - 1 )) / 2.0 - ); - scale.append( sScale ); - unscaledBorder.append( sBorder ); - scaledSize.append( size ); - scaledOffset.append( offset ); - } + geom.x() + (geom.width() - size.width() * gridSize.width() - border *(gridSize.width() - 1)) / 2.0, + geom.y() + (geom.height() - size.height() * gridSize.height() - border *(gridSize.height() - 1)) / 2.0 + ); + scale.append(sScale); + unscaledBorder.append(sBorder); + scaledSize.append(size); + scaledOffset.append(offset); } +} void DesktopGridEffect::finish() - { - if( desktopNameAlignment ) - { +{ + if (desktopNameAlignment) { qDeleteAll(desktopNames); desktopNames.clear(); - } + } - if( keyboardGrab ) + if (keyboardGrab) effects->ungrabKeyboard(); keyboardGrab = false; - effects->destroyInputWindow( input ); - effects->setActiveFullScreenEffect( 0 ); - if( isUsingPresentWindows() ) - { - while( !m_managers.isEmpty() ) - { + effects->destroyInputWindow(input); + effects->setActiveFullScreenEffect(0); + if (isUsingPresentWindows()) { + while (!m_managers.isEmpty()) { m_managers.first().unmanageAll(); m_managers.removeFirst(); - } - m_proxy = 0; } - + m_proxy = 0; + } + QHash< DesktopButtonsView*, EffectWindow* >::iterator i = m_desktopButtonsViews.begin(); - while (i != m_desktopButtonsViews.end()) - { - if( *i && (*i)->isDeleted() ) + while (i != m_desktopButtonsViews.end()) { + if (*i && (*i)->isDeleted()) (*i)->unrefWindow(); DesktopButtonsView *view = i.key(); i = m_desktopButtonsViews.erase(i); view->deleteLater(); - } } +} -void DesktopGridEffect::globalShortcutChanged( const QKeySequence& seq ) - { - shortcut = KShortcut( seq ); - } +void DesktopGridEffect::globalShortcutChanged(const QKeySequence& seq) +{ + shortcut = KShortcut(seq); +} bool DesktopGridEffect::isMotionManagerMovingWindows() - { - if( isUsingPresentWindows() ) - { +{ + if (isUsingPresentWindows()) { QList::iterator it; - for( it = m_managers.begin(); it != m_managers.end(); ++it ) - { - if( (*it).areWindowsMoving() ) + for (it = m_managers.begin(); it != m_managers.end(); ++it) { + if ((*it).areWindowsMoving()) return true; - } } - return false; } + return false; +} bool DesktopGridEffect::isUsingPresentWindows() const - { +{ return (m_proxy != NULL); - } +} // transforms the geometry of the moved window to a geometry on the desktop // internal method only used when a window is dropped onto a desktop -QRectF DesktopGridEffect::moveGeometryToDesktop( int desktop ) const - { - QPointF point = unscalePos( m_windowMoveGeometry.topLeft() + cursorPos() - m_windowMoveStartPoint ); - const double scaleFactor = scale[ windowMove->screen() ]; - if( posToDesktop( m_windowMoveGeometry.topLeft() + cursorPos() - m_windowMoveStartPoint ) != desktop ) - { +QRectF DesktopGridEffect::moveGeometryToDesktop(int desktop) const +{ + QPointF point = unscalePos(m_windowMoveGeometry.topLeft() + cursorPos() - m_windowMoveStartPoint); + const double scaleFactor = scale[ windowMove->screen()]; + if (posToDesktop(m_windowMoveGeometry.topLeft() + cursorPos() - m_windowMoveStartPoint) != desktop) { // topLeft is not on the desktop - check other corners // if all corners are not on the desktop the window is bigger than the desktop - no matter what it will look strange - if( posToDesktop( m_windowMoveGeometry.topRight() + cursorPos() - m_windowMoveStartPoint ) == desktop ) - { - point = unscalePos( m_windowMoveGeometry.topRight() + cursorPos() - m_windowMoveStartPoint ) - - QPointF( m_windowMoveGeometry.width(), 0) / scaleFactor; - } - else if( posToDesktop( m_windowMoveGeometry.bottomLeft() + cursorPos() - m_windowMoveStartPoint ) == desktop ) - { - point = unscalePos( m_windowMoveGeometry.bottomLeft() + cursorPos() - m_windowMoveStartPoint ) - - QPointF(0, m_windowMoveGeometry.height() ) / scaleFactor; - } - else if( posToDesktop( m_windowMoveGeometry.bottomRight() + cursorPos() - m_windowMoveStartPoint ) == desktop ) - { - point = unscalePos( m_windowMoveGeometry.bottomRight() + cursorPos() - m_windowMoveStartPoint ) - - QPointF(m_windowMoveGeometry.width(), m_windowMoveGeometry.height() ) / scaleFactor; - } + if (posToDesktop(m_windowMoveGeometry.topRight() + cursorPos() - m_windowMoveStartPoint) == desktop) { + point = unscalePos(m_windowMoveGeometry.topRight() + cursorPos() - m_windowMoveStartPoint) - + QPointF(m_windowMoveGeometry.width(), 0) / scaleFactor; + } else if (posToDesktop(m_windowMoveGeometry.bottomLeft() + cursorPos() - m_windowMoveStartPoint) == desktop) { + point = unscalePos(m_windowMoveGeometry.bottomLeft() + cursorPos() - m_windowMoveStartPoint) - + QPointF(0, m_windowMoveGeometry.height()) / scaleFactor; + } else if (posToDesktop(m_windowMoveGeometry.bottomRight() + cursorPos() - m_windowMoveStartPoint) == desktop) { + point = unscalePos(m_windowMoveGeometry.bottomRight() + cursorPos() - m_windowMoveStartPoint) - + QPointF(m_windowMoveGeometry.width(), m_windowMoveGeometry.height()) / scaleFactor; } - return QRectF( point, m_windowMoveGeometry.size() / scaleFactor ); } + return QRectF(point, m_windowMoveGeometry.size() / scaleFactor); +} void DesktopGridEffect::slotAddDesktop() - { - effects->setNumberOfDesktops( effects->numberOfDesktops() + 1 ); - } +{ + effects->setNumberOfDesktops(effects->numberOfDesktops() + 1); +} void DesktopGridEffect::slotRemoveDesktop() - { - effects->setNumberOfDesktops( effects->numberOfDesktops() - 1 ); - } +{ + effects->setNumberOfDesktops(effects->numberOfDesktops() - 1); +} -void DesktopGridEffect::numberDesktopsChanged( int old ) - { - if( !activated ) +void DesktopGridEffect::numberDesktopsChanged(int old) +{ + if (!activated) return; const int desktop = effects->numberOfDesktops(); bool enableAdd = desktop < 20; bool enableRemove = desktop > 1; - for( QHash< DesktopButtonsView*, EffectWindow* >::iterator it = m_desktopButtonsViews.begin(); - it != m_desktopButtonsViews.end(); ++it ) - { - it.key()->setAddDesktopEnabled( enableAdd ); - it.key()->setRemoveDesktopEnabled( enableRemove ); - } - if( old < desktop ) - desktopsAdded( old ); + for (QHash< DesktopButtonsView*, EffectWindow* >::iterator it = m_desktopButtonsViews.begin(); + it != m_desktopButtonsViews.end(); ++it) { + it.key()->setAddDesktopEnabled(enableAdd); + it.key()->setRemoveDesktopEnabled(enableRemove); + } + if (old < desktop) + desktopsAdded(old); else - desktopsRemoved( old ); + desktopsRemoved(old); +} + +void DesktopGridEffect::desktopsAdded(int old) +{ + const int desktop = effects->numberOfDesktops(); + for (int i = old; i <= effects->numberOfDesktops(); i++) { + // add a timeline for the new desktop + TimeLine newTimeline(animationTime(zoomDuration)); + newTimeline.setCurveShape(TimeLine::EaseInOutCurve); + hoverTimeline.append(newTimeline); } -void DesktopGridEffect::desktopsAdded( int old ) - { - const int desktop = effects->numberOfDesktops(); - for( int i=old; i<=effects->numberOfDesktops(); i++ ) - { - // add a timeline for the new desktop - TimeLine newTimeline( animationTime( zoomDuration )); - newTimeline.setCurveShape( TimeLine::EaseInOutCurve ); - hoverTimeline.append( newTimeline ); - } - // Create desktop name textures if enabled - if( desktopNameAlignment ) - { + if (desktopNameAlignment) { QFont font; - font.setBold( true ); - font.setPointSize( 12 ); - for( int i = old; i < desktop; i++ ) - { - EffectFrame* frame = effects->effectFrame( EffectFrameUnstyled, false ); - frame->setFont( font ); - frame->setText( effects->desktopName( i+1 )); - frame->setAlignment( desktopNameAlignment ); - desktopNames.append( frame ); - } + font.setBold(true); + font.setPointSize(12); + for (int i = old; i < desktop; i++) { + EffectFrame* frame = effects->effectFrame(EffectFrameUnstyled, false); + frame->setFont(font); + frame->setText(effects->desktopName(i + 1)); + frame->setAlignment(desktopNameAlignment); + desktopNames.append(frame); } + } - if( isUsingPresentWindows() ) - { - for( int i=old; i<=effects->numberOfDesktops(); i++ ) - { - for( int j=0; jnumScreens(); j++ ) - { + if (isUsingPresentWindows()) { + for (int i = old; i <= effects->numberOfDesktops(); i++) { + for (int j = 0; j < effects->numScreens(); j++) { WindowMotionManager manager; - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( w->isOnDesktop( i ) && w->screen() == j && !w->isDesktop() && !w->isDock() && - w->visibleInClientGroup() ) - { - manager.manage( w ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + if (w->isOnDesktop(i) && w->screen() == j && !w->isDesktop() && !w->isDock() && + w->visibleInClientGroup()) { + manager.manage(w); } + } m_proxy->calculateWindowTransformations(manager.managedWindows(), j, manager); m_managers.append(manager); - } } } + } setupGrid(); // and repaint effects->addRepaintFull(); - } +} -void DesktopGridEffect::desktopsRemoved( int old ) - { +void DesktopGridEffect::desktopsRemoved(int old) +{ const int desktop = effects->numberOfDesktops(); - for( int i = desktop; i < old; i++ ) - { + for (int i = desktop; i < old; i++) { hoverTimeline.removeLast(); - if( desktopNameAlignment ) - { + if (desktopNameAlignment) { delete desktopNames.last(); desktopNames.removeLast(); - } - if( isUsingPresentWindows() ) - { - for( int j=0; jnumScreens(); ++j ) - { + } + if (isUsingPresentWindows()) { + for (int j = 0; j < effects->numScreens(); ++j) { WindowMotionManager& manager = m_managers.last(); manager.unmanageAll(); m_managers.removeLast(); - } } } + } // add removed windows to the last desktop - if( isUsingPresentWindows() ) - { - for( int j=0; jnumScreens(); ++j ) - { - WindowMotionManager& manager = m_managers[ (desktop-1)*(effects->numScreens())+j ]; - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( !manager.isManaging( w ) && w->isOnDesktop( desktop ) && w->screen() == j && - !w->isDesktop() && !w->isDock() && w->visibleInClientGroup() ) - { - manager.manage( w ); - } + if (isUsingPresentWindows()) { + for (int j = 0; j < effects->numScreens(); ++j) { + WindowMotionManager& manager = m_managers[(desktop-1)*(effects->numScreens())+j ]; + foreach (EffectWindow * w, effects->stackingOrder()) { + if (!manager.isManaging(w) && w->isOnDesktop(desktop) && w->screen() == j && + !w->isDesktop() && !w->isDock() && w->visibleInClientGroup()) { + manager.manage(w); } - m_proxy->calculateWindowTransformations( manager.managedWindows(), j, manager ); } + m_proxy->calculateWindowTransformations(manager.managedWindows(), j, manager); } + } setupGrid(); // and repaint effects->addRepaintFull(); - } +} /************************************************ * DesktopButtonView ************************************************/ -DesktopButtonsView::DesktopButtonsView( QWidget* parent ) - : QGraphicsView( parent ) - { - setWindowFlags( Qt::X11BypassWindowManagerHint ); - setAttribute( Qt::WA_TranslucentBackground ); - setFrameShape( QFrame::NoFrame ); +DesktopButtonsView::DesktopButtonsView(QWidget* parent) + : QGraphicsView(parent) +{ + setWindowFlags(Qt::X11BypassWindowManagerHint); + setAttribute(Qt::WA_TranslucentBackground); + setFrameShape(QFrame::NoFrame); QPalette pal = palette(); - pal.setColor( backgroundRole(), Qt::transparent ); - setPalette( pal ); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + pal.setColor(backgroundRole(), Qt::transparent); + setPalette(pal); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // setup the scene - QGraphicsScene* scene = new QGraphicsScene( this ); + QGraphicsScene* scene = new QGraphicsScene(this); m_addDesktopButton = new Plasma::PushButton(); - m_addDesktopButton->setIcon( KIcon( "list-add" ) ); + m_addDesktopButton->setIcon(KIcon("list-add")); m_removeDesktopButton = new Plasma::PushButton(); m_removeDesktopButton->setIcon(KIcon("list-remove")); - scene->addItem( m_addDesktopButton ); - scene->addItem( m_removeDesktopButton ); - connect( m_addDesktopButton, SIGNAL(clicked()), SIGNAL(addDesktop())); - connect( m_removeDesktopButton, SIGNAL(clicked()), SIGNAL(removeDesktop())); + scene->addItem(m_addDesktopButton); + scene->addItem(m_removeDesktopButton); + connect(m_addDesktopButton, SIGNAL(clicked()), SIGNAL(addDesktop())); + connect(m_removeDesktopButton, SIGNAL(clicked()), SIGNAL(removeDesktop())); QGraphicsLinearLayout *layout = new QGraphicsLinearLayout; - layout->addItem( m_addDesktopButton ); - layout->addItem( m_removeDesktopButton ); + layout->addItem(m_addDesktopButton); + layout->addItem(m_removeDesktopButton); QGraphicsWidget *form = new QGraphicsWidget; - form->setLayout( layout ); - form->setGeometry(0, 0, 64*2, 64); - scene->addItem( form ); + form->setLayout(layout); + form->setGeometry(0, 0, 64 * 2, 64); + scene->addItem(form); - m_frame = new Plasma::FrameSvg( this ); - m_frame->setImagePath( "dialogs/background" ); - m_frame->setCacheAllRenderedFrames( true ); - m_frame->setEnabledBorders( Plasma::FrameSvg::AllBorders ); + m_frame = new Plasma::FrameSvg(this); + m_frame->setImagePath("dialogs/background"); + m_frame->setCacheAllRenderedFrames(true); + m_frame->setEnabledBorders(Plasma::FrameSvg::AllBorders); qreal left, top, right, bottom; - m_frame->getMargins( left, top, right, bottom ); + m_frame->getMargins(left, top, right, bottom); qreal width = form->size().width() + left + right; qreal height = form->size().height() + top + bottom; - m_frame->resizeFrame( QSizeF( width, height ) ); - Plasma::WindowEffects::enableBlurBehind( winId(), true, m_frame->mask() ); - Plasma::WindowEffects::overrideShadow( winId(), true ); - form->setPos( left, top ); - scene->setSceneRect( QRectF( QPointF( 0, 0 ), QSizeF( width, height ) ) ); - setScene( scene ); - } + m_frame->resizeFrame(QSizeF(width, height)); + Plasma::WindowEffects::enableBlurBehind(winId(), true, m_frame->mask()); + Plasma::WindowEffects::overrideShadow(winId(), true); + form->setPos(left, top); + scene->setSceneRect(QRectF(QPointF(0, 0), QSizeF(width, height))); + setScene(scene); +} -void DesktopButtonsView::windowInputMouseEvent( QMouseEvent* e ) - { - if( e->type() == QEvent::MouseMove ) - { - mouseMoveEvent( e ); - } - else if( e->type() == QEvent::MouseButtonPress ) - { - mousePressEvent( e ); - } - else if( e->type() == QEvent::MouseButtonDblClick ) - { - mouseDoubleClickEvent( e ); - } - else if( e->type() == QEvent::MouseButtonRelease ) - { - mouseReleaseEvent( e ); - } +void DesktopButtonsView::windowInputMouseEvent(QMouseEvent* e) +{ + if (e->type() == QEvent::MouseMove) { + mouseMoveEvent(e); + } else if (e->type() == QEvent::MouseButtonPress) { + mousePressEvent(e); + } else if (e->type() == QEvent::MouseButtonDblClick) { + mouseDoubleClickEvent(e); + } else if (e->type() == QEvent::MouseButtonRelease) { + mouseReleaseEvent(e); } +} -void DesktopButtonsView::setAddDesktopEnabled( bool enable ) - { - m_addDesktopButton->setEnabled( enable ); - } +void DesktopButtonsView::setAddDesktopEnabled(bool enable) +{ + m_addDesktopButton->setEnabled(enable); +} -void DesktopButtonsView::setRemoveDesktopEnabled( bool enable ) - { - m_removeDesktopButton->setEnabled( enable ); - } +void DesktopButtonsView::setRemoveDesktopEnabled(bool enable) +{ + m_removeDesktopButton->setEnabled(enable); +} -void DesktopButtonsView::drawBackground( QPainter* painter, const QRectF& rect ) - { - Q_UNUSED( rect ) - painter->setRenderHint( QPainter::Antialiasing ); - m_frame->paintFrame( painter ); - } +void DesktopButtonsView::drawBackground(QPainter* painter, const QRectF& rect) +{ + Q_UNUSED(rect) + painter->setRenderHint(QPainter::Antialiasing); + m_frame->paintFrame(painter); +} } // namespace diff --git a/effects/desktopgrid/desktopgrid.h b/effects/desktopgrid/desktopgrid.h index 31a7b7677..c283b1a5b 100644 --- a/effects/desktopgrid/desktopgrid.h +++ b/effects/desktopgrid/desktopgrid.h @@ -38,122 +38,122 @@ namespace KWin class PresentWindowsEffectProxy; class DesktopButtonsView : public QGraphicsView - { +{ Q_OBJECT - public: - DesktopButtonsView( QWidget* parent = 0 ); - void windowInputMouseEvent( QMouseEvent* e ); - void setAddDesktopEnabled( bool enable ); - void setRemoveDesktopEnabled( bool enable ); - virtual void drawBackground( QPainter* painter, const QRectF& rect ); +public: + DesktopButtonsView(QWidget* parent = 0); + void windowInputMouseEvent(QMouseEvent* e); + void setAddDesktopEnabled(bool enable); + void setRemoveDesktopEnabled(bool enable); + virtual void drawBackground(QPainter* painter, const QRectF& rect); - Q_SIGNALS: - void addDesktop(); - void removeDesktop(); +Q_SIGNALS: + void addDesktop(); + void removeDesktop(); - private: - Plasma::PushButton* m_addDesktopButton; - Plasma::PushButton* m_removeDesktopButton; - Plasma::FrameSvg* m_frame; - }; +private: + Plasma::PushButton* m_addDesktopButton; + Plasma::PushButton* m_removeDesktopButton; + Plasma::FrameSvg* m_frame; +}; class DesktopGridEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - DesktopGridEffect(); - ~DesktopGridEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowClosed( EffectWindow* w ); - virtual void windowDeleted( EffectWindow* w ); - virtual void windowAdded( EffectWindow* w ); - virtual void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - virtual void windowInputMouseEvent( Window w, QEvent* e ); - virtual void grabbedKeyboardEvent( QKeyEvent* e ); - virtual bool borderActivated( ElectricBorder border ); - virtual void numberDesktopsChanged( int old ); +public: + DesktopGridEffect(); + ~DesktopGridEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowClosed(EffectWindow* w); + virtual void windowDeleted(EffectWindow* w); + virtual void windowAdded(EffectWindow* w); + virtual void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + virtual void windowInputMouseEvent(Window w, QEvent* e); + virtual void grabbedKeyboardEvent(QKeyEvent* e); + virtual bool borderActivated(ElectricBorder border); + virtual void numberDesktopsChanged(int old); - enum { LayoutPager, LayoutAutomatic, LayoutCustom }; // Layout modes + enum { LayoutPager, LayoutAutomatic, LayoutCustom }; // Layout modes - private slots: - void toggle(); - // slots for global shortcut changed - // needed to toggle the effect - void globalShortcutChanged( const QKeySequence& seq ); - void slotAddDesktop(); - void slotRemoveDesktop(); +private slots: + void toggle(); + // slots for global shortcut changed + // needed to toggle the effect + void globalShortcutChanged(const QKeySequence& seq); + void slotAddDesktop(); + void slotRemoveDesktop(); - private: - QPointF scalePos( const QPoint& pos, int desktop, int screen = -1 ) const; - QPoint unscalePos( const QPoint& pos, int* desktop = NULL ) const; - int posToDesktop( const QPoint& pos ) const; - EffectWindow* windowAt( QPoint pos ) const; - void setCurrentDesktop( int desktop ); - void setHighlightedDesktop( int desktop ); - int desktopToRight( int desktop, bool wrap = true ) const; - int desktopToLeft( int desktop, bool wrap = true ) const; - int desktopUp( int desktop, bool wrap = true ) const; - int desktopDown( int desktop, bool wrap = true ) const; - void setActive( bool active ); - void setup(); - void setupGrid(); - void finish(); - bool isMotionManagerMovingWindows(); - bool isUsingPresentWindows() const; - QRectF moveGeometryToDesktop( int desktop ) const; - void desktopsAdded( int old ); - void desktopsRemoved( int old ); - - QList borderActivate; - int zoomDuration; - int border; - Qt::Alignment desktopNameAlignment; - int layoutMode; - int customLayoutRows; - - bool activated; - TimeLine timeline; - int paintingDesktop; - int highlightedDesktop; - Window input; - bool keyboardGrab; - bool wasWindowMove, wasDesktopMove; - EffectWindow* windowMove; - QPoint windowMoveDiff; - QPoint dragStartPos; - - // Soft highlighting - QList hoverTimeline; +private: + QPointF scalePos(const QPoint& pos, int desktop, int screen = -1) const; + QPoint unscalePos(const QPoint& pos, int* desktop = NULL) const; + int posToDesktop(const QPoint& pos) const; + EffectWindow* windowAt(QPoint pos) const; + void setCurrentDesktop(int desktop); + void setHighlightedDesktop(int desktop); + int desktopToRight(int desktop, bool wrap = true) const; + int desktopToLeft(int desktop, bool wrap = true) const; + int desktopUp(int desktop, bool wrap = true) const; + int desktopDown(int desktop, bool wrap = true) const; + void setActive(bool active); + void setup(); + void setupGrid(); + void finish(); + bool isMotionManagerMovingWindows(); + bool isUsingPresentWindows() const; + QRectF moveGeometryToDesktop(int desktop) const; + void desktopsAdded(int old); + void desktopsRemoved(int old); - QList< EffectFrame* > desktopNames; + QList borderActivate; + int zoomDuration; + int border; + Qt::Alignment desktopNameAlignment; + int layoutMode; + int customLayoutRows; - QSize gridSize; - Qt::Orientation orientation; - QPoint activeCell; - // Per screen variables - QList scale; // Because the border isn't a ratio each screen is different - QList unscaledBorder; - QList scaledSize; - QList scaledOffset; + bool activated; + TimeLine timeline; + int paintingDesktop; + int highlightedDesktop; + Window input; + bool keyboardGrab; + bool wasWindowMove, wasDesktopMove; + EffectWindow* windowMove; + QPoint windowMoveDiff; + QPoint dragStartPos; - // Shortcut - needed to toggle the effect - KShortcut shortcut; + // Soft highlighting + QList hoverTimeline; - PresentWindowsEffectProxy* m_proxy; - QList m_managers; - bool m_usePresentWindows; - QRect m_windowMoveGeometry; - QPoint m_windowMoveStartPoint; + QList< EffectFrame* > desktopNames; - QHash< DesktopButtonsView*, EffectWindow* > m_desktopButtonsViews; + QSize gridSize; + Qt::Orientation orientation; + QPoint activeCell; + // Per screen variables + QList scale; // Because the border isn't a ratio each screen is different + QList unscaledBorder; + QList scaledSize; + QList scaledOffset; - }; + // Shortcut - needed to toggle the effect + KShortcut shortcut; + + PresentWindowsEffectProxy* m_proxy; + QList m_managers; + bool m_usePresentWindows; + QRect m_windowMoveGeometry; + QPoint m_windowMoveStartPoint; + + QHash< DesktopButtonsView*, EffectWindow* > m_desktopButtonsViews; + +}; } // namespace diff --git a/effects/desktopgrid/desktopgrid_config.cpp b/effects/desktopgrid/desktopgrid_config.cpp index e57f710d8..a58bfab5a 100644 --- a/effects/desktopgrid/desktopgrid_config.cpp +++ b/effects/desktopgrid/desktopgrid_config.cpp @@ -35,149 +35,146 @@ KWIN_EFFECT_CONFIG_FACTORY DesktopGridEffectConfigForm::DesktopGridEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } DesktopGridEffectConfig::DesktopGridEffectConfig(QWidget* parent, const QVariantList& args) - : KCModule( EffectFactory::componentData(), parent, args ) - { - m_ui = new DesktopGridEffectConfigForm( this ); + : KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new DesktopGridEffectConfigForm(this); - QVBoxLayout* layout = new QVBoxLayout( this ); + QVBoxLayout* layout = new QVBoxLayout(this); - layout->addWidget( m_ui ); + layout->addWidget(m_ui); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); - m_actionCollection->setConfigGroup( "DesktopGrid" ); - m_actionCollection->setConfigGlobal( true ); + m_actionCollection->setConfigGroup("DesktopGrid"); + m_actionCollection->setConfigGlobal(true); - KAction* a = (KAction*) m_actionCollection->addAction( "ShowDesktopGrid" ); - a->setText( i18n( "Show Desktop Grid" )); - a->setProperty( "isConfigurationAction", true ); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F8 )); + KAction* a = (KAction*) m_actionCollection->addAction("ShowDesktopGrid"); + a->setText(i18n("Show Desktop Grid")); + a->setProperty("isConfigurationAction", true); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F8)); - m_ui->shortcutEditor->addCollection( m_actionCollection ); + m_ui->shortcutEditor->addCollection(m_actionCollection); - m_alignmentItems.append( Qt::Alignment( 0 )); - m_ui->desktopNameAlignmentCombo->addItem( i18nc( "Desktop name alignment:", "Disabled" )); - m_alignmentItems.append( Qt::AlignHCenter | Qt::AlignTop ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Top" )); - m_alignmentItems.append( Qt::AlignRight | Qt::AlignTop ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Top-Right" )); - m_alignmentItems.append( Qt::AlignRight | Qt::AlignVCenter ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Right" )); - m_alignmentItems.append( Qt::AlignRight | Qt::AlignBottom ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Bottom-Right" )); - m_alignmentItems.append( Qt::AlignHCenter | Qt::AlignBottom ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Bottom" )); - m_alignmentItems.append( Qt::AlignLeft | Qt::AlignBottom ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Bottom-Left" )); - m_alignmentItems.append( Qt::AlignLeft | Qt::AlignVCenter ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Left" )); - m_alignmentItems.append( Qt::AlignLeft | Qt::AlignTop ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Top-Left" )); - m_alignmentItems.append( Qt::AlignCenter ); - m_ui->desktopNameAlignmentCombo->addItem( i18n( "Center" )); + m_alignmentItems.append(Qt::Alignment(0)); + m_ui->desktopNameAlignmentCombo->addItem(i18nc("Desktop name alignment:", "Disabled")); + m_alignmentItems.append(Qt::AlignHCenter | Qt::AlignTop); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Top")); + m_alignmentItems.append(Qt::AlignRight | Qt::AlignTop); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Top-Right")); + m_alignmentItems.append(Qt::AlignRight | Qt::AlignVCenter); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Right")); + m_alignmentItems.append(Qt::AlignRight | Qt::AlignBottom); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Bottom-Right")); + m_alignmentItems.append(Qt::AlignHCenter | Qt::AlignBottom); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Bottom")); + m_alignmentItems.append(Qt::AlignLeft | Qt::AlignBottom); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Bottom-Left")); + m_alignmentItems.append(Qt::AlignLeft | Qt::AlignVCenter); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Left")); + m_alignmentItems.append(Qt::AlignLeft | Qt::AlignTop); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Top-Left")); + m_alignmentItems.append(Qt::AlignCenter); + m_ui->desktopNameAlignmentCombo->addItem(i18n("Center")); - connect( m_ui->zoomDurationSpin, SIGNAL( valueChanged( int )), this, SLOT( changed() )); - connect( m_ui->borderWidthSpin, SIGNAL( valueChanged( int )), this, SLOT( changed() )); - connect( m_ui->desktopNameAlignmentCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->layoutCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->layoutCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( layoutSelectionChanged() )); - connect( m_ui->layoutRowsSpin, SIGNAL( valueChanged( int )), this, SLOT( changed() )); - connect( m_ui->shortcutEditor, SIGNAL( keyChange() ), this, SLOT( changed() )); - connect( m_ui->presentWindowsCheckBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); + connect(m_ui->zoomDurationSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->borderWidthSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->desktopNameAlignmentCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->layoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->layoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(layoutSelectionChanged())); + connect(m_ui->layoutRowsSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->shortcutEditor, SIGNAL(keyChange()), this, SLOT(changed())); + connect(m_ui->presentWindowsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); load(); - } +} DesktopGridEffectConfig::~DesktopGridEffectConfig() - { +{ // If save() is called undoChanges() has no effect m_ui->shortcutEditor->undoChanges(); - } +} void DesktopGridEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "DesktopGrid" ); + KConfigGroup conf = EffectsHandler::effectConfig("DesktopGrid"); - m_ui->zoomDurationSpin->setValue( conf.readEntry( "ZoomDuration", 0 )); - m_ui->zoomDurationSpin->setSuffix( ki18np( " millisecond", " milliseconds")); - m_ui->borderWidthSpin->setValue( conf.readEntry( "BorderWidth", 10 )); - m_ui->borderWidthSpin->setSuffix( ki18np( " pixel", " pixels")); + m_ui->zoomDurationSpin->setValue(conf.readEntry("ZoomDuration", 0)); + m_ui->zoomDurationSpin->setSuffix(ki18np(" millisecond", " milliseconds")); + m_ui->borderWidthSpin->setValue(conf.readEntry("BorderWidth", 10)); + m_ui->borderWidthSpin->setSuffix(ki18np(" pixel", " pixels")); - Qt::Alignment alignment = Qt::Alignment( conf.readEntry( "DesktopNameAlignment", 0 )); - m_ui->desktopNameAlignmentCombo->setCurrentIndex( m_alignmentItems.indexOf( alignment )); + Qt::Alignment alignment = Qt::Alignment(conf.readEntry("DesktopNameAlignment", 0)); + m_ui->desktopNameAlignmentCombo->setCurrentIndex(m_alignmentItems.indexOf(alignment)); - int layoutMode = conf.readEntry( "LayoutMode", int( DesktopGridEffect::LayoutPager )); - m_ui->layoutCombo->setCurrentIndex( layoutMode ); + int layoutMode = conf.readEntry("LayoutMode", int(DesktopGridEffect::LayoutPager)); + m_ui->layoutCombo->setCurrentIndex(layoutMode); layoutSelectionChanged(); - m_ui->layoutRowsSpin->setValue( conf.readEntry( "CustomLayoutRows", 2 )); - m_ui->layoutRowsSpin->setSuffix( ki18np( " row", " rows")); + m_ui->layoutRowsSpin->setValue(conf.readEntry("CustomLayoutRows", 2)); + m_ui->layoutRowsSpin->setSuffix(ki18np(" row", " rows")); - m_ui->presentWindowsCheckBox->setChecked( conf.readEntry( "PresentWindows", true )); + m_ui->presentWindowsCheckBox->setChecked(conf.readEntry("PresentWindows", true)); emit changed(false); - } +} void DesktopGridEffectConfig::save() - { +{ KCModule::save(); - KConfigGroup conf = EffectsHandler::effectConfig( "DesktopGrid" ); + KConfigGroup conf = EffectsHandler::effectConfig("DesktopGrid"); - conf.writeEntry( "ZoomDuration", m_ui->zoomDurationSpin->value() ); - conf.writeEntry( "BorderWidth", m_ui->borderWidthSpin->value() ); + conf.writeEntry("ZoomDuration", m_ui->zoomDurationSpin->value()); + conf.writeEntry("BorderWidth", m_ui->borderWidthSpin->value()); int alignment = m_ui->desktopNameAlignmentCombo->currentIndex(); - alignment = int( m_alignmentItems[alignment] ); - conf.writeEntry( "DesktopNameAlignment", alignment ); + alignment = int(m_alignmentItems[alignment]); + conf.writeEntry("DesktopNameAlignment", alignment); int layoutMode = m_ui->layoutCombo->currentIndex(); - conf.writeEntry( "LayoutMode", layoutMode ); + conf.writeEntry("LayoutMode", layoutMode); - conf.writeEntry( "CustomLayoutRows", m_ui->layoutRowsSpin->value() ); + conf.writeEntry("CustomLayoutRows", m_ui->layoutRowsSpin->value()); - conf.writeEntry( "PresentWindows", m_ui->presentWindowsCheckBox->isChecked() ); + conf.writeEntry("PresentWindows", m_ui->presentWindowsCheckBox->isChecked()); m_ui->shortcutEditor->save(); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "desktopgrid" ); - } + EffectsHandler::sendReloadMessage("desktopgrid"); +} void DesktopGridEffectConfig::defaults() - { - m_ui->zoomDurationSpin->setValue( 0 ); - m_ui->borderWidthSpin->setValue( 10 ); - m_ui->desktopNameAlignmentCombo->setCurrentIndex( 0 ); - m_ui->layoutCombo->setCurrentIndex( int( DesktopGridEffect::LayoutPager )); - m_ui->layoutRowsSpin->setValue( 2 ); +{ + m_ui->zoomDurationSpin->setValue(0); + m_ui->borderWidthSpin->setValue(10); + m_ui->desktopNameAlignmentCombo->setCurrentIndex(0); + m_ui->layoutCombo->setCurrentIndex(int(DesktopGridEffect::LayoutPager)); + m_ui->layoutRowsSpin->setValue(2); m_ui->shortcutEditor->allDefault(); - m_ui->presentWindowsCheckBox->setChecked( true ); + m_ui->presentWindowsCheckBox->setChecked(true); emit changed(true); - } +} void DesktopGridEffectConfig::layoutSelectionChanged() - { - if( m_ui->layoutCombo->currentIndex() == DesktopGridEffect::LayoutCustom ) - { - m_ui->layoutRowsLabel->setEnabled( true ); - m_ui->layoutRowsSpin->setEnabled( true ); - } - else - { - m_ui->layoutRowsLabel->setEnabled( false ); - m_ui->layoutRowsSpin->setEnabled( false ); - } +{ + if (m_ui->layoutCombo->currentIndex() == DesktopGridEffect::LayoutCustom) { + m_ui->layoutRowsLabel->setEnabled(true); + m_ui->layoutRowsSpin->setEnabled(true); + } else { + m_ui->layoutRowsLabel->setEnabled(false); + m_ui->layoutRowsSpin->setEnabled(false); } +} } // namespace diff --git a/effects/desktopgrid/desktopgrid_config.h b/effects/desktopgrid/desktopgrid_config.h index 457ab31dc..3a65c5d06 100644 --- a/effects/desktopgrid/desktopgrid_config.h +++ b/effects/desktopgrid/desktopgrid_config.h @@ -33,30 +33,30 @@ namespace KWin class DesktopGridEffectConfigForm : public QWidget, public Ui::DesktopGridEffectConfigForm { Q_OBJECT - public: - explicit DesktopGridEffectConfigForm(QWidget* parent); +public: + explicit DesktopGridEffectConfigForm(QWidget* parent); }; class DesktopGridEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit DesktopGridEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~DesktopGridEffectConfig(); +public: + explicit DesktopGridEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~DesktopGridEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private slots: - void layoutSelectionChanged(); +private slots: + void layoutSelectionChanged(); - private: - DesktopGridEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - QList m_alignmentItems; - }; +private: + DesktopGridEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; + QList m_alignmentItems; +}; } // namespace diff --git a/effects/dialogparent/dialogparent.cpp b/effects/dialogparent/dialogparent.cpp index cc663aa13..dc6e978bb 100644 --- a/effects/dialogparent/dialogparent.cpp +++ b/effects/dialogparent/dialogparent.cpp @@ -23,92 +23,86 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( dialogparent, DialogParentEffect ) +KWIN_EFFECT(dialogparent, DialogParentEffect) DialogParentEffect::DialogParentEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} -void DialogParentEffect::reconfigure( ReconfigureFlags ) - { +void DialogParentEffect::reconfigure(ReconfigureFlags) +{ // How long does it take for the effect to get it's full strength (in ms) - changeTime = animationTime( 200 ); - } + changeTime = animationTime(200); +} -void DialogParentEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void DialogParentEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // Check if this window has a modal dialog and change the window's // effect's strength accordingly bool hasDialog = w->findModal() != NULL; - if( hasDialog ) - { + if (hasDialog) { // Increase effect strength of this window - effectStrength[w] = qMin(1.0, effectStrength[w] + time/changeTime); - } - else - { - effectStrength[w] = qMax(0.0, effectStrength[w] - time/changeTime); - } - - // Call the next effect - effects->prePaintWindow( w, data, time ); + effectStrength[w] = qMin(1.0, effectStrength[w] + time / changeTime); + } else { + effectStrength[w] = qMax(0.0, effectStrength[w] - time / changeTime); } -void DialogParentEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { + // Call the next effect + effects->prePaintWindow(w, data, time); +} + +void DialogParentEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ double s = effectStrength[w]; - if(s > 0.0f) - { + if (s > 0.0f) { // Brightness will be within [1.0; 0.6] data.brightness *= (1.0 - s * 0.4); // Saturation within [1.0; 0.4] data.saturation *= (1.0 - s * 0.6); - } - - // Call the next effect. - effects->paintWindow( w, mask, region, data ); } -void DialogParentEffect::postPaintWindow( EffectWindow* w ) - { + // Call the next effect. + effects->paintWindow(w, mask, region, data); +} + +void DialogParentEffect::postPaintWindow(EffectWindow* w) +{ double s = effectStrength[w]; // If strength is between 0 and 1, the effect is still in progress and the // window has to be repainted during the next pass - if( s > 0.0 && s < 1.0 ) + if (s > 0.0 && s < 1.0) w->addRepaintFull(); // trigger next animation repaint // Call the next effect. - effects->postPaintWindow( w ); - } + effects->postPaintWindow(w); +} -void DialogParentEffect::windowActivated( EffectWindow* w ) - { +void DialogParentEffect::windowActivated(EffectWindow* w) +{ // If this window is a dialog, we need to repaint it's parent window, so // that the effect could be run for it // Set the window to be faded (or NULL if no window is active). - if( w && w->isModal() ) - { + if (w && w->isModal()) { // w is a modal dialog EffectWindowList mainwindows = w->mainWindows(); - foreach( EffectWindow* parent, mainwindows ) - parent->addRepaintFull(); - } + foreach (EffectWindow * parent, mainwindows) + parent->addRepaintFull(); } +} -void DialogParentEffect::windowClosed( EffectWindow* w ) - { +void DialogParentEffect::windowClosed(EffectWindow* w) +{ // If this window is a dialog, we need to repaint it's parent window, so // that the effect could be run for it // Set the window to be faded (or NULL if no window is active). - if ( w && w->isModal() ) - { + if (w && w->isModal()) { // w is a modal dialog EffectWindowList mainwindows = w->mainWindows(); - foreach( EffectWindow* parent, mainwindows ) - parent->addRepaintFull(); - } + foreach (EffectWindow * parent, mainwindows) + parent->addRepaintFull(); } +} } // namespace diff --git a/effects/dialogparent/dialogparent.h b/effects/dialogparent/dialogparent.h index 08eef031d..6a78e47a7 100644 --- a/effects/dialogparent/dialogparent.h +++ b/effects/dialogparent/dialogparent.h @@ -36,25 +36,25 @@ namespace KWin **/ class DialogParentEffect : public Effect - { - public: - DialogParentEffect(); - virtual void reconfigure( ReconfigureFlags ); +{ +public: + DialogParentEffect(); + virtual void reconfigure(ReconfigureFlags); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); - virtual void windowClosed( EffectWindow* c ); - virtual void windowActivated( EffectWindow* c ); + virtual void windowClosed(EffectWindow* c); + virtual void windowActivated(EffectWindow* c); - protected: - bool hasModalWindow( EffectWindow* t ); - private: - // The progress of the fading. - QHash effectStrength; - double changeTime; - }; +protected: + bool hasModalWindow(EffectWindow* t); +private: + // The progress of the fading. + QHash effectStrength; + double changeTime; +}; } // namespace diff --git a/effects/diminactive/diminactive.cpp b/effects/diminactive/diminactive.cpp index ce851ee13..b2e9108c3 100644 --- a/effects/diminactive/diminactive.cpp +++ b/effects/diminactive/diminactive.cpp @@ -26,120 +26,113 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( diminactive, DimInactiveEffect ) +KWIN_EFFECT(diminactive, DimInactiveEffect) DimInactiveEffect::DimInactiveEffect() - { - reconfigure( ReconfigureAll ); - timeline.setDuration( animationTime( 250 )); - previousActiveTimeline.setDuration( animationTime( 250 )); +{ + reconfigure(ReconfigureAll); + timeline.setDuration(animationTime(250)); + previousActiveTimeline.setDuration(animationTime(250)); active = effects->activeWindow(); previousActive = NULL; - } +} -void DimInactiveEffect::reconfigure( ReconfigureFlags ) - { +void DimInactiveEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("DimInactive"); dim_panels = conf.readEntry("DimPanels", false); dim_desktop = conf.readEntry("DimDesktop", false); dim_keepabove = conf.readEntry("DimKeepAbove", false); dim_by_group = conf.readEntry("DimByGroup", true); dim_strength = conf.readEntry("Strength", 25); - } +} -void DimInactiveEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void DimInactiveEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ double oldValue = timeline.value(); - if( effects->activeFullScreenEffect() ) - timeline.removeTime( time ); + if (effects->activeFullScreenEffect()) + timeline.removeTime(time); else - timeline.addTime( time ); - if( oldValue != timeline.value() ) + timeline.addTime(time); + if (oldValue != timeline.value()) effects->addRepaintFull(); - if( previousActive ) - { // We are fading out the previous window + if (previousActive) { + // We are fading out the previous window previousActive->addRepaintFull(); - previousActiveTimeline.addTime( time ); - } - effects->prePaintScreen( data, time ); + previousActiveTimeline.addTime(time); } + effects->prePaintScreen(data, time); +} -void DimInactiveEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( dimWindow( w ) || w == previousActive ) - { +void DimInactiveEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (dimWindow(w) || w == previousActive) { double previous = 1.0; - if( w == previousActive ) + if (w == previousActive) previous = previousActiveTimeline.value(); - if( previousActiveTimeline.value() == 1.0 ) + if (previousActiveTimeline.value() == 1.0) previousActive = NULL; - data.brightness *= (1.0 - (dim_strength / 100.0) * timeline.value() * previous ); - data.saturation *= (1.0 - (dim_strength / 100.0) * timeline.value() * previous ); - } - effects->paintWindow( w, mask, region, data ); + data.brightness *= (1.0 - (dim_strength / 100.0) * timeline.value() * previous); + data.saturation *= (1.0 - (dim_strength / 100.0) * timeline.value() * previous); } + effects->paintWindow(w, mask, region, data); +} -bool DimInactiveEffect::dimWindow( const EffectWindow* w ) const - { - if( effects->activeWindow() == w ) +bool DimInactiveEffect::dimWindow(const EffectWindow* w) const +{ + if (effects->activeWindow() == w) return false; // never dim active window - if( active && dim_by_group && active->group() == w->group()) + if (active && dim_by_group && active->group() == w->group()) return false; // don't dim in active group if configured so - if( w->isDock() && !dim_panels ) + if (w->isDock() && !dim_panels) return false; // don't dim panels if configured so - if( w->isDesktop() && !dim_desktop ) + if (w->isDesktop() && !dim_desktop) return false; // don't dim the desktop if configured so - if( w->keepAbove() && !dim_keepabove ) + if (w->keepAbove() && !dim_keepabove) return false; // don't dim keep-above windows if configured so - if( !w->isNormalWindow() && !w->isDialog() && !w->isDock() && !w->isDesktop()) + if (!w->isNormalWindow() && !w->isDialog() && !w->isDock() && !w->isDesktop()) return false; // don't dim more special window types // don't dim unmanaged windows, grouping doesn't work for them and maybe dimming // them doesn't make sense in general (they should be short-lived anyway) - if( !w->isManaged()) + if (!w->isManaged()) return false; return true; // dim the rest - } +} -void DimInactiveEffect::windowDeleted( EffectWindow* w ) - { - if( w == previousActive ) +void DimInactiveEffect::windowDeleted(EffectWindow* w) +{ + if (w == previousActive) previousActive = NULL; - } +} -void DimInactiveEffect::windowActivated( EffectWindow* w ) - { - if( active != NULL ) - { +void DimInactiveEffect::windowActivated(EffectWindow* w) +{ + if (active != NULL) { previousActive = active; - previousActiveTimeline.setProgress( 0.0 ); - if( !dimWindow( previousActive ) ) + previousActiveTimeline.setProgress(0.0); + if (!dimWindow(previousActive)) previousActive = NULL; - if( dim_by_group ) - { - if(( w == NULL || w->group() != active->group()) && active->group() != NULL ) - { // repaint windows that are no longer in the active group - foreach( EffectWindow* tmp, active->group()->members()) - tmp->addRepaintFull(); - } + if (dim_by_group) { + if ((w == NULL || w->group() != active->group()) && active->group() != NULL) { + // repaint windows that are no longer in the active group + foreach (EffectWindow * tmp, active->group()->members()) + tmp->addRepaintFull(); } - else + } else active->addRepaintFull(); - } - active = w; - if( active != NULL ) - { - if( dim_by_group ) - { - if( active->group() != NULL ) - { // repaint newly active windows - foreach( EffectWindow* tmp, active->group()->members()) - tmp->addRepaintFull(); - } - } - else - active->addRepaintFull(); - } } + active = w; + if (active != NULL) { + if (dim_by_group) { + if (active->group() != NULL) { + // repaint newly active windows + foreach (EffectWindow * tmp, active->group()->members()) + tmp->addRepaintFull(); + } + } else + active->addRepaintFull(); + } +} } // namespace diff --git a/effects/diminactive/diminactive.h b/effects/diminactive/diminactive.h index d5be4f246..5fd1178a8 100644 --- a/effects/diminactive/diminactive.h +++ b/effects/diminactive/diminactive.h @@ -31,26 +31,26 @@ namespace KWin class DimInactiveEffect : public Effect - { - public: - DimInactiveEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowDeleted( EffectWindow* w ); - virtual void windowActivated( EffectWindow* c ); - private: - bool dimWindow( const EffectWindow* w ) const; - TimeLine timeline; - EffectWindow* active; - EffectWindow* previousActive; - TimeLine previousActiveTimeline; - int dim_strength; // reduce saturation and brightness by this percentage - bool dim_panels; // do/don't dim also all panels - bool dim_desktop; // do/don't dim the desktop - bool dim_keepabove; // do/don't dim keep-above windows - bool dim_by_group; // keep visible all windows from the active window's group or only the active window - }; +{ +public: + DimInactiveEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowDeleted(EffectWindow* w); + virtual void windowActivated(EffectWindow* c); +private: + bool dimWindow(const EffectWindow* w) const; + TimeLine timeline; + EffectWindow* active; + EffectWindow* previousActive; + TimeLine previousActiveTimeline; + int dim_strength; // reduce saturation and brightness by this percentage + bool dim_panels; // do/don't dim also all panels + bool dim_desktop; // do/don't dim the desktop + bool dim_keepabove; // do/don't dim keep-above windows + bool dim_by_group; // keep visible all windows from the active window's group or only the active window +}; } // namespace diff --git a/effects/diminactive/diminactive_config.cpp b/effects/diminactive/diminactive_config.cpp index 011998fb1..d71bd4d0c 100644 --- a/effects/diminactive/diminactive_config.cpp +++ b/effects/diminactive/diminactive_config.cpp @@ -38,12 +38,12 @@ KWIN_EFFECT_CONFIG_FACTORY DimInactiveEffectConfigForm::DimInactiveEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } DimInactiveEffectConfig::DimInactiveEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new DimInactiveEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -57,10 +57,10 @@ DimInactiveEffectConfig::DimInactiveEffectConfig(QWidget* parent, const QVariant connect(m_ui->checkGroup, SIGNAL(toggled(bool)), this, SLOT(changed())); load(); - } +} void DimInactiveEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("DimInactive"); @@ -77,10 +77,10 @@ void DimInactiveEffectConfig::load() m_ui->checkGroup->setChecked(group); emit changed(false); - } +} void DimInactiveEffectConfig::save() - { +{ KConfigGroup conf = EffectsHandler::effectConfig("DimInactive"); conf.writeEntry("Strength", m_ui->spinStrength->value()); @@ -93,18 +93,18 @@ void DimInactiveEffectConfig::save() KCModule::save(); emit changed(false); - EffectsHandler::sendReloadMessage( "diminactive" ); - } + EffectsHandler::sendReloadMessage("diminactive"); +} void DimInactiveEffectConfig::defaults() - { +{ m_ui->spinStrength->setValue(25); m_ui->checkPanel->setChecked(false); m_ui->checkDesktop->setChecked(false); m_ui->checkKeepAbove->setChecked(false); m_ui->checkGroup->setChecked(true); emit changed(true); - } +} } // namespace diff --git a/effects/diminactive/diminactive_config.h b/effects/diminactive/diminactive_config.h index a9059e680..116994a13 100644 --- a/effects/diminactive/diminactive_config.h +++ b/effects/diminactive/diminactive_config.h @@ -31,23 +31,23 @@ namespace KWin class DimInactiveEffectConfigForm : public QWidget, public Ui::DimInactiveEffectConfigForm { Q_OBJECT - public: - explicit DimInactiveEffectConfigForm(QWidget* parent); +public: + explicit DimInactiveEffectConfigForm(QWidget* parent); }; class DimInactiveEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit DimInactiveEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit DimInactiveEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - DimInactiveEffectConfigForm* m_ui; - }; +private: + DimInactiveEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/dimscreen/dimscreen.cpp b/effects/dimscreen/dimscreen.cpp index 22832df8a..1f42cb11b 100644 --- a/effects/dimscreen/dimscreen.cpp +++ b/effects/dimscreen/dimscreen.cpp @@ -24,95 +24,87 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( dimscreen, DimScreenEffect ) +KWIN_EFFECT(dimscreen, DimScreenEffect) DimScreenEffect::DimScreenEffect() - : mActivated( false ) - , activateAnimation( false ) - , deactivateAnimation( false ) - { - reconfigure( ReconfigureAll ); - } + : mActivated(false) + , activateAnimation(false) + , deactivateAnimation(false) +{ + reconfigure(ReconfigureAll); +} DimScreenEffect::~DimScreenEffect() - { - } +{ +} -void DimScreenEffect::reconfigure( ReconfigureFlags ) - { - timeline.setDuration( animationTime( 250 )); - } +void DimScreenEffect::reconfigure(ReconfigureFlags) +{ + timeline.setDuration(animationTime(250)); +} -void DimScreenEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( mActivated && activateAnimation && !effects->activeFullScreenEffect() ) - timeline.addTime( time ); - if( mActivated && deactivateAnimation ) - timeline.removeTime( time ); - if( mActivated && effects->activeFullScreenEffect() ) - timeline.removeTime( time ); - if( mActivated && !activateAnimation && !deactivateAnimation && !effects->activeFullScreenEffect() && timeline.value() != 1.0 ) - timeline.addTime( time ); - effects->prePaintScreen( data, time ); - } +void DimScreenEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (mActivated && activateAnimation && !effects->activeFullScreenEffect()) + timeline.addTime(time); + if (mActivated && deactivateAnimation) + timeline.removeTime(time); + if (mActivated && effects->activeFullScreenEffect()) + timeline.removeTime(time); + if (mActivated && !activateAnimation && !deactivateAnimation && !effects->activeFullScreenEffect() && timeline.value() != 1.0) + timeline.addTime(time); + effects->prePaintScreen(data, time); +} void DimScreenEffect::postPaintScreen() - { - if( mActivated ) - { - if( activateAnimation && timeline.value() == 1.0 ) - { +{ + if (mActivated) { + if (activateAnimation && timeline.value() == 1.0) { activateAnimation = false; effects->addRepaintFull(); - } - if( deactivateAnimation && timeline.value() == 0.0 ) - { + } + if (deactivateAnimation && timeline.value() == 0.0) { deactivateAnimation = false; mActivated = false; effects->addRepaintFull(); - } + } // still animating - if( timeline.value() > 0.0 && timeline.value() < 1.0 ) + if (timeline.value() > 0.0 && timeline.value() < 1.0) effects->addRepaintFull(); - } + } effects->postPaintScreen(); - } +} -void DimScreenEffect::paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ) - { - if( mActivated && ( w != window ) && w->isManaged() ) - { - data.brightness *= (1.0 - 0.33 * timeline.value() ); - data.saturation *= (1.0 - 0.33 * timeline.value() ); - } - effects->paintWindow( w, mask, region, data ); +void DimScreenEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) +{ + if (mActivated && (w != window) && w->isManaged()) { + data.brightness *= (1.0 - 0.33 * timeline.value()); + data.saturation *= (1.0 - 0.33 * timeline.value()); } + effects->paintWindow(w, mask, region, data); +} -void DimScreenEffect::windowActivated( EffectWindow *w ) - { - if( !w ) return; +void DimScreenEffect::windowActivated(EffectWindow *w) +{ + if (!w) return; QStringList check; check << "kdesu kdesu"; check << "kdesudo kdesudo"; check << "polkit-kde-manager polkit-kde-manager"; check << "polkit-kde-authentication-agent-1 polkit-kde-authentication-agent-1"; check << "pinentry pinentry"; - if( check.contains( w->windowClass() ) ) - { + if (check.contains(w->windowClass())) { mActivated = true; activateAnimation = true; deactivateAnimation = false; window = w; effects->addRepaintFull(); - } - else - { - if( mActivated) - { + } else { + if (mActivated) { activateAnimation = false; deactivateAnimation = true; effects->addRepaintFull(); - } } } +} } // namespace diff --git a/effects/dimscreen/dimscreen.h b/effects/dimscreen/dimscreen.h index 310fa6a09..8023022e3 100644 --- a/effects/dimscreen/dimscreen.h +++ b/effects/dimscreen/dimscreen.h @@ -28,24 +28,24 @@ namespace KWin class DimScreenEffect : public Effect - { - public: - DimScreenEffect(); - ~DimScreenEffect(); +{ +public: + DimScreenEffect(); + ~DimScreenEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); - virtual void paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ); - virtual void windowActivated( EffectWindow *w ); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); + virtual void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data); + virtual void windowActivated(EffectWindow *w); - private: - bool mActivated; - bool activateAnimation; - bool deactivateAnimation; - TimeLine timeline; - EffectWindow* window; - }; +private: + bool mActivated; + bool activateAnimation; + bool deactivateAnimation; + TimeLine timeline; + EffectWindow* window; +}; } // namespace diff --git a/effects/explosion/explosion.cpp b/effects/explosion/explosion.cpp index 90cddb0a6..19c77a992 100644 --- a/effects/explosion/explosion.cpp +++ b/effects/explosion/explosion.cpp @@ -33,11 +33,11 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( explosion, ExplosionEffect ) -KWIN_EFFECT_SUPPORTED( explosion, ExplosionEffect::supported() ) +KWIN_EFFECT(explosion, ExplosionEffect) +KWIN_EFFECT_SUPPORTED(explosion, ExplosionEffect::supported()) ExplosionEffect::ExplosionEffect() : Effect() - { +{ mShader = 0; mStartOffsetTex = 0; mEndOffsetTex = 0; @@ -45,20 +45,20 @@ ExplosionEffect::ExplosionEffect() : Effect() mActiveAnimations = 0; mValid = true; mInited = false; - } +} ExplosionEffect::~ExplosionEffect() - { +{ delete mShader; delete mStartOffsetTex; delete mEndOffsetTex; - } +} bool ExplosionEffect::supported() - { +{ return GLShader::fragmentShaderSupported() && - (effects->compositingType() == OpenGLCompositing); - } + (effects->compositingType() == OpenGLCompositing); +} bool ExplosionEffect::loadData() { @@ -67,20 +67,16 @@ bool ExplosionEffect::loadData() const QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/explosion.frag"); QString starttexture = KGlobal::dirs()->findResource("data", "kwin/explosion-start.png"); QString endtexture = KGlobal::dirs()->findResource("data", "kwin/explosion-end.png"); - if(starttexture.isEmpty() || endtexture.isEmpty()) - { + if (starttexture.isEmpty() || endtexture.isEmpty()) { kError(1212) << "Couldn't locate texture files" << endl; return false; } mShader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, fragmentshader); - if(!mShader->isValid()) - { + if (!mShader->isValid()) { kError(1212) << "The shader failed to load!" << endl; return false; - } - else - { + } else { ShaderManager::instance()->pushShader(mShader); mShader->setUniform("startOffsetTexture", 4); mShader->setUniform("endOffsetTexture", 5); @@ -89,70 +85,61 @@ bool ExplosionEffect::loadData() mStartOffsetTex = new GLTexture(starttexture); mEndOffsetTex = new GLTexture(endtexture); - if(mStartOffsetTex->isNull() || mEndOffsetTex->isNull()) - { + if (mStartOffsetTex->isNull() || mEndOffsetTex->isNull()) { kError(1212) << "The textures failed to load!" << endl; return false; - } - else - { - mStartOffsetTex->setFilter( GL_LINEAR ); - mEndOffsetTex->setFilter( GL_LINEAR ); + } else { + mStartOffsetTex->setFilter(GL_LINEAR); + mEndOffsetTex->setFilter(GL_LINEAR); } return true; - } +} -void ExplosionEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( mActiveAnimations > 0 ) +void ExplosionEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (mActiveAnimations > 0) // We need to mark the screen as transformed. Otherwise the whole screen // won't be repainted, resulting in artefacts data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void ExplosionEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( mWindows.contains( w )) - { - if( mValid && !mInited ) +void ExplosionEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (mWindows.contains(w)) { + if (mValid && !mInited) mValid = loadData(); - if( mValid ) - { - mWindows[ w ] += time / animationTime( 700.0 ); // complete change in 700ms - if( mWindows[ w ] < 1 ) - { + if (mValid) { + mWindows[ w ] += time / animationTime(700.0); // complete change in 700ms + if (mWindows[ w ] < 1) { data.setTranslucent(); data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - } - else - { - mWindows.remove( w ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); + } else { + mWindows.remove(w); w->unrefWindow(); mActiveAnimations--; - } } } - - effects->prePaintWindow( w, data, time ); } -void ExplosionEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { + effects->prePaintWindow(w, data, time); +} + +void ExplosionEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ // Make sure we have OpenGL compositing and the window is vidible and not a // special window - bool useshader = ( mValid && mWindows.contains( w ) ); - if( useshader ) - { + bool useshader = (mValid && mWindows.contains(w)); + if (useshader) { double maxscaleadd = 1.5f; - double scale = 1 + maxscaleadd*mWindows[w]; + double scale = 1 + maxscaleadd * mWindows[w]; data.xScale = scale; data.yScale = scale; - data.xTranslate += int( w->width() / 2 * ( 1 - scale )); - data.yTranslate += int( w->height() / 2 * ( 1 - scale )); + data.xTranslate += int(w->width() / 2 * (1 - scale)); + data.yTranslate += int(w->height() / 2 * (1 - scale)); data.opacity *= 0.99; // Force blending ShaderManager *manager = ShaderManager::instance(); GLShader *shader = manager->pushShader(ShaderManager::GenericShader); @@ -168,49 +155,47 @@ void ExplosionEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Wi mEndOffsetTex->bind(); glActiveTexture(GL_TEXTURE0); data.shader = mShader; - } + } // Call the next effect. - effects->paintWindow( w, mask, region, data ); + effects->paintWindow(w, mask, region, data); - if( useshader ) - { + if (useshader) { ShaderManager::instance()->popShader(); glActiveTexture(GL_TEXTURE4); mStartOffsetTex->unbind(); glActiveTexture(GL_TEXTURE5); mEndOffsetTex->unbind(); glActiveTexture(GL_TEXTURE0); - } } +} void ExplosionEffect::postPaintScreen() - { - if( mActiveAnimations > 0 ) +{ + if (mActiveAnimations > 0) effects->addRepaintFull(); // Call the next effect. effects->postPaintScreen(); - } +} -void ExplosionEffect::windowClosed( EffectWindow* c ) - { - const void* e = c->data( WindowClosedGrabRole ).value(); - if( e && e != this ) +void ExplosionEffect::windowClosed(EffectWindow* c) +{ + const void* e = c->data(WindowClosedGrabRole).value(); + if (e && e != this) return; - if( c->isOnCurrentDesktop() && !c->isMinimized()) - { + if (c->isOnCurrentDesktop() && !c->isMinimized()) { mWindows[ c ] = 0; // count up to 1 c->addRepaintFull(); c->refWindow(); mActiveAnimations++; - } } +} -void ExplosionEffect::windowDeleted( EffectWindow* c ) - { - mWindows.remove( c ); - } +void ExplosionEffect::windowDeleted(EffectWindow* c) +{ + mWindows.remove(c); +} } // namespace diff --git a/effects/explosion/explosion.h b/effects/explosion/explosion.h index 6c21d5126..bdda28b4c 100644 --- a/effects/explosion/explosion.h +++ b/effects/explosion/explosion.h @@ -37,34 +37,34 @@ class GLTexture; **/ class ExplosionEffect : public Effect - { - public: - ExplosionEffect(); - ~ExplosionEffect(); +{ +public: + ExplosionEffect(); + ~ExplosionEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); - static bool supported(); + static bool supported(); - protected: - bool loadData(); +protected: + bool loadData(); - private: - GLShader* mShader; - GLTexture* mStartOffsetTex; - GLTexture* mEndOffsetTex; - QMap< const EffectWindow*, double > mWindows; - int mActiveAnimations; - bool mValid; - bool mInited; - }; +private: + GLShader* mShader; + GLTexture* mStartOffsetTex; + GLTexture* mEndOffsetTex; + QMap< const EffectWindow*, double > mWindows; + int mActiveAnimations; + bool mValid; + bool mInited; +}; } // namespace diff --git a/effects/fade/fade.cpp b/effects/fade/fade.cpp index 4911527e4..d735aa1ab 100644 --- a/effects/fade/fade.cpp +++ b/effects/fade/fade.cpp @@ -25,190 +25,174 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( fade, FadeEffect ) +KWIN_EFFECT(fade, FadeEffect) FadeEffect::FadeEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} -void FadeEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "Fade" ); - fadeInTime = animationTime( conf, "FadeInTime", 150 ); - fadeOutTime = animationTime( conf, "FadeOutTime", 150 ); - fadeWindows = conf.readEntry( "FadeWindows", true ); +void FadeEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("Fade"); + fadeInTime = animationTime(conf, "FadeInTime", 150); + fadeOutTime = animationTime(conf, "FadeOutTime", 150); + fadeWindows = conf.readEntry("FadeWindows", true); // Add all existing windows to the window list // TODO: Enabling desktop effects should trigger windowAdded() on all windows windows.clear(); - if( !fadeWindows ) + if (!fadeWindows) return; - foreach( EffectWindow *w, effects->stackingOrder() ) - if( w && isFadeWindow( w )) // TODO: Apparently w can == NULL here? - windows[ w ] = WindowInfo(); - } + foreach (EffectWindow * w, effects->stackingOrder()) + if (w && isFadeWindow(w)) // TODO: Apparently w can == NULL here? + windows[ w ] = WindowInfo(); +} -void FadeEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty()) - { - fadeInStep = time / double( fadeInTime ); - fadeOutStep = time / double( fadeOutTime ); - } - effects->prePaintScreen( data, time ); +void FadeEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) { + fadeInStep = time / double(fadeInTime); + fadeOutStep = time / double(fadeOutTime); } + effects->prePaintScreen(data, time); +} -void FadeEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( windows.contains( w )) - { +void FadeEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (windows.contains(w)) { windows[ w ].fadeInStep += fadeInStep; windows[ w ].fadeOutStep += fadeOutStep; - if( windows[ w ].opacity < 1.0 ) + if (windows[ w ].opacity < 1.0) data.setTranslucent(); - if( windows[ w ].deleted ) - { - if( windows[ w ].opacity <= 0.0 ) - { - windows.remove( w ); + if (windows[ w ].deleted) { + if (windows[ w ].opacity <= 0.0) { + windows.remove(w); w->unrefWindow(); - } - else - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - } - } - effects->prePaintWindow( w, data, time ); - if( windows.contains( w ) && !w->isPaintingEnabled() && !effects->activeFullScreenEffect() ) - { // if the window isn't to be painted, then let's make sure - // to track its progress - if( windows[ w ].fadeInStep < 1.0 - || windows[ w ].fadeOutStep < 1.0 ) - { // but only if the total change is less than the - // maximum possible change - w->addRepaintFull(); - } + } else + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } } + effects->prePaintWindow(w, data, time); + if (windows.contains(w) && !w->isPaintingEnabled() && !effects->activeFullScreenEffect()) { + // if the window isn't to be painted, then let's make sure + // to track its progress + if (windows[ w ].fadeInStep < 1.0 + || windows[ w ].fadeOutStep < 1.0) { + // but only if the total change is less than the + // maximum possible change + w->addRepaintFull(); + } + } +} -void FadeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( windows.contains( w )) - { - if( windows[ w ].deleted - || windows[ w ].opacity != data.opacity - || windows[ w ].saturation != data.saturation - || windows[ w ].brightness != data.brightness ) - { +void FadeEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (windows.contains(w)) { + if (windows[ w ].deleted + || windows[ w ].opacity != data.opacity + || windows[ w ].saturation != data.saturation + || windows[ w ].brightness != data.brightness) { WindowPaintData new_data = data; - if( windows[ w ].deleted ) + if (windows[ w ].deleted) new_data.opacity = 0.0; - if( new_data.opacity > windows[ w ].opacity ) - { - windows[ w ].opacity = qMin( new_data.opacity, - windows[ w ].opacity + windows[ w ].fadeInStep ); - } - else if( new_data.opacity < windows[ w ].opacity ) - { - windows[ w ].opacity = qMax( new_data.opacity, - windows[ w ].opacity - windows[ w ].fadeOutStep ); - } + if (new_data.opacity > windows[ w ].opacity) { + windows[ w ].opacity = qMin(new_data.opacity, + windows[ w ].opacity + windows[ w ].fadeInStep); + } else if (new_data.opacity < windows[ w ].opacity) { + windows[ w ].opacity = qMax(new_data.opacity, + windows[ w ].opacity - windows[ w ].fadeOutStep); + } - if( new_data.saturation > windows[ w ].saturation ) - { - windows[ w ].saturation = qMin( new_data.saturation, - windows[ w ].saturation + windows[ w ].fadeInStep ); - } - else if( new_data.saturation < windows[ w ].saturation ) - { - windows[ w ].saturation = qMax( new_data.saturation, - windows[ w ].saturation - windows[ w ].fadeOutStep ); - } + if (new_data.saturation > windows[ w ].saturation) { + windows[ w ].saturation = qMin(new_data.saturation, + windows[ w ].saturation + windows[ w ].fadeInStep); + } else if (new_data.saturation < windows[ w ].saturation) { + windows[ w ].saturation = qMax(new_data.saturation, + windows[ w ].saturation - windows[ w ].fadeOutStep); + } - if( new_data.brightness > windows[ w ].brightness ) - { - windows[ w ].brightness = qMin( new_data.brightness, - windows[ w ].brightness + windows[ w ].fadeInStep ); - } - else if( new_data.brightness < windows[ w ].brightness ) - { - windows[ w ].brightness = qMax( new_data.brightness, - windows[ w ].brightness - windows[ w ].fadeOutStep ); - } + if (new_data.brightness > windows[ w ].brightness) { + windows[ w ].brightness = qMin(new_data.brightness, + windows[ w ].brightness + windows[ w ].fadeInStep); + } else if (new_data.brightness < windows[ w ].brightness) { + windows[ w ].brightness = qMax(new_data.brightness, + windows[ w ].brightness - windows[ w ].fadeOutStep); + } - windows[ w ].opacity = qBound( 0.0, windows[ w ].opacity, 1.0 ); - windows[ w ].saturation = qBound( 0.0, windows[ w ].saturation, 1.0 ); - windows[ w ].brightness = qBound( 0.0, windows[ w ].brightness, 1.0 ); + windows[ w ].opacity = qBound(0.0, windows[ w ].opacity, 1.0); + windows[ w ].saturation = qBound(0.0, windows[ w ].saturation, 1.0); + windows[ w ].brightness = qBound(0.0, windows[ w ].brightness, 1.0); windows[ w ].fadeInStep = 0.0; windows[ w ].fadeOutStep = 0.0; new_data.opacity = windows[ w ].opacity; new_data.saturation = windows[ w ].saturation; new_data.brightness = windows[ w ].brightness; - effects->paintWindow( w, mask, region, new_data ); - if( windows[ w ].opacity != data.opacity - || windows[ w ].saturation != data.saturation - || windows[ w ].brightness != data.brightness ) + effects->paintWindow(w, mask, region, new_data); + if (windows[ w ].opacity != data.opacity + || windows[ w ].saturation != data.saturation + || windows[ w ].brightness != data.brightness) w->addRepaintFull(); return; - } + } windows[ w ].fadeInStep = 0.0; windows[ w ].fadeOutStep = 0.0; - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void FadeEffect::windowOpacityChanged( EffectWindow* w, double old_opacity ) - { - if( !windows.contains( w )) +void FadeEffect::windowOpacityChanged(EffectWindow* w, double old_opacity) +{ + if (!windows.contains(w)) windows[ w ].opacity = old_opacity; - if( windows[ w ].opacity == 1.0 ) + if (windows[ w ].opacity == 1.0) windows[ w ].opacity -= 0.1 / fadeOutTime; w->addRepaintFull(); - } +} -void FadeEffect::windowAdded( EffectWindow* w ) - { - if( !fadeWindows || !isFadeWindow( w )) +void FadeEffect::windowAdded(EffectWindow* w) +{ + if (!fadeWindows || !isFadeWindow(w)) return; windows[ w ].opacity = 0.0; w->addRepaintFull(); - } +} -void FadeEffect::windowClosed( EffectWindow* w ) - { - if( !fadeWindows || !isFadeWindow( w )) +void FadeEffect::windowClosed(EffectWindow* w) +{ + if (!fadeWindows || !isFadeWindow(w)) return; - if( !windows.contains( w )) + if (!windows.contains(w)) windows[ w ].opacity = w->opacity(); - if( windows[ w ].opacity == 1.0 ) + if (windows[ w ].opacity == 1.0) windows[ w ].opacity -= 0.1 / fadeOutTime; windows[ w ].deleted = true; w->refWindow(); w->addRepaintFull(); - } +} -void FadeEffect::windowDeleted( EffectWindow* w ) - { - windows.remove( w ); - } +void FadeEffect::windowDeleted(EffectWindow* w) +{ + windows.remove(w); +} -bool FadeEffect::isFadeWindow( EffectWindow* w ) - { +bool FadeEffect::isFadeWindow(EffectWindow* w) +{ void* e; - if( w->isDeleted() ) - e = w->data( WindowClosedGrabRole ).value(); + if (w->isDeleted()) + e = w->data(WindowClosedGrabRole).value(); else - e = w->data( WindowAddedGrabRole ).value(); - if( w->windowClass() == "ksplashx ksplashx" - || w->windowClass() == "ksplashsimple ksplashsimple" - || ( e && e != this )) - { // see login effect + e = w->data(WindowAddedGrabRole).value(); + if (w->windowClass() == "ksplashx ksplashx" + || w->windowClass() == "ksplashsimple ksplashsimple" + || (e && e != this)) { + // see login effect return false; - } - return ( !w->isDesktop() && !w->isUtility() ); } + return (!w->isDesktop() && !w->isUtility()); +} } // namespace diff --git a/effects/fade/fade.h b/effects/fade/fade.h index 48b100e63..1a20bf73c 100644 --- a/effects/fade/fade.h +++ b/effects/fade/fade.h @@ -28,45 +28,45 @@ namespace KWin class FadeEffect : public Effect - { - public: - FadeEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); +{ +public: + FadeEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); - // TODO react also on virtual desktop changes - virtual void windowOpacityChanged( EffectWindow* c, double old_opacity ); - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); + // TODO react also on virtual desktop changes + virtual void windowOpacityChanged(EffectWindow* c, double old_opacity); + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); - bool isFadeWindow( EffectWindow* w ); - private: - class WindowInfo; - QHash< const EffectWindow*, WindowInfo > windows; - double fadeInStep, fadeOutStep; - int fadeInTime, fadeOutTime; - bool fadeWindows; - }; + bool isFadeWindow(EffectWindow* w); +private: + class WindowInfo; + QHash< const EffectWindow*, WindowInfo > windows; + double fadeInStep, fadeOutStep; + int fadeInTime, fadeOutTime; + bool fadeWindows; +}; class FadeEffect::WindowInfo - { - public: - WindowInfo() - : fadeInStep( 0.0 ) - , fadeOutStep( 0.0 ) - , opacity( 1.0 ) - , saturation( 1.0 ) - , brightness( 1.0 ) - , deleted( false ) - {} - double fadeInStep, fadeOutStep; - double opacity; - double saturation, brightness; - bool deleted; - }; +{ +public: + WindowInfo() + : fadeInStep(0.0) + , fadeOutStep(0.0) + , opacity(1.0) + , saturation(1.0) + , brightness(1.0) + , deleted(false) + {} + double fadeInStep, fadeOutStep; + double opacity; + double saturation, brightness; + bool deleted; +}; } // namespace diff --git a/effects/fadedesktop/fadedesktop.cpp b/effects/fadedesktop/fadedesktop.cpp index 990c7430b..1858fa7b6 100644 --- a/effects/fadedesktop/fadedesktop.cpp +++ b/effects/fadedesktop/fadedesktop.cpp @@ -25,92 +25,86 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( fadedesktop, FadeDesktopEffect ) +KWIN_EFFECT(fadedesktop, FadeDesktopEffect) FadeDesktopEffect::FadeDesktopEffect() - : m_fading( false ) - { - m_timeline.setCurveShape( TimeLine::LinearCurve ); - reconfigure( ReconfigureAll ); - } + : m_fading(false) +{ + m_timeline.setCurveShape(TimeLine::LinearCurve); + reconfigure(ReconfigureAll); +} -void FadeDesktopEffect::reconfigure( ReconfigureFlags ) - { - m_timeline.setDuration( animationTime( 250 )); - } +void FadeDesktopEffect::reconfigure(ReconfigureFlags) +{ + m_timeline.setDuration(animationTime(250)); +} -void FadeDesktopEffect::prePaintScreen( ScreenPrePaintData &data, int time ) - { - if( m_fading ) - { - m_timeline.addTime( time ); +void FadeDesktopEffect::prePaintScreen(ScreenPrePaintData &data, int time) +{ + if (m_fading) { + m_timeline.addTime(time); // PAINT_SCREEN_BACKGROUND_FIRST is needed because screen will be actually painted more than once, // so with normal screen painting second screen paint would erase parts of the first paint - if( m_timeline.value() != 1.0 ) + if (m_timeline.value() != 1.0) data.mask |= PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST; - else - { + else { m_fading = false; - m_timeline.setProgress( 0.0 ); - foreach( EffectWindow* w, effects->stackingOrder() ) - { - w->setData( WindowForceBlurRole, QVariant( false ) ); - } - effects->setActiveFullScreenEffect( NULL ); + m_timeline.setProgress(0.0); + foreach (EffectWindow * w, effects->stackingOrder()) { + w->setData(WindowForceBlurRole, QVariant(false)); } + effects->setActiveFullScreenEffect(NULL); } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} void FadeDesktopEffect::postPaintScreen() - { - if( m_fading ) +{ + if (m_fading) effects->addRepaintFull(); effects->postPaintScreen(); - } +} -void FadeDesktopEffect::prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ) - { - if( m_fading ) - { - if( w->isOnDesktop( m_oldDesktop )) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); +void FadeDesktopEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) +{ + if (m_fading) { + if (w->isOnDesktop(m_oldDesktop)) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); data.setTranslucent(); - } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void FadeDesktopEffect::paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ) - { - if( m_fading && !( w->isOnCurrentDesktop() && w->isOnDesktop( m_oldDesktop ))) - { - if( w->isOnDesktop( m_oldDesktop )) +void FadeDesktopEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) +{ + if (m_fading && !(w->isOnCurrentDesktop() && w->isOnDesktop(m_oldDesktop))) { + if (w->isOnDesktop(m_oldDesktop)) data.opacity *= 1 - m_timeline.value(); else data.opacity *= m_timeline.value(); - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void FadeDesktopEffect::desktopChanged( int old ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void FadeDesktopEffect::desktopChanged(int old) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - + // TODO: Fix glitches when fading while a previous fade is still happening - effects->setActiveFullScreenEffect( this ); + effects->setActiveFullScreenEffect(this); m_fading = true; - m_timeline.setProgress( 0 ); + m_timeline.setProgress(0); m_oldDesktop = old; - foreach( EffectWindow* w, effects->stackingOrder() ) - { - w->setData( WindowForceBlurRole, QVariant( true ) ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + w->setData(WindowForceBlurRole, QVariant(true)); + } effects->addRepaintFull(); - } +} } // namespace diff --git a/effects/fadedesktop/fadedesktop.h b/effects/fadedesktop/fadedesktop.h index 9cee7b74d..81cac9ff2 100644 --- a/effects/fadedesktop/fadedesktop.h +++ b/effects/fadedesktop/fadedesktop.h @@ -29,22 +29,22 @@ namespace KWin class FadeDesktopEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - FadeDesktopEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ); - virtual void desktopChanged( int old ); +public: + FadeDesktopEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data); + virtual void desktopChanged(int old); - private: - bool m_fading; - TimeLine m_timeline; - int m_oldDesktop; - }; +private: + bool m_fading; + TimeLine m_timeline; + int m_oldDesktop; +}; } // namespace diff --git a/effects/fallapart/fallapart.cpp b/effects/fallapart/fallapart.cpp index 8e3c0e775..36bda5251 100644 --- a/effects/fallapart/fallapart.cpp +++ b/effects/fallapart/fallapart.cpp @@ -26,112 +26,104 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( fallapart, FallApartEffect ) +KWIN_EFFECT(fallapart, FallApartEffect) FallApartEffect::FallApartEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} -void FallApartEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "FallApart" ); - blockSize = qBound( 1, conf.readEntry( "BlockSize", 40 ), 100000 ); - } +void FallApartEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("FallApart"); + blockSize = qBound(1, conf.readEntry("BlockSize", 40), 100000); +} -void FallApartEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty()) +void FallApartEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void FallApartEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( windows.contains( w ) && isRealWindow( w )) - { - if( windows[ w ] < 1 ) - { - windows[ w ] += time / animationTime( 1000. ); +void FallApartEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (windows.contains(w) && isRealWindow(w)) { + if (windows[ w ] < 1) { + windows[ w ] += time / animationTime(1000.); data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); // Request the window to be divided into cells - data.quads = data.quads.makeGrid( blockSize ); - } - else - { - windows.remove( w ); + data.quads = data.quads.makeGrid(blockSize); + } else { + windows.remove(w); w->unrefWindow(); - } } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void FallApartEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( windows.contains( w ) && isRealWindow( w ) ) - { +void FallApartEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (windows.contains(w) && isRealWindow(w)) { WindowQuadList new_quads; int cnt = 0; - foreach( WindowQuad quad, data.quads ) // krazy:exclude=foreach - { + foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach // make fragments move in various directions, based on where // they are (left pieces generally move to the left, etc.) - QPointF p1( quad[ 0 ].x(), quad[ 0 ].y()); + QPointF p1(quad[ 0 ].x(), quad[ 0 ].y()); double xdiff = 0; - if( p1.x() < w->width() / 2 ) - xdiff = -( w->width() / 2 - p1.x()) / w->width() * 100; - if( p1.x() > w->width() / 2 ) - xdiff = ( p1.x() - w->width() / 2 ) / w->width() * 100; + if (p1.x() < w->width() / 2) + xdiff = -(w->width() / 2 - p1.x()) / w->width() * 100; + if (p1.x() > w->width() / 2) + xdiff = (p1.x() - w->width() / 2) / w->width() * 100; double ydiff = 0; - if( p1.y() < w->height() / 2 ) - ydiff = -( w->height() / 2 - p1.y()) / w->height() * 100; - if( p1.y() > w->height() / 2 ) - ydiff = ( p1.y() - w->height() / 2 ) / w->height() * 100; + if (p1.y() < w->height() / 2) + ydiff = -(w->height() / 2 - p1.y()) / w->height() * 100; + if (p1.y() > w->height() / 2) + ydiff = (p1.y() - w->height() / 2) / w->height() * 100; double modif = windows[ w ] * windows[ w ] * 64; - srandom( cnt ); // change direction randomly but consistently - xdiff += ( rand() % 21 - 10 ); - ydiff += ( rand() % 21 - 10 ); - for( int j = 0; - j < 4; - ++j ) - { - quad[ j ].move( quad[ j ].x() + xdiff * modif, quad[ j ].y() + ydiff * modif ); - } + srandom(cnt); // change direction randomly but consistently + xdiff += (rand() % 21 - 10); + ydiff += (rand() % 21 - 10); + for (int j = 0; + j < 4; + ++j) { + quad[ j ].move(quad[ j ].x() + xdiff * modif, quad[ j ].y() + ydiff * modif); + } // also make the fragments rotate around their center - QPointF center(( quad[ 0 ].x() + quad[ 1 ].x() + quad[ 2 ].x() + quad[ 3 ].x()) / 4, - ( quad[ 0 ].y() + quad[ 1 ].y() + quad[ 2 ].y() + quad[ 3 ].y()) / 4 ); - double adiff = ( rand() % 720 - 360 ) / 360. * 2 * M_PI; // spin randomly - for( int j = 0; - j < 4; - ++j ) - { + QPointF center((quad[ 0 ].x() + quad[ 1 ].x() + quad[ 2 ].x() + quad[ 3 ].x()) / 4, + (quad[ 0 ].y() + quad[ 1 ].y() + quad[ 2 ].y() + quad[ 3 ].y()) / 4); + double adiff = (rand() % 720 - 360) / 360. * 2 * M_PI; // spin randomly + for (int j = 0; + j < 4; + ++j) { double x = quad[ j ].x() - center.x(); double y = quad[ j ].y() - center.y(); - double angle = atan2( y, x ); + double angle = atan2(y, x); angle += windows[ w ] * adiff; - double dist = sqrt( x * x + y * y ); - x = dist * cos( angle ); - y = dist * sin( angle ); - quad[ j ].move( center.x() + x, center.y() + y ); - } - new_quads.append( quad ); - ++cnt; + double dist = sqrt(x * x + y * y); + x = dist * cos(angle); + y = dist * sin(angle); + quad[ j ].move(center.x() + x, center.y() + y); } - data.quads = new_quads; + new_quads.append(quad); + ++cnt; } - effects->paintWindow( w, mask, region, data ); + data.quads = new_quads; } + effects->paintWindow(w, mask, region, data); +} void FallApartEffect::postPaintScreen() - { - if( !windows.isEmpty()) +{ + if (!windows.isEmpty()) effects->addRepaintFull(); effects->postPaintScreen(); - } +} -bool FallApartEffect::isRealWindow( EffectWindow* w ) - { +bool FallApartEffect::isRealWindow(EffectWindow* w) +{ // TODO: isSpecialWindow is rather generic, maybe tell windowtypes separately? /* kDebug(1212) << "--" << w->caption() << "--------------------------------"; @@ -144,25 +136,25 @@ bool FallApartEffect::isRealWindow( EffectWindow* w ) kDebug(1212) << "Splash:" << w->isSplash(); kDebug(1212) << "Normal:" << w->isNormalWindow(); */ - if ( !w->isNormalWindow() ) + if (!w->isNormalWindow()) return false; return true; - } +} -void FallApartEffect::windowClosed( EffectWindow* c ) - { - if ( !isRealWindow( c ) ) +void FallApartEffect::windowClosed(EffectWindow* c) +{ + if (!isRealWindow(c)) return; - const void* e = c->data( WindowClosedGrabRole ).value(); - if( e && e != this ) + const void* e = c->data(WindowClosedGrabRole).value(); + if (e && e != this) return; windows[ c ] = 0; c->refWindow(); - } +} -void FallApartEffect::windowDeleted( EffectWindow* c ) - { - windows.remove( c ); - } +void FallApartEffect::windowDeleted(EffectWindow* c) +{ + windows.remove(c); +} } // namespace diff --git a/effects/fallapart/fallapart.h b/effects/fallapart/fallapart.h index 5bdce5e24..f159e180a 100644 --- a/effects/fallapart/fallapart.h +++ b/effects/fallapart/fallapart.h @@ -28,21 +28,21 @@ namespace KWin class FallApartEffect : public Effect - { - public: - FallApartEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); - private: - QHash< const EffectWindow*, double > windows; - bool isRealWindow ( EffectWindow* w ); - int blockSize; - }; +{ +public: + FallApartEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); +private: + QHash< const EffectWindow*, double > windows; + bool isRealWindow(EffectWindow* w); + int blockSize; +}; } // namespace diff --git a/effects/flipswitch/flipswitch.cpp b/effects/flipswitch/flipswitch.cpp index 20476189d..3f2a96aed 100644 --- a/effects/flipswitch/flipswitch.cpp +++ b/effects/flipswitch/flipswitch.cpp @@ -35,218 +35,198 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( flipswitch, FlipSwitchEffect ) -KWIN_EFFECT_SUPPORTED( flipswitch, FlipSwitchEffect::supported() ) +KWIN_EFFECT(flipswitch, FlipSwitchEffect) +KWIN_EFFECT_SUPPORTED(flipswitch, FlipSwitchEffect::supported()) FlipSwitchEffect::FlipSwitchEffect() - : m_currentAnimationShape( TimeLine::EaseInOutCurve ) - , m_active( false ) - , m_start( false ) - , m_stop( false ) - , m_animation( false ) - , m_hasKeyboardGrab( false ) - , m_captionFrame( effects->effectFrame( EffectFrameStyled ) ) - { - reconfigure( ReconfigureAll ); + : m_currentAnimationShape(TimeLine::EaseInOutCurve) + , m_active(false) + , m_start(false) + , m_stop(false) + , m_animation(false) + , m_hasKeyboardGrab(false) + , m_captionFrame(effects->effectFrame(EffectFrameStyled)) +{ + reconfigure(ReconfigureAll); // Caption frame - m_captionFont.setBold( true ); - m_captionFont.setPointSize( m_captionFont.pointSize() * 2 ); - m_captionFrame->setFont( m_captionFont ); - m_captionFrame->enableCrossFade( true ); + m_captionFont.setBold(true); + m_captionFont.setPointSize(m_captionFont.pointSize() * 2); + m_captionFrame->setFont(m_captionFont); + m_captionFrame->enableCrossFade(true); - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = ( KAction* )actionCollection->addAction( "FlipSwitchCurrent" ); - a->setText( i18n( "Toggle Flip Switch (Current desktop)" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = (KAction*)actionCollection->addAction("FlipSwitchCurrent"); + a->setText(i18n("Toggle Flip Switch (Current desktop)")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); m_shortcutCurrent = a->globalShortcut(); - connect( a, SIGNAL( triggered(bool) ), this, SLOT( toggleActiveCurrent() )); - connect( a, SIGNAL( globalShortcutChanged(QKeySequence) ), this, SLOT( globalShortcutChangedCurrent(QKeySequence))); - KAction* b = ( KAction* )actionCollection->addAction( "FlipSwitchAll" ); - b->setText( i18n( "Toggle Flip Switch (All desktops)" )); - b->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggleActiveCurrent())); + connect(a, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChangedCurrent(QKeySequence))); + KAction* b = (KAction*)actionCollection->addAction("FlipSwitchAll"); + b->setText(i18n("Toggle Flip Switch (All desktops)")); + b->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); m_shortcutAll = b->globalShortcut(); - connect( b, SIGNAL( triggered(bool) ), this, SLOT( toggleActiveAllDesktops() )); - connect( b, SIGNAL( globalShortcutChanged(QKeySequence) ), this, SLOT( globalShortcutChangedAll(QKeySequence))); - } + connect(b, SIGNAL(triggered(bool)), this, SLOT(toggleActiveAllDesktops())); + connect(b, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChangedAll(QKeySequence))); +} FlipSwitchEffect::~FlipSwitchEffect() - { - foreach( ElectricBorder border, m_borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, m_borderActivateAll ) - { - effects->unreserveElectricBorder( border ); - } - delete m_captionFrame; +{ + foreach (ElectricBorder border, m_borderActivate) { + effects->unreserveElectricBorder(border); } + foreach (ElectricBorder border, m_borderActivateAll) { + effects->unreserveElectricBorder(border); + } + delete m_captionFrame; +} bool FlipSwitchEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void FlipSwitchEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "FlipSwitch" ); - foreach( ElectricBorder border, m_borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, m_borderActivateAll ) - { - effects->unreserveElectricBorder( border ); - } +void FlipSwitchEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("FlipSwitch"); + foreach (ElectricBorder border, m_borderActivate) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, m_borderActivateAll) { + effects->unreserveElectricBorder(border); + } m_borderActivate.clear(); m_borderActivateAll.clear(); QList borderList = QList(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivate", borderList ); - foreach( int i, borderList ) - { - m_borderActivate.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivate", borderList); + foreach (int i, borderList) { + m_borderActivate.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); + } borderList.clear(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivateAll", borderList ); - foreach( int i, borderList ) - { - m_borderActivateAll.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } - m_tabbox = conf.readEntry( "TabBox", false ); - m_tabboxAlternative = conf.readEntry( "TabBoxAlternative", false ); - float duration = animationTime( conf, "Duration", 200 ); - m_timeLine.setDuration( duration ); - m_startStopTimeLine.setDuration( duration ); - - m_angle = conf.readEntry( "Angle", 30 ); - m_xPosition = float( conf.readEntry( "XPosition", 33 ))/100.0f; - m_yPosition = float( conf.readEntry( "YPosition", 100 ))/100.0f; - m_windowTitle = conf.readEntry( "WindowTitle", true ); + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivateAll", borderList); + foreach (int i, borderList) { + m_borderActivateAll.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); } + m_tabbox = conf.readEntry("TabBox", false); + m_tabboxAlternative = conf.readEntry("TabBoxAlternative", false); + float duration = animationTime(conf, "Duration", 200); + m_timeLine.setDuration(duration); + m_startStopTimeLine.setDuration(duration); -void FlipSwitchEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( m_active ) - { + m_angle = conf.readEntry("Angle", 30); + m_xPosition = float(conf.readEntry("XPosition", 33)) / 100.0f; + m_yPosition = float(conf.readEntry("YPosition", 100)) / 100.0f; + m_windowTitle = conf.readEntry("WindowTitle", true); +} + +void FlipSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (m_active) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - if( m_start ) - m_startStopTimeLine.addTime( time ); - if( m_stop && m_scheduledDirections.isEmpty() ) - m_startStopTimeLine.removeTime( time ); - if( m_animation ) - m_timeLine.addTime( time ); - } - effects->prePaintScreen( data, time ); + if (m_start) + m_startStopTimeLine.addTime(time); + if (m_stop && m_scheduledDirections.isEmpty()) + m_startStopTimeLine.removeTime(time); + if (m_animation) + m_timeLine.addTime(time); } + effects->prePaintScreen(data, time); +} -void FlipSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( m_active ) - { +void FlipSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (m_active) { EffectWindowList tempList; - if( m_mode == TabboxMode ) + if (m_mode == TabboxMode) tempList = effects->currentTabBoxWindowList(); - else - { + else { // we have to setup the list // using stacking order directly is not possible // as not each window in stacking order is shown // TODO: store list instead of calculating in each frame? - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( m_windows.contains( w ) ) - tempList.append( w ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + if (m_windows.contains(w)) + tempList.append(w); } + } m_flipOrderedWindows.clear(); - int index = tempList.indexOf( m_selectedWindow ); + int index = tempList.indexOf(m_selectedWindow); int tabIndex = index; - if( m_mode == TabboxMode ) - { - foreach( SwitchingDirection direction, m_scheduledDirections ) // krazy:exclude=foreach - { - if( direction == DirectionBackward ) + if (m_mode == TabboxMode) { + foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach + if (direction == DirectionBackward) index++; else index--; - if( index < 0 ) + if (index < 0) index = tempList.count() + index; - if( index >= tempList.count() ) + if (index >= tempList.count()) index = index % tempList.count(); - } + } tabIndex = index; EffectWindow* w = NULL; - if( !m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward ) - { + if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index--; - if( index < 0 ) + if (index < 0) index = tempList.count() + index; - w = tempList.at( index ); - } - for( int i=index-1; i>=0; i-- ) - m_flipOrderedWindows.append(tempList.at( i )); - for( int i=effects->currentTabBoxWindowList().count()-1; i>=index; i-- ) - m_flipOrderedWindows.append(tempList.at( i )); - if( w ) - { - m_flipOrderedWindows.removeAll( w ); - m_flipOrderedWindows.append( w ); - } + w = tempList.at(index); } - else - { - foreach( SwitchingDirection direction, m_scheduledDirections ) // krazy:exclude=foreach - { - if( direction == DirectionForward ) + for (int i = index - 1; i >= 0; i--) + m_flipOrderedWindows.append(tempList.at(i)); + for (int i = effects->currentTabBoxWindowList().count() - 1; i >= index; i--) + m_flipOrderedWindows.append(tempList.at(i)); + if (w) { + m_flipOrderedWindows.removeAll(w); + m_flipOrderedWindows.append(w); + } + } else { + foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach + if (direction == DirectionForward) index++; else index--; - if( index < 0 ) - index = tempList.count() -1; - if( index >= tempList.count() ) + if (index < 0) + index = tempList.count() - 1; + if (index >= tempList.count()) index = 0; - } + } tabIndex = index; EffectWindow* w = NULL; - if( !m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward ) - { + if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index++; - if( index >= tempList.count() ) + if (index >= tempList.count()) index = 0; - } - // sort from stacking order - for( int i=index+1; inumScreens() > 1 ) - { + if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode - QRect fullRect = effects->clientArea( FullArea, effects->activeScreen(), effects->currentDesktop() ); + QRect fullRect = effects->clientArea(FullArea, effects->activeScreen(), effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; - float ymax = zNear * tan( fovy * M_PI / 360.0f ); + float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; @@ -256,36 +236,32 @@ void FlipSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d float xmaxFactor = 1.0; float yminFactor = 1.0; float ymaxFactor = 1.0; - if( m_screenArea.x() == 0 && m_screenArea.width() != fullRect.width() ) - { + if (m_screenArea.x() == 0 && m_screenArea.width() != fullRect.width()) { // horizontal layout: left screen - xminFactor = (float)m_screenArea.width()/(float)fullRect.width(); - xmaxFactor = ((float)fullRect.width()-(float)m_screenArea.width()*0.5f)/((float)fullRect.width()*0.5f); - xTranslate = (float)fullRect.width()*0.5f-(float)m_screenArea.width()*0.5f; - } - if( m_screenArea.x() != 0 && m_screenArea.width() != fullRect.width() ) - { + xminFactor = (float)m_screenArea.width() / (float)fullRect.width(); + xmaxFactor = ((float)fullRect.width() - (float)m_screenArea.width() * 0.5f) / ((float)fullRect.width() * 0.5f); + xTranslate = (float)fullRect.width() * 0.5f - (float)m_screenArea.width() * 0.5f; + } + if (m_screenArea.x() != 0 && m_screenArea.width() != fullRect.width()) { // horizontal layout: right screen - xminFactor = ((float)fullRect.width()-(float)m_screenArea.width()*0.5f)/((float)fullRect.width()*0.5f); - xmaxFactor = (float)m_screenArea.width()/(float)fullRect.width(); - xTranslate = (float)fullRect.width()*0.5f-(float)m_screenArea.width()*0.5f; - } - if( m_screenArea.y() == 0 && m_screenArea.height() != fullRect.height() ) - { + xminFactor = ((float)fullRect.width() - (float)m_screenArea.width() * 0.5f) / ((float)fullRect.width() * 0.5f); + xmaxFactor = (float)m_screenArea.width() / (float)fullRect.width(); + xTranslate = (float)fullRect.width() * 0.5f - (float)m_screenArea.width() * 0.5f; + } + if (m_screenArea.y() == 0 && m_screenArea.height() != fullRect.height()) { // vertical layout: top screen - yminFactor = ((float)fullRect.height()-(float)m_screenArea.height()*0.5f)/((float)fullRect.height()*0.5f); - ymaxFactor = (float)m_screenArea.height()/(float)fullRect.height(); - yTranslate = (float)fullRect.height()*0.5f-(float)m_screenArea.height()*0.5f; - } - if( m_screenArea.y() != 0 && m_screenArea.height() != fullRect.height() ) - { + yminFactor = ((float)fullRect.height() - (float)m_screenArea.height() * 0.5f) / ((float)fullRect.height() * 0.5f); + ymaxFactor = (float)m_screenArea.height() / (float)fullRect.height(); + yTranslate = (float)fullRect.height() * 0.5f - (float)m_screenArea.height() * 0.5f; + } + if (m_screenArea.y() != 0 && m_screenArea.height() != fullRect.height()) { // vertical layout: bottom screen - yminFactor = (float)m_screenArea.height()/(float)fullRect.height(); - ymaxFactor = ((float)fullRect.height()-(float)m_screenArea.height()*0.5f)/((float)fullRect.height()*0.5f); - yTranslate = (float)fullRect.height()*0.5f-(float)m_screenArea.height()*0.5f; - } + yminFactor = (float)m_screenArea.height() / (float)fullRect.height(); + ymaxFactor = ((float)fullRect.height() - (float)m_screenArea.height() * 0.5f) / ((float)fullRect.height() * 0.5f); + yTranslate = (float)fullRect.height() * 0.5f - (float)m_screenArea.height() * 0.5f; + } QMatrix4x4 projection; - projection.frustum(xmin*xminFactor, xmax*xmaxFactor, ymin*yminFactor, ymax*ymaxFactor, zNear, zFar); + projection.frustum(xmin * xminFactor, xmax * xmaxFactor, ymin * yminFactor, ymax * ymaxFactor, zNear, zFar); QMatrix4x4 modelview; modelview.translate(xTranslate, yTranslate, 0.0); if (shaderManager->isShaderBound()) { @@ -293,7 +269,7 @@ void FlipSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d origProjection = shader->getUniformMatrix4x4("projection"); origModelview = shader->getUniformMatrix4x4("modelview"); shader->setUniform("projection", projection); - shader->setUniform("modelview", origModelview*modelview); + shader->setUniform("modelview", origModelview * modelview); shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES @@ -304,118 +280,102 @@ void FlipSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d pushMatrix(modelview); #endif } - } + } int winMask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT; RotationData rot; rot.axis = RotationData::YAxis; rot.angle = m_angle * m_startStopTimeLine.value(); // fade in/out one window at the end of the stack during animation - if( m_animation && !m_scheduledDirections.isEmpty() ) - { + if (m_animation && !m_scheduledDirections.isEmpty()) { EffectWindow* w = m_flipOrderedWindows.last(); - if( m_windows.contains( w ) ) - { - WindowPaintData data( w ); + if (m_windows.contains(w)) { + WindowPaintData data(w); data.opacity = m_windows[ w ]->opacity; data.brightness = m_windows[ w ]->brightness; data.saturation = m_windows[ w ]->saturation; int distance = tempList.count() - 1; float zDistance = 500.0f; data.xTranslate -= (w->x() - m_screenArea.x() + data.xTranslate) * m_startStopTimeLine.value(); - data.xTranslate += m_screenArea.width()*m_xPosition * m_startStopTimeLine.value(); - data.yTranslate += (m_screenArea.y() + m_screenArea.height()*m_yPosition - ( w->y() + w->height() + data.yTranslate )) * m_startStopTimeLine.value(); + data.xTranslate += m_screenArea.width() * m_xPosition * m_startStopTimeLine.value(); + data.yTranslate += (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslate)) * m_startStopTimeLine.value(); - data.xTranslate -= (m_screenArea.width()*0.25f) * distance * m_startStopTimeLine.value(); - data.yTranslate -= (m_screenArea.height()*0.10f) * distance * m_startStopTimeLine.value(); + data.xTranslate -= (m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.value(); + data.yTranslate -= (m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.value(); data.zTranslate -= (zDistance * distance) * m_startStopTimeLine.value(); - if( m_scheduledDirections.head() == DirectionForward ) + if (m_scheduledDirections.head() == DirectionForward) data.opacity *= 0.8 * m_timeLine.value(); else - data.opacity *= 0.8 * (1.0 - m_timeLine.value() ); + data.opacity *= 0.8 * (1.0 - m_timeLine.value()); - if( effects->numScreens() > 1) - { - adjustWindowMultiScreen( w, data ); - } - data.rotation = &rot; - effects->drawWindow( w, winMask, infiniteRegion(), data ); + if (effects->numScreens() > 1) { + adjustWindowMultiScreen(w, data); } + data.rotation = &rot; + effects->drawWindow(w, winMask, infiniteRegion(), data); } + } - foreach( EffectWindow* w, m_flipOrderedWindows ) - { - if( !m_windows.contains( w ) ) + foreach (EffectWindow * w, m_flipOrderedWindows) { + if (!m_windows.contains(w)) continue; - WindowPaintData data( w ); + WindowPaintData data(w); data.opacity = m_windows[ w ]->opacity; data.brightness = m_windows[ w ]->brightness; data.saturation = m_windows[ w ]->saturation; - int windowIndex = tempList.indexOf( w ); + int windowIndex = tempList.indexOf(w); int distance; - if( m_mode == TabboxMode ) - { - if( windowIndex < tabIndex ) + if (m_mode == TabboxMode) { + if (windowIndex < tabIndex) distance = tempList.count() - (tabIndex - windowIndex); - else if( windowIndex > tabIndex) + else if (windowIndex > tabIndex) distance = windowIndex - tabIndex; else distance = 0; - } - else - { - distance = m_flipOrderedWindows.count() - m_flipOrderedWindows.indexOf( w ) - 1; + } else { + distance = m_flipOrderedWindows.count() - m_flipOrderedWindows.indexOf(w) - 1; - if( !m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward ) - { + if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { distance--; - } } - if( !m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward ) - { - if( w == m_flipOrderedWindows.last() ) - { + } + if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { + if (w == m_flipOrderedWindows.last()) { distance = -1; data.opacity *= m_timeLine.value(); - } } + } float zDistance = 500.0f; data.xTranslate -= (w->x() - m_screenArea.x() + data.xTranslate) * m_startStopTimeLine.value(); - data.xTranslate += m_screenArea.width()*m_xPosition * m_startStopTimeLine.value(); - data.yTranslate += (m_screenArea.y() + m_screenArea.height()*m_yPosition - ( w->y() + w->height() + data.yTranslate )) * m_startStopTimeLine.value(); + data.xTranslate += m_screenArea.width() * m_xPosition * m_startStopTimeLine.value(); + data.yTranslate += (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslate)) * m_startStopTimeLine.value(); - data.xTranslate -= (m_screenArea.width()*0.25f) * distance * m_startStopTimeLine.value(); - data.yTranslate -= (m_screenArea.height()*0.10f) * distance * m_startStopTimeLine.value(); + data.xTranslate -= (m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.value(); + data.yTranslate -= (m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.value(); data.zTranslate -= (zDistance * distance) * m_startStopTimeLine.value(); - if( m_animation && !m_scheduledDirections.isEmpty() ) - { - if( m_scheduledDirections.head() == DirectionForward ) - { - data.xTranslate += (m_screenArea.width()*0.25f) * m_timeLine.value(); - data.yTranslate += (m_screenArea.height()*0.10f) * m_timeLine.value(); + if (m_animation && !m_scheduledDirections.isEmpty()) { + if (m_scheduledDirections.head() == DirectionForward) { + data.xTranslate += (m_screenArea.width() * 0.25f) * m_timeLine.value(); + data.yTranslate += (m_screenArea.height() * 0.10f) * m_timeLine.value(); data.zTranslate += zDistance * m_timeLine.value(); - if( distance == 0 ) - data.opacity *= (1.0 - m_timeLine.value() ); - } - else - { - data.xTranslate -= (m_screenArea.width()*0.25f) * m_timeLine.value(); - data.yTranslate -= (m_screenArea.height()*0.10f) * m_timeLine.value(); + if (distance == 0) + data.opacity *= (1.0 - m_timeLine.value()); + } else { + data.xTranslate -= (m_screenArea.width() * 0.25f) * m_timeLine.value(); + data.yTranslate -= (m_screenArea.height() * 0.10f) * m_timeLine.value(); data.zTranslate -= zDistance * m_timeLine.value(); - } } + } data.opacity *= (0.8 + 0.2 * (1.0 - m_startStopTimeLine.value())); - if( effects->numScreens() > 1) - { - adjustWindowMultiScreen( w, data ); - } - - data.rotation = &rot; - effects->drawWindow( w, winMask, infiniteRegion(), data ); + if (effects->numScreens() > 1) { + adjustWindowMultiScreen(w, data); } - if( effects->numScreens() > 1 ) - { + data.rotation = &rot; + effects->drawWindow(w, winMask, infiniteRegion(), data); + } + + if (effects->numScreens() > 1) { if (shaderManager->isShaderBound()) { GLShader *shader = shaderManager->pushShader(ShaderManager::GenericShader); shader->setUniform("projection", origProjection); @@ -430,657 +390,557 @@ void FlipSwitchEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d glMatrixMode(GL_MODELVIEW); #endif } - } + } - if( m_windowTitle ) - { + if (m_windowTitle) { // Render the caption frame - if( m_animation ) - { - m_captionFrame->setCrossFadeProgress( m_timeLine.value() ); - } - m_captionFrame->render( region, m_startStopTimeLine.value() ); + if (m_animation) { + m_captionFrame->setCrossFadeProgress(m_timeLine.value()); } + m_captionFrame->render(region, m_startStopTimeLine.value()); } } +} void FlipSwitchEffect::postPaintScreen() - { - if( m_active ) - { - if( m_start && m_startStopTimeLine.value() == 1.0f ) - { +{ + if (m_active) { + if (m_start && m_startStopTimeLine.value() == 1.0f) { m_start = false; - if( !m_scheduledDirections.isEmpty() ) - { + if (!m_scheduledDirections.isEmpty()) { m_animation = true; - m_timeLine.setProgress( 0.0f ); - if( m_scheduledDirections.count() == 1 ) - { + m_timeLine.setProgress(0.0f); + if (m_scheduledDirections.count() == 1) { m_currentAnimationShape = TimeLine::EaseOutCurve; - m_timeLine.setCurveShape( m_currentAnimationShape ); - } - else - { + m_timeLine.setCurveShape(m_currentAnimationShape); + } else { m_currentAnimationShape = TimeLine::LinearCurve; - m_timeLine.setCurveShape( m_currentAnimationShape ); - } + m_timeLine.setCurveShape(m_currentAnimationShape); } - effects->addRepaintFull(); } - if( m_stop && m_startStopTimeLine.value() == 0.0f ) - { + effects->addRepaintFull(); + } + if (m_stop && m_startStopTimeLine.value() == 0.0f) { m_stop = false; m_active = false; m_captionFrame->free(); - effects->setActiveFullScreenEffect( 0 ); + effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); - qDeleteAll( m_windows ); + qDeleteAll(m_windows); m_windows.clear(); - } - if( m_animation && m_timeLine.value() == 1.0f ) - { - m_timeLine.setProgress( 0.0f ); + } + if (m_animation && m_timeLine.value() == 1.0f) { + m_timeLine.setProgress(0.0f); m_scheduledDirections.dequeue(); - if( m_scheduledDirections.isEmpty() ) - { + if (m_scheduledDirections.isEmpty()) { m_animation = false; effects->addRepaintFull(); - } - else - { - if( m_scheduledDirections.count() == 1 ) - { - if( m_stop ) + } else { + if (m_scheduledDirections.count() == 1) { + if (m_stop) m_currentAnimationShape = TimeLine::LinearCurve; else m_currentAnimationShape = TimeLine::EaseOutCurve; - } - else - { + } else { m_currentAnimationShape = TimeLine::LinearCurve; - } - m_timeLine.setCurveShape( m_currentAnimationShape ); } + m_timeLine.setCurveShape(m_currentAnimationShape); } - if( m_start || m_stop || m_animation ) - effects->addRepaintFull(); } - effects->postPaintScreen(); + if (m_start || m_stop || m_animation) + effects->addRepaintFull(); } + effects->postPaintScreen(); +} -void FlipSwitchEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( m_active ) - { - if( m_windows.contains( w ) ) - { +void FlipSwitchEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (m_active) { + if (m_windows.contains(w)) { data.setTransformed(); data.setTranslucent(); - if( !w->isOnCurrentDesktop() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - if( w->isMinimized() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); - if( !w->visibleInClientGroup() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP ); - } - else - { - if( ( m_start || m_stop ) && !w->isDesktop() && w->isOnCurrentDesktop() ) + if (!w->isOnCurrentDesktop()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + if (w->isMinimized()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); + if (!w->visibleInClientGroup()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP); + } else { + if ((m_start || m_stop) && !w->isDesktop() && w->isOnCurrentDesktop()) data.setTranslucent(); - else if( !w->isDesktop() ) - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } + else if (!w->isDesktop()) + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void FlipSwitchEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( m_active ) - { - if( w->isDesktop() ) - { +void FlipSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (m_active) { + if (w->isDesktop()) { // desktop is painted in normal way - if( m_windows.contains( w ) ) - { + if (m_windows.contains(w)) { m_windows[ w ]->opacity = data.opacity; m_windows[ w ]->brightness = data.brightness; m_windows[ w ]->saturation = data.saturation; - } - effects->paintWindow( w, mask, region, data ); - return; } - if( ( m_start || m_stop ) && !m_windows.contains( w ) ) - { + effects->paintWindow(w, mask, region, data); + return; + } + if ((m_start || m_stop) && !m_windows.contains(w)) { // fade out all windows not in window list - data.opacity *= ( 1.0 - m_startStopTimeLine.value() ); - effects->paintWindow( w, mask, region, data ); + data.opacity *= (1.0 - m_startStopTimeLine.value()); + effects->paintWindow(w, mask, region, data); return; - } + } m_windows[ w ]->opacity = data.opacity; m_windows[ w ]->brightness = data.brightness; m_windows[ w ]->saturation = data.saturation; // it's not nice but it removes flickering return; - } - else - { - effects->paintWindow( w, mask, region, data ); - } + } else { + effects->paintWindow(w, mask, region, data); } +} //************************************************************* // Tabbox handling //************************************************************* -void FlipSwitchEffect::tabBoxAdded( int mode ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void FlipSwitchEffect::tabBoxAdded(int mode) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; // only for windows mode - if( (( mode == TabBoxWindowsMode && m_tabbox ) || - ( mode == TabBoxWindowsAlternativeMode && m_tabboxAlternative )) - && (!m_active || (m_active && m_stop)) - && !effects->currentTabBoxWindowList().isEmpty() ) - { - setActive( true, TabboxMode ); - if( m_active ) + if (((mode == TabBoxWindowsMode && m_tabbox) || + (mode == TabBoxWindowsAlternativeMode && m_tabboxAlternative)) + && (!m_active || (m_active && m_stop)) + && !effects->currentTabBoxWindowList().isEmpty()) { + setActive(true, TabboxMode); + if (m_active) effects->refTabBox(); - } } +} void FlipSwitchEffect::tabBoxClosed() - { - if( m_active ) - { - setActive( false, TabboxMode ); +{ + if (m_active) { + setActive(false, TabboxMode); effects->unrefTabBox(); - } } +} void FlipSwitchEffect::tabBoxUpdated() - { - if( m_active && !m_stop ) - { - if( !effects->currentTabBoxWindowList().isEmpty() ) - { +{ + if (m_active && !m_stop) { + if (!effects->currentTabBoxWindowList().isEmpty()) { // determine the switch direction - if( m_selectedWindow != effects->currentTabBoxWindow() ) - { - if( m_selectedWindow != NULL ) - { - int old_index = effects->currentTabBoxWindowList().indexOf( m_selectedWindow ); - int new_index = effects->currentTabBoxWindowList().indexOf( effects->currentTabBoxWindow() ); + if (m_selectedWindow != effects->currentTabBoxWindow()) { + if (m_selectedWindow != NULL) { + int old_index = effects->currentTabBoxWindowList().indexOf(m_selectedWindow); + int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); SwitchingDirection new_direction; int distance = new_index - old_index; - if( distance > 0 ) + if (distance > 0) new_direction = DirectionForward; - if( distance < 0 ) + if (distance < 0) new_direction = DirectionBackward; - if( effects->currentTabBoxWindowList().count() == 2 ) - { + if (effects->currentTabBoxWindowList().count() == 2) { new_direction = DirectionForward; distance = 1; - } - if( distance != 0 ) - { - distance = abs( distance ); + } + if (distance != 0) { + distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; - if( tempDistance < abs( distance ) ) - { + if (tempDistance < abs(distance)) { distance = tempDistance; - if( new_direction == DirectionForward ) + if (new_direction == DirectionForward) new_direction = DirectionBackward; else new_direction = DirectionForward; - } - scheduleAnimation( new_direction, distance ); } + scheduleAnimation(new_direction, distance); } - m_selectedWindow = effects->currentTabBoxWindow(); - m_captionFrame->setText( m_selectedWindow->caption() ); - m_captionFrame->setIcon( m_selectedWindow->icon() ); } + m_selectedWindow = effects->currentTabBoxWindow(); + m_captionFrame->setText(m_selectedWindow->caption()); + m_captionFrame->setIcon(m_selectedWindow->icon()); } - effects->addRepaintFull(); } + effects->addRepaintFull(); } +} //************************************************************* // Window adding/removing handling //************************************************************* -void FlipSwitchEffect::windowAdded( EffectWindow* w ) - { - if( m_active && isSelectableWindow( w ) ) - { +void FlipSwitchEffect::windowAdded(EffectWindow* w) +{ + if (m_active && isSelectableWindow(w)) { m_windows[ w ] = new ItemInfo(); - } } +} -void FlipSwitchEffect::windowClosed( EffectWindow* w ) - { - if( m_active && m_windows.contains( w ) ) - { - m_windows.remove( w ); - } +void FlipSwitchEffect::windowClosed(EffectWindow* w) +{ + if (m_active && m_windows.contains(w)) { + m_windows.remove(w); } +} //************************************************************* // Activation //************************************************************* -void FlipSwitchEffect::setActive( bool activate, FlipSwitchMode mode ) - { - if( activate ) - { +void FlipSwitchEffect::setActive(bool activate, FlipSwitchMode mode) +{ + if (activate) { // effect already active, do some sanity checks - if( m_active ) - { - if( m_stop ) - { - if( mode != m_mode ) - { + if (m_active) { + if (m_stop) { + if (mode != m_mode) { // only the same mode may reactivate the effect return; - } } - else - { + } else { // active, but not scheduled for closing -> abort return; - } } + } m_mode = mode; - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( isSelectableWindow( w ) && !m_windows.contains( w ) ) + foreach (EffectWindow * w, effects->stackingOrder()) { + if (isSelectableWindow(w) && !m_windows.contains(w)) m_windows[ w ] = new ItemInfo(); - } - if( m_windows.isEmpty() ) + } + if (m_windows.isEmpty()) return; - effects->setActiveFullScreenEffect( this ); + effects->setActiveFullScreenEffect(this); m_active = true; m_start = true; - m_startStopTimeLine.setCurveShape( TimeLine::EaseInOutCurve ); + m_startStopTimeLine.setCurveShape(TimeLine::EaseInOutCurve); m_activeScreen = effects->activeScreen(); - m_screenArea = effects->clientArea( ScreenArea, m_activeScreen, effects->currentDesktop() ); + m_screenArea = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); - if( m_stop ) - { + if (m_stop) { // effect is still closing from last usage m_stop = false; - } - else - { + } else { // things to do only when there is no closing animation m_scheduledDirections.clear(); - } + } - switch( m_mode ) - { - case TabboxMode: - m_selectedWindow = effects->currentTabBoxWindow(); - break; - case CurrentDesktopMode: - m_selectedWindow = effects->activeWindow(); - m_input = effects->createFullScreenInputWindow( this, Qt::BlankCursor ); - m_hasKeyboardGrab = effects->grabKeyboard( this ); - break; - case AllDesktopsMode: - m_selectedWindow = effects->activeWindow(); - m_input = effects->createFullScreenInputWindow( this, Qt::BlankCursor ); - m_hasKeyboardGrab = effects->grabKeyboard( this ); - break; - } + switch(m_mode) { + case TabboxMode: + m_selectedWindow = effects->currentTabBoxWindow(); + break; + case CurrentDesktopMode: + m_selectedWindow = effects->activeWindow(); + m_input = effects->createFullScreenInputWindow(this, Qt::BlankCursor); + m_hasKeyboardGrab = effects->grabKeyboard(this); + break; + case AllDesktopsMode: + m_selectedWindow = effects->activeWindow(); + m_input = effects->createFullScreenInputWindow(this, Qt::BlankCursor); + m_hasKeyboardGrab = effects->grabKeyboard(this); + break; + } // Setup caption frame geometry - QRect frameRect = QRect( m_screenArea.width() * 0.25f + m_screenArea.x(), - m_screenArea.height() * 0.1f + m_screenArea.y() - QFontMetrics( m_captionFont ).height(), - m_screenArea.width() * 0.5f, - QFontMetrics( m_captionFont ).height() ); - m_captionFrame->setGeometry( frameRect ); - m_captionFrame->setIconSize( QSize( frameRect.height(), frameRect.height() )); - m_captionFrame->setText( m_selectedWindow->caption() ); - m_captionFrame->setIcon( m_selectedWindow->icon() ); + QRect frameRect = QRect(m_screenArea.width() * 0.25f + m_screenArea.x(), + m_screenArea.height() * 0.1f + m_screenArea.y() - QFontMetrics(m_captionFont).height(), + m_screenArea.width() * 0.5f, + QFontMetrics(m_captionFont).height()); + m_captionFrame->setGeometry(frameRect); + m_captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); + m_captionFrame->setText(m_selectedWindow->caption()); + m_captionFrame->setIcon(m_selectedWindow->icon()); effects->addRepaintFull(); - } - else - { + } else { // only deactivate if mode is current mode - if( mode != m_mode ) + if (mode != m_mode) return; - if( m_start && m_scheduledDirections.isEmpty() ) - { + if (m_start && m_scheduledDirections.isEmpty()) { m_start = false; - } + } m_stop = true; - if( m_animation ) - { - m_startStopTimeLine.setCurveShape( TimeLine::EaseOutCurve ); - if( m_scheduledDirections.count() == 1 ) - { - if( m_currentAnimationShape == TimeLine::EaseInOutCurve ) + if (m_animation) { + m_startStopTimeLine.setCurveShape(TimeLine::EaseOutCurve); + if (m_scheduledDirections.count() == 1) { + if (m_currentAnimationShape == TimeLine::EaseInOutCurve) m_currentAnimationShape = TimeLine::EaseInCurve; - else if( m_currentAnimationShape == TimeLine::EaseOutCurve ) + else if (m_currentAnimationShape == TimeLine::EaseOutCurve) m_currentAnimationShape = TimeLine::LinearCurve; - m_timeLine.setCurveShape( m_currentAnimationShape ); - } + m_timeLine.setCurveShape(m_currentAnimationShape); } - else - m_startStopTimeLine.setCurveShape( TimeLine::EaseInOutCurve ); - if( mode != TabboxMode ) - effects->destroyInputWindow( m_input ); - if( m_hasKeyboardGrab ) - { + } else + m_startStopTimeLine.setCurveShape(TimeLine::EaseInOutCurve); + if (mode != TabboxMode) + effects->destroyInputWindow(m_input); + if (m_hasKeyboardGrab) { effects->ungrabKeyboard(); m_hasKeyboardGrab = false; - } - effects->addRepaintFull(); } + effects->addRepaintFull(); } +} void FlipSwitchEffect::toggleActiveAllDesktops() - { - if( m_active ) - { - if( m_stop ) - { +{ + if (m_active) { + if (m_stop) { // reactivate if stopping - setActive( true, AllDesktopsMode ); - } - else - { + setActive(true, AllDesktopsMode); + } else { // deactivate if not stopping - setActive( false, AllDesktopsMode ); - } - } - else - { - setActive( true, AllDesktopsMode ); + setActive(false, AllDesktopsMode); } + } else { + setActive(true, AllDesktopsMode); } +} void FlipSwitchEffect::toggleActiveCurrent() - { - if( m_active ) - { - if( m_stop ) - { +{ + if (m_active) { + if (m_stop) { // reactivate if stopping - setActive( true, CurrentDesktopMode ); - } - else - { + setActive(true, CurrentDesktopMode); + } else { // deactivate if not stopping - setActive( false, CurrentDesktopMode ); - } - } - else - { - setActive( true, CurrentDesktopMode ); + setActive(false, CurrentDesktopMode); } + } else { + setActive(true, CurrentDesktopMode); } +} bool FlipSwitchEffect::borderActivated(ElectricBorder border) - { - if( !m_borderActivate.contains( border ) && !m_borderActivateAll.contains( border ) ) +{ + if (!m_borderActivate.contains(border) && !m_borderActivateAll.contains(border)) return false; - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return true; - if( m_borderActivate.contains( border ) ) + if (m_borderActivate.contains(border)) toggleActiveCurrent(); else toggleActiveAllDesktops(); return true; - } +} //************************************************************* // Helper function //************************************************************* -bool FlipSwitchEffect::isSelectableWindow( EffectWindow* w ) const - { +bool FlipSwitchEffect::isSelectableWindow(EffectWindow* w) const +{ // desktop windows might be included - if( (w->isSpecialWindow() && !w->isDesktop()) || w->isUtility() ) + if ((w->isSpecialWindow() && !w->isDesktop()) || w->isUtility()) return false; - if( w->isDesktop() ) - return (m_mode == TabboxMode && effects->currentTabBoxWindowList().contains( w )); - if( w->isDeleted() ) + if (w->isDesktop()) + return (m_mode == TabboxMode && effects->currentTabBoxWindowList().contains(w)); + if (w->isDeleted()) return false; - if( !w->acceptsFocus() ) + if (!w->acceptsFocus()) return false; - switch( m_mode ) - { - case TabboxMode: - return effects->currentTabBoxWindowList().contains( w ); - case CurrentDesktopMode: - return w->isOnCurrentDesktop(); - case AllDesktopsMode: - //nothing special - break; - } - return true; + switch(m_mode) { + case TabboxMode: + return effects->currentTabBoxWindowList().contains(w); + case CurrentDesktopMode: + return w->isOnCurrentDesktop(); + case AllDesktopsMode: + //nothing special + break; } + return true; +} -void FlipSwitchEffect::scheduleAnimation( const SwitchingDirection& direction, int distance ) - { - if( m_start ) - { +void FlipSwitchEffect::scheduleAnimation(const SwitchingDirection& direction, int distance) +{ + if (m_start) { // start is still active so change the shape to have a nice transition - m_startStopTimeLine.setCurveShape( TimeLine::EaseInCurve ); - } - if( !m_animation && !m_start ) - { + m_startStopTimeLine.setCurveShape(TimeLine::EaseInCurve); + } + if (!m_animation && !m_start) { m_animation = true; - m_scheduledDirections.enqueue( direction ); + m_scheduledDirections.enqueue(direction); distance--; // reset shape just to make sure m_currentAnimationShape = TimeLine::EaseInOutCurve; - m_timeLine.setCurveShape( m_currentAnimationShape ); - } - for( int i=0; i 1 && m_scheduledDirections.last() != direction ) + m_timeLine.setCurveShape(m_currentAnimationShape); + } + for (int i = 0; i < distance; i++) { + if (m_scheduledDirections.count() > 1 && m_scheduledDirections.last() != direction) m_scheduledDirections.pop_back(); else - m_scheduledDirections.enqueue( direction ); - if( m_scheduledDirections.count() == m_windows.count() + 1 ) - { + m_scheduledDirections.enqueue(direction); + if (m_scheduledDirections.count() == m_windows.count() + 1) { SwitchingDirection temp = m_scheduledDirections.dequeue(); m_scheduledDirections.clear(); - m_scheduledDirections.enqueue( temp ); - } + m_scheduledDirections.enqueue(temp); } - if( m_scheduledDirections.count() > 1 ) - { + } + if (m_scheduledDirections.count() > 1) { TimeLine::CurveShape newShape = TimeLine::EaseInOutCurve; - switch( m_currentAnimationShape ) - { - case TimeLine::EaseInOutCurve: - newShape = TimeLine::EaseInCurve; - break; - case TimeLine::EaseOutCurve: - newShape = TimeLine::LinearCurve; - break; - default: - newShape = m_currentAnimationShape; - } - if( newShape != m_currentAnimationShape ) - { + switch(m_currentAnimationShape) { + case TimeLine::EaseInOutCurve: + newShape = TimeLine::EaseInCurve; + break; + case TimeLine::EaseOutCurve: + newShape = TimeLine::LinearCurve; + break; + default: + newShape = m_currentAnimationShape; + } + if (newShape != m_currentAnimationShape) { m_currentAnimationShape = newShape; - m_timeLine.setCurveShape( m_currentAnimationShape ); - } + m_timeLine.setCurveShape(m_currentAnimationShape); } } +} -void FlipSwitchEffect::adjustWindowMultiScreen( const KWin::EffectWindow* w, WindowPaintData& data ) - { - if( effects->numScreens() <= 1 ) +void FlipSwitchEffect::adjustWindowMultiScreen(const KWin::EffectWindow* w, WindowPaintData& data) +{ + if (effects->numScreens() <= 1) return; - QRect clientRect = effects->clientArea( FullScreenArea, w->screen(), effects->currentDesktop() ); - QRect rect = effects->clientArea( ScreenArea, m_activeScreen, effects->currentDesktop() ); - QRect fullRect = effects->clientArea( FullArea, m_activeScreen, effects->currentDesktop() ); - if( w->screen() == m_activeScreen ) - { - if( clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x() ) - { + QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); + QRect rect = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); + QRect fullRect = effects->clientArea(FullArea, m_activeScreen, effects->currentDesktop()); + if (w->screen() == m_activeScreen) { + if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.xTranslate -= clientRect.x(); - } - if( clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y() ) - { - data.yTranslate -= clientRect.y(); - } } - else - { - if( clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) - { + if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { + data.yTranslate -= clientRect.y(); + } + } else { + if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { data.xTranslate -= clientRect.width(); - } - if( clientRect.height() != fullRect.height() && clientRect.y() < m_screenArea.y() ) - { + } + if (clientRect.height() != fullRect.height() && clientRect.y() < m_screenArea.y()) { data.yTranslate -= clientRect.height(); - } } } +} //************************************************************* // Keyboard handling //************************************************************* -void FlipSwitchEffect::globalShortcutChangedAll( QKeySequence shortcut ) - { - m_shortcutAll = KShortcut( shortcut ); - } +void FlipSwitchEffect::globalShortcutChangedAll(QKeySequence shortcut) +{ + m_shortcutAll = KShortcut(shortcut); +} void FlipSwitchEffect::globalShortcutChangedCurrent(QKeySequence shortcut) - { - m_shortcutCurrent = KShortcut( shortcut ); - } +{ + m_shortcutCurrent = KShortcut(shortcut); +} void FlipSwitchEffect::grabbedKeyboardEvent(QKeyEvent* e) - { - if( e->type() == QEvent::KeyPress ) - { +{ + if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) - if( m_mode == CurrentDesktopMode && m_shortcutCurrent.contains( e->key() + e->modifiers() ) ) - { + if (m_mode == CurrentDesktopMode && m_shortcutCurrent.contains(e->key() + e->modifiers())) { toggleActiveCurrent(); return; - } - if( m_mode == AllDesktopsMode && m_shortcutAll.contains( e->key() + e->modifiers() ) ) - { + } + if (m_mode == AllDesktopsMode && m_shortcutAll.contains(e->key() + e->modifiers())) { toggleActiveAllDesktops(); return; - } - - switch( e->key() ) - { - case Qt::Key_Escape: - setActive( false, m_mode ); - return; - case Qt::Key_Tab: - { - // find next window - if( m_windows.isEmpty() ) - return; // sanity check - bool found = false; - for( int i=effects->stackingOrder().indexOf( m_selectedWindow)-1; i>=0; i-- ) - { - if( isSelectableWindow( effects->stackingOrder().at( i )) ) - { - m_selectedWindow = effects->stackingOrder().at( i ); - found = true; - break; - } - } - if( !found ) - { - for( int i=effects->stackingOrder().count()-1; i>effects->stackingOrder().indexOf( m_selectedWindow); i-- ) - { - if( isSelectableWindow( effects->stackingOrder().at( i )) ) - { - m_selectedWindow = effects->stackingOrder().at( i ); - found = true; - break; - } - } - } - if( found ) - { - m_captionFrame->setText( m_selectedWindow->caption() ); - m_captionFrame->setIcon( m_selectedWindow->icon() ); - scheduleAnimation( DirectionForward ); - } - break; - } - case Qt::Key_Backtab: - { - // find previous window - if( m_windows.isEmpty() ) - return; // sanity check - bool found = false; - for( int i=effects->stackingOrder().indexOf( m_selectedWindow)+1; istackingOrder().count(); i++ ) - { - if( isSelectableWindow( effects->stackingOrder().at( i )) ) - { - m_selectedWindow = effects->stackingOrder().at( i ); - found = true; - break; - } - } - if( !found ) - { - for( int i=0; istackingOrder().indexOf( m_selectedWindow); i++ ) - { - if( isSelectableWindow( effects->stackingOrder().at( i )) ) - { - m_selectedWindow = effects->stackingOrder().at( i ); - found = true; - break; - } - } - } - if( found ) - { - m_captionFrame->setText( m_selectedWindow->caption() ); - m_captionFrame->setIcon( m_selectedWindow->icon() ); - scheduleAnimation( DirectionBackward ); - } - break; - } - case Qt::Key_Return: - case Qt::Key_Enter: - case Qt::Key_Space: - if( m_selectedWindow ) - effects->activateWindow( m_selectedWindow ); - setActive( false, m_mode ); - break; - default: - break; - } - effects->addRepaintFull(); } + + switch(e->key()) { + case Qt::Key_Escape: + setActive(false, m_mode); + return; + case Qt::Key_Tab: { + // find next window + if (m_windows.isEmpty()) + return; // sanity check + bool found = false; + for (int i = effects->stackingOrder().indexOf(m_selectedWindow) - 1; i >= 0; i--) { + if (isSelectableWindow(effects->stackingOrder().at(i))) { + m_selectedWindow = effects->stackingOrder().at(i); + found = true; + break; + } + } + if (!found) { + for (int i = effects->stackingOrder().count() - 1; i > effects->stackingOrder().indexOf(m_selectedWindow); i--) { + if (isSelectableWindow(effects->stackingOrder().at(i))) { + m_selectedWindow = effects->stackingOrder().at(i); + found = true; + break; + } + } + } + if (found) { + m_captionFrame->setText(m_selectedWindow->caption()); + m_captionFrame->setIcon(m_selectedWindow->icon()); + scheduleAnimation(DirectionForward); + } + break; + } + case Qt::Key_Backtab: { + // find previous window + if (m_windows.isEmpty()) + return; // sanity check + bool found = false; + for (int i = effects->stackingOrder().indexOf(m_selectedWindow) + 1; i < effects->stackingOrder().count(); i++) { + if (isSelectableWindow(effects->stackingOrder().at(i))) { + m_selectedWindow = effects->stackingOrder().at(i); + found = true; + break; + } + } + if (!found) { + for (int i = 0; i < effects->stackingOrder().indexOf(m_selectedWindow); i++) { + if (isSelectableWindow(effects->stackingOrder().at(i))) { + m_selectedWindow = effects->stackingOrder().at(i); + found = true; + break; + } + } + } + if (found) { + m_captionFrame->setText(m_selectedWindow->caption()); + m_captionFrame->setIcon(m_selectedWindow->icon()); + scheduleAnimation(DirectionBackward); + } + break; + } + case Qt::Key_Return: + case Qt::Key_Enter: + case Qt::Key_Space: + if (m_selectedWindow) + effects->activateWindow(m_selectedWindow); + setActive(false, m_mode); + break; + default: + break; + } + effects->addRepaintFull(); } +} //************************************************************* // Item Info //************************************************************* FlipSwitchEffect::ItemInfo::ItemInfo() : deleted(false) - , opacity( 0.0 ) - , brightness( 0.0 ) - , saturation( 0.0 ) - { - } + , opacity(0.0) + , brightness(0.0) + , saturation(0.0) +{ +} FlipSwitchEffect::ItemInfo::~ItemInfo() - { - } +{ +} } // namespace diff --git a/effects/flipswitch/flipswitch.h b/effects/flipswitch/flipswitch.h index 50f846e27..701fc30b6 100644 --- a/effects/flipswitch/flipswitch.h +++ b/effects/flipswitch/flipswitch.h @@ -32,92 +32,90 @@ namespace KWin class FlipSwitchEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - FlipSwitchEffect(); - ~FlipSwitchEffect(); +public: + FlipSwitchEffect(); + ~FlipSwitchEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void tabBoxAdded( int mode ); - virtual void tabBoxClosed(); - virtual void tabBoxUpdated(); - virtual void windowAdded( EffectWindow* w ); - virtual void windowClosed( EffectWindow* w ); - virtual bool borderActivated( ElectricBorder border ); - virtual void grabbedKeyboardEvent( QKeyEvent* e ); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void tabBoxAdded(int mode); + virtual void tabBoxClosed(); + virtual void tabBoxUpdated(); + virtual void windowAdded(EffectWindow* w); + virtual void windowClosed(EffectWindow* w); + virtual bool borderActivated(ElectricBorder border); + virtual void grabbedKeyboardEvent(QKeyEvent* e); - static bool supported(); - private Q_SLOTS: - void toggleActiveCurrent(); - void toggleActiveAllDesktops(); - void globalShortcutChangedCurrent( QKeySequence shortcut ); - void globalShortcutChangedAll( QKeySequence shortcut ); + static bool supported(); +private Q_SLOTS: + void toggleActiveCurrent(); + void toggleActiveAllDesktops(); + void globalShortcutChangedCurrent(QKeySequence shortcut); + void globalShortcutChangedAll(QKeySequence shortcut); - private: - class ItemInfo; - enum SwitchingDirection - { - DirectionForward, - DirectionBackward - }; - enum FlipSwitchMode - { - TabboxMode, - CurrentDesktopMode, - AllDesktopsMode - }; - void setActive( bool activate, FlipSwitchMode mode ); - bool isSelectableWindow( EffectWindow *w ) const; - void scheduleAnimation( const SwitchingDirection& direction, int distance = 1 ); - void adjustWindowMultiScreen( const EffectWindow *w, WindowPaintData& data ); - QQueue< SwitchingDirection> m_scheduledDirections; - EffectWindow* m_selectedWindow; - TimeLine m_timeLine; - TimeLine m_startStopTimeLine; - TimeLine::CurveShape m_currentAnimationShape; - QRect m_screenArea; - int m_activeScreen; - bool m_active; - bool m_start; - bool m_stop; - bool m_animation; - bool m_hasKeyboardGrab; - Window m_input; - FlipSwitchMode m_mode; - EffectFrame* m_captionFrame; - QFont m_captionFont; - EffectWindowList m_flipOrderedWindows; - QHash< const EffectWindow*, ItemInfo* > m_windows; - // options - QList m_borderActivate; - QList m_borderActivateAll; - bool m_tabbox; - bool m_tabboxAlternative; - float m_angle; - float m_xPosition; - float m_yPosition; - bool m_windowTitle; - // Shortcuts - KShortcut m_shortcutCurrent; - KShortcut m_shortcutAll; +private: + class ItemInfo; + enum SwitchingDirection { + DirectionForward, + DirectionBackward }; + enum FlipSwitchMode { + TabboxMode, + CurrentDesktopMode, + AllDesktopsMode + }; + void setActive(bool activate, FlipSwitchMode mode); + bool isSelectableWindow(EffectWindow *w) const; + void scheduleAnimation(const SwitchingDirection& direction, int distance = 1); + void adjustWindowMultiScreen(const EffectWindow *w, WindowPaintData& data); + QQueue< SwitchingDirection> m_scheduledDirections; + EffectWindow* m_selectedWindow; + TimeLine m_timeLine; + TimeLine m_startStopTimeLine; + TimeLine::CurveShape m_currentAnimationShape; + QRect m_screenArea; + int m_activeScreen; + bool m_active; + bool m_start; + bool m_stop; + bool m_animation; + bool m_hasKeyboardGrab; + Window m_input; + FlipSwitchMode m_mode; + EffectFrame* m_captionFrame; + QFont m_captionFont; + EffectWindowList m_flipOrderedWindows; + QHash< const EffectWindow*, ItemInfo* > m_windows; + // options + QList m_borderActivate; + QList m_borderActivateAll; + bool m_tabbox; + bool m_tabboxAlternative; + float m_angle; + float m_xPosition; + float m_yPosition; + bool m_windowTitle; + // Shortcuts + KShortcut m_shortcutCurrent; + KShortcut m_shortcutAll; +}; class FlipSwitchEffect::ItemInfo - { - public: - ItemInfo(); - ~ItemInfo(); - bool deleted; - double opacity; - double brightness; - double saturation; - }; +{ +public: + ItemInfo(); + ~ItemInfo(); + bool deleted; + double opacity; + double brightness; + double saturation; +}; } // namespace diff --git a/effects/flipswitch/flipswitch_config.cpp b/effects/flipswitch/flipswitch_config.cpp index acdf79f53..4e9560c7d 100644 --- a/effects/flipswitch/flipswitch_config.cpp +++ b/effects/flipswitch/flipswitch_config.cpp @@ -33,12 +33,12 @@ KWIN_EFFECT_CONFIG_FACTORY FlipSwitchEffectConfigForm::FlipSwitchEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } FlipSwitchEffectConfig::FlipSwitchEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new FlipSwitchEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -46,79 +46,79 @@ FlipSwitchEffectConfig::FlipSwitchEffectConfig(QWidget* parent, const QVariantLi layout->addWidget(m_ui); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); - KAction* a = ( KAction* )m_actionCollection->addAction( "FlipSwitchCurrent" ); - a->setText( i18n( "Toggle Flip Switch (Current desktop)" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); - KAction* b = ( KAction* )m_actionCollection->addAction( "FlipSwitchAll" ); - b->setText( i18n( "Toggle Flip Switch (All desktops)" )); - b->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); + KAction* a = (KAction*)m_actionCollection->addAction("FlipSwitchCurrent"); + a->setText(i18n("Toggle Flip Switch (Current desktop)")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); + KAction* b = (KAction*)m_actionCollection->addAction("FlipSwitchAll"); + b->setText(i18n("Toggle Flip Switch (All desktops)")); + b->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - m_actionCollection->setConfigGroup( "FlipSwitch" ); - m_actionCollection->setConfigGlobal( true ); + m_actionCollection->setConfigGroup("FlipSwitch"); + m_actionCollection->setConfigGlobal(true); - m_ui->shortcutEditor->addCollection( m_actionCollection ); + m_ui->shortcutEditor->addCollection(m_actionCollection); connect(m_ui->durationSpin, SIGNAL(valueChanged(int)), SLOT(changed())); connect(m_ui->angleSpin, SIGNAL(valueChanged(int)), SLOT(changed())); connect(m_ui->horizontalSlider, SIGNAL(valueChanged(int)), SLOT(changed())); connect(m_ui->verticalSlider, SIGNAL(valueChanged(int)), SLOT(changed())); connect(m_ui->windowTitleBox, SIGNAL(stateChanged(int)), SLOT(changed())); - connect( m_ui->shortcutEditor, SIGNAL( keyChange() ), this, SLOT( changed() )); + connect(m_ui->shortcutEditor, SIGNAL(keyChange()), this, SLOT(changed())); load(); - } +} FlipSwitchEffectConfig::~FlipSwitchEffectConfig() - { - } +{ +} void FlipSwitchEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "FlipSwitch" ); + KConfigGroup conf = EffectsHandler::effectConfig("FlipSwitch"); - m_ui->durationSpin->setValue( conf.readEntry( "Duration", 0 )); - m_ui->angleSpin->setValue( conf.readEntry( "Angle", 30 )); - m_ui->horizontalSlider->setValue( conf.readEntry( "XPosition", 33 )); + m_ui->durationSpin->setValue(conf.readEntry("Duration", 0)); + m_ui->angleSpin->setValue(conf.readEntry("Angle", 30)); + m_ui->horizontalSlider->setValue(conf.readEntry("XPosition", 33)); // slider bottom is 0, effect bottom is 100 - m_ui->verticalSlider->setValue( 100 - conf.readEntry( "YPosition", 100 )); - m_ui->windowTitleBox->setChecked( conf.readEntry( "WindowTitle", true )); + m_ui->verticalSlider->setValue(100 - conf.readEntry("YPosition", 100)); + m_ui->windowTitleBox->setChecked(conf.readEntry("WindowTitle", true)); emit changed(false); - } +} void FlipSwitchEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "FlipSwitch" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("FlipSwitch"); - conf.writeEntry( "Duration", m_ui->durationSpin->value() ); - conf.writeEntry( "Angle", m_ui->angleSpin->value() ); - conf.writeEntry( "XPosition", m_ui->horizontalSlider->value() ); + conf.writeEntry("Duration", m_ui->durationSpin->value()); + conf.writeEntry("Angle", m_ui->angleSpin->value()); + conf.writeEntry("XPosition", m_ui->horizontalSlider->value()); // slider bottom is 0, effect bottom is 100 - conf.writeEntry( "YPosition", 100 - m_ui->verticalSlider->value() ); - conf.writeEntry( "WindowTitle", m_ui->windowTitleBox->isChecked() ); + conf.writeEntry("YPosition", 100 - m_ui->verticalSlider->value()); + conf.writeEntry("WindowTitle", m_ui->windowTitleBox->isChecked()); m_ui->shortcutEditor->save(); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "flipswitch" ); - } + EffectsHandler::sendReloadMessage("flipswitch"); +} void FlipSwitchEffectConfig::defaults() - { - m_ui->durationSpin->setValue( 0 ); - m_ui->angleSpin->setValue( 30 ); - m_ui->horizontalSlider->setValue( 33 ); +{ + m_ui->durationSpin->setValue(0); + m_ui->angleSpin->setValue(30); + m_ui->horizontalSlider->setValue(33); // slider bottom is 0, effect bottom is 100 - m_ui->verticalSlider->setValue( 0 ); - m_ui->windowTitleBox->setChecked( true ); + m_ui->verticalSlider->setValue(0); + m_ui->windowTitleBox->setChecked(true); m_ui->shortcutEditor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/flipswitch/flipswitch_config.h b/effects/flipswitch/flipswitch_config.h index 54a473e09..3ae7bbe0d 100644 --- a/effects/flipswitch/flipswitch_config.h +++ b/effects/flipswitch/flipswitch_config.h @@ -33,26 +33,26 @@ namespace KWin class FlipSwitchEffectConfigForm : public QWidget, public Ui::FlipSwitchEffectConfigForm { Q_OBJECT - public: - explicit FlipSwitchEffectConfigForm(QWidget* parent); +public: + explicit FlipSwitchEffectConfigForm(QWidget* parent); }; class FlipSwitchEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit FlipSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~FlipSwitchEffectConfig(); +public: + explicit FlipSwitchEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~FlipSwitchEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - FlipSwitchEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + FlipSwitchEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/glide/glide.cpp b/effects/glide/glide.cpp index c3f2466f2..2bc3bf98c 100644 --- a/effects/glide/glide.cpp +++ b/effects/glide/glide.cpp @@ -29,203 +29,194 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( glide, GlideEffect ) -KWIN_EFFECT_SUPPORTED( glide, GlideEffect::supported() ) +KWIN_EFFECT(glide, GlideEffect) +KWIN_EFFECT_SUPPORTED(glide, GlideEffect::supported()) static const int IsGlideWindow = 0x22A982D4; GlideEffect::GlideEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} bool GlideEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void GlideEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "Glide" ); - duration = animationTime( conf, "AnimationTime", 350 ); - effect = (EffectStyle) conf.readEntry( "GlideEffect", 0 ); - angle = conf.readEntry( "GlideAngle", -90 ); - } +void GlideEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("Glide"); + duration = animationTime(conf, "AnimationTime", 350); + effect = (EffectStyle) conf.readEntry("GlideEffect", 0); + angle = conf.readEntry("GlideAngle", -90); +} -void GlideEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty() ) +void GlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - effects->prePaintScreen( data, time ); + effects->prePaintScreen(data, time); +} + +void GlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + InfoHash::iterator info = windows.find(w); + if (info != windows.end()) { + data.setTransformed(); + if (info->added) + info->timeLine.addTime(time); + else if (info->closed) { + info->timeLine.removeTime(time); + if (info->deleted) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); + } } -void GlideEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - InfoHash::iterator info = windows.find( w ); - if( info != windows.end() ) - { - data.setTransformed(); - if( info->added ) - info->timeLine.addTime( time ); - else if( info->closed ) - { - info->timeLine.removeTime( time ); - if( info->deleted ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - } - } - - effects->prePaintWindow( w, data, time ); - + effects->prePaintWindow(w, data, time); + // if the window isn't to be painted, then let's make sure // to track its progress - if( info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect() ) + if (info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect()) w->addRepaintFull(); - } +} -void GlideEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - InfoHash::const_iterator info = windows.constFind( w ); - if( info != windows.constEnd() ) - { +void GlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + InfoHash::const_iterator info = windows.constFind(w); + if (info != windows.constEnd()) { const double progress = info->timeLine.value(); RotationData rot; rot.axis = RotationData::XAxis; - rot.angle = angle * ( 1 - progress ); + rot.angle = angle * (1 - progress); data.rotation = &rot; data.opacity *= progress; - switch ( effect ) - { - default: - case GlideInOut: - if( info->added ) - glideIn( w, data ); - else if( info->closed ) - glideOut( w, data ); - break; - case GlideOutIn: - if( info->added ) - glideOut( w, data ); - if( info->closed ) - glideIn( w, data ); - break; - case GlideIn: glideIn( w, data ); break; - case GlideOut: glideOut( w, data ); break; - } + switch(effect) { + default: + case GlideInOut: + if (info->added) + glideIn(w, data); + else if (info->closed) + glideOut(w, data); + break; + case GlideOutIn: + if (info->added) + glideOut(w, data); + if (info->closed) + glideIn(w, data); + break; + case GlideIn: glideIn(w, data); break; + case GlideOut: glideOut(w, data); break; } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void GlideEffect::glideIn(EffectWindow* w, WindowPaintData& data ) - { - InfoHash::const_iterator info = windows.constFind( w ); - if ( info == windows.constEnd() ) +void GlideEffect::glideIn(EffectWindow* w, WindowPaintData& data) +{ + InfoHash::const_iterator info = windows.constFind(w); + if (info == windows.constEnd()) return; const double progress = info->timeLine.value(); data.xScale *= progress; data.yScale *= progress; data.zScale *= progress; - data.xTranslate += int( w->width() / 2 * ( 1 - progress ) ); - data.yTranslate += int( w->height() / 2 * ( 1 - progress ) ); - } + data.xTranslate += int(w->width() / 2 * (1 - progress)); + data.yTranslate += int(w->height() / 2 * (1 - progress)); +} -void GlideEffect::glideOut(EffectWindow* w, WindowPaintData& data ) - { - InfoHash::const_iterator info = windows.constFind( w ); - if ( info == windows.constEnd() ) +void GlideEffect::glideOut(EffectWindow* w, WindowPaintData& data) +{ + InfoHash::const_iterator info = windows.constFind(w); + if (info == windows.constEnd()) return; const double progress = info->timeLine.value(); - data.xScale *= ( 2 - progress ); - data.yScale *= ( 2 - progress ); - data.zScale *= ( 2 - progress ); - data.xTranslate -= int( w->width() / 2 * ( 1 - progress ) ); - data.yTranslate -= int( w->height() / 2 * ( 1 - progress ) ); - } + data.xScale *= (2 - progress); + data.yScale *= (2 - progress); + data.zScale *= (2 - progress); + data.xTranslate -= int(w->width() / 2 * (1 - progress)); + data.yTranslate -= int(w->height() / 2 * (1 - progress)); +} -void GlideEffect::postPaintWindow( EffectWindow* w ) - { - InfoHash::iterator info = windows.find( w ); - if( info != windows.end() ) - { - if( info->added && info->timeLine.value() == 1.0 ) - { - windows.remove( w ); +void GlideEffect::postPaintWindow(EffectWindow* w) +{ + InfoHash::iterator info = windows.find(w); + if (info != windows.end()) { + if (info->added && info->timeLine.value() == 1.0) { + windows.remove(w); effects->addRepaintFull(); - } - else if( info->closed && info->timeLine.value() == 0.0 ) - { + } else if (info->closed && info->timeLine.value() == 0.0) { info->closed = false; - if( info->deleted ) - { - windows.remove( w ); + if (info->deleted) { + windows.remove(w); w->unrefWindow(); - } - effects->addRepaintFull(); } - if( info->added || info->closed ) - w->addRepaintFull(); + effects->addRepaintFull(); } - effects->postPaintWindow( w ); + if (info->added || info->closed) + w->addRepaintFull(); } + effects->postPaintWindow(w); +} -void GlideEffect::windowAdded( EffectWindow* w ) - { - if( !isGlideWindow( w ) ) +void GlideEffect::windowAdded(EffectWindow* w) +{ + if (!isGlideWindow(w)) return; - w->setData( IsGlideWindow, true ); - const void *addGrab = w->data( WindowAddedGrabRole ).value(); - if ( addGrab && addGrab != this ) + w->setData(IsGlideWindow, true); + const void *addGrab = w->data(WindowAddedGrabRole).value(); + if (addGrab && addGrab != this) return; - w->setData( WindowAddedGrabRole, QVariant::fromValue( static_cast( this ))); - - InfoHash::iterator it = windows.find( w ); - WindowInfo *info = ( it == windows.end() ) ? &windows[w] : &it.value(); + w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); + + InfoHash::iterator it = windows.find(w); + WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = true; info->closed = false; info->deleted = false; - info->timeLine.setDuration( duration ); - info->timeLine.setCurveShape( TimeLine::EaseOutCurve ); + info->timeLine.setDuration(duration); + info->timeLine.setCurveShape(TimeLine::EaseOutCurve); w->addRepaintFull(); - } +} -void GlideEffect::windowClosed( EffectWindow* w ) - { - if ( !isGlideWindow( w ) ) +void GlideEffect::windowClosed(EffectWindow* w) +{ + if (!isGlideWindow(w)) return; - const void *closeGrab = w->data( WindowClosedGrabRole ).value(); - if ( closeGrab && closeGrab != this ) + const void *closeGrab = w->data(WindowClosedGrabRole).value(); + if (closeGrab && closeGrab != this) return; w->refWindow(); - w->setData( WindowClosedGrabRole, QVariant::fromValue( static_cast( this ))); - - InfoHash::iterator it = windows.find( w ); - WindowInfo *info = ( it == windows.end() ) ? &windows[w] : &it.value(); + w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); + + InfoHash::iterator it = windows.find(w); + WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = false; info->closed = true; info->deleted = true; - info->timeLine.setDuration( duration ); - info->timeLine.setCurveShape( TimeLine::EaseInCurve ); - info->timeLine.setProgress( 1.0 ); + info->timeLine.setDuration(duration); + info->timeLine.setCurveShape(TimeLine::EaseInCurve); + info->timeLine.setProgress(1.0); w->addRepaintFull(); - } +} -void GlideEffect::windowDeleted( EffectWindow* w ) - { - windows.remove( w ); - } +void GlideEffect::windowDeleted(EffectWindow* w) +{ + windows.remove(w); +} -bool GlideEffect::isGlideWindow( EffectWindow* w ) - { - if ( effects->activeFullScreenEffect() ) +bool GlideEffect::isGlideWindow(EffectWindow* w) +{ + if (effects->activeFullScreenEffect()) return false; - if ( w->data( IsGlideWindow ).toBool() ) + if (w->data(IsGlideWindow).toBool()) return true; - if ( w->hasDecoration() ) + if (w->hasDecoration()) return true; - if ( !w->isManaged() || w->isMenu() || w->isNotification() || w->isDesktop() || - w->isDock() || w->isSplash() || w->isTopMenu() || w->isToolbar() || - w->windowClass() == "dashboard dashboard" ) + if (!w->isManaged() || w->isMenu() || w->isNotification() || w->isDesktop() || + w->isDock() || w->isSplash() || w->isTopMenu() || w->isToolbar() || + w->windowClass() == "dashboard dashboard") return false; return true; - } +} } // namespace diff --git a/effects/glide/glide.h b/effects/glide/glide.h index 2e8fde8d3..9a1aebd37 100644 --- a/effects/glide/glide.h +++ b/effects/glide/glide.h @@ -30,54 +30,52 @@ namespace KWin class GlideEffect : public Effect - { - public: - GlideEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); +{ +public: + GlideEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); - static bool supported(); - private: - class WindowInfo; - typedef QMap< const EffectWindow*, WindowInfo > InfoHash; - void glideIn( EffectWindow* w, WindowPaintData& data ); - void glideOut( EffectWindow* w, WindowPaintData& data ); - bool isGlideWindow( EffectWindow* w ); - InfoHash windows; - float duration; - int angle; - enum EffectStyle - { - GlideIn = 0, - GlideInOut = 1, - GlideOutIn = 2, - GlideOut = 3 - }; - EffectStyle effect; + static bool supported(); +private: + class WindowInfo; + typedef QMap< const EffectWindow*, WindowInfo > InfoHash; + void glideIn(EffectWindow* w, WindowPaintData& data); + void glideOut(EffectWindow* w, WindowPaintData& data); + bool isGlideWindow(EffectWindow* w); + InfoHash windows; + float duration; + int angle; + enum EffectStyle { + GlideIn = 0, + GlideInOut = 1, + GlideOutIn = 2, + GlideOut = 3 }; + EffectStyle effect; +}; class GlideEffect::WindowInfo - { - public: - WindowInfo() - : deleted( false ) - , added( false ) - , closed( false ) { } - ~WindowInfo() - { - } - bool deleted; - bool added; - bool closed; - TimeLine timeLine; - }; +{ +public: + WindowInfo() + : deleted(false) + , added(false) + , closed(false) { } + ~WindowInfo() { + } + bool deleted; + bool added; + bool closed; + TimeLine timeLine; +}; } // namespace diff --git a/effects/glide/glide_config.cpp b/effects/glide/glide_config.cpp index 124ac730f..cad00d694 100644 --- a/effects/glide/glide_config.cpp +++ b/effects/glide/glide_config.cpp @@ -29,48 +29,48 @@ KWIN_EFFECT_CONFIG_FACTORY GlideEffectConfig::GlideEffectConfig(QWidget *parent, const QVariantList &args) : KCModule(EffectFactory::componentData(), parent, args) - { +{ ui.setupUi(this); connect(ui.slider, SIGNAL(valueChanged(int)), SLOT(valueChanged(int))); connect(ui.slider2, SIGNAL(valueChanged(int)), SLOT(valueChanged(int))); load(); - } +} GlideEffectConfig::~GlideEffectConfig() - { - } +{ +} void GlideEffectConfig::load() - { +{ KCModule::load(); KConfigGroup cg = EffectsHandler::effectConfig("Glide"); - ui.slider->setValue(cg.readEntry("GlideEffect", 0) ); - ui.slider2->setValue(cg.readEntry("GlideAngle", -90) ); + ui.slider->setValue(cg.readEntry("GlideEffect", 0)); + ui.slider2->setValue(cg.readEntry("GlideAngle", -90)); emit changed(false); - } +} void GlideEffectConfig::save() - { +{ KCModule::save(); KConfigGroup cg = EffectsHandler::effectConfig("Glide"); - cg.writeEntry("GlideEffect", ui.slider->value() ); - cg.writeEntry("GlideAngle", ui.slider2->value() ); + cg.writeEntry("GlideEffect", ui.slider->value()); + cg.writeEntry("GlideAngle", ui.slider2->value()); cg.sync(); emit changed(false); EffectsHandler::sendReloadMessage("glide"); - } +} void GlideEffectConfig::defaults() - { +{ ui.slider->setValue(0); ui.slider2->setValue(-90); emit changed(true); - } +} void GlideEffectConfig::valueChanged(int value) - { +{ Q_UNUSED(value) emit changed(true); - } +} } // namespace KWin #include "glide_config.moc" diff --git a/effects/highlightwindow/highlightwindow.cpp b/effects/highlightwindow/highlightwindow.cpp index a7d9b6d1f..218f56af4 100644 --- a/effects/highlightwindow/highlightwindow.cpp +++ b/effects/highlightwindow/highlightwindow.cpp @@ -25,162 +25,157 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( highlightwindow, HighlightWindowEffect ) +KWIN_EFFECT(highlightwindow, HighlightWindowEffect) HighlightWindowEffect::HighlightWindowEffect() - : m_finishing( false ) - , m_fadeDuration( double( animationTime( 150 ))) - , m_monitorWindow( NULL ) - { - m_atom = XInternAtom( display(), "_KDE_WINDOW_HIGHLIGHT", False ); - effects->registerPropertyType( m_atom, true ); + : m_finishing(false) + , m_fadeDuration(double(animationTime(150))) + , m_monitorWindow(NULL) +{ + m_atom = XInternAtom(display(), "_KDE_WINDOW_HIGHLIGHT", False); + effects->registerPropertyType(m_atom, true); // Announce support by creating a dummy version on the root window unsigned char dummy = 0; - XChangeProperty( display(), rootWindow(), m_atom, m_atom, 8, PropModeReplace, &dummy, 1 ); - } + XChangeProperty(display(), rootWindow(), m_atom, m_atom, 8, PropModeReplace, &dummy, 1); +} HighlightWindowEffect::~HighlightWindowEffect() - { - XDeleteProperty( display(), rootWindow(), m_atom ); - effects->registerPropertyType( m_atom, false ); - } +{ + XDeleteProperty(display(), rootWindow(), m_atom); + effects->registerPropertyType(m_atom, false); +} -static bool isInitiallyHidden( EffectWindow* w ) - { // Is the window initially hidden until it is highlighted? +static bool isInitiallyHidden(EffectWindow* w) +{ + // Is the window initially hidden until it is highlighted? return !w->visibleInClientGroup() || !w->isOnCurrentDesktop(); - } +} -void HighlightWindowEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void HighlightWindowEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // Calculate window opacities - if( !m_highlightedWindows.isEmpty() ) - { // Initial fade out and changing highlight animation + if (!m_highlightedWindows.isEmpty()) { + // Initial fade out and changing highlight animation double oldOpacity = m_windowOpacity[w]; - if( m_highlightedWindows.contains( w )) - m_windowOpacity[w] = qMin( 1.0, m_windowOpacity[w] + time / m_fadeDuration ); - else if( w->isNormalWindow() || w->isDialog() ) // Only fade out windows - m_windowOpacity[w] = qMax( isInitiallyHidden( w ) ? 0.0 : 0.15, - m_windowOpacity[w] - time / m_fadeDuration ); + if (m_highlightedWindows.contains(w)) + m_windowOpacity[w] = qMin(1.0, m_windowOpacity[w] + time / m_fadeDuration); + else if (w->isNormalWindow() || w->isDialog()) // Only fade out windows + m_windowOpacity[w] = qMax(isInitiallyHidden(w) ? 0.0 : 0.15, + m_windowOpacity[w] - time / m_fadeDuration); - if( m_windowOpacity[w] != 1.0 ) + if (m_windowOpacity[w] != 1.0) data.setTranslucent(); - if( oldOpacity != m_windowOpacity[w] ) + if (oldOpacity != m_windowOpacity[w]) w->addRepaintFull(); - } - else if( m_finishing && m_windowOpacity.contains( w )) - { // Final fading back in animation + } else if (m_finishing && m_windowOpacity.contains(w)) { + // Final fading back in animation double oldOpacity = m_windowOpacity[w]; - if( isInitiallyHidden( w )) - m_windowOpacity[w] = qMax( 0.0, m_windowOpacity[w] - time / m_fadeDuration ); + if (isInitiallyHidden(w)) + m_windowOpacity[w] = qMax(0.0, m_windowOpacity[w] - time / m_fadeDuration); else - m_windowOpacity[w] = qMin( 1.0, m_windowOpacity[w] + time / m_fadeDuration ); + m_windowOpacity[w] = qMin(1.0, m_windowOpacity[w] + time / m_fadeDuration); - if( m_windowOpacity[w] != 1.0 ) + if (m_windowOpacity[w] != 1.0) data.setTranslucent(); - if( oldOpacity != m_windowOpacity[w] ) + if (oldOpacity != m_windowOpacity[w]) w->addRepaintFull(); - if( m_windowOpacity[w] == 1.0 || m_windowOpacity[w] == 0.0 ) - m_windowOpacity.remove( w ); // We default to 1.0 - } + if (m_windowOpacity[w] == 1.0 || m_windowOpacity[w] == 0.0) + m_windowOpacity.remove(w); // We default to 1.0 + } // Show tabbed windows and windows on other desktops if highlighted - if( m_windowOpacity.contains( w ) && m_windowOpacity[w] != 0.0 ) - { - if( !w->visibleInClientGroup() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP ); - if( !w->isOnCurrentDesktop() ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - - effects->prePaintWindow( w, data, time ); + if (m_windowOpacity.contains(w) && m_windowOpacity[w] != 0.0) { + if (!w->visibleInClientGroup()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP); + if (!w->isOnCurrentDesktop()) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } -void HighlightWindowEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( m_windowOpacity.contains( w )) + effects->prePaintWindow(w, data, time); +} + +void HighlightWindowEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (m_windowOpacity.contains(w)) data.opacity *= m_windowOpacity[w]; - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); +} -void HighlightWindowEffect::windowAdded( EffectWindow* w ) - { - if( !m_highlightedWindows.isEmpty() ) - { // The effect is activated thus we need to add it to the opacity hash - if( w->isNormalWindow() || w->isDialog() ) // Only fade out windows - m_windowOpacity[w] = isInitiallyHidden( w ) ? 0.0 : 0.15; +void HighlightWindowEffect::windowAdded(EffectWindow* w) +{ + if (!m_highlightedWindows.isEmpty()) { + // The effect is activated thus we need to add it to the opacity hash + if (w->isNormalWindow() || w->isDialog()) // Only fade out windows + m_windowOpacity[w] = isInitiallyHidden(w) ? 0.0 : 0.15; else m_windowOpacity[w] = 1.0; - } - propertyNotify( w, m_atom ); // Check initial value } + propertyNotify(w, m_atom); // Check initial value +} -void HighlightWindowEffect::windowClosed( EffectWindow* w ) - { - if( m_monitorWindow == w ) // The monitoring window was destroyed +void HighlightWindowEffect::windowClosed(EffectWindow* w) +{ + if (m_monitorWindow == w) // The monitoring window was destroyed finishHighlighting(); - } +} -void HighlightWindowEffect::windowDeleted( EffectWindow* w ) - { - m_windowOpacity.remove( w ); - } +void HighlightWindowEffect::windowDeleted(EffectWindow* w) +{ + m_windowOpacity.remove(w); +} -void HighlightWindowEffect::propertyNotify( EffectWindow* w, long a ) - { - if( a != m_atom ) +void HighlightWindowEffect::propertyNotify(EffectWindow* w, long a) +{ + if (a != m_atom) return; // Not our atom // if the window is null, the property was set on the root window - see events.cpp - QByteArray byteData = w ? w->readProperty( m_atom, m_atom, 32 ) : - effects->readRootProperty( m_atom, m_atom, 32 ); - if( byteData.length() < 1 ) - { // Property was removed, clearing highlight + QByteArray byteData = w ? w->readProperty(m_atom, m_atom, 32) : + effects->readRootProperty(m_atom, m_atom, 32); + if (byteData.length() < 1) { + // Property was removed, clearing highlight finishHighlighting(); return; - } - long* data = reinterpret_cast( byteData.data() ); + } + long* data = reinterpret_cast(byteData.data()); - if( !data[0] ) - { // Purposely clearing highlight by issuing a NULL target + if (!data[0]) { + // Purposely clearing highlight by issuing a NULL target finishHighlighting(); return; - } + } m_monitorWindow = w; bool found = false; - int length = byteData.length() / sizeof( data[0] ); - //foreach( EffectWindow* e, m_highlightedWindows ) + int length = byteData.length() / sizeof(data[0]); + //foreach ( EffectWindow* e, m_highlightedWindows ) // effects->setElevatedWindow( e, false ); m_highlightedWindows.clear(); - for( int i=0; ifindWindow( data[i] ); - if( !foundWin ) - { + for (int i = 0; i < length; i++) { + EffectWindow* foundWin = effects->findWindow(data[i]); + if (!foundWin) { kDebug(1212) << "Invalid window targetted for highlight. Requested:" << data[i]; continue; - } - if( !foundWin->isMinimized() ) - { - m_highlightedWindows.append( foundWin ); + } + if (!foundWin->isMinimized()) { + m_highlightedWindows.append(foundWin); // TODO: We cannot just simply elevate the window as this will elevate it over // Plasma tooltips and other such windows as well //effects->setElevatedWindow( foundWin, true ); - } - found = true; } - if( !found ) - { + found = true; + } + if (!found) { finishHighlighting(); return; - } + } prepareHighlighting(); - if( w ) + if (w) m_windowOpacity[w] = 1.0; // Because it's not in stackingOrder() yet /* TODO: Finish thumbnails of offscreen windows, not sure if it's worth it though - if( !m_highlightedWindow->isOnCurrentDesktop() ) + if ( !m_highlightedWindow->isOnCurrentDesktop() ) { // Window is offscreen, determine thumbnail position QRect screenArea = effects->clientArea( MaximizeArea ); // Workable area of the active screen QRect outerArea = outerArea.adjusted( outerArea.width() / 10, outerArea.height() / 10, @@ -193,12 +188,12 @@ void HighlightWindowEffect::propertyNotify( EffectWindow* w, long a ) double areaAspect = double( thumbArea.width() ) / double( thumbArea.height() ); double windowAspect = aspectRatio( m_highlightedWindow ); QRect thumbRect; // Position doesn't matter right now, but it will later - if( windowAspect > areaAspect ) + if ( windowAspect > areaAspect ) // Top/bottom will touch first thumbRect = QRect( 0, 0, widthForHeight( thumbArea.height() ), thumbArea.height() ); else // Left/right will touch first thumbRect = QRect( 0, 0, thumbArea.width(), heightForWidth( thumbArea.width() )); - if( thumbRect.width() >= m_highlightedWindow->width() ) + if ( thumbRect.width() >= m_highlightedWindow->width() ) // Area is larger than the window, just use the window's size thumbRect = m_highlightedWindow->geometry(); @@ -215,17 +210,17 @@ void HighlightWindowEffect::propertyNotify( EffectWindow* w, long a ) QLineF testLine( // Top outerArea.x(), outerArea.y(), outerArea.x() + outerArea.width(), outerArea.y() ); - if( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) + if ( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) { testLine = QLineF( // Right outerArea.x() + outerArea.width(), outerArea.y(), outerArea.x() + outerArea.width(), outerArea.y() + outerArea.height() ); - if( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) + if ( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) { testLine = QLineF( // Bottom outerArea.x() + outerArea.width(), outerArea.y() + outerArea.height(), outerArea.x(), outerArea.y() + outerArea.height() ); - if( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) + if ( desktopLine.intersect( testLine, &arrowTip ) != QLineF::BoundedIntersection ) { testLine = QLineF( // Left outerArea.x(), outerArea.y() + outerArea.height(), @@ -236,22 +231,22 @@ void HighlightWindowEffect::propertyNotify( EffectWindow* w, long a ) } m_arrowTip = arrowTip.toPoint(); } */ - } +} void HighlightWindowEffect::prepareHighlighting() - { +{ // Create window data for every window. Just calling [w] creates it. m_finishing = false; - foreach( EffectWindow *w, effects->stackingOrder() ) - if( !m_windowOpacity.contains( w )) // Just in case we are still finishing from last time - m_windowOpacity[w] = isInitiallyHidden( w ) ? 0.0 : 1.0; - } + foreach (EffectWindow * w, effects->stackingOrder()) + if (!m_windowOpacity.contains(w)) // Just in case we are still finishing from last time + m_windowOpacity[w] = isInitiallyHidden(w) ? 0.0 : 1.0; +} void HighlightWindowEffect::finishHighlighting() - { +{ m_finishing = true; m_monitorWindow = NULL; m_highlightedWindows.clear(); - } +} } // namespace diff --git a/effects/highlightwindow/highlightwindow.h b/effects/highlightwindow/highlightwindow.h index faf738831..a96623c2c 100644 --- a/effects/highlightwindow/highlightwindow.h +++ b/effects/highlightwindow/highlightwindow.h @@ -28,47 +28,47 @@ namespace KWin class HighlightWindowEffect : public Effect - { - public: - HighlightWindowEffect(); - virtual ~HighlightWindowEffect(); +{ +public: + HighlightWindowEffect(); + virtual ~HighlightWindowEffect(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); - virtual void windowAdded( EffectWindow* w ); - virtual void windowClosed( EffectWindow* w ); - virtual void windowDeleted( EffectWindow* w ); + virtual void windowAdded(EffectWindow* w); + virtual void windowClosed(EffectWindow* w); + virtual void windowDeleted(EffectWindow* w); - virtual void propertyNotify( EffectWindow* w, long atom ); + virtual void propertyNotify(EffectWindow* w, long atom); - private: - void prepareHighlighting(); - void finishHighlighting(); +private: + void prepareHighlighting(); + void finishHighlighting(); - bool m_finishing; + bool m_finishing; - double m_fadeDuration; - QHash m_windowOpacity; + double m_fadeDuration; + QHash m_windowOpacity; - long m_atom; - QList m_highlightedWindows; - EffectWindow* m_monitorWindow; + long m_atom; + QList m_highlightedWindows; + EffectWindow* m_monitorWindow; - // Offscreen position cache - /*QRect m_thumbArea; // Thumbnail area - QPoint m_arrowTip; // Position of the arrow's tip - QPoint m_arrowA; // Arrow vertex position at the base (First) - QPoint m_arrowB; // Arrow vertex position at the base (Second) + // Offscreen position cache + /*QRect m_thumbArea; // Thumbnail area + QPoint m_arrowTip; // Position of the arrow's tip + QPoint m_arrowA; // Arrow vertex position at the base (First) + QPoint m_arrowB; // Arrow vertex position at the base (Second) - // Helper functions - inline double aspectRatio( EffectWindow *w ) - { return w->width() / double( w->height() ); } - inline int widthForHeight( EffectWindow *w, int height ) - { return int(( height / double( w->height() )) * w->width() ); } - inline int heightForWidth( EffectWindow *w, int width ) - { return int(( width / double( w->width() )) * w->height() ); }*/ - }; + // Helper functions + inline double aspectRatio( EffectWindow *w ) + { return w->width() / double( w->height() ); } + inline int widthForHeight( EffectWindow *w, int height ) + { return int(( height / double( w->height() )) * w->width() ); } + inline int heightForWidth( EffectWindow *w, int width ) + { return int(( width / double( w->width() )) * w->height() ); }*/ +}; } // namespace diff --git a/effects/invert/invert.cpp b/effects/invert/invert.cpp index ed7beda65..342187b4e 100644 --- a/effects/invert/invert.cpp +++ b/effects/invert/invert.cpp @@ -34,38 +34,38 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( invert, InvertEffect ) -KWIN_EFFECT_SUPPORTED( invert, InvertEffect::supported() ) +KWIN_EFFECT(invert, InvertEffect) +KWIN_EFFECT_SUPPORTED(invert, InvertEffect::supported()) InvertEffect::InvertEffect() - : m_inited( false ), - m_valid( true ), - m_shader( NULL ), - m_allWindows( false ) - { - KActionCollection* actionCollection = new KActionCollection( this ); + : m_inited(false), + m_valid(true), + m_shader(NULL), + m_allWindows(false) +{ + KActionCollection* actionCollection = new KActionCollection(this); - KAction* a = (KAction*)actionCollection->addAction( "Invert" ); - a->setText( i18n( "Toggle Invert Effect" )); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::META + Qt::Key_I )); - connect(a, SIGNAL( triggered(bool) ), this, SLOT( toggle() )); + KAction* a = (KAction*)actionCollection->addAction("Invert"); + a->setText(i18n("Toggle Invert Effect")); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_I)); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggle())); - KAction* b = (KAction*)actionCollection->addAction( "InvertWindow" ); - b->setText( i18n( "Toggle Invert Effect on Window" )); - b->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::META + Qt::Key_U )); - connect(b, SIGNAL( triggered(bool) ), this, SLOT( toggleWindow() )); - } + KAction* b = (KAction*)actionCollection->addAction("InvertWindow"); + b->setText(i18n("Toggle Invert Effect on Window")); + b->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_U)); + connect(b, SIGNAL(triggered(bool)), this, SLOT(toggleWindow())); +} InvertEffect::~InvertEffect() - { +{ delete m_shader; - } +} bool InvertEffect::supported() { return GLRenderTarget::supported() && - GLShader::fragmentShaderSupported() && - (effects->compositingType() == OpenGLCompositing); + GLShader::fragmentShaderSupported() && + (effects->compositingType() == OpenGLCompositing); } bool InvertEffect::loadData() @@ -78,14 +78,13 @@ bool InvertEffect::loadData() const QString fragmentshader = KGlobal::dirs()->findResource("data", "kwin/invert.frag"); m_shader = ShaderManager::instance()->loadFragmentShader(ShaderManager::GenericShader, fragmentshader); - if( !m_shader->isValid() ) - { + if (!m_shader->isValid()) { kError(1212) << "The shader failed to load!" << endl; return false; - } + } return true; - } +} void InvertEffect::prePaintScreen(ScreenPrePaintData &data, int time) { @@ -97,19 +96,19 @@ void InvertEffect::prePaintScreen(ScreenPrePaintData &data, int time) void InvertEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { - if (m_valid && ( m_allWindows != m_windows.contains( w ))) { + if (m_valid && (m_allWindows != m_windows.contains(w))) { data.mask |= PAINT_WINDOW_TRANSFORMED; } effects->prePaintWindow(w, data, time); } -void InvertEffect::drawWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void InvertEffect::drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ // Load if we haven't already - if( m_valid && !m_inited ) + if (m_valid && !m_inited) m_valid = loadData(); - bool useShader = m_valid && ( m_allWindows != m_windows.contains( w )); + bool useShader = m_valid && (m_allWindows != m_windows.contains(w)); if (useShader) { ShaderManager *shaderManager = ShaderManager::instance(); GLShader *genericShader = shaderManager->pushShader(ShaderManager::GenericShader); @@ -121,49 +120,46 @@ void InvertEffect::drawWindow( EffectWindow* w, int mask, QRegion region, Window data.shader = m_shader; } - effects->drawWindow( w, mask, region, data ); + effects->drawWindow(w, mask, region, data); if (useShader) { ShaderManager::instance()->popShader(); } - } +} -void InvertEffect::paintEffectFrame( KWin::EffectFrame* frame, QRegion region, double opacity, double frameOpacity ) - { - if( m_valid && m_allWindows ) - { - frame->setShader( m_shader ); +void InvertEffect::paintEffectFrame(KWin::EffectFrame* frame, QRegion region, double opacity, double frameOpacity) +{ + if (m_valid && m_allWindows) { + frame->setShader(m_shader); ShaderManager::instance()->pushShader(m_shader); m_shader->setUniform("screenTransformation", QMatrix4x4()); m_shader->setUniform("windowTransformation", QMatrix4x4()); - effects->paintEffectFrame( frame, region, opacity, frameOpacity ); + effects->paintEffectFrame(frame, region, opacity, frameOpacity); ShaderManager::instance()->popShader(); - } - else - { - effects->paintEffectFrame( frame, region, opacity, frameOpacity ); - } + } else { + effects->paintEffectFrame(frame, region, opacity, frameOpacity); } +} -void InvertEffect::windowClosed( EffectWindow* w ) - { - m_windows.removeOne( w ); - } +void InvertEffect::windowClosed(EffectWindow* w) +{ + m_windows.removeOne(w); +} void InvertEffect::toggle() - { +{ m_allWindows = !m_allWindows; effects->addRepaintFull(); - } +} void InvertEffect::toggleWindow() - { - if( !m_windows.contains( effects->activeWindow() )) - m_windows.append( effects->activeWindow() ); +{ + if (!m_windows.contains(effects->activeWindow())) + m_windows.append(effects->activeWindow()); else - m_windows.removeOne( effects->activeWindow() ); + m_windows.removeOne(effects->activeWindow()); effects->activeWindow()->addRepaintFull(); - } +} } // namespace diff --git a/effects/invert/invert.h b/effects/invert/invert.h index bf3c52d87..b0da55171 100644 --- a/effects/invert/invert.h +++ b/effects/invert/invert.h @@ -34,34 +34,34 @@ class GLShader; **/ class InvertEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - InvertEffect(); - ~InvertEffect(); +public: + InvertEffect(); + ~InvertEffect(); - virtual void drawWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void prePaintScreen(ScreenPrePaintData &data, int time); - virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); - virtual void paintEffectFrame( KWin::EffectFrame* frame, QRegion region, double opacity, double frameOpacity ); - virtual void windowClosed( EffectWindow* w ); + virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintEffectFrame(KWin::EffectFrame* frame, QRegion region, double opacity, double frameOpacity); + virtual void windowClosed(EffectWindow* w); - static bool supported(); + static bool supported(); - public slots: - void toggle(); - void toggleWindow(); +public slots: + void toggle(); + void toggleWindow(); - protected: - bool loadData(); +protected: + bool loadData(); - private: - bool m_inited; - bool m_valid; - GLShader* m_shader; - bool m_allWindows; - QList m_windows; - }; +private: + bool m_inited; + bool m_valid; + GLShader* m_shader; + bool m_allWindows; + QList m_windows; +}; } // namespace diff --git a/effects/invert/invert_config.cpp b/effects/invert/invert_config.cpp index 8ffa23daa..310d3eaac 100644 --- a/effects/invert/invert_config.cpp +++ b/effects/invert/invert_config.cpp @@ -36,59 +36,59 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY InvertEffectConfig::InvertEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ QVBoxLayout* layout = new QVBoxLayout(this); // Shortcut config. The shortcut belongs to the component "kwin"! - KActionCollection *actionCollection = new KActionCollection( this, KComponentData("kwin") ); + KActionCollection *actionCollection = new KActionCollection(this, KComponentData("kwin")); - KAction* a = static_cast(actionCollection->addAction( "Invert" )); - a->setText( i18n("Toggle Invert Effect" )); + KAction* a = static_cast(actionCollection->addAction("Invert")); + a->setText(i18n("Toggle Invert Effect")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_I)); - KAction* b = static_cast(actionCollection->addAction( "InvertWindow" )); - b->setText( i18n("Toggle Invert Effect on Window" )); + KAction* b = static_cast(actionCollection->addAction("InvertWindow")); + b->setText(i18n("Toggle Invert Effect on Window")); b->setProperty("isConfigurationAction", true); b->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_U)); mShortcutEditor = new KShortcutsEditor(actionCollection, this, - KShortcutsEditor::GlobalAction, KShortcutsEditor::LetterShortcutsDisallowed); + KShortcutsEditor::GlobalAction, KShortcutsEditor::LetterShortcutsDisallowed); connect(mShortcutEditor, SIGNAL(keyChange()), this, SLOT(changed())); layout->addWidget(mShortcutEditor); load(); - } +} InvertEffectConfig::~InvertEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts mShortcutEditor->undoChanges(); - } +} void InvertEffectConfig::load() - { +{ KCModule::load(); emit changed(false); - } +} void InvertEffectConfig::save() - { +{ KCModule::save(); mShortcutEditor->save(); // undo() will restore to this state from now on emit changed(false); - EffectsHandler::sendReloadMessage( "invert" ); - } + EffectsHandler::sendReloadMessage("invert"); +} void InvertEffectConfig::defaults() - { +{ mShortcutEditor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/invert/invert_config.h b/effects/invert/invert_config.h index 01797b183..0d14c479c 100644 --- a/effects/invert/invert_config.h +++ b/effects/invert/invert_config.h @@ -29,20 +29,20 @@ namespace KWin { class InvertEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit InvertEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~InvertEffectConfig(); +public: + explicit InvertEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~InvertEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - KShortcutsEditor* mShortcutEditor; - }; +private: + KShortcutsEditor* mShortcutEditor; +}; } // namespace diff --git a/effects/login/login.cpp b/effects/login/login.cpp index 3bde11e4a..94f07d9aa 100644 --- a/effects/login/login.cpp +++ b/effects/login/login.cpp @@ -25,79 +25,74 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( login, LoginEffect ) +KWIN_EFFECT(login, LoginEffect) LoginEffect::LoginEffect() - : progress( 1.0 ) - , login_window( NULL ) - { - } + : progress(1.0) + , login_window(NULL) +{ +} -void LoginEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( login_window != NULL ) - { - if( progress != 1.0 ) - { - progress = qBound( 0.0, progress + time / animationTime( 2000 ), 1.0 ); - if( progress == 1.0 ) - { +void LoginEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (login_window != NULL) { + if (progress != 1.0) { + progress = qBound(0.0, progress + time / animationTime(2000), 1.0); + if (progress == 1.0) { login_window->unrefWindow(); login_window = NULL; - effects->prePaintScreen( data, time ); + effects->prePaintScreen(data, time); return; - } } } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void LoginEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( progress != 1.0 && w == login_window ) - { - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); +void LoginEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (progress != 1.0 && w == login_window) { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); data.setTranslucent(); - } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void LoginEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( w == login_window && progress != 1.0 ) - data.opacity *= ( 1.0 - progress ); - effects->paintWindow( w, mask, region, data ); - } +void LoginEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (w == login_window && progress != 1.0) + data.opacity *= (1.0 - progress); + effects->paintWindow(w, mask, region, data); +} void LoginEffect::postPaintScreen() - { - if( login_window != NULL && progress != 1.0 ) +{ + if (login_window != NULL && progress != 1.0) effects->addRepaintFull(); effects->postPaintScreen(); - } +} -void LoginEffect::windowClosed( EffectWindow* w ) - { - if( isLoginSplash( w )) - { - if( login_window ) +void LoginEffect::windowClosed(EffectWindow* w) +{ + if (isLoginSplash(w)) { + if (login_window) return; // We already have a window... should never happen. login_window = w; login_window->refWindow(); progress = 0.0; effects->addRepaintFull(); - } } +} -bool LoginEffect::isLoginSplash( EffectWindow* w ) - { // TODO there should be probably a better way (window type?) +bool LoginEffect::isLoginSplash(EffectWindow* w) +{ + // TODO there should be probably a better way (window type?) // see also fade effect and composite.cpp - if( w->windowClass() == "ksplashx ksplashx" - || w->windowClass() == "ksplashsimple ksplashsimple" ) - { + if (w->windowClass() == "ksplashx ksplashx" + || w->windowClass() == "ksplashsimple ksplashsimple") { return true; - } - return false; } + return false; +} } // namespace diff --git a/effects/login/login.h b/effects/login/login.h index 42b59c148..c61f3d1a1 100644 --- a/effects/login/login.h +++ b/effects/login/login.h @@ -29,19 +29,19 @@ namespace KWin class LoginEffect : public Effect - { - public: - LoginEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowClosed( EffectWindow* w ); - private: - bool isLoginSplash( EffectWindow* w ); - double progress; // 0-1 - EffectWindow* login_window; - }; +{ +public: + LoginEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowClosed(EffectWindow* w); +private: + bool isLoginSplash(EffectWindow* w); + double progress; // 0-1 + EffectWindow* login_window; +}; } // namespace diff --git a/effects/logout/logout.cpp b/effects/logout/logout.cpp index 5c2350a4a..8eaea94f0 100644 --- a/effects/logout/logout.cpp +++ b/effects/logout/logout.cpp @@ -31,235 +31,220 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( logout, LogoutEffect ) +KWIN_EFFECT(logout, LogoutEffect) LogoutEffect::LogoutEffect() - : progress( 0.0 ) - , displayEffect( false ) - , logoutWindow( NULL ) - , logoutWindowClosed( true ) - , logoutWindowPassed( false ) - , canDoPersistent( false ) + : progress(0.0) + , displayEffect(false) + , logoutWindow(NULL) + , logoutWindowClosed(true) + , logoutWindowPassed(false) + , canDoPersistent(false) , ignoredWindows() - { +{ // Persistent effect - logoutAtom = XInternAtom( display(), "_KDE_LOGGING_OUT", False ); - effects->registerPropertyType( logoutAtom, true ); + logoutAtom = XInternAtom(display(), "_KDE_LOGGING_OUT", False); + effects->registerPropertyType(logoutAtom, true); // Block KSMServer's effect char net_wm_cm_name[ 100 ]; - sprintf( net_wm_cm_name, "_NET_WM_CM_S%d", DefaultScreen( display())); - Atom net_wm_cm = XInternAtom( display(), net_wm_cm_name, False ); - Window sel = XGetSelectionOwner( display(), net_wm_cm ); - Atom hack = XInternAtom( display(), "_KWIN_LOGOUT_EFFECT", False ); - XChangeProperty( display(), sel, hack, hack, 8, PropModeReplace, (unsigned char*)&hack, 1 ); + sprintf(net_wm_cm_name, "_NET_WM_CM_S%d", DefaultScreen(display())); + Atom net_wm_cm = XInternAtom(display(), net_wm_cm_name, False); + Window sel = XGetSelectionOwner(display(), net_wm_cm); + Atom hack = XInternAtom(display(), "_KWIN_LOGOUT_EFFECT", False); + XChangeProperty(display(), sel, hack, hack, 8, PropModeReplace, (unsigned char*)&hack, 1); // the atom is not removed when effect is destroyed, this is temporary anyway #ifdef KWIN_HAVE_OPENGL_COMPOSITING blurTexture = NULL; blurTarget = NULL; #endif - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} LogoutEffect::~LogoutEffect() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING delete blurTexture; delete blurTarget; #endif - } +} -void LogoutEffect::reconfigure( ReconfigureFlags ) - { +void LogoutEffect::reconfigure(ReconfigureFlags) +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING frameDelay = 0; - KConfigGroup conf = effects->effectConfig( "Logout" ); - useBlur = conf.readEntry( "UseBlur", true ); + KConfigGroup conf = effects->effectConfig("Logout"); + useBlur = conf.readEntry("UseBlur", true); delete blurTexture; blurTexture = NULL; delete blurTarget; blurTarget = NULL; blurSupported = false; #endif - } +} -void LogoutEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void LogoutEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( !displayEffect && progress == 0.0 ) - { - if( blurTexture ) - { + if (!displayEffect && progress == 0.0) { + if (blurTexture) { delete blurTexture; blurTexture = NULL; delete blurTarget; blurTarget = NULL; blurSupported = false; - } } - else if( !blurTexture ) - { + } else if (!blurTexture) { blurSupported = false; delete blurTarget; // catch as we just tested the texture ;-P - if( effects->compositingType() == OpenGLCompositing && GLTexture::NPOTTextureSupported() && useBlur ) - { // TODO: It seems that it is not possible to create a GLRenderTarget that has + if (effects->compositingType() == OpenGLCompositing && GLTexture::NPOTTextureSupported() && useBlur) { + // TODO: It seems that it is not possible to create a GLRenderTarget that has // a different size than the display right now. Most likely a KWin core bug. // Create texture and render target - blurTexture = new GLTexture( displayWidth(), displayHeight() ); - blurTexture->setFilter( GL_LINEAR_MIPMAP_LINEAR ); - blurTexture->setWrapMode( GL_CLAMP_TO_EDGE ); + blurTexture = new GLTexture(displayWidth(), displayHeight()); + blurTexture->setFilter(GL_LINEAR_MIPMAP_LINEAR); + blurTexture->setWrapMode(GL_CLAMP_TO_EDGE); - blurTarget = new GLRenderTarget( blurTexture ); - if( blurTarget->valid() ) + blurTarget = new GLRenderTarget(blurTexture); + if (blurTarget->valid()) blurSupported = true; // As creating the render target takes time it can cause the first two frames of the // blur animation to be jerky. For this reason we only start the animation after the // third frame. frameDelay = 2; - } } + } - if( frameDelay ) + if (frameDelay) --frameDelay; else #endif - { - if( displayEffect ) - progress = qMin( 1.0, progress + time / animationTime( 2000.0 )); - else if( progress > 0.0 ) - progress = qMax( 0.0, progress - time / animationTime( 500.0 )); - } - -#ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( blurSupported && progress > 0.0 ) - { - data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - } -#endif - - effects->prePaintScreen( data, time ); + { + if (displayEffect) + progress = qMin(1.0, progress + time / animationTime(2000.0)); + else if (progress > 0.0) + progress = qMax(0.0, progress - time / animationTime(500.0)); } -void LogoutEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( progress > 0.0 ) - { #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == KWin::OpenGLCompositing ) - { // In OpenGL mode we add vignetting and, if supported, a slight blur - if( blurSupported ) - { // When using blur we render everything to an FBO and as such don't do the vignetting - // until after we render the FBO to the screen. - if( w == logoutWindow ) - { // Window is rendered after the FBO + if (blurSupported && progress > 0.0) { + data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; + } +#endif + + effects->prePaintScreen(data, time); +} + +void LogoutEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (progress > 0.0) { +#ifdef KWIN_HAVE_OPENGL_COMPOSITING + if (effects->compositingType() == KWin::OpenGLCompositing) { + // In OpenGL mode we add vignetting and, if supported, a slight blur + if (blurSupported) { + // When using blur we render everything to an FBO and as such don't do the vignetting + // until after we render the FBO to the screen. + if (w == logoutWindow) { + // Window is rendered after the FBO windowOpacity = data.opacity; data.opacity = 0.0; // Cheat, we need the opacity for later but don't want to blur it - } - else - { - if( logoutWindowPassed || ignoredWindows.contains( w )) - { // Window is rendered after the FBO - windows.append( w ); + } else { + if (logoutWindowPassed || ignoredWindows.contains(w)) { + // Window is rendered after the FBO + windows.append(w); windowsOpacities[ w ] = data.opacity; data.opacity = 0.0; - } - else // Window is added to the FBO - data.saturation *= ( 1.0 - progress * 0.2 ); - } + } else // Window is added to the FBO + data.saturation *= (1.0 - progress * 0.2); } - else - { // If we are not blurring then we are not rendering to an FBO - if( w == logoutWindow ) + } else { + // If we are not blurring then we are not rendering to an FBO + if (w == logoutWindow) // This is the logout window don't alter it but render our vignetting now renderVignetting(); - else if( !logoutWindowPassed && !ignoredWindows.contains( w )) + else if (!logoutWindowPassed && !ignoredWindows.contains(w)) // Window is in the background, desaturate - data.saturation *= ( 1.0 - progress * 0.2 ); + data.saturation *= (1.0 - progress * 0.2); // All other windows are unaltered - } } + } #endif - if( effects->compositingType() == KWin::XRenderCompositing ) - { // Since we can't do vignetting in XRender just do a stronger desaturation and darken - if( w != logoutWindow && !logoutWindowPassed && !ignoredWindows.contains( w )) - { - data.saturation *= ( 1.0 - progress * 0.8 ); - data.brightness *= ( 1.0 - progress * 0.3 ); - } + if (effects->compositingType() == KWin::XRenderCompositing) { + // Since we can't do vignetting in XRender just do a stronger desaturation and darken + if (w != logoutWindow && !logoutWindowPassed && !ignoredWindows.contains(w)) { + data.saturation *= (1.0 - progress * 0.8); + data.brightness *= (1.0 - progress * 0.3); } - if( w == logoutWindow || - ignoredWindows.contains( w )) // HACK: All windows past the first ignored one should not be - // blurred as it affects the stacking order. + } + if (w == logoutWindow || + ignoredWindows.contains(w)) // HACK: All windows past the first ignored one should not be + // blurred as it affects the stacking order. // All following windows are on top of the logout window and should not be altered either logoutWindowPassed = true; - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -void LogoutEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { +void LogoutEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( blurSupported && progress > 0.0 ) - effects->pushRenderTarget( blurTarget ); + if (blurSupported && progress > 0.0) + effects->pushRenderTarget(blurTarget); #endif - effects->paintScreen( mask, region, data ); + effects->paintScreen(mask, region, data); #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == KWin::OpenGLCompositing && progress > 0.0 ) - { - if( !blurSupported ) - { - if( !logoutWindowPassed ) + if (effects->compositingType() == KWin::OpenGLCompositing && progress > 0.0) { + if (!blurSupported) { + if (!logoutWindowPassed) // The logout window has been deleted but we still want to fade out the vignetting, thus // render it on the top of everything if still animating. We don't check if logoutWindow // is set as it may still be even if it wasn't rendered. renderVignetting(); - } - else - { + } else { GLRenderTarget* target = effects->popRenderTarget(); - assert( target == blurTarget ); - Q_UNUSED( target ); + assert(target == blurTarget); + Q_UNUSED(target); //-------------------------- // Render the screen effect - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT); // Unmodified base image blurTexture->bind(); - glBegin( GL_QUADS ); - glTexCoord2f( 0.0, 0.0 ); - glVertex2f( 0.0, displayHeight() ); - glTexCoord2f( 1.0, 0.0 ); - glVertex2f( displayWidth(), displayHeight() ); - glTexCoord2f( 1.0, 1.0 ); - glVertex2f( displayWidth(), 0.0 ); - glTexCoord2f( 0.0, 1.0 ); - glVertex2f( 0.0, 0.0 ); + glBegin(GL_QUADS); + glTexCoord2f(0.0, 0.0); + glVertex2f(0.0, displayHeight()); + glTexCoord2f(1.0, 0.0); + glVertex2f(displayWidth(), displayHeight()); + glTexCoord2f(1.0, 1.0); + glVertex2f(displayWidth(), 0.0); + glTexCoord2f(0.0, 1.0); + glVertex2f(0.0, 0.0); glEnd(); // Blurred image GLfloat bias[1]; - glGetTexEnvfv( GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, bias ); - glTexEnvf( GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, 1.75 ); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - glColor4f( 1.0f, 1.0f, 1.0f, progress * 0.4 ); - glBegin( GL_QUADS ); - glTexCoord2f( 0.0, 0.0 ); - glVertex2f( 0.0, displayHeight() ); - glTexCoord2f( 1.0, 0.0 ); - glVertex2f( displayWidth(), displayHeight() ); - glTexCoord2f( 1.0, 1.0 ); - glVertex2f( displayWidth(), 0.0 ); - glTexCoord2f( 0.0, 1.0 ); - glVertex2f( 0.0, 0.0 ); + glGetTexEnvfv(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, bias); + glTexEnvf(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, 1.75); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(1.0f, 1.0f, 1.0f, progress * 0.4); + glBegin(GL_QUADS); + glTexCoord2f(0.0, 0.0); + glVertex2f(0.0, displayHeight()); + glTexCoord2f(1.0, 0.0); + glVertex2f(displayWidth(), displayHeight()); + glTexCoord2f(1.0, 1.0); + glVertex2f(displayWidth(), 0.0); + glTexCoord2f(0.0, 1.0); + glVertex2f(0.0, 0.0); glEnd(); - glTexEnvf( GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, bias[0] ); + glTexEnvf(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, bias[0]); blurTexture->unbind(); // Vignetting (Radial gradient with transparent middle and black edges) @@ -270,134 +255,128 @@ void LogoutEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data //-------------------------- // Render the logout window - if( logoutWindow ) - { + if (logoutWindow) { int winMask = logoutWindow->hasAlpha() ? PAINT_WINDOW_TRANSLUCENT : PAINT_WINDOW_OPAQUE; - WindowPaintData winData( logoutWindow ); + WindowPaintData winData(logoutWindow); winData.opacity = windowOpacity; - effects->drawWindow( logoutWindow, winMask, region, winData ); - } + effects->drawWindow(logoutWindow, winMask, region, winData); + } // Render all windows on top of logout window - foreach( EffectWindow* w, windows ) - { + foreach (EffectWindow * w, windows) { int winMask = w->hasAlpha() ? PAINT_WINDOW_TRANSLUCENT : PAINT_WINDOW_OPAQUE; - WindowPaintData winData( w ); + WindowPaintData winData(w); winData.opacity = windowsOpacities[ w ]; - effects->drawWindow( w, winMask, region, winData ); - } + effects->drawWindow(w, winMask, region, winData); + } windows.clear(); windowsOpacities.clear(); - } } -#endif } +#endif +} void LogoutEffect::postPaintScreen() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if(( progress != 0.0 && progress != 1.0 ) || frameDelay ) + if ((progress != 0.0 && progress != 1.0) || frameDelay) effects->addRepaintFull(); #else - if( progress != 0.0 && progress != 1.0 ) + if (progress != 0.0 && progress != 1.0) effects->addRepaintFull(); #endif - if( progress > 0.0 ) + if (progress > 0.0) logoutWindowPassed = false; effects->postPaintScreen(); - } +} -void LogoutEffect::windowAdded( EffectWindow* w ) - { - if( isLogoutDialog( w )) - { +void LogoutEffect::windowAdded(EffectWindow* w) +{ + if (isLogoutDialog(w)) { logoutWindow = w; logoutWindowClosed = false; // So we don't blur the window on close progress = 0.0; displayEffect = true; ignoredWindows.clear(); effects->addRepaintFull(); - } - else if( canDoPersistent ) + } else if (canDoPersistent) // TODO: Add parent - ignoredWindows.append( w ); - } + ignoredWindows.append(w); +} -void LogoutEffect::windowClosed( EffectWindow* w ) - { - if( w == logoutWindow ) - { +void LogoutEffect::windowClosed(EffectWindow* w) +{ + if (w == logoutWindow) { logoutWindowClosed = true; - if( !canDoPersistent ) + if (!canDoPersistent) displayEffect = false; // Fade back to normal effects->addRepaintFull(); - } } +} -void LogoutEffect::windowDeleted( EffectWindow* w ) - { - ignoredWindows.removeAll( w ); - if( w == logoutWindow ) +void LogoutEffect::windowDeleted(EffectWindow* w) +{ + ignoredWindows.removeAll(w); + if (w == logoutWindow) logoutWindow = NULL; - } +} -bool LogoutEffect::isLogoutDialog( EffectWindow* w ) - { // TODO there should be probably a better way (window type?) - if( w->windowClass() == "ksmserver ksmserver" - && ( w->windowRole() == "logoutdialog" || w->windowRole() == "logouteffect" )) - { +bool LogoutEffect::isLogoutDialog(EffectWindow* w) +{ + // TODO there should be probably a better way (window type?) + if (w->windowClass() == "ksmserver ksmserver" + && (w->windowRole() == "logoutdialog" || w->windowRole() == "logouteffect")) { return true; - } - return false; } + return false; +} #ifdef KWIN_HAVE_OPENGL_COMPOSITING void LogoutEffect::renderVignetting() - { - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT ); - glEnable( GL_BLEND ); // If not already (Such as when rendered straight to the screen) - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - for( int screen = 0; screen < effects->numScreens(); screen++ ) - { - QRect screenGeom = effects->clientArea( ScreenArea, screen, 0 ); - glScissor( screenGeom.x(), displayHeight() - screenGeom.y() - screenGeom.height(), - screenGeom.width(), screenGeom.height() ); // GL coords are flipped - glEnable( GL_SCISSOR_TEST ); // Geom must be set before enable +{ + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT); + glEnable(GL_BLEND); // If not already (Such as when rendered straight to the screen) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + for (int screen = 0; screen < effects->numScreens(); screen++) { + QRect screenGeom = effects->clientArea(ScreenArea, screen, 0); + glScissor(screenGeom.x(), displayHeight() - screenGeom.y() - screenGeom.height(), + screenGeom.width(), screenGeom.height()); // GL coords are flipped + glEnable(GL_SCISSOR_TEST); // Geom must be set before enable const float cenX = screenGeom.x() + screenGeom.width() / 2; const float cenY = screenGeom.y() + screenGeom.height() / 2; const float a = M_PI / 16.0f; // Angle of increment - const float r = float(( screenGeom.width() > screenGeom.height() ) - ? screenGeom.width() : screenGeom.height() ) * 0.8f; // Radius - glBegin( GL_TRIANGLE_FAN ); - glColor4f( 0.0f, 0.0f, 0.0f, 0.0f ); - glVertex3f( cenX, cenY, 0.0f ); - glColor4f( 0.0f, 0.0f, 0.0f, progress * 0.9f ); - for( float i = 0.0f; i <= M_PI * 2.01f; i += a ) - glVertex3f( cenX + r * cos( i ), cenY + r * sin( i ), 0.0f ); + const float r = float((screenGeom.width() > screenGeom.height()) + ? screenGeom.width() : screenGeom.height()) * 0.8f; // Radius + glBegin(GL_TRIANGLE_FAN); + glColor4f(0.0f, 0.0f, 0.0f, 0.0f); + glVertex3f(cenX, cenY, 0.0f); + glColor4f(0.0f, 0.0f, 0.0f, progress * 0.9f); + for (float i = 0.0f; i <= M_PI * 2.01f; i += a) + glVertex3f(cenX + r * cos(i), cenY + r * sin(i), 0.0f); glEnd(); - glDisable( GL_SCISSOR_TEST ); - } - glPopAttrib(); + glDisable(GL_SCISSOR_TEST); } + glPopAttrib(); +} #endif -void LogoutEffect::propertyNotify( EffectWindow* w, long a ) - { - if( w || a != logoutAtom ) +void LogoutEffect::propertyNotify(EffectWindow* w, long a) +{ + if (w || a != logoutAtom) return; // Not our atom - QByteArray byteData = effects->readRootProperty( logoutAtom, logoutAtom, 8 ); - if( byteData.length() < 1 ) - { // Property was deleted + QByteArray byteData = effects->readRootProperty(logoutAtom, logoutAtom, 8); + if (byteData.length() < 1) { + // Property was deleted displayEffect = false; return; - } + } // We are using a compatible KSMServer therefore only terminate the effect when the // atom is deleted, not when the dialog is closed. canDoPersistent = true; - } +} } // namespace diff --git a/effects/logout/logout.h b/effects/logout/logout.h index 0a640c0d0..1567edb88 100644 --- a/effects/logout/logout.h +++ b/effects/logout/logout.h @@ -34,43 +34,43 @@ class GLTexture; class LogoutEffect : public Effect - { - public: - LogoutEffect(); - ~LogoutEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowAdded( EffectWindow* w ); - virtual void windowClosed( EffectWindow* w ); - virtual void windowDeleted( EffectWindow* w ); - virtual void propertyNotify( EffectWindow* w, long a ); - private: - bool isLogoutDialog( EffectWindow* w ); - double progress; // 0-1 - bool displayEffect; - EffectWindow* logoutWindow; - bool logoutWindowClosed; - bool logoutWindowPassed; +{ +public: + LogoutEffect(); + ~LogoutEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowAdded(EffectWindow* w); + virtual void windowClosed(EffectWindow* w); + virtual void windowDeleted(EffectWindow* w); + virtual void propertyNotify(EffectWindow* w, long a); +private: + bool isLogoutDialog(EffectWindow* w); + double progress; // 0-1 + bool displayEffect; + EffectWindow* logoutWindow; + bool logoutWindowClosed; + bool logoutWindowPassed; - // Persistent effect - long logoutAtom; - bool canDoPersistent; - EffectWindowList ignoredWindows; + // Persistent effect + long logoutAtom; + bool canDoPersistent; + EffectWindowList ignoredWindows; #ifdef KWIN_HAVE_OPENGL_COMPOSITING - void renderVignetting(); - int frameDelay; - bool blurSupported, useBlur; - GLTexture* blurTexture; - GLRenderTarget* blurTarget; - double windowOpacity; - EffectWindowList windows; - QHash< EffectWindow*, double > windowsOpacities; + void renderVignetting(); + int frameDelay; + bool blurSupported, useBlur; + GLTexture* blurTexture; + GLRenderTarget* blurTarget; + double windowOpacity; + EffectWindowList windows; + QHash< EffectWindow*, double > windowsOpacities; #endif - }; +}; } // namespace diff --git a/effects/lookingglass/lookingglass.cpp b/effects/lookingglass/lookingglass.cpp index 5d4c8a763..024e86585 100644 --- a/effects/lookingglass/lookingglass.cpp +++ b/effects/lookingglass/lookingglass.cpp @@ -37,60 +37,60 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( lookingglass, LookingGlassEffect ) -KWIN_EFFECT_SUPPORTED( lookingglass, LookingGlassEffect::supported() ) +KWIN_EFFECT(lookingglass, LookingGlassEffect) +KWIN_EFFECT_SUPPORTED(lookingglass, LookingGlassEffect::supported()) LookingGlassEffect::LookingGlassEffect() : QObject() - , zoom( 1.0f ) - , target_zoom( 1.0f ) - , polling( false ) - , m_texture( NULL ) - , m_fbo( NULL ) - , m_vbo( NULL ) - , m_shader( NULL ) - , m_enabled( false ) - , m_valid( false ) - { - actionCollection = new KActionCollection( this ); + , zoom(1.0f) + , target_zoom(1.0f) + , polling(false) + , m_texture(NULL) + , m_fbo(NULL) + , m_vbo(NULL) + , m_shader(NULL) + , m_enabled(false) + , m_valid(false) +{ + actionCollection = new KActionCollection(this); actionCollection->setConfigGlobal(true); actionCollection->setConfigGroup("LookingGlass"); KAction* a; - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomIn, this, SLOT( zoomIn()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomIn, this, SLOT(zoomIn()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Plus)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomOut, this, SLOT( zoomOut()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomOut, this, SLOT(zoomOut()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ActualSize, this, SLOT( toggle()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ActualSize, this, SLOT(toggle()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} LookingGlassEffect::~LookingGlassEffect() - { +{ delete m_texture; delete m_fbo; delete m_shader; delete m_vbo; - } +} bool LookingGlassEffect::supported() { return GLRenderTarget::supported() && - GLShader::fragmentShaderSupported() && - (effects->compositingType() == OpenGLCompositing); + GLShader::fragmentShaderSupported() && + (effects->compositingType() == OpenGLCompositing); } -void LookingGlassEffect::reconfigure( ReconfigureFlags ) - { +void LookingGlassEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("LookingGlass"); initialradius = conf.readEntry("Radius", 200); radius = initialradius; kDebug(1212) << QString("Radius from config: %1").arg(radius) << endl; actionCollection->readSettings(); m_valid = loadData(); - } +} bool LookingGlassEffect::loadData() { @@ -100,7 +100,7 @@ bool LookingGlassEffect::loadData() int texw = displayWidth(); int texh = displayHeight(); if (!GLTexture::NPOTTextureSupported()) { - kWarning( 1212 ) << "NPOT textures not supported, wasting some memory" ; + kWarning(1212) << "NPOT textures not supported, wasting some memory" ; texw = nearestPowerOfTwo(texw); texh = nearestPowerOfTwo(texh); } @@ -145,93 +145,83 @@ bool LookingGlassEffect::loadData() } void LookingGlassEffect::toggle() - { - if( target_zoom == 1.0f ) - { +{ + if (target_zoom == 1.0f) { target_zoom = 2.0f; - if( !polling ) - { + if (!polling) { polling = true; effects->startMousePolling(); - } - m_enabled = true; } - else - { + m_enabled = true; + } else { target_zoom = 1.0f; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } - m_enabled = false; } + m_enabled = false; } +} void LookingGlassEffect::zoomIn() - { +{ target_zoom = qMin(7.0, target_zoom + 0.5); m_enabled = true; - if( !polling ) - { + if (!polling) { polling = true; effects->startMousePolling(); - } - effects->addRepaint( cursorPos().x() - radius, cursorPos().y() - radius, 2*radius, 2*radius ); } + effects->addRepaint(cursorPos().x() - radius, cursorPos().y() - radius, 2 * radius, 2 * radius); +} void LookingGlassEffect::zoomOut() - { +{ target_zoom -= 0.5; - if( target_zoom < 1 ) - { + if (target_zoom < 1) { target_zoom = 1; m_enabled = false; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } } - effects->addRepaint( cursorPos().x() - radius, cursorPos().y() - radius, 2*radius, 2*radius ); } + effects->addRepaint(cursorPos().x() - radius, cursorPos().y() - radius, 2 * radius, 2 * radius); +} -void LookingGlassEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( zoom != target_zoom ) - { - double diff = time / animationTime( 500.0 ); - if( target_zoom > zoom ) - zoom = qMin( zoom * qMax( 1.0 + diff, 1.2 ), target_zoom ); +void LookingGlassEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (zoom != target_zoom) { + double diff = time / animationTime(500.0); + if (target_zoom > zoom) + zoom = qMin(zoom * qMax(1.0 + diff, 1.2), target_zoom); else - zoom = qMax( zoom * qMin( 1.0 - diff, 0.8 ), target_zoom ); + zoom = qMax(zoom * qMin(1.0 - diff, 0.8), target_zoom); kDebug(1212) << "zoom is now " << zoom; - radius = qBound((double)initialradius, initialradius * zoom, 3.5*initialradius); + radius = qBound((double)initialradius, initialradius * zoom, 3.5 * initialradius); - if( zoom <= 1.0f ) { + if (zoom <= 1.0f) { m_enabled = false; } - effects->addRepaint( cursorPos().x() - radius, cursorPos().y() - radius, 2*radius, 2*radius ); - } + effects->addRepaint(cursorPos().x() - radius, cursorPos().y() - radius, 2 * radius, 2 * radius); + } if (m_valid && m_enabled) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; // Start rendering to texture effects->pushRenderTarget(m_fbo); } - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void LookingGlassEffect::mouseChanged( const QPoint& pos, const QPoint& old, Qt::MouseButtons, - Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers ) - { - if( pos != old && m_enabled ) - { - effects->addRepaint( pos.x() - radius, pos.y() - radius, 2*radius, 2*radius ); - effects->addRepaint( old.x() - radius, old.y() - radius, 2*radius, 2*radius ); - } +void LookingGlassEffect::mouseChanged(const QPoint& pos, const QPoint& old, Qt::MouseButtons, + Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers) +{ + if (pos != old && m_enabled) { + effects->addRepaint(pos.x() - radius, pos.y() - radius, 2 * radius, 2 * radius); + effects->addRepaint(old.x() - radius, old.y() - radius, 2 * radius, 2 * radius); } +} void LookingGlassEffect::postPaintScreen() { @@ -240,8 +230,8 @@ void LookingGlassEffect::postPaintScreen() if (m_valid && m_enabled) { // Disable render texture GLRenderTarget* target = effects->popRenderTarget(); - assert( target == m_fbo ); - Q_UNUSED( target ); + assert(target == m_fbo); + Q_UNUSED(target); m_texture->bind(); // Use the shader diff --git a/effects/lookingglass/lookingglass.h b/effects/lookingglass/lookingglass.h index 5b82d0874..032a888a6 100644 --- a/effects/lookingglass/lookingglass.h +++ b/effects/lookingglass/lookingglass.h @@ -38,42 +38,42 @@ class GLVertexBuffer; * Enhanced magnifier **/ class LookingGlassEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - LookingGlassEffect(); - virtual ~LookingGlassEffect(); +public: + LookingGlassEffect(); + virtual ~LookingGlassEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); + virtual void reconfigure(ReconfigureFlags); + virtual void mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void postPaintScreen(); - static bool supported(); + static bool supported(); - public slots: - void toggle(); - void zoomIn(); - void zoomOut(); +public slots: + void toggle(); + void zoomIn(); + void zoomOut(); - private: - bool loadData(); - double zoom; - double target_zoom; - bool polling; // Mouse polling - int radius; - int initialradius; - KActionCollection* actionCollection; - GLTexture *m_texture; - GLRenderTarget *m_fbo; - GLVertexBuffer *m_vbo; - GLShader *m_shader; - bool m_enabled; - bool m_valid; - }; +private: + bool loadData(); + double zoom; + double target_zoom; + bool polling; // Mouse polling + int radius; + int initialradius; + KActionCollection* actionCollection; + GLTexture *m_texture; + GLRenderTarget *m_fbo; + GLVertexBuffer *m_vbo; + GLShader *m_shader; + bool m_enabled; + bool m_valid; +}; } // namespace diff --git a/effects/lookingglass/lookingglass_config.cpp b/effects/lookingglass/lookingglass_config.cpp index 9d698550e..fc5b2acd0 100644 --- a/effects/lookingglass/lookingglass_config.cpp +++ b/effects/lookingglass/lookingglass_config.cpp @@ -39,12 +39,12 @@ KWIN_EFFECT_CONFIG_FACTORY LookingGlassEffectConfigForm::LookingGlassEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } LookingGlassEffectConfig::LookingGlassEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new LookingGlassEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -53,37 +53,37 @@ LookingGlassEffectConfig::LookingGlassEffectConfig(QWidget* parent, const QVaria connect(m_ui->editor, SIGNAL(keyChange()), this, SLOT(changed())); connect(m_ui->radiusSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); - + // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); m_actionCollection->setConfigGroup("LookingGlass"); m_actionCollection->setConfigGlobal(true); - + KAction* a; - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ZoomIn)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ZoomIn)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Plus)); - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ZoomOut)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ZoomOut)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ActualSize)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ActualSize)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); m_ui->editor->addCollection(m_actionCollection); - } +} LookingGlassEffectConfig::~LookingGlassEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts m_ui->editor->undoChanges(); - } +} void LookingGlassEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("LookingGlass"); @@ -91,10 +91,10 @@ void LookingGlassEffectConfig::load() int radius = conf.readEntry("Radius", 200); m_ui->radiusSpin->setValue(radius); emit changed(false); - } +} void LookingGlassEffectConfig::save() - { +{ kDebug(1212) << "Saving config of LookingGlass" ; //KCModule::save(); @@ -107,15 +107,15 @@ void LookingGlassEffectConfig::save() conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "lookingglass" ); - } + EffectsHandler::sendReloadMessage("lookingglass"); +} void LookingGlassEffectConfig::defaults() - { +{ m_ui->radiusSpin->setValue(200); m_ui->editor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/lookingglass/lookingglass_config.h b/effects/lookingglass/lookingglass_config.h index d3bd07a6d..593cc8677 100644 --- a/effects/lookingglass/lookingglass_config.h +++ b/effects/lookingglass/lookingglass_config.h @@ -33,25 +33,25 @@ namespace KWin class LookingGlassEffectConfigForm : public QWidget, public Ui::LookingGlassEffectConfigForm { Q_OBJECT - public: - explicit LookingGlassEffectConfigForm(QWidget* parent); +public: + explicit LookingGlassEffectConfigForm(QWidget* parent); }; class LookingGlassEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit LookingGlassEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual ~LookingGlassEffectConfig(); +public: + explicit LookingGlassEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + virtual ~LookingGlassEffectConfig(); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - LookingGlassEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + LookingGlassEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/magiclamp/magiclamp.cpp b/effects/magiclamp/magiclamp.cpp index bd1a4fc3e..3d1edf699 100644 --- a/effects/magiclamp/magiclamp.cpp +++ b/effects/magiclamp/magiclamp.cpp @@ -27,130 +27,118 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( magiclamp, MagicLampEffect ) -KWIN_EFFECT_SUPPORTED( magiclamp, MagicLampEffect::supported() ) +KWIN_EFFECT(magiclamp, MagicLampEffect) +KWIN_EFFECT_SUPPORTED(magiclamp, MagicLampEffect::supported()) MagicLampEffect::MagicLampEffect() - { +{ mActiveAnimations = 0; - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} bool MagicLampEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void MagicLampEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "MagicLamp" ); - mAnimationDuration = animationTime( conf, "AnimationDuration", 250 ); - conf = effects->effectConfig( "Shadow" ); - int v = conf.readEntry( "Size", 5 ); - v += conf.readEntry( "Fuzzyness", 10 ); +void MagicLampEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("MagicLamp"); + mAnimationDuration = animationTime(conf, "AnimationDuration", 250); + conf = effects->effectConfig("Shadow"); + int v = conf.readEntry("Size", 5); + v += conf.readEntry("Fuzzyness", 10); mShadowOffset[0] = mShadowOffset[1] = -v; mShadowOffset[2] = mShadowOffset[3] = v; - v = conf.readEntry( "XOffset", 0 ); + v = conf.readEntry("XOffset", 0); mShadowOffset[0] -= v; mShadowOffset[2] += v; - v = conf.readEntry( "YOffset", 3 ); + v = conf.readEntry("YOffset", 3); mShadowOffset[1] -= v; mShadowOffset[3] += v; - } +} -void MagicLampEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void MagicLampEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ QHash< EffectWindow*, TimeLine >::iterator entry = mTimeLineWindows.begin(); bool erase = false; - while( entry != mTimeLineWindows.end() ) - { + while (entry != mTimeLineWindows.end()) { TimeLine &timeline = entry.value(); - if( entry.key()->isMinimized() ) - { + if (entry.key()->isMinimized()) { timeline.addTime(time); erase = (timeline.progress() >= 1.0f); - } - else - { + } else { timeline.removeTime(time); erase = (timeline.progress() <= 0.0f); - } - if( erase ) - entry = mTimeLineWindows.erase( entry ); + } + if (erase) + entry = mTimeLineWindows.erase(entry); else ++entry; - } - + } + mActiveAnimations = mTimeLineWindows.count(); - if( mActiveAnimations > 0 ) + if (mActiveAnimations > 0) // We need to mark the screen windows as transformed. Otherwise the // whole screen won't be repainted, resulting in artefacts data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void MagicLampEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void MagicLampEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // Schedule window for transformation if the animation is still in // progress - if( mTimeLineWindows.contains( w )) - { + if (mTimeLineWindows.contains(w)) { // We'll transform this window data.setTransformed(); - data.quads = data.quads.makeGrid( 40 ); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); - } - - effects->prePaintWindow( w, data, time ); + data.quads = data.quads.makeGrid(40); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); } -void MagicLampEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( mTimeLineWindows.contains( w )) - { + effects->prePaintWindow(w, data, time); +} + +void MagicLampEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (mTimeLineWindows.contains(w)) { // 0 = not minimized, 1 = fully minimized float progress = mTimeLineWindows[w].value(); QRect geo = w->geometry(); QRect icon = w->iconGeometry(); - QRect area = effects->clientArea( ScreenArea, w ); + QRect area = effects->clientArea(ScreenArea, w); IconPosition position = Top; // If there's no icon geometry, minimize to the center of the screen - if( !icon.isValid() ) - { + if (!icon.isValid()) { QRect extG = geo.adjusted(mShadowOffset[0], mShadowOffset[1], mShadowOffset[2], mShadowOffset[3]); QPoint pt = QCursor::pos(); // focussing inside the window is no good, leads to ugly artefacts, find nearest border - if (extG.contains(pt)) - { + if (extG.contains(pt)) { const int d[2][2] = { {pt.x() - extG.x(), extG.right() - pt.x()}, - {pt.y() - extG.y(), extG.bottom() - pt.y()} }; + {pt.y() - extG.y(), extG.bottom() - pt.y()} + }; int di = d[1][0]; position = Top; - if (d[0][0] < di) - { + if (d[0][0] < di) { di = d[0][0]; position = Left; - } - if (d[1][1] < di) - { + } + if (d[1][1] < di) { di = d[1][1]; position = Bottom; - } + } if (d[0][1] < di) position = Right; - switch (position) - { - case Top: pt.setY(extG.y()); break; - case Left: pt.setX(extG.x()); break; - case Bottom: pt.setY(extG.bottom()); break; - case Right: pt.setX(extG.right()); break; - } - } - else - { + switch(position) { + case Top: pt.setY(extG.y()); break; + case Left: pt.setX(extG.x()); break; + case Bottom: pt.setY(extG.bottom()); break; + case Right: pt.setX(extG.right()); break; + } + } else { if (pt.y() < geo.y()) position = Top; else if (pt.x() < geo.x()) @@ -159,81 +147,62 @@ void MagicLampEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Wi position = Bottom; else if (pt.x() > geo.right()) position = Right; - } - icon = QRect(pt, QSize(0,0)); } - else - { + icon = QRect(pt, QSize(0, 0)); + } else { // Assumption: there is a panel containing the icon position EffectWindow* panel = NULL; - foreach( EffectWindow* window, effects->stackingOrder() ) - { - if( !window->isDock() ) + foreach (EffectWindow * window, effects->stackingOrder()) { + if (!window->isDock()) continue; // we have to use intersects as there seems to be a Plasma bug // the published icon geometry might be bigger than the panel - if( window->geometry().intersects( icon ) ) - { + if (window->geometry().intersects(icon)) { panel = window; break; - } } - if( panel ) - { + } + if (panel) { // Assumption: width of horizonal panel is greater than its height and vice versa // The panel has to border one screen edge, so get it's screen area - QRect panelScreen = effects->clientArea( ScreenArea, panel ); - if( panel->width() >= panel->height() ) - { + QRect panelScreen = effects->clientArea(ScreenArea, panel); + if (panel->width() >= panel->height()) { // horizontal panel - if( panel->y() == panelScreen.y() ) + if (panel->y() == panelScreen.y()) position = Top; else position = Bottom; - } - else - { + } else { // vertical panel - if( panel->x() == panelScreen.x() ) + if (panel->x() == panelScreen.x()) position = Left; else position = Right; - } } - else - { + } else { // we did not find a panel, so it might be autohidden - QRect iconScreen = effects->clientArea( ScreenArea, icon.topLeft(), effects->currentDesktop() ); + QRect iconScreen = effects->clientArea(ScreenArea, icon.topLeft(), effects->currentDesktop()); // as the icon geometry could be overlap a screen edge we use an intersection - QRect rect = iconScreen.intersected( icon ); + QRect rect = iconScreen.intersected(icon); // here we need a different assumption: icon geometry borders one screen edge // this assumption might be wrong for e.g. task applet being the only applet in panel // in this case the icon borders two screen edges // there might be a wrong animation, but not distorted - if( rect.x() == iconScreen.x() ) - { + if (rect.x() == iconScreen.x()) { position = Left; - } - else if( rect.x() + rect.width() == iconScreen.x() + iconScreen.width() ) - { + } else if (rect.x() + rect.width() == iconScreen.x() + iconScreen.width()) { position = Right; - } - else if( rect.y() == iconScreen.y() ) - { + } else if (rect.y() == iconScreen.y()) { position = Top; - } - else - { + } else { position = Bottom; - } } } + } WindowQuadList newQuads; - foreach( WindowQuad quad, data.quads ) // krazy:exclude=foreach - { - if( position == Top || position == Bottom ) - { + foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach + if (position == Top || position == Bottom) { // quadFactor defines how fast a quad is vertically moved: y coordinates near to window top are slowed down // it is used as quadFactor^3/windowHeight^3 // quadFactor is the y position of the quad but is changed towards becomming the window height @@ -246,143 +215,133 @@ void MagicLampEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Wi // factor is the current moved y value diveded by the distance between icon and window float topProgress; float bottomProgress; - if( position == Bottom ) - { - quadFactor = quad[0].y() + (geo.height() - quad[0].y())*progress; - yOffsetTop = (icon.y() + quad[0].y() - geo.y())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.height()*geo.height()*geo.height())); - quadFactor = quad[2].y() + (geo.height() - quad[2].y())*progress; - yOffsetBottom = (icon.y() + quad[2].y() - geo.y())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.height()*geo.height()*geo.height())); - topProgress = qMin( yOffsetTop/(icon.y()+icon.height() - geo.y()-(float)(quad[0].y()/geo.height()*geo.height())), 1.0f ); - bottomProgress = qMin( yOffsetBottom/(icon.y()+icon.height() - geo.y()-(float)(quad[2].y()/geo.height()*geo.height())), 1.0f ); - } - else - { - quadFactor = geo.height() - quad[0].y() + (quad[0].y())*progress; - yOffsetTop = (geo.y() - icon.height() + geo.height() + quad[0].y() - icon.y())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.height()*geo.height()*geo.height())); - quadFactor = geo.height() - quad[2].y() + (quad[2].y())*progress; - yOffsetBottom = (geo.y() - icon.height() + geo.height() + quad[2].y() - icon.y())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.height()*geo.height()*geo.height())); - topProgress = qMin( yOffsetTop/(geo.y() - icon.height() + geo.height() - icon.y() - - (float)((geo.height()-quad[0].y())/geo.height()*geo.height())), 1.0f ); - bottomProgress = qMin( yOffsetBottom/(geo.y() - icon.height() + geo.height() - icon.y() - - (float)((geo.height()-quad[2].y())/geo.height()*geo.height())), 1.0f ); - } - if( position == Top ) - { + if (position == Bottom) { + quadFactor = quad[0].y() + (geo.height() - quad[0].y()) * progress; + yOffsetTop = (icon.y() + quad[0].y() - geo.y()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.height() * geo.height() * geo.height())); + quadFactor = quad[2].y() + (geo.height() - quad[2].y()) * progress; + yOffsetBottom = (icon.y() + quad[2].y() - geo.y()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.height() * geo.height() * geo.height())); + topProgress = qMin(yOffsetTop / (icon.y() + icon.height() - geo.y() - (float)(quad[0].y() / geo.height() * geo.height())), 1.0f); + bottomProgress = qMin(yOffsetBottom / (icon.y() + icon.height() - geo.y() - (float)(quad[2].y() / geo.height() * geo.height())), 1.0f); + } else { + quadFactor = geo.height() - quad[0].y() + (quad[0].y()) * progress; + yOffsetTop = (geo.y() - icon.height() + geo.height() + quad[0].y() - icon.y()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.height() * geo.height() * geo.height())); + quadFactor = geo.height() - quad[2].y() + (quad[2].y()) * progress; + yOffsetBottom = (geo.y() - icon.height() + geo.height() + quad[2].y() - icon.y()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.height() * geo.height() * geo.height())); + topProgress = qMin(yOffsetTop / (geo.y() - icon.height() + geo.height() - icon.y() - + (float)((geo.height() - quad[0].y()) / geo.height() * geo.height())), 1.0f); + bottomProgress = qMin(yOffsetBottom / (geo.y() - icon.height() + geo.height() - icon.y() - + (float)((geo.height() - quad[2].y()) / geo.height() * geo.height())), 1.0f); + } + if (position == Top) { yOffsetTop *= -1; yOffsetBottom *= -1; - } - if( topProgress < 0 ) + } + if (topProgress < 0) topProgress *= -1; - if( bottomProgress < 0 ) + if (bottomProgress < 0) bottomProgress *= -1; // x values are moved towards the center of the icon - quad[0].setX( (icon.x() + icon.width()*(quad[0].x()/geo.width()) - (quad[0].x() + geo.x()))*topProgress + quad[0].x() ); - quad[1].setX( (icon.x() + icon.width()*(quad[1].x()/geo.width()) - (quad[1].x() + geo.x()))*topProgress + quad[1].x() ); - quad[2].setX( (icon.x() + icon.width()*(quad[2].x()/geo.width()) - (quad[2].x() + geo.x()))*bottomProgress + quad[2].x() ); - quad[3].setX( (icon.x() + icon.width()*(quad[3].x()/geo.width()) - (quad[3].x() + geo.x()))*bottomProgress + quad[3].x() ); + quad[0].setX((icon.x() + icon.width()*(quad[0].x() / geo.width()) - (quad[0].x() + geo.x()))*topProgress + quad[0].x()); + quad[1].setX((icon.x() + icon.width()*(quad[1].x() / geo.width()) - (quad[1].x() + geo.x()))*topProgress + quad[1].x()); + quad[2].setX((icon.x() + icon.width()*(quad[2].x() / geo.width()) - (quad[2].x() + geo.x()))*bottomProgress + quad[2].x()); + quad[3].setX((icon.x() + icon.width()*(quad[3].x() / geo.width()) - (quad[3].x() + geo.x()))*bottomProgress + quad[3].x()); - quad[0].setY( quad[0].y() + yOffsetTop ); - quad[1].setY( quad[1].y() + yOffsetTop ); - quad[2].setY( quad[2].y() + yOffsetBottom ); - quad[3].setY( quad[3].y() + yOffsetBottom ); - } - else - { + quad[0].setY(quad[0].y() + yOffsetTop); + quad[1].setY(quad[1].y() + yOffsetTop); + quad[2].setY(quad[2].y() + yOffsetBottom); + quad[3].setY(quad[3].y() + yOffsetBottom); + } else { float quadFactor; float xOffsetLeft; float xOffsetRight; float leftProgress; float rightProgress; - if( position == Right ) - { - quadFactor = quad[0].x() + (geo.width() - quad[0].x())*progress; - xOffsetLeft = (icon.x() + quad[0].x() - geo.x())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.width()*geo.width()*geo.width())); - quadFactor = quad[1].x() + (geo.width() - quad[1].x())*progress; - xOffsetRight = (icon.x() + quad[1].x() - geo.x())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.width()*geo.width()*geo.width())); - leftProgress = qMin( xOffsetLeft/(icon.x()+icon.width() - geo.x()-(float)(quad[0].x()/geo.width()*geo.width())), 1.0f ); - rightProgress = qMin( xOffsetRight/(icon.x()+icon.width() - geo.x()-(float)(quad[1].x()/geo.width()*geo.width())), 1.0f ); - } - else - { - quadFactor = geo.width() - quad[0].x() + (quad[0].x())*progress; - xOffsetLeft = (geo.x() - icon.width() + geo.width() + quad[0].x() - icon.x())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.width()*geo.width()*geo.width())); - quadFactor = geo.width() - quad[1].x() + (quad[1].x())*progress; - xOffsetRight = (geo.x() - icon.width() + geo.width() + quad[1].x() - icon.x())*progress* - ((quadFactor*quadFactor*quadFactor)/(geo.width()*geo.width()*geo.width())); - leftProgress = qMin( xOffsetLeft/(geo.x() - icon.width() + geo.width() - icon.x() - - (float)((geo.width()-quad[0].x())/geo.width()*geo.width())), 1.0f ); - rightProgress = qMin( xOffsetRight/(geo.x() - icon.width() + geo.width() - icon.x() - - (float)((geo.width()-quad[1].x())/geo.width()*geo.width())), 1.0f ); - } - if( position == Left ) - { + if (position == Right) { + quadFactor = quad[0].x() + (geo.width() - quad[0].x()) * progress; + xOffsetLeft = (icon.x() + quad[0].x() - geo.x()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.width() * geo.width() * geo.width())); + quadFactor = quad[1].x() + (geo.width() - quad[1].x()) * progress; + xOffsetRight = (icon.x() + quad[1].x() - geo.x()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.width() * geo.width() * geo.width())); + leftProgress = qMin(xOffsetLeft / (icon.x() + icon.width() - geo.x() - (float)(quad[0].x() / geo.width() * geo.width())), 1.0f); + rightProgress = qMin(xOffsetRight / (icon.x() + icon.width() - geo.x() - (float)(quad[1].x() / geo.width() * geo.width())), 1.0f); + } else { + quadFactor = geo.width() - quad[0].x() + (quad[0].x()) * progress; + xOffsetLeft = (geo.x() - icon.width() + geo.width() + quad[0].x() - icon.x()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.width() * geo.width() * geo.width())); + quadFactor = geo.width() - quad[1].x() + (quad[1].x()) * progress; + xOffsetRight = (geo.x() - icon.width() + geo.width() + quad[1].x() - icon.x()) * progress * + ((quadFactor * quadFactor * quadFactor) / (geo.width() * geo.width() * geo.width())); + leftProgress = qMin(xOffsetLeft / (geo.x() - icon.width() + geo.width() - icon.x() - + (float)((geo.width() - quad[0].x()) / geo.width() * geo.width())), 1.0f); + rightProgress = qMin(xOffsetRight / (geo.x() - icon.width() + geo.width() - icon.x() - + (float)((geo.width() - quad[1].x()) / geo.width() * geo.width())), 1.0f); + } + if (position == Left) { xOffsetLeft *= -1; xOffsetRight *= -1; - } - if( leftProgress < 0 ) + } + if (leftProgress < 0) leftProgress *= -1; - if( rightProgress < 0 ) + if (rightProgress < 0) rightProgress *= -1; - quad[0].setY( (icon.y() + icon.height()*(quad[0].y()/geo.height()) - (quad[0].y() + geo.y()))*leftProgress + quad[0].y() ); - quad[1].setY( (icon.y() + icon.height()*(quad[1].y()/geo.height()) - (quad[1].y() + geo.y()))*rightProgress + quad[1].y() ); - quad[2].setY( (icon.y() + icon.height()*(quad[2].y()/geo.height()) - (quad[2].y() + geo.y()))*rightProgress + quad[2].y() ); - quad[3].setY( (icon.y() + icon.height()*(quad[3].y()/geo.height()) - (quad[3].y() + geo.y()))*leftProgress + quad[3].y() ); + quad[0].setY((icon.y() + icon.height()*(quad[0].y() / geo.height()) - (quad[0].y() + geo.y()))*leftProgress + quad[0].y()); + quad[1].setY((icon.y() + icon.height()*(quad[1].y() / geo.height()) - (quad[1].y() + geo.y()))*rightProgress + quad[1].y()); + quad[2].setY((icon.y() + icon.height()*(quad[2].y() / geo.height()) - (quad[2].y() + geo.y()))*rightProgress + quad[2].y()); + quad[3].setY((icon.y() + icon.height()*(quad[3].y() / geo.height()) - (quad[3].y() + geo.y()))*leftProgress + quad[3].y()); - quad[0].setX( quad[0].x() + xOffsetLeft ); - quad[1].setX( quad[1].x() + xOffsetRight ); - quad[2].setX( quad[2].x() + xOffsetRight ); - quad[3].setX( quad[3].x() + xOffsetLeft ); - } - newQuads.append( quad ); + quad[0].setX(quad[0].x() + xOffsetLeft); + quad[1].setX(quad[1].x() + xOffsetRight); + quad[2].setX(quad[2].x() + xOffsetRight); + quad[3].setX(quad[3].x() + xOffsetLeft); } + newQuads.append(quad); + } data.quads = newQuads; } // Call the next effect. - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); +} void MagicLampEffect::postPaintScreen() - { - if( mActiveAnimations > 0 ) +{ + if (mActiveAnimations > 0) // Repaint the workspace so that everything would be repainted next time effects->addRepaintFull(); mActiveAnimations = mTimeLineWindows.count(); // Call the next effect. effects->postPaintScreen(); - } +} -void MagicLampEffect::windowDeleted( EffectWindow* w ) - { - mTimeLineWindows.remove( w ); - } +void MagicLampEffect::windowDeleted(EffectWindow* w) +{ + mTimeLineWindows.remove(w); +} -void MagicLampEffect::windowMinimized( EffectWindow* w ) - { - if ( effects->activeFullScreenEffect() ) +void MagicLampEffect::windowMinimized(EffectWindow* w) +{ + if (effects->activeFullScreenEffect()) return; mTimeLineWindows[w].setCurveShape(TimeLine::LinearCurve); - mTimeLineWindows[w].setDuration( mAnimationDuration ); + mTimeLineWindows[w].setDuration(mAnimationDuration); mTimeLineWindows[w].setProgress(0.0f); - } +} -void MagicLampEffect::windowUnminimized( EffectWindow* w ) - { - if ( effects->activeFullScreenEffect() ) +void MagicLampEffect::windowUnminimized(EffectWindow* w) +{ + if (effects->activeFullScreenEffect()) return; mTimeLineWindows[w].setCurveShape(TimeLine::LinearCurve); - mTimeLineWindows[w].setDuration( mAnimationDuration ); + mTimeLineWindows[w].setDuration(mAnimationDuration); mTimeLineWindows[w].setProgress(1.0f); - } +} } // namespace diff --git a/effects/magiclamp/magiclamp.h b/effects/magiclamp/magiclamp.h index eeedf7d5f..99326b2f6 100644 --- a/effects/magiclamp/magiclamp.h +++ b/effects/magiclamp/magiclamp.h @@ -28,36 +28,35 @@ namespace KWin class MagicLampEffect : public Effect - { - public: - MagicLampEffect(); +{ +public: + MagicLampEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); - virtual void windowDeleted( EffectWindow* c ); - virtual void windowMinimized( EffectWindow* c ); - virtual void windowUnminimized( EffectWindow* c ); + virtual void windowDeleted(EffectWindow* c); + virtual void windowMinimized(EffectWindow* c); + virtual void windowUnminimized(EffectWindow* c); - static bool supported(); + static bool supported(); - private: - QHash< EffectWindow*, TimeLine > mTimeLineWindows; - int mActiveAnimations; - int mAnimationDuration; - int mShadowOffset[4]; +private: + QHash< EffectWindow*, TimeLine > mTimeLineWindows; + int mActiveAnimations; + int mAnimationDuration; + int mShadowOffset[4]; - enum IconPosition - { - Top, - Bottom, - Left, - Right - }; + enum IconPosition { + Top, + Bottom, + Left, + Right }; +}; } // namespace diff --git a/effects/magiclamp/magiclamp_config.cpp b/effects/magiclamp/magiclamp_config.cpp index 1656354e9..a1822af57 100644 --- a/effects/magiclamp/magiclamp_config.cpp +++ b/effects/magiclamp/magiclamp_config.cpp @@ -31,12 +31,12 @@ KWIN_EFFECT_CONFIG_FACTORY MagicLampEffectConfigForm::MagicLampEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } MagicLampEffectConfig::MagicLampEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new MagicLampEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -45,37 +45,37 @@ MagicLampEffectConfig::MagicLampEffectConfig(QWidget* parent, const QVariantList connect(m_ui->animationDurationSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); load(); - } +} void MagicLampEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "MagicLamp" ); + KConfigGroup conf = EffectsHandler::effectConfig("MagicLamp"); - int duration = conf.readEntry( "AnimationDuration", 0 ); - m_ui->animationDurationSpin->setValue( duration ); + int duration = conf.readEntry("AnimationDuration", 0); + m_ui->animationDurationSpin->setValue(duration); m_ui->animationDurationSpin->setSuffix(ki18np(" millisecond", " milliseconds")); emit changed(false); - } +} void MagicLampEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "MagicLamp" ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("MagicLamp"); - conf.writeEntry( "AnimationDuration", m_ui->animationDurationSpin->value() ); + conf.writeEntry("AnimationDuration", m_ui->animationDurationSpin->value()); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "magiclamp" ); - } + EffectsHandler::sendReloadMessage("magiclamp"); +} void MagicLampEffectConfig::defaults() - { - m_ui->animationDurationSpin->setValue( 0 ); +{ + m_ui->animationDurationSpin->setValue(0); emit changed(true); - } +} } // namespace #include "magiclamp_config.moc" diff --git a/effects/magiclamp/magiclamp_config.h b/effects/magiclamp/magiclamp_config.h index e0486658d..edb1a844c 100644 --- a/effects/magiclamp/magiclamp_config.h +++ b/effects/magiclamp/magiclamp_config.h @@ -32,23 +32,23 @@ namespace KWin class MagicLampEffectConfigForm : public QWidget, public Ui::MagicLampEffectConfigForm { Q_OBJECT - public: - explicit MagicLampEffectConfigForm(QWidget* parent); +public: + explicit MagicLampEffectConfigForm(QWidget* parent); }; class MagicLampEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit MagicLampEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit MagicLampEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); - private: - MagicLampEffectConfigForm* m_ui; - }; +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); +private: + MagicLampEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/magnifier/magnifier.cpp b/effects/magnifier/magnifier.cpp index b1f862ea4..802de3c39 100644 --- a/effects/magnifier/magnifier.cpp +++ b/effects/magnifier/magnifier.cpp @@ -33,67 +33,66 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( magnifier, MagnifierEffect ) +KWIN_EFFECT(magnifier, MagnifierEffect) const int FRAME_WIDTH = 5; MagnifierEffect::MagnifierEffect() - : zoom( 1 ) - , target_zoom( 1 ) - , polling( false ) - { - KActionCollection* actionCollection = new KActionCollection( this ); + : zoom(1) + , target_zoom(1) + , polling(false) +{ + KActionCollection* actionCollection = new KActionCollection(this); KAction* a; - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomIn, this, SLOT( zoomIn()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomIn, this, SLOT(zoomIn()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Equal)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomOut, this, SLOT( zoomOut()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomOut, this, SLOT(zoomOut()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ActualSize, this, SLOT( toggle()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ActualSize, this, SLOT(toggle()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} -void MagnifierEffect::reconfigure( ReconfigureFlags ) - { +void MagnifierEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("Magnifier"); int width, height; width = conf.readEntry("Width", 200); height = conf.readEntry("Height", 200); - magnifier_size = QSize( width, height ); - } + magnifier_size = QSize(width, height); +} -void MagnifierEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( zoom != target_zoom ) - { - double diff = time / animationTime( 500.0 ); - if( target_zoom > zoom ) - zoom = qMin( zoom * qMax( 1 + diff, 1.2 ), target_zoom ); +void MagnifierEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (zoom != target_zoom) { + double diff = time / animationTime(500.0); + if (target_zoom > zoom) + zoom = qMin(zoom * qMax(1 + diff, 1.2), target_zoom); else - zoom = qMax( zoom * qMin( 1 - diff, 0.8 ), target_zoom ); - } - effects->prePaintScreen( data, time ); - if( zoom != 1.0 ) - data.paint |= magnifierArea().adjusted( -FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH ); + zoom = qMax(zoom * qMin(1 - diff, 0.8), target_zoom); } + effects->prePaintScreen(data, time); + if (zoom != 1.0) + data.paint |= magnifierArea().adjusted(-FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH); +} -void MagnifierEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { +void MagnifierEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ ScreenPaintData data2 = data; - effects->paintScreen( mask, region, data ); // paint normal screen - if( zoom != 1.0 ) - { // paint magnifier + effects->paintScreen(mask, region, data); // paint normal screen + if (zoom != 1.0) { + // paint magnifier QRect area = magnifierArea(); - PaintClipper::push( area ); // don't allow any painting outside of the area + PaintClipper::push(area); // don't allow any painting outside of the area mask |= PAINT_SCREEN_TRANSFORMED; data2.xScale *= zoom; data2.yScale *= zoom; QPoint cursor = cursorPos(); // set the position so that the cursor is in the same position in the scaled view - data2.xTranslate = - int( cursor.x() * ( zoom - 1 )); - data2.yTranslate = - int( cursor.y() * ( zoom - 1 )); - effects->paintScreen( mask, region, data2 ); - PaintClipper::pop( area ); + data2.xTranslate = - int(cursor.x() * (zoom - 1)); + data2.yTranslate = - int(cursor.y() * (zoom - 1)); + effects->paintScreen(mask, region, data2); + PaintClipper::pop(area); QVector verts; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); @@ -126,7 +125,7 @@ void MagnifierEffect::paintScreen( int mask, QRegion region, ScreenPaintData& da verts << area.left() - FRAME_WIDTH << area.bottom() + FRAME_WIDTH; verts << area.right() + FRAME_WIDTH << area.bottom() + FRAME_WIDTH; verts << area.right() + FRAME_WIDTH << area.bottom() + 1; - vbo->setData(verts.size()/2, 2, verts.constData(), NULL); + vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } @@ -134,82 +133,73 @@ void MagnifierEffect::paintScreen( int mask, QRegion region, ScreenPaintData& da if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } - } } +} void MagnifierEffect::postPaintScreen() - { - if( zoom != target_zoom ) - { - QRect framedarea = magnifierArea().adjusted( -FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH ); - effects->addRepaint( framedarea ); +{ + if (zoom != target_zoom) { + QRect framedarea = magnifierArea().adjusted(-FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH); + effects->addRepaint(framedarea); } effects->postPaintScreen(); - } +} -QRect MagnifierEffect::magnifierArea( QPoint pos ) const - { - return QRect( pos.x() - magnifier_size.width() / 2, pos.y() - magnifier_size.height() / 2, - magnifier_size.width(), magnifier_size.height()); - } +QRect MagnifierEffect::magnifierArea(QPoint pos) const +{ + return QRect(pos.x() - magnifier_size.width() / 2, pos.y() - magnifier_size.height() / 2, + magnifier_size.width(), magnifier_size.height()); +} void MagnifierEffect::zoomIn() - { +{ target_zoom *= 1.2; - if( !polling ) - { + if (!polling) { polling = true; effects->startMousePolling(); - } - effects->addRepaint( magnifierArea().adjusted( -FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH )); } + effects->addRepaint(magnifierArea().adjusted(-FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH)); +} void MagnifierEffect::zoomOut() - { +{ target_zoom /= 1.2; - if( target_zoom < 1 ) - { + if (target_zoom < 1) { target_zoom = 1; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } } - effects->addRepaint( magnifierArea().adjusted( -FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH )); } + effects->addRepaint(magnifierArea().adjusted(-FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH)); +} void MagnifierEffect::toggle() - { - if( target_zoom == 1.0 ) - { +{ + if (target_zoom == 1.0) { target_zoom = 2; - if( !polling ) - { + if (!polling) { polling = true; effects->startMousePolling(); - } } - else - { + } else { target_zoom = 1; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } } - effects->addRepaint( magnifierArea().adjusted( -FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH )); } + effects->addRepaint(magnifierArea().adjusted(-FRAME_WIDTH, -FRAME_WIDTH, FRAME_WIDTH, FRAME_WIDTH)); +} -void MagnifierEffect::mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons, Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers ) - { - if( pos != old && zoom != 1 ) +void MagnifierEffect::mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons, Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers) +{ + if (pos != old && zoom != 1) // need full repaint as we might lose some change events on fast mouse movements // see Bug 187658 effects->addRepaintFull(); - } +} } // namespace diff --git a/effects/magnifier/magnifier.h b/effects/magnifier/magnifier.h index 7ed501884..9001f1f93 100644 --- a/effects/magnifier/magnifier.h +++ b/effects/magnifier/magnifier.h @@ -28,28 +28,28 @@ namespace KWin class MagnifierEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - MagnifierEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - private slots: - void zoomIn(); - void zoomOut(); - void toggle(); - private: - QRect magnifierArea( QPoint pos = cursorPos()) const; - double zoom; - double target_zoom; - bool polling; // Mouse polling - QSize magnifier_size; - }; +public: + MagnifierEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); +private slots: + void zoomIn(); + void zoomOut(); + void toggle(); +private: + QRect magnifierArea(QPoint pos = cursorPos()) const; + double zoom; + double target_zoom; + bool polling; // Mouse polling + QSize magnifier_size; +}; } // namespace diff --git a/effects/magnifier/magnifier_config.cpp b/effects/magnifier/magnifier_config.cpp index fcc20f024..67c22ded9 100644 --- a/effects/magnifier/magnifier_config.cpp +++ b/effects/magnifier/magnifier_config.cpp @@ -39,12 +39,12 @@ KWIN_EFFECT_CONFIG_FACTORY MagnifierEffectConfigForm::MagnifierEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } MagnifierEffectConfig::MagnifierEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new MagnifierEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -56,35 +56,35 @@ MagnifierEffectConfig::MagnifierEffectConfig(QWidget* parent, const QVariantList connect(m_ui->spinHeight, SIGNAL(valueChanged(int)), this, SLOT(changed())); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); m_actionCollection->setConfigGroup("Magnifier"); m_actionCollection->setConfigGlobal(true); KAction* a; - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ZoomIn)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ZoomIn)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Plus)); - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ZoomOut)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ZoomOut)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( m_actionCollection->addAction( KStandardAction::ActualSize)); + a = static_cast< KAction* >(m_actionCollection->addAction(KStandardAction::ActualSize)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); m_ui->editor->addCollection(m_actionCollection); - } +} MagnifierEffectConfig::~MagnifierEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts m_ui->editor->undoChanges(); - } +} void MagnifierEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("Magnifier"); @@ -96,10 +96,10 @@ void MagnifierEffectConfig::load() emit changed(false); - } +} void MagnifierEffectConfig::save() - { +{ kDebug(1212) << "Saving config of Magnifier" ; //KCModule::save(); @@ -113,16 +113,16 @@ void MagnifierEffectConfig::save() conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "magnifier" ); - } + EffectsHandler::sendReloadMessage("magnifier"); +} void MagnifierEffectConfig::defaults() - { +{ m_ui->spinWidth->setValue(200); m_ui->spinHeight->setValue(200); m_ui->editor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/magnifier/magnifier_config.h b/effects/magnifier/magnifier_config.h index 908c55585..e0b5ac2af 100644 --- a/effects/magnifier/magnifier_config.h +++ b/effects/magnifier/magnifier_config.h @@ -33,25 +33,25 @@ namespace KWin class MagnifierEffectConfigForm : public QWidget, public Ui::MagnifierEffectConfigForm { Q_OBJECT - public: - explicit MagnifierEffectConfigForm(QWidget* parent); +public: + explicit MagnifierEffectConfigForm(QWidget* parent); }; class MagnifierEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit MagnifierEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual ~MagnifierEffectConfig(); +public: + explicit MagnifierEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + virtual ~MagnifierEffectConfig(); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - MagnifierEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + MagnifierEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/minimizeanimation/minimizeanimation.cpp b/effects/minimizeanimation/minimizeanimation.cpp index fddcfccb4..4c7148a84 100644 --- a/effects/minimizeanimation/minimizeanimation.cpp +++ b/effects/minimizeanimation/minimizeanimation.cpp @@ -23,121 +23,115 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( minimizeanimation, MinimizeAnimationEffect ) +KWIN_EFFECT(minimizeanimation, MinimizeAnimationEffect) MinimizeAnimationEffect::MinimizeAnimationEffect() - { +{ mActiveAnimations = 0; - } +} -void MinimizeAnimationEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void MinimizeAnimationEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ QHash< EffectWindow*, TimeLine >::iterator entry = mTimeLineWindows.begin(); bool erase = false; - while( entry != mTimeLineWindows.end() ) - { + while (entry != mTimeLineWindows.end()) { TimeLine &timeline = entry.value(); - if( entry.key()->isMinimized() ) - { + if (entry.key()->isMinimized()) { timeline.addTime(time); erase = (timeline.progress() >= 1.0f); - } - else - { + } else { timeline.removeTime(time); erase = (timeline.progress() <= 0.0f); - } - if( erase ) - entry = mTimeLineWindows.erase( entry ); + } + if (erase) + entry = mTimeLineWindows.erase(entry); else ++entry; - } + } mActiveAnimations = mTimeLineWindows.count(); - if( mActiveAnimations > 0 ) + if (mActiveAnimations > 0) // We need to mark the screen windows as transformed. Otherwise the // whole screen won't be repainted, resulting in artefacts data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); - } +} -void MinimizeAnimationEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void MinimizeAnimationEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // Schedule window for transformation if the animation is still in // progress - if( mTimeLineWindows.contains( w ) ) - { + if (mTimeLineWindows.contains(w)) { // We'll transform this window data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); - } - - effects->prePaintWindow( w, data, time ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); } -void MinimizeAnimationEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { + effects->prePaintWindow(w, data, time); +} + +void MinimizeAnimationEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ QHash< EffectWindow*, TimeLine >::const_iterator entry = mTimeLineWindows.constFind(w); - if( entry != mTimeLineWindows.constEnd() ) - { + if (entry != mTimeLineWindows.constEnd()) { // 0 = not minimized, 1 = fully minimized double progress = entry->value(); QRect geo = w->geometry(); QRect icon = w->iconGeometry(); // If there's no icon geometry, minimize to the center of the screen - if( !icon.isValid() ) - icon = QRect( displayWidth() / 2, displayHeight() / 2, 0, 0 ); + if (!icon.isValid()) + icon = QRect(displayWidth() / 2, displayHeight() / 2, 0, 0); data.xScale *= interpolate(1.0, icon.width() / (double)geo.width(), progress); data.yScale *= interpolate(1.0, icon.height() / (double)geo.height(), progress); data.xTranslate = (int)interpolate(data.xTranslate, icon.x() - geo.x(), progress); data.yTranslate = (int)interpolate(data.yTranslate, icon.y() - geo.y(), progress); - data.opacity *= 0.1 + (1-progress)*0.9; + data.opacity *= 0.1 + (1 - progress) * 0.9; } // Call the next effect. - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); +} void MinimizeAnimationEffect::postPaintScreen() - { - if( mActiveAnimations > 0 ) +{ + if (mActiveAnimations > 0) // Repaint the workspace so that everything would be repainted next time effects->addRepaintFull(); mActiveAnimations = mTimeLineWindows.count(); // Call the next effect. effects->postPaintScreen(); - } +} -void MinimizeAnimationEffect::windowDeleted( EffectWindow* w ) - { - mTimeLineWindows.remove( w ); - } +void MinimizeAnimationEffect::windowDeleted(EffectWindow* w) +{ + mTimeLineWindows.remove(w); +} -void MinimizeAnimationEffect::windowMinimized( EffectWindow* w ) - { - if ( effects->activeFullScreenEffect() ) +void MinimizeAnimationEffect::windowMinimized(EffectWindow* w) +{ + if (effects->activeFullScreenEffect()) return; TimeLine &timeline = mTimeLineWindows[w]; timeline.setCurveShape(TimeLine::EaseInCurve); - timeline.setDuration( animationTime( 250 )); + timeline.setDuration(animationTime(250)); timeline.setProgress(0.0f); - } +} -void MinimizeAnimationEffect::windowUnminimized( EffectWindow* w ) - { - if ( effects->activeFullScreenEffect() ) +void MinimizeAnimationEffect::windowUnminimized(EffectWindow* w) +{ + if (effects->activeFullScreenEffect()) return; TimeLine &timeline = mTimeLineWindows[w]; timeline.setCurveShape(TimeLine::EaseOutCurve); - timeline.setDuration( animationTime( 250 )); + timeline.setDuration(animationTime(250)); timeline.setProgress(1.0f); - } +} } // namespace diff --git a/effects/minimizeanimation/minimizeanimation.h b/effects/minimizeanimation/minimizeanimation.h index 96e4578d2..64f76bee3 100644 --- a/effects/minimizeanimation/minimizeanimation.h +++ b/effects/minimizeanimation/minimizeanimation.h @@ -33,23 +33,23 @@ namespace KWin **/ class MinimizeAnimationEffect : public Effect - { - public: - MinimizeAnimationEffect(); +{ +public: + MinimizeAnimationEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); - virtual void windowDeleted( EffectWindow* c ); - virtual void windowMinimized( EffectWindow* c ); - virtual void windowUnminimized( EffectWindow* c ); + virtual void windowDeleted(EffectWindow* c); + virtual void windowMinimized(EffectWindow* c); + virtual void windowUnminimized(EffectWindow* c); - private: - QHash< EffectWindow*, TimeLine > mTimeLineWindows; - int mActiveAnimations; - }; +private: + QHash< EffectWindow*, TimeLine > mTimeLineWindows; + int mActiveAnimations; +}; } // namespace diff --git a/effects/mousemark/mousemark.cpp b/effects/mousemark/mousemark.cpp index 9808be48e..880ea0fca 100644 --- a/effects/mousemark/mousemark.cpp +++ b/effects/mousemark/mousemark.cpp @@ -40,47 +40,47 @@ namespace KWin #define NULL_POINT (QPoint( -1, -1 )) // null point is (0,0), which is valid :-/ -KWIN_EFFECT( mousemark, MouseMarkEffect ) +KWIN_EFFECT(mousemark, MouseMarkEffect) MouseMarkEffect::MouseMarkEffect() - { - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = static_cast< KAction* >( actionCollection->addAction( "ClearMouseMarks" )); - a->setText( i18n( "Clear All Mouse Marks" )); - a->setGlobalShortcut( KShortcut( Qt::SHIFT + Qt::META + Qt::Key_F11 )); - connect( a, SIGNAL( triggered( bool )), this, SLOT( clear())); - a = static_cast< KAction* >( actionCollection->addAction( "ClearLastMouseMark" )); - a->setText( i18n( "Clear Last Mouse Mark" )); - a->setGlobalShortcut( KShortcut( Qt::SHIFT + Qt::META + Qt::Key_F12 )); - connect( a, SIGNAL( triggered( bool )), this, SLOT( clearLast())); - reconfigure( ReconfigureAll ); +{ + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = static_cast< KAction* >(actionCollection->addAction("ClearMouseMarks")); + a->setText(i18n("Clear All Mouse Marks")); + a->setGlobalShortcut(KShortcut(Qt::SHIFT + Qt::META + Qt::Key_F11)); + connect(a, SIGNAL(triggered(bool)), this, SLOT(clear())); + a = static_cast< KAction* >(actionCollection->addAction("ClearLastMouseMark")); + a->setText(i18n("Clear Last Mouse Mark")); + a->setGlobalShortcut(KShortcut(Qt::SHIFT + Qt::META + Qt::Key_F12)); + connect(a, SIGNAL(triggered(bool)), this, SLOT(clearLast())); + reconfigure(ReconfigureAll); arrow_start = NULL_POINT; effects->startMousePolling(); // We require it to detect activation as well - } +} MouseMarkEffect::~MouseMarkEffect() - { +{ effects->stopMousePolling(); - } +} -void MouseMarkEffect::reconfigure( ReconfigureFlags ) - { +void MouseMarkEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("MouseMark"); - width = conf.readEntry( "LineWidth", 3 ); - color = conf.readEntry( "Color", QColor( Qt::red )); + width = conf.readEntry("LineWidth", 3); + color = conf.readEntry("Color", QColor(Qt::red)); color.setAlphaF(1.0); - } +} -void MouseMarkEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); // paint normal screen - if( marks.isEmpty() && drawing.isEmpty()) +void MouseMarkEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); // paint normal screen + if (marks.isEmpty() && drawing.isEmpty()) return; #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_ENABLE_BIT | GL_CURRENT_BIT | GL_LINE_BIT ); - glEnable( GL_LINE_SMOOTH ); + glPushAttrib(GL_ENABLE_BIT | GL_CURRENT_BIT | GL_LINE_BIT); + glEnable(GL_LINE_SMOOTH); #endif - glLineWidth( width ); + glLineWidth(width); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setUseColor(true); @@ -89,112 +89,101 @@ void MouseMarkEffect::paintScreen( int mask, QRegion region, ScreenPaintData& da ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } QVector verts; - foreach (const Mark& mark, marks) { + foreach (const Mark & mark, marks) { verts.clear(); - verts.reserve(mark.size()*2); - foreach (const QPoint& p, mark) { + verts.reserve(mark.size() * 2); + foreach (const QPoint & p, mark) { verts << p.x() << p.y(); } - vbo->setData(verts.size()/2, 2, verts.data(), NULL); + vbo->setData(verts.size() / 2, 2, verts.data(), NULL); vbo->render(GL_LINE_STRIP); } if (!drawing.isEmpty()) { verts.clear(); - verts.reserve(drawing.size()*2); - foreach (const QPoint& p, drawing) { + verts.reserve(drawing.size() * 2); + foreach (const QPoint & p, drawing) { verts << p.x() << p.y(); } - vbo->setData(verts.size()/2, 2, verts.data(), NULL); + vbo->setData(verts.size() / 2, 2, verts.data(), NULL); vbo->render(GL_LINE_STRIP); } if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } - glLineWidth( 1.0 ); + glLineWidth(1.0); #ifndef KWIN_HAVE_OPENGLES - glDisable( GL_LINE_SMOOTH ); + glDisable(GL_LINE_SMOOTH); glPopAttrib(); #endif - } +} -void MouseMarkEffect::mouseChanged( const QPoint& pos, const QPoint&, - Qt::MouseButtons, Qt::MouseButtons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers ) - { - if( modifiers == ( Qt::META | Qt::SHIFT | Qt::CTRL )) // start/finish arrow - { - if( arrow_start != NULL_POINT ) - { - marks.append( createArrow( arrow_start, pos )); +void MouseMarkEffect::mouseChanged(const QPoint& pos, const QPoint&, + Qt::MouseButtons, Qt::MouseButtons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers) +{ + if (modifiers == (Qt::META | Qt::SHIFT | Qt::CTRL)) { // start/finish arrow + if (arrow_start != NULL_POINT) { + marks.append(createArrow(arrow_start, pos)); arrow_start = NULL_POINT; effects->addRepaintFull(); return; - } - else + } else arrow_start = pos; - } - if( arrow_start != NULL_POINT ) + } + if (arrow_start != NULL_POINT) return; // TODO the shortcuts now trigger this right before they're activated - if( modifiers == ( Qt::META | Qt::SHIFT )) // activated - { - if( drawing.isEmpty()) - drawing.append( pos ); - if( drawing.last() == pos ) + if (modifiers == (Qt::META | Qt::SHIFT)) { // activated + if (drawing.isEmpty()) + drawing.append(pos); + if (drawing.last() == pos) return; QPoint pos2 = drawing.last(); - drawing.append( pos ); - QRect repaint = QRect( qMin( pos.x(), pos2.x()), qMin( pos.y(), pos2.y()), - qMax( pos.x(), pos2.x()), qMax( pos.y(), pos2.y())); - repaint.adjust( -width, -width, width, width ); - effects->addRepaint( repaint ); - } - else if( !drawing.isEmpty()) - { - marks.append( drawing ); + drawing.append(pos); + QRect repaint = QRect(qMin(pos.x(), pos2.x()), qMin(pos.y(), pos2.y()), + qMax(pos.x(), pos2.x()), qMax(pos.y(), pos2.y())); + repaint.adjust(-width, -width, width, width); + effects->addRepaint(repaint); + } else if (!drawing.isEmpty()) { + marks.append(drawing); drawing.clear(); - } } +} void MouseMarkEffect::clear() - { +{ drawing.clear(); marks.clear(); effects->addRepaintFull(); - } +} void MouseMarkEffect::clearLast() - { - if( arrow_start != NULL_POINT ) - { +{ + if (arrow_start != NULL_POINT) { arrow_start = NULL_POINT; - } - else if( !drawing.isEmpty()) - { + } else if (!drawing.isEmpty()) { drawing.clear(); effects->addRepaintFull(); - } - else if( !marks.isEmpty()) - { + } else if (!marks.isEmpty()) { marks.pop_back(); effects->addRepaintFull(); - } } +} -MouseMarkEffect::Mark MouseMarkEffect::createArrow( QPoint arrow_start, QPoint arrow_end ) - { +MouseMarkEffect::Mark MouseMarkEffect::createArrow(QPoint arrow_start, QPoint arrow_end) +{ Mark ret; - double angle = atan2( (double) (arrow_end.y() - arrow_start.y()), (double) (arrow_end.x() - arrow_start.x())); - ret += arrow_start + QPoint( 50 * cos( angle + M_PI / 6 ), - 50 * sin( angle + M_PI / 6 )); // right one + double angle = atan2((double)(arrow_end.y() - arrow_start.y()), (double)(arrow_end.x() - arrow_start.x())); + ret += arrow_start + QPoint(50 * cos(angle + M_PI / 6), + 50 * sin(angle + M_PI / 6)); // right one ret += arrow_start; ret += arrow_end; ret += arrow_start; // it's connected lines, so go back with the middle one - ret += arrow_start + QPoint( 50 * cos( angle - M_PI / 6 ), - 50 * sin( angle - M_PI / 6 )); // left one + ret += arrow_start + QPoint(50 * cos(angle - M_PI / 6), + 50 * sin(angle - M_PI / 6)); // left one return ret; - } - +} + } // namespace #include "mousemark.moc" diff --git a/effects/mousemark/mousemark.h b/effects/mousemark/mousemark.h index 11edfb7f4..da222a919 100644 --- a/effects/mousemark/mousemark.h +++ b/effects/mousemark/mousemark.h @@ -29,28 +29,28 @@ namespace KWin class MouseMarkEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - MouseMarkEffect(); - ~MouseMarkEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - private slots: - void clear(); - void clearLast(); - private: - typedef QVector< QPoint > Mark; - static Mark createArrow( QPoint arrow_start, QPoint arrow_end ); - QVector< Mark > marks; - Mark drawing; - QPoint arrow_start; - int width; - QColor color; - }; +public: + MouseMarkEffect(); + ~MouseMarkEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); +private slots: + void clear(); + void clearLast(); +private: + typedef QVector< QPoint > Mark; + static Mark createArrow(QPoint arrow_start, QPoint arrow_end); + QVector< Mark > marks; + Mark drawing; + QPoint arrow_start; + int width; + QColor color; +}; } // namespace diff --git a/effects/mousemark/mousemark_config.cpp b/effects/mousemark/mousemark_config.cpp index 85139e3ed..373bfe951 100644 --- a/effects/mousemark/mousemark_config.cpp +++ b/effects/mousemark/mousemark_config.cpp @@ -38,12 +38,12 @@ KWIN_EFFECT_CONFIG_FACTORY MouseMarkEffectConfigForm::MouseMarkEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } MouseMarkEffectConfig::MouseMarkEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new MouseMarkEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -55,31 +55,31 @@ MouseMarkEffectConfig::MouseMarkEffectConfig(QWidget* parent, const QVariantList connect(m_ui->comboColors, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); - KAction* a = static_cast< KAction* >( m_actionCollection->addAction( "ClearMouseMarks" )); - a->setText( i18n( "Clear Mouse Marks" )); + KAction* a = static_cast< KAction* >(m_actionCollection->addAction("ClearMouseMarks")); + a->setText(i18n("Clear Mouse Marks")); a->setProperty("isConfigurationAction", true); - a->setGlobalShortcut( KShortcut( Qt::SHIFT + Qt::META + Qt::Key_F11 )); + a->setGlobalShortcut(KShortcut(Qt::SHIFT + Qt::META + Qt::Key_F11)); - a = static_cast< KAction* >( m_actionCollection->addAction( "ClearLastMouseMark" )); - a->setText( i18n( "Clear Last Mouse Mark" )); + a = static_cast< KAction* >(m_actionCollection->addAction("ClearLastMouseMark")); + a->setText(i18n("Clear Last Mouse Mark")); a->setProperty("isConfigurationAction", true); - a->setGlobalShortcut( KShortcut( Qt::SHIFT + Qt::META + Qt::Key_F12 )); + a->setGlobalShortcut(KShortcut(Qt::SHIFT + Qt::META + Qt::Key_F12)); m_ui->editor->addCollection(m_actionCollection); load(); - } +} MouseMarkEffectConfig::~MouseMarkEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts m_ui->editor->undoChanges(); - } +} void MouseMarkEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("MouseMark"); @@ -91,10 +91,10 @@ void MouseMarkEffectConfig::load() m_ui->comboColors->setColor(color); emit changed(false); - } +} void MouseMarkEffectConfig::save() - { +{ kDebug(1212) << "Saving config of MouseMark" ; //KCModule::save(); @@ -109,15 +109,15 @@ void MouseMarkEffectConfig::save() conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "mousemark" ); - } + EffectsHandler::sendReloadMessage("mousemark"); +} void MouseMarkEffectConfig::defaults() - { +{ m_ui->spinWidth->setValue(3); m_ui->comboColors->setColor(Qt::red); emit changed(true); - } +} } // namespace diff --git a/effects/mousemark/mousemark_config.h b/effects/mousemark/mousemark_config.h index e54cf357f..6af811231 100644 --- a/effects/mousemark/mousemark_config.h +++ b/effects/mousemark/mousemark_config.h @@ -33,25 +33,25 @@ namespace KWin class MouseMarkEffectConfigForm : public QWidget, public Ui::MouseMarkEffectConfigForm { Q_OBJECT - public: - explicit MouseMarkEffectConfigForm(QWidget* parent); +public: + explicit MouseMarkEffectConfigForm(QWidget* parent); }; class MouseMarkEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit MouseMarkEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual ~MouseMarkEffectConfig(); +public: + explicit MouseMarkEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + virtual ~MouseMarkEffectConfig(); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - MouseMarkEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + MouseMarkEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/presentwindows/presentwindows.cpp b/effects/presentwindows/presentwindows.cpp index 7608a27af..887d6d84d 100644 --- a/effects/presentwindows/presentwindows.cpp +++ b/effects/presentwindows/presentwindows.cpp @@ -46,838 +46,764 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( presentwindows, PresentWindowsEffect ) +KWIN_EFFECT(presentwindows, PresentWindowsEffect) PresentWindowsEffect::PresentWindowsEffect() - : m_proxy( this ) - , m_activated( false ) - , m_ignoreMinimized( false ) - , m_decalOpacity( 0.0 ) - , m_hasKeyboardGrab( false ) - , m_tabBoxEnabled( false ) - , m_mode( ModeCurrentDesktop ) - , m_managerWindow( NULL ) - , m_highlightedWindow( NULL ) - , m_filterFrame( effects->effectFrame( EffectFrameStyled, false ) ) - , m_closeView( NULL ) - { - m_atomDesktop = XInternAtom( display(), "_KDE_PRESENT_WINDOWS_DESKTOP", False ); - m_atomWindows = XInternAtom( display(), "_KDE_PRESENT_WINDOWS_GROUP", False ); - effects->registerPropertyType( m_atomDesktop, true ); - effects->registerPropertyType( m_atomWindows, true ); + : m_proxy(this) + , m_activated(false) + , m_ignoreMinimized(false) + , m_decalOpacity(0.0) + , m_hasKeyboardGrab(false) + , m_tabBoxEnabled(false) + , m_mode(ModeCurrentDesktop) + , m_managerWindow(NULL) + , m_highlightedWindow(NULL) + , m_filterFrame(effects->effectFrame(EffectFrameStyled, false)) + , m_closeView(NULL) +{ + m_atomDesktop = XInternAtom(display(), "_KDE_PRESENT_WINDOWS_DESKTOP", False); + m_atomWindows = XInternAtom(display(), "_KDE_PRESENT_WINDOWS_GROUP", False); + effects->registerPropertyType(m_atomDesktop, true); + effects->registerPropertyType(m_atomWindows, true); // Announce support by creating a dummy version on the root window unsigned char dummy = 0; - XChangeProperty( display(), rootWindow(), m_atomDesktop, m_atomDesktop, 8, PropModeReplace, &dummy, 1 ); - XChangeProperty( display(), rootWindow(), m_atomWindows, m_atomWindows, 8, PropModeReplace, &dummy, 1 ); + XChangeProperty(display(), rootWindow(), m_atomDesktop, m_atomDesktop, 8, PropModeReplace, &dummy, 1); + XChangeProperty(display(), rootWindow(), m_atomWindows, m_atomWindows, 8, PropModeReplace, &dummy, 1); QFont font; - font.setPointSize( font.pointSize() * 2 ); - font.setBold( true ); - m_filterFrame->setFont( font ); + font.setPointSize(font.pointSize() * 2); + font.setBold(true); + m_filterFrame->setFont(font); - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = ( KAction* )actionCollection->addAction( "Expose" ); - a->setText( i18n( "Toggle Present Windows (Current desktop)" )); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F9 )); + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = (KAction*)actionCollection->addAction("Expose"); + a->setText(i18n("Toggle Present Windows (Current desktop)")); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F9)); shortcut = a->globalShortcut(); - connect( a, SIGNAL( triggered(bool) ), this, SLOT( toggleActive() )); - connect( a, SIGNAL( globalShortcutChanged(QKeySequence) ), this, SLOT( globalShortcutChanged(QKeySequence))); - KAction* b = ( KAction* )actionCollection->addAction( "ExposeAll" ); - b->setText( i18n( "Toggle Present Windows (All desktops)" )); - b->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F10 )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggleActive())); + connect(a, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChanged(QKeySequence))); + KAction* b = (KAction*)actionCollection->addAction("ExposeAll"); + b->setText(i18n("Toggle Present Windows (All desktops)")); + b->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F10)); shortcutAll = b->globalShortcut(); - connect( b, SIGNAL( triggered(bool) ), this, SLOT( toggleActiveAllDesktops() )); - connect( b, SIGNAL( globalShortcutChanged(QKeySequence) ), this, SLOT( globalShortcutChangedAll(QKeySequence))); - KAction* c = ( KAction* )actionCollection->addAction( "ExposeClass" ); - c->setText( i18n( "Toggle Present Windows (Window class)" )); - c->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F7 )); - connect( c, SIGNAL( triggered(bool) ), this, SLOT( toggleActiveClass() )); - connect( c, SIGNAL( globalShortcutChanged(QKeySequence) ), this, SLOT( globalShortcutChangedClass(QKeySequence))); + connect(b, SIGNAL(triggered(bool)), this, SLOT(toggleActiveAllDesktops())); + connect(b, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChangedAll(QKeySequence))); + KAction* c = (KAction*)actionCollection->addAction("ExposeClass"); + c->setText(i18n("Toggle Present Windows (Window class)")); + c->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F7)); + connect(c, SIGNAL(triggered(bool)), this, SLOT(toggleActiveClass())); + connect(c, SIGNAL(globalShortcutChanged(QKeySequence)), this, SLOT(globalShortcutChangedClass(QKeySequence))); shortcutClass = c->globalShortcut(); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} PresentWindowsEffect::~PresentWindowsEffect() - { - XDeleteProperty( display(), rootWindow(), m_atomDesktop ); - effects->registerPropertyType( m_atomDesktop, false ); - XDeleteProperty( display(), rootWindow(), m_atomWindows ); - effects->registerPropertyType( m_atomWindows, false ); - foreach( ElectricBorder border, m_borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, m_borderActivateAll ) - { - effects->unreserveElectricBorder( border ); - } +{ + XDeleteProperty(display(), rootWindow(), m_atomDesktop); + effects->registerPropertyType(m_atomDesktop, false); + XDeleteProperty(display(), rootWindow(), m_atomWindows); + effects->registerPropertyType(m_atomWindows, false); + foreach (ElectricBorder border, m_borderActivate) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, m_borderActivateAll) { + effects->unreserveElectricBorder(border); + } delete m_filterFrame; delete m_closeView; - } +} -void PresentWindowsEffect::reconfigure( ReconfigureFlags ) - { +void PresentWindowsEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = effects->effectConfig("PresentWindows"); - foreach( ElectricBorder border, m_borderActivate ) - { - effects->unreserveElectricBorder( border ); - } - foreach( ElectricBorder border, m_borderActivateAll ) - { - effects->unreserveElectricBorder( border ); - } + foreach (ElectricBorder border, m_borderActivate) { + effects->unreserveElectricBorder(border); + } + foreach (ElectricBorder border, m_borderActivateAll) { + effects->unreserveElectricBorder(border); + } m_borderActivate.clear(); m_borderActivateAll.clear(); QList borderList = QList(); - borderList.append( int( ElectricNone ) ); - borderList = conf.readEntry( "BorderActivate", borderList ); - foreach( int i, borderList ) - { - m_borderActivate.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } - borderList.clear(); - borderList.append( int( ElectricTopLeft ) ); - borderList = conf.readEntry( "BorderActivateAll", borderList ); - foreach( int i, borderList ) - { - m_borderActivateAll.append( ElectricBorder( i ) ); - effects->reserveElectricBorder( ElectricBorder( i ) ); - } - m_layoutMode = conf.readEntry( "LayoutMode", int( LayoutNatural )); - m_showCaptions = conf.readEntry( "DrawWindowCaptions", true ); - m_showIcons = conf.readEntry( "DrawWindowIcons", true ); - m_doNotCloseWindows = !conf.readEntry( "AllowClosingWindows", true ); - m_tabBoxAllowed = conf.readEntry( "TabBox", false ); - m_tabBoxAlternativeAllowed = conf.readEntry( "TabBoxAlternative", false ); - m_ignoreMinimized = conf.readEntry( "IgnoreMinimized", false ); - m_accuracy = conf.readEntry( "Accuracy", 1 ) * 20; - m_fillGaps = conf.readEntry( "FillGaps", true ); - m_fadeDuration = double( animationTime( 150 )); - m_showPanel = conf.readEntry( "ShowPanel", false ); - m_leftButtonWindow = (WindowMouseAction)conf.readEntry( "LeftButtonWindow", (int)WindowActivateAction ); - m_middleButtonWindow = (WindowMouseAction)conf.readEntry( "MiddleButtonWindow", (int)WindowNoAction ); - m_rightButtonWindow = (WindowMouseAction)conf.readEntry( "RightButtonWindow", (int)WindowExitAction ); - m_leftButtonDesktop = (DesktopMouseAction)conf.readEntry( "LeftButtonDesktop", (int)DesktopExitAction ); - m_middleButtonDesktop = (DesktopMouseAction)conf.readEntry( "MiddleButtonDesktop", (int)DesktopNoAction ); - m_rightButtonDesktop = (DesktopMouseAction)conf.readEntry( "RightButtonDesktop", (int)DesktopNoAction ); + borderList.append(int(ElectricNone)); + borderList = conf.readEntry("BorderActivate", borderList); + foreach (int i, borderList) { + m_borderActivate.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); } + borderList.clear(); + borderList.append(int(ElectricTopLeft)); + borderList = conf.readEntry("BorderActivateAll", borderList); + foreach (int i, borderList) { + m_borderActivateAll.append(ElectricBorder(i)); + effects->reserveElectricBorder(ElectricBorder(i)); + } + m_layoutMode = conf.readEntry("LayoutMode", int(LayoutNatural)); + m_showCaptions = conf.readEntry("DrawWindowCaptions", true); + m_showIcons = conf.readEntry("DrawWindowIcons", true); + m_doNotCloseWindows = !conf.readEntry("AllowClosingWindows", true); + m_tabBoxAllowed = conf.readEntry("TabBox", false); + m_tabBoxAlternativeAllowed = conf.readEntry("TabBoxAlternative", false); + m_ignoreMinimized = conf.readEntry("IgnoreMinimized", false); + m_accuracy = conf.readEntry("Accuracy", 1) * 20; + m_fillGaps = conf.readEntry("FillGaps", true); + m_fadeDuration = double(animationTime(150)); + m_showPanel = conf.readEntry("ShowPanel", false); + m_leftButtonWindow = (WindowMouseAction)conf.readEntry("LeftButtonWindow", (int)WindowActivateAction); + m_middleButtonWindow = (WindowMouseAction)conf.readEntry("MiddleButtonWindow", (int)WindowNoAction); + m_rightButtonWindow = (WindowMouseAction)conf.readEntry("RightButtonWindow", (int)WindowExitAction); + m_leftButtonDesktop = (DesktopMouseAction)conf.readEntry("LeftButtonDesktop", (int)DesktopExitAction); + m_middleButtonDesktop = (DesktopMouseAction)conf.readEntry("MiddleButtonDesktop", (int)DesktopNoAction); + m_rightButtonDesktop = (DesktopMouseAction)conf.readEntry("RightButtonDesktop", (int)DesktopNoAction); +} void* PresentWindowsEffect::proxy() - { +{ return &m_proxy; - } +} void PresentWindowsEffect::toggleActiveClass() { - if( !m_activated ) - { - if( !effects->activeWindow() ) + if (!m_activated) { + if (!effects->activeWindow()) return; m_mode = ModeWindowClass; m_class = effects->activeWindow()->windowClass(); - } - setActive( !m_activated ); + } + setActive(!m_activated); } //----------------------------------------------------------------------------- // Screen painting -void PresentWindowsEffect::prePaintScreen( ScreenPrePaintData &data, int time ) - { - m_motionManager.calculate( time ); +void PresentWindowsEffect::prePaintScreen(ScreenPrePaintData &data, int time) +{ + m_motionManager.calculate(time); // We need to mark the screen as having been transformed otherwise there will be no repainting - if( m_activated || m_motionManager.managingWindows() ) + if (m_activated || m_motionManager.managingWindows()) data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - if( m_activated ) - m_decalOpacity = qMin( 1.0, m_decalOpacity + time / m_fadeDuration ); + if (m_activated) + m_decalOpacity = qMin(1.0, m_decalOpacity + time / m_fadeDuration); else - m_decalOpacity = qMax( 0.0, m_decalOpacity - time / m_fadeDuration ); + m_decalOpacity = qMax(0.0, m_decalOpacity - time / m_fadeDuration); - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void PresentWindowsEffect::paintScreen( int mask, QRegion region, ScreenPaintData &data ) - { - effects->paintScreen( mask, region, data ); +void PresentWindowsEffect::paintScreen(int mask, QRegion region, ScreenPaintData &data) +{ + effects->paintScreen(mask, region, data); // Display the filter box - if( !m_windowFilter.isEmpty() ) - m_filterFrame->render( region ); - } + if (!m_windowFilter.isEmpty()) + m_filterFrame->render(region); +} void PresentWindowsEffect::postPaintScreen() - { - if( m_motionManager.areWindowsMoving() ) +{ + if (m_motionManager.areWindowsMoving()) effects->addRepaintFull(); - else if( !m_activated && m_motionManager.managingWindows() ) - { // We have finished moving them back, stop processing + else if (!m_activated && m_motionManager.managingWindows()) { + // We have finished moving them back, stop processing m_motionManager.unmanageAll(); DataHash::iterator i = m_windowData.begin(); - while( i != m_windowData.end() ) - { + while (i != m_windowData.end()) { delete i.value().textFrame; delete i.value().iconFrame; i++; - } + } m_windowData.clear(); - foreach( EffectWindow *w, effects->stackingOrder() ) - { - if( w->isDock() ) - { - w->setData( WindowForceBlurRole, QVariant( false ) ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + if (w->isDock()) { + w->setData(WindowForceBlurRole, QVariant(false)); } - effects->setActiveFullScreenEffect( NULL ); } + effects->setActiveFullScreenEffect(NULL); + } // Update windows that are changing brightness or opacity DataHash::const_iterator i; - for( i = m_windowData.constBegin(); i != m_windowData.constEnd(); ++i ) - { - if( i.value().opacity > 0.0 && i.value().opacity < 1.0 ) + for (i = m_windowData.constBegin(); i != m_windowData.constEnd(); ++i) { + if (i.value().opacity > 0.0 && i.value().opacity < 1.0) i.key()->addRepaintFull(); - if( i.value().highlight > 0.0 && i.value().highlight < 1.0 ) + if (i.value().highlight > 0.0 && i.value().highlight < 1.0) i.key()->addRepaintFull(); - } + } effects->postPaintScreen(); - } +} //----------------------------------------------------------------------------- // Window painting -void PresentWindowsEffect::prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ) - { +void PresentWindowsEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) +{ // TODO: We should also check to see if any windows are fading just in case fading takes longer // than moving the windows when the effect is deactivated. - if(( m_activated || m_motionManager.areWindowsMoving() ) && m_windowData.contains( w )) - { - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); // Display always - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - if( m_windowData[w].visible ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP ); + if ((m_activated || m_motionManager.areWindowsMoving()) && m_windowData.contains(w)) { + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); // Display always + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + if (m_windowData[w].visible) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_CLIENT_GROUP); // Calculate window's opacity // TODO: Minimized windows or windows not on the current desktop are only 75% visible? - if( m_windowData[w].visible ) - { - if( m_windowData[w].deleted ) - m_windowData[w].opacity = qMax( 0.0, m_windowData[w].opacity - time / m_fadeDuration ); + if (m_windowData[w].visible) { + if (m_windowData[w].deleted) + m_windowData[w].opacity = qMax(0.0, m_windowData[w].opacity - time / m_fadeDuration); else m_windowData[w].opacity = qMin(/*( w->isMinimized() || !w->isOnCurrentDesktop() ) ? 0.75 :*/ 1.0, - m_windowData[w].opacity + time / m_fadeDuration ); - } - else - m_windowData[w].opacity = qMax( 0.0, m_windowData[w].opacity - time / m_fadeDuration ); - if( m_windowData[w].opacity == 0.0 ) - { + m_windowData[w].opacity + time / m_fadeDuration); + } else + m_windowData[w].opacity = qMax(0.0, m_windowData[w].opacity - time / m_fadeDuration); + if (m_windowData[w].opacity == 0.0) { // don't disable painting for panels if show panel is set - if( !w->isDock() || ( w->isDock() && !m_showPanel )) - w->disablePainting( EffectWindow::PAINT_DISABLED ); - } - else if( m_windowData[w].opacity != 1.0 ) + if (!w->isDock() || (w->isDock() && !m_showPanel)) + w->disablePainting(EffectWindow::PAINT_DISABLED); + } else if (m_windowData[w].opacity != 1.0) data.setTranslucent(); // Calculate window's brightness - if( w == m_highlightedWindow || w == m_closeWindow || !m_activated ) - m_windowData[w].highlight = qMin( 1.0, m_windowData[w].highlight + time / m_fadeDuration ); + if (w == m_highlightedWindow || w == m_closeWindow || !m_activated) + m_windowData[w].highlight = qMin(1.0, m_windowData[w].highlight + time / m_fadeDuration); else - m_windowData[w].highlight = qMax( 0.0, m_windowData[w].highlight - time / m_fadeDuration ); + m_windowData[w].highlight = qMax(0.0, m_windowData[w].highlight - time / m_fadeDuration); - // Closed windows - if( m_windowData[w].deleted ) - { + // Closed windows + if (m_windowData[w].deleted) { data.setTranslucent(); - if( m_windowData[w].opacity <= 0.0 && m_windowData[w].referenced ) - { + if (m_windowData[w].opacity <= 0.0 && m_windowData[w].referenced) { // it's possible that another effect has referenced the window // we have to keep the window in the list to prevent flickering m_windowData[w].referenced = false; w->unrefWindow(); - } - else - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - } + } else + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); + } // desktop windows on other desktops (Plasma activity per desktop) should not be painted - if( w->isDesktop() && !w->isOnCurrentDesktop() ) - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); + if (w->isDesktop() && !w->isOnCurrentDesktop()) + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); - if( m_motionManager.isManaging( w )) + if (m_motionManager.isManaging(w)) data.setTransformed(); // We will be moving this window - } - effects->prePaintWindow( w, data, time ); } + effects->prePaintWindow(w, data, time); +} -void PresentWindowsEffect::paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ) - { - if(( m_activated || m_motionManager.areWindowsMoving() ) && m_windowData.contains( w )) - { - if( w->isDock() && m_showPanel ) - { +void PresentWindowsEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) +{ + if ((m_activated || m_motionManager.areWindowsMoving()) && m_windowData.contains(w)) { + if (w->isDock() && m_showPanel) { // in case the panel should be shown just display it without any changes - effects->paintWindow( w, mask, region, data ); + effects->paintWindow(w, mask, region, data); return; - } + } // Apply opacity and brightness data.opacity *= m_windowData[w].opacity; - data.brightness *= interpolate( 0.7, 1.0, m_windowData[w].highlight ); + data.brightness *= interpolate(0.7, 1.0, m_windowData[w].highlight); - if( m_motionManager.isManaging( w )) - { - m_motionManager.apply( w, data ); + if (m_motionManager.isManaging(w)) { + m_motionManager.apply(w, data); - if( !m_motionManager.areWindowsMoving() ) - { + if (!m_motionManager.areWindowsMoving()) { mask |= PAINT_WINDOW_LANCZOS; - } - effects->paintWindow( w, mask, region, data ); - - QRect rect = m_motionManager.transformedGeometry( w ).toRect(); - if( m_showIcons ) - { - QPoint point( rect.x() + rect.width() * 0.95, - rect.y() + rect.height() * 0.95 ); - m_windowData[w].iconFrame->setPosition( point ); -#ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == KWin::OpenGLCompositing && data.shader ) - { - data.shader->setUniform( "textureWidth", 1.0f ); - data.shader->setUniform( "textureHeight", 1.0f ); - data.shader->setUniform( "opacity", (float)(0.9 * data.opacity * m_decalOpacity * 0.75) ); - } -#endif - m_windowData[w].iconFrame->render( region, 0.9 * data.opacity * m_decalOpacity, 0.75 ); - } - if( m_showCaptions ) - { - QPoint point( rect.x() + rect.width() / 2, - rect.y() + rect.height() / 2 ); - m_windowData[w].textFrame->setPosition( point ); -#ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == KWin::OpenGLCompositing && data.shader ) - { - data.shader->setUniform( "textureWidth", 1.0f ); - data.shader->setUniform( "textureHeight", 1.0f ); - data.shader->setUniform( "opacity", (float)(0.9 * data.opacity * m_decalOpacity * 0.75) ); - } -#endif - m_windowData[w].textFrame->render( region, 0.9 * data.opacity * m_decalOpacity, 0.75 ); - } } - else - effects->paintWindow( w, mask, region, data ); - } - else - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); + + QRect rect = m_motionManager.transformedGeometry(w).toRect(); + if (m_showIcons) { + QPoint point(rect.x() + rect.width() * 0.95, + rect.y() + rect.height() * 0.95); + m_windowData[w].iconFrame->setPosition(point); +#ifdef KWIN_HAVE_OPENGL_COMPOSITING + if (effects->compositingType() == KWin::OpenGLCompositing && data.shader) { + data.shader->setUniform("textureWidth", 1.0f); + data.shader->setUniform("textureHeight", 1.0f); + data.shader->setUniform("opacity", (float)(0.9 * data.opacity * m_decalOpacity * 0.75)); + } +#endif + m_windowData[w].iconFrame->render(region, 0.9 * data.opacity * m_decalOpacity, 0.75); + } + if (m_showCaptions) { + QPoint point(rect.x() + rect.width() / 2, + rect.y() + rect.height() / 2); + m_windowData[w].textFrame->setPosition(point); +#ifdef KWIN_HAVE_OPENGL_COMPOSITING + if (effects->compositingType() == KWin::OpenGLCompositing && data.shader) { + data.shader->setUniform("textureWidth", 1.0f); + data.shader->setUniform("textureHeight", 1.0f); + data.shader->setUniform("opacity", (float)(0.9 * data.opacity * m_decalOpacity * 0.75)); + } +#endif + m_windowData[w].textFrame->render(region, 0.9 * data.opacity * m_decalOpacity, 0.75); + } + } else + effects->paintWindow(w, mask, region, data); + } else + effects->paintWindow(w, mask, region, data); +} //----------------------------------------------------------------------------- // User interaction -void PresentWindowsEffect::windowAdded( EffectWindow *w ) - { - if( !m_activated ) +void PresentWindowsEffect::windowAdded(EffectWindow *w) +{ + if (!m_activated) return; - m_windowData[w].visible = isVisibleWindow( w ); + m_windowData[w].visible = isVisibleWindow(w); m_windowData[w].opacity = 0.0; m_windowData[w].highlight = 0.0; - m_windowData[w].textFrame = effects->effectFrame( EffectFrameUnstyled, false ); + m_windowData[w].textFrame = effects->effectFrame(EffectFrameUnstyled, false); QFont font; - font.setBold( true ); - font.setPointSize( 12 ); - m_windowData[w].textFrame->setFont( font ); - m_windowData[w].iconFrame = effects->effectFrame( EffectFrameUnstyled, false ); - m_windowData[w].iconFrame->setAlignment( Qt::AlignRight | Qt::AlignBottom ); - m_windowData[w].iconFrame->setIcon( w->icon() ); - if( isSelectableWindow( w )) - { - m_motionManager.manage( w ); + font.setBold(true); + font.setPointSize(12); + m_windowData[w].textFrame->setFont(font); + m_windowData[w].iconFrame = effects->effectFrame(EffectFrameUnstyled, false); + m_windowData[w].iconFrame->setAlignment(Qt::AlignRight | Qt::AlignBottom); + m_windowData[w].iconFrame->setIcon(w->icon()); + if (isSelectableWindow(w)) { + m_motionManager.manage(w); rearrangeWindows(); - } - if( w == effects->findWindow( m_closeView->winId() ) ) - { + } + if (w == effects->findWindow(m_closeView->winId())) { m_windowData[w].visible = true; m_windowData[w].highlight = 1.0; m_closeWindow = w; - w->setData( WindowForceBlurRole, QVariant( true ) ); - } + w->setData(WindowForceBlurRole, QVariant(true)); } +} -void PresentWindowsEffect::windowClosed( EffectWindow *w ) - { - if( m_managerWindow == w ) +void PresentWindowsEffect::windowClosed(EffectWindow *w) +{ + if (m_managerWindow == w) m_managerWindow = NULL; - if( !m_windowData.contains( w )) + if (!m_windowData.contains(w)) return; m_windowData[w].deleted = true; m_windowData[w].referenced = true; w->refWindow(); - if( m_highlightedWindow == w ) - setHighlightedWindow( findFirstWindow() ); - if( m_closeWindow == w ) - { + if (m_highlightedWindow == w) + setHighlightedWindow(findFirstWindow()); + if (m_closeWindow == w) { m_closeWindow = 0; return; // don't rearrange - } - rearrangeWindows(); } + rearrangeWindows(); +} -void PresentWindowsEffect::windowDeleted( EffectWindow *w ) - { - if( !m_windowData.contains( w )) +void PresentWindowsEffect::windowDeleted(EffectWindow *w) +{ + if (!m_windowData.contains(w)) return; delete m_windowData[w].textFrame; delete m_windowData[w].iconFrame; - m_windowData.remove( w ); - m_motionManager.unmanage( w ); - } + m_windowData.remove(w); + m_motionManager.unmanage(w); +} -void PresentWindowsEffect::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - Q_UNUSED( old ) - if( !m_activated ) +void PresentWindowsEffect::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + Q_UNUSED(old) + if (!m_activated) return; - if( !m_windowData.contains( w )) + if (!m_windowData.contains(w)) return; rearrangeWindows(); - } +} -bool PresentWindowsEffect::borderActivated( ElectricBorder border ) - { - if( !m_borderActivate.contains( border ) && !m_borderActivateAll.contains( border ) ) +bool PresentWindowsEffect::borderActivated(ElectricBorder border) +{ + if (!m_borderActivate.contains(border) && !m_borderActivateAll.contains(border)) return false; - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return true; - if( m_borderActivate.contains( border ) ) + if (m_borderActivate.contains(border)) toggleActive(); else toggleActiveAllDesktops(); return true; - } +} -void PresentWindowsEffect::windowInputMouseEvent( Window w, QEvent *e ) - { - assert( w == m_input ); - Q_UNUSED( w ); +void PresentWindowsEffect::windowInputMouseEvent(Window w, QEvent *e) +{ + assert(w == m_input); + Q_UNUSED(w); - QMouseEvent* me = static_cast< QMouseEvent* >( e ); - if( m_closeView->geometry().contains( me->pos() ) ) - { - if( !m_closeView->isVisible() ) - { + QMouseEvent* me = static_cast< QMouseEvent* >(e); + if (m_closeView->geometry().contains(me->pos())) { + if (!m_closeView->isVisible()) { updateCloseWindow(); - } - if( m_closeView->isVisible() ) - { - const QPoint widgetPos = m_closeView->mapFromGlobal( me->pos() ); - const QPointF scenePos = m_closeView->mapToScene( widgetPos ); - QMouseEvent event( me->type(), widgetPos, me->pos(), me->button(), me->buttons(), me->modifiers() ); - m_closeView->windowInputMouseEvent( &event ); - return; - } } + if (m_closeView->isVisible()) { + const QPoint widgetPos = m_closeView->mapFromGlobal(me->pos()); + const QPointF scenePos = m_closeView->mapToScene(widgetPos); + QMouseEvent event(me->type(), widgetPos, me->pos(), me->button(), me->buttons(), me->modifiers()); + m_closeView->windowInputMouseEvent(&event); + return; + } + } // Which window are we hovering over? Always trigger as we don't always get move events before clicking // We cannot use m_motionManager.windowAtPoint() as the window might not be visible EffectWindowList windows = m_motionManager.managedWindows(); bool hovering = false; - for( int i = 0; i < windows.size(); i++ ) - { - assert( m_windowData.contains( windows.at( i ))); - if( m_motionManager.transformedGeometry( windows.at( i )).contains( cursorPos() ) && - m_windowData[windows.at( i )].visible && !m_windowData[windows.at( i )].deleted ) - { + for (int i = 0; i < windows.size(); i++) { + assert(m_windowData.contains(windows.at(i))); + if (m_motionManager.transformedGeometry(windows.at(i)).contains(cursorPos()) && + m_windowData[windows.at(i)].visible && !m_windowData[windows.at(i)].deleted) { hovering = true; - if( windows.at( i ) && m_highlightedWindow != windows.at( i )) - setHighlightedWindow( windows.at( i )); + if (windows.at(i) && m_highlightedWindow != windows.at(i)) + setHighlightedWindow(windows.at(i)); break; - } } - if( m_highlightedWindow && m_motionManager.transformedGeometry( m_highlightedWindow ).contains( me->pos() ) ) + } + if (m_highlightedWindow && m_motionManager.transformedGeometry(m_highlightedWindow).contains(me->pos())) updateCloseWindow(); else m_closeView->hide(); - if( e->type() != QEvent::MouseButtonPress ) + if (e->type() != QEvent::MouseButtonPress) return; - if( me->button() == Qt::LeftButton ) - { - if( hovering ) - { + if (me->button() == Qt::LeftButton) { + if (hovering) { // mouse is hovering above a window - use MouseActionsWindow - mouseActionWindow( m_leftButtonWindow ); - } - else - { + mouseActionWindow(m_leftButtonWindow); + } else { // mouse is hovering above desktop - use MouseActionsDesktop - mouseActionDesktop( m_leftButtonDesktop ); - } - } - if( me->button() == Qt::MidButton ) - { - if( hovering ) - { - // mouse is hovering above a window - use MouseActionsWindow - mouseActionWindow( m_middleButtonWindow ); - } - else - { - // mouse is hovering above desktop - use MouseActionsDesktop - mouseActionDesktop( m_middleButtonDesktop ); - } - } - if( me->button() == Qt::RightButton ) - { - if( hovering ) - { - // mouse is hovering above a window - use MouseActionsWindow - mouseActionWindow( m_rightButtonWindow ); - } - else - { - // mouse is hovering above desktop - use MouseActionsDesktop - mouseActionDesktop( m_rightButtonDesktop ); - } + mouseActionDesktop(m_leftButtonDesktop); } } - -void PresentWindowsEffect::mouseActionWindow( WindowMouseAction& action ) - { - switch( action ) - { - case WindowActivateAction: - if( m_highlightedWindow ) - effects->activateWindow( m_highlightedWindow ); - setActive( false ); - break; - case WindowExitAction: - setActive( false ); - break; - case WindowToCurrentDesktopAction: - if( m_highlightedWindow ) - effects->windowToDesktop( m_highlightedWindow, effects->currentDesktop() ); - break; - case WindowToAllDesktopsAction: - if( m_highlightedWindow ) - { - if( m_highlightedWindow->isOnAllDesktops() ) - effects->windowToDesktop( m_highlightedWindow, effects->currentDesktop() ); - else - effects->windowToDesktop( m_highlightedWindow, NET::OnAllDesktops ); - } - break; - case WindowMinimizeAction: - if( m_highlightedWindow ) - { - if( m_highlightedWindow->isMinimized() ) - m_highlightedWindow->unminimize(); - else - m_highlightedWindow->minimize(); - } - break; - case WindowCloseAction: - if( m_highlightedWindow ) - { - m_highlightedWindow->closeWindow(); - } - break; - default: - break; + if (me->button() == Qt::MidButton) { + if (hovering) { + // mouse is hovering above a window - use MouseActionsWindow + mouseActionWindow(m_middleButtonWindow); + } else { + // mouse is hovering above desktop - use MouseActionsDesktop + mouseActionDesktop(m_middleButtonDesktop); } } - -void PresentWindowsEffect::mouseActionDesktop( DesktopMouseAction& action ) - { - switch( action ) - { - case DesktopActivateAction: - if( m_highlightedWindow ) - effects->activateWindow( m_highlightedWindow ); - setActive( false ); - break; - case DesktopExitAction: - setActive( false ); - break; - case DesktopShowDesktopAction: - effects->setShowingDesktop( true ); - setActive( false ); - default: - break; + if (me->button() == Qt::RightButton) { + if (hovering) { + // mouse is hovering above a window - use MouseActionsWindow + mouseActionWindow(m_rightButtonWindow); + } else { + // mouse is hovering above desktop - use MouseActionsDesktop + mouseActionDesktop(m_rightButtonDesktop); } } +} + +void PresentWindowsEffect::mouseActionWindow(WindowMouseAction& action) +{ + switch(action) { + case WindowActivateAction: + if (m_highlightedWindow) + effects->activateWindow(m_highlightedWindow); + setActive(false); + break; + case WindowExitAction: + setActive(false); + break; + case WindowToCurrentDesktopAction: + if (m_highlightedWindow) + effects->windowToDesktop(m_highlightedWindow, effects->currentDesktop()); + break; + case WindowToAllDesktopsAction: + if (m_highlightedWindow) { + if (m_highlightedWindow->isOnAllDesktops()) + effects->windowToDesktop(m_highlightedWindow, effects->currentDesktop()); + else + effects->windowToDesktop(m_highlightedWindow, NET::OnAllDesktops); + } + break; + case WindowMinimizeAction: + if (m_highlightedWindow) { + if (m_highlightedWindow->isMinimized()) + m_highlightedWindow->unminimize(); + else + m_highlightedWindow->minimize(); + } + break; + case WindowCloseAction: + if (m_highlightedWindow) { + m_highlightedWindow->closeWindow(); + } + break; + default: + break; + } +} + +void PresentWindowsEffect::mouseActionDesktop(DesktopMouseAction& action) +{ + switch(action) { + case DesktopActivateAction: + if (m_highlightedWindow) + effects->activateWindow(m_highlightedWindow); + setActive(false); + break; + case DesktopExitAction: + setActive(false); + break; + case DesktopShowDesktopAction: + effects->setShowingDesktop(true); + setActive(false); + default: + break; + } +} -void PresentWindowsEffect::grabbedKeyboardEvent( QKeyEvent *e ) - { - if( e->type() == QEvent::KeyPress ) - { +void PresentWindowsEffect::grabbedKeyboardEvent(QKeyEvent *e) +{ + if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) - if( m_mode == ModeCurrentDesktop && shortcut.contains( e->key() + e->modifiers() ) ) - { + if (m_mode == ModeCurrentDesktop && shortcut.contains(e->key() + e->modifiers())) { toggleActive(); return; - } - if( m_mode == ModeAllDesktops && shortcutAll.contains( e->key() + e->modifiers() ) ) - { + } + if (m_mode == ModeAllDesktops && shortcutAll.contains(e->key() + e->modifiers())) { toggleActiveAllDesktops(); return; - } - if( m_mode == ModeWindowClass && shortcutClass.contains( e->key() + e->modifiers() ) ) - { + } + if (m_mode == ModeWindowClass && shortcutClass.contains(e->key() + e->modifiers())) { toggleActiveClass(); return; - } + } - switch( e->key() ) - { // Wrap only if not auto-repeating - case Qt::Key_Left: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, -1, 0, !e->isAutoRepeat() )); - break; - case Qt::Key_Right: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 1, 0, !e->isAutoRepeat() )); - break; - case Qt::Key_Up: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, -1, !e->isAutoRepeat() )); - break; - case Qt::Key_Down: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, 1, !e->isAutoRepeat() )); - break; - case Qt::Key_Home: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, -1000, 0, false )); - break; - case Qt::Key_End: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 1000, 0, false )); - break; - case Qt::Key_PageUp: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, -1000, false )); - break; - case Qt::Key_PageDown: - if( m_highlightedWindow ) - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, 1000, false )); - break; - case Qt::Key_Backspace: - if( !m_windowFilter.isEmpty() ) - { - m_windowFilter.remove( m_windowFilter.length() - 1, 1 ); - updateFilterFrame(); - rearrangeWindows(); - } - return; - case Qt::Key_Escape: - setActive( false ); - return; - case Qt::Key_Return: - case Qt::Key_Enter: - if( m_highlightedWindow ) - effects->activateWindow( m_highlightedWindow ); - setActive( false ); - return; - case Qt::Key_Tab: - return; // Nothing at the moment - case Qt::Key_Delete: - if( !m_windowFilter.isEmpty() ) - { - m_windowFilter.clear(); - updateFilterFrame(); - rearrangeWindows(); - } - break; - case 0: - return; // HACK: Workaround for Qt bug on unbound keys (#178547) - default: - if( !e->text().isEmpty() ) - { - m_windowFilter.append( e->text() ); - updateFilterFrame(); - rearrangeWindows(); - return; - } - break; + switch(e->key()) { + // Wrap only if not auto-repeating + case Qt::Key_Left: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, -1, 0, !e->isAutoRepeat())); + break; + case Qt::Key_Right: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 1, 0, !e->isAutoRepeat())); + break; + case Qt::Key_Up: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, -1, !e->isAutoRepeat())); + break; + case Qt::Key_Down: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, 1, !e->isAutoRepeat())); + break; + case Qt::Key_Home: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, -1000, 0, false)); + break; + case Qt::Key_End: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 1000, 0, false)); + break; + case Qt::Key_PageUp: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, -1000, false)); + break; + case Qt::Key_PageDown: + if (m_highlightedWindow) + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, 1000, false)); + break; + case Qt::Key_Backspace: + if (!m_windowFilter.isEmpty()) { + m_windowFilter.remove(m_windowFilter.length() - 1, 1); + updateFilterFrame(); + rearrangeWindows(); } + return; + case Qt::Key_Escape: + setActive(false); + return; + case Qt::Key_Return: + case Qt::Key_Enter: + if (m_highlightedWindow) + effects->activateWindow(m_highlightedWindow); + setActive(false); + return; + case Qt::Key_Tab: + return; // Nothing at the moment + case Qt::Key_Delete: + if (!m_windowFilter.isEmpty()) { + m_windowFilter.clear(); + updateFilterFrame(); + rearrangeWindows(); + } + break; + case 0: + return; // HACK: Workaround for Qt bug on unbound keys (#178547) + default: + if (!e->text().isEmpty()) { + m_windowFilter.append(e->text()); + updateFilterFrame(); + rearrangeWindows(); + return; + } + break; } } +} //----------------------------------------------------------------------------- // Tab box -void PresentWindowsEffect::tabBoxAdded( int mode ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void PresentWindowsEffect::tabBoxAdded(int mode) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - if( m_activated ) + if (m_activated) return; - if( (( mode == TabBoxWindowsMode && m_tabBoxAllowed ) || - ( mode == TabBoxWindowsAlternativeMode && m_tabBoxAlternativeAllowed )) && - effects->currentTabBoxWindowList().count() > 0 ) - { + if (((mode == TabBoxWindowsMode && m_tabBoxAllowed) || + (mode == TabBoxWindowsAlternativeMode && m_tabBoxAlternativeAllowed)) && + effects->currentTabBoxWindowList().count() > 0) { m_tabBoxEnabled = true; - setActive( true ); - if( m_activated ) + setActive(true); + if (m_activated) effects->refTabBox(); else m_tabBoxEnabled = false; - } } +} void PresentWindowsEffect::tabBoxClosed() - { - if( m_activated ) - { +{ + if (m_activated) { effects->unrefTabBox(); - setActive( false, true ); + setActive(false, true); m_tabBoxEnabled = false; - } } +} void PresentWindowsEffect::tabBoxUpdated() - { - if( m_activated ) - setHighlightedWindow( effects->currentTabBoxWindow() ); - } +{ + if (m_activated) + setHighlightedWindow(effects->currentTabBoxWindow()); +} -void PresentWindowsEffect::tabBoxKeyEvent( QKeyEvent* event ) - { - if( !m_activated ) +void PresentWindowsEffect::tabBoxKeyEvent(QKeyEvent* event) +{ + if (!m_activated) return; // not using the "normal" grabbedKeyboardEvent as we don't want to filter in tabbox - if( event->type() == QEvent::KeyPress ) - { - switch( event->key() ) - { // Wrap only if not auto-repeating - case Qt::Key_Left: - setHighlightedWindow( relativeWindow( m_highlightedWindow, -1, 0, !event->isAutoRepeat() )); - break; - case Qt::Key_Right: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 1, 0, !event->isAutoRepeat() )); - break; - case Qt::Key_Up: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, -1, !event->isAutoRepeat() )); - break; - case Qt::Key_Down: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, 1, !event->isAutoRepeat() )); - break; - case Qt::Key_Home: - setHighlightedWindow( relativeWindow( m_highlightedWindow, -1000, 0, false )); - break; - case Qt::Key_End: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 1000, 0, false )); - break; - case Qt::Key_PageUp: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, -1000, false )); - break; - case Qt::Key_PageDown: - setHighlightedWindow( relativeWindow( m_highlightedWindow, 0, 1000, false )); - break; - default: - // nothing - break; - } + if (event->type() == QEvent::KeyPress) { + switch(event->key()) { + // Wrap only if not auto-repeating + case Qt::Key_Left: + setHighlightedWindow(relativeWindow(m_highlightedWindow, -1, 0, !event->isAutoRepeat())); + break; + case Qt::Key_Right: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 1, 0, !event->isAutoRepeat())); + break; + case Qt::Key_Up: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, -1, !event->isAutoRepeat())); + break; + case Qt::Key_Down: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, 1, !event->isAutoRepeat())); + break; + case Qt::Key_Home: + setHighlightedWindow(relativeWindow(m_highlightedWindow, -1000, 0, false)); + break; + case Qt::Key_End: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 1000, 0, false)); + break; + case Qt::Key_PageUp: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, -1000, false)); + break; + case Qt::Key_PageDown: + setHighlightedWindow(relativeWindow(m_highlightedWindow, 0, 1000, false)); + break; + default: + // nothing + break; } } +} //----------------------------------------------------------------------------- // Atom handling -void PresentWindowsEffect::propertyNotify( EffectWindow* w, long a ) - { - if( !w || ( a != m_atomDesktop && a != m_atomWindows )) +void PresentWindowsEffect::propertyNotify(EffectWindow* w, long a) +{ + if (!w || (a != m_atomDesktop && a != m_atomWindows)) return; // Not our atom - if( a == m_atomDesktop ) - { - QByteArray byteData = w->readProperty( m_atomDesktop, m_atomDesktop, 32 ); - if( byteData.length() < 1 ) - { + if (a == m_atomDesktop) { + QByteArray byteData = w->readProperty(m_atomDesktop, m_atomDesktop, 32); + if (byteData.length() < 1) { // Property was removed, end present windows - setActive( false ); + setActive(false); return; - } - long* data = reinterpret_cast( byteData.data() ); + } + long* data = reinterpret_cast(byteData.data()); - if( !data[0] ) - { + if (!data[0]) { // Purposely ending present windows by issuing a NULL target - setActive( false ); + setActive(false); return; - } + } // present windows is active so don't do anything - if( m_activated ) + if (m_activated) return; int desktop = data[0]; - if( desktop > effects->numberOfDesktops() ) + if (desktop > effects->numberOfDesktops()) return; - if( desktop == -1 ) + if (desktop == -1) toggleActiveAllDesktops(); - else - { + else { m_mode = ModeSelectedDesktop; m_desktop = desktop; m_managerWindow = w; - setActive( true ); - } + setActive(true); } - else if( a == m_atomWindows ) - { - QByteArray byteData = w->readProperty( m_atomWindows, m_atomWindows, 32 ); - if( byteData.length() < 1 ) - { + } else if (a == m_atomWindows) { + QByteArray byteData = w->readProperty(m_atomWindows, m_atomWindows, 32); + if (byteData.length() < 1) { // Property was removed, end present windows - setActive( false ); + setActive(false); return; - } - long* data = reinterpret_cast( byteData.data() ); + } + long* data = reinterpret_cast(byteData.data()); - if( !data[0] ) - { + if (!data[0]) { // Purposely ending present windows by issuing a NULL target - setActive( false ); + setActive(false); return; - } + } // present windows is active so don't do anything - if( m_activated ) + if (m_activated) return; // for security clear selected windows m_selectedWindows.clear(); - int length = byteData.length() / sizeof( data[0] ); - for( int i=0; ifindWindow( data[i] ); - if( !foundWin ) - { + int length = byteData.length() / sizeof(data[0]); + for (int i = 0; i < length; i++) { + EffectWindow* foundWin = effects->findWindow(data[i]); + if (!foundWin) { kDebug(1212) << "Invalid window targetted for present windows. Requested:" << data[i]; continue; - } - m_selectedWindows.append( foundWin ); } + m_selectedWindows.append(foundWin); + } m_mode = ModeWindowGroup; m_managerWindow = w; - setActive( true ); - } + setActive(true); } +} //----------------------------------------------------------------------------- // Window rearranging void PresentWindowsEffect::rearrangeWindows() - { - if( !m_activated ) +{ + if (!m_activated) return; effects->addRepaintFull(); // Trigger the first repaint @@ -886,224 +812,204 @@ void PresentWindowsEffect::rearrangeWindows() // Work out which windows are on which screens EffectWindowList windowlist; QList windowlists; - for( int i = 0; i < effects->numScreens(); i++ ) - windowlists.append( EffectWindowList() ); + for (int i = 0; i < effects->numScreens(); i++) + windowlists.append(EffectWindowList()); - if( m_windowFilter.isEmpty() ) - { - if( m_tabBoxEnabled ) + if (m_windowFilter.isEmpty()) { + if (m_tabBoxEnabled) // Assume we correctly set things up, should be identical to // m_motionManager except just in a slightly different order. windowlist = effects->currentTabBoxWindowList(); else windowlist = m_motionManager.managedWindows(); - foreach( EffectWindow *w, m_motionManager.managedWindows() ) - { - if( m_windowData[w].deleted ) + foreach (EffectWindow * w, m_motionManager.managedWindows()) { + if (m_windowData[w].deleted) continue; // don't include closed windows - windowlists[w->screen()].append( w ); - assert( m_windowData.contains( w )); + windowlists[w->screen()].append(w); + assert(m_windowData.contains(w)); m_windowData[w].visible = true; - } } - else - { // Can we move this filtering somewhere else? - foreach( EffectWindow *w, m_motionManager.managedWindows() ) - { - assert( m_windowData.contains( w )); - if( m_windowData[w].deleted ) + } else { + // Can we move this filtering somewhere else? + foreach (EffectWindow * w, m_motionManager.managedWindows()) { + assert(m_windowData.contains(w)); + if (m_windowData[w].deleted) continue; // don't include closed windows - if( w->caption().contains( m_windowFilter, Qt::CaseInsensitive ) || - w->windowClass().contains( m_windowFilter, Qt::CaseInsensitive ) || - w->windowRole().contains( m_windowFilter, Qt::CaseInsensitive )) - { - windowlist.append( w ); - windowlists[w->screen()].append( w ); + if (w->caption().contains(m_windowFilter, Qt::CaseInsensitive) || + w->windowClass().contains(m_windowFilter, Qt::CaseInsensitive) || + w->windowRole().contains(m_windowFilter, Qt::CaseInsensitive)) { + windowlist.append(w); + windowlists[w->screen()].append(w); m_windowData[w].visible = true; - } - else + } else m_windowData[w].visible = false; - } } - if( windowlist.isEmpty() ) - { - setHighlightedWindow( NULL ); // TODO: Having a NULL highlighted window isn't really safe + } + if (windowlist.isEmpty()) { + setHighlightedWindow(NULL); // TODO: Having a NULL highlighted window isn't really safe return; - } + } // We filtered out the highlighted window - if( m_highlightedWindow ) - { - assert( m_windowData.contains( m_highlightedWindow )); - if( m_windowData[m_highlightedWindow].visible == false ) - setHighlightedWindow( findFirstWindow() ); - } - else if( m_tabBoxEnabled ) - setHighlightedWindow( effects->currentTabBoxWindow() ); + if (m_highlightedWindow) { + assert(m_windowData.contains(m_highlightedWindow)); + if (m_windowData[m_highlightedWindow].visible == false) + setHighlightedWindow(findFirstWindow()); + } else if (m_tabBoxEnabled) + setHighlightedWindow(effects->currentTabBoxWindow()); else - setHighlightedWindow( findFirstWindow() ); + setHighlightedWindow(findFirstWindow()); int screens = m_tabBoxEnabled ? 1 : effects->numScreens(); - for( int screen = 0; screen < screens; screen++ ) - { + for (int screen = 0; screen < screens; screen++) { EffectWindowList windows; - if( m_tabBoxEnabled ) - { // Kind of cheating here + if (m_tabBoxEnabled) { + // Kind of cheating here screen = effects->activeScreen(); windows = windowlist; - } - else + } else windows = windowlists[screen]; // Don't rearrange if the grid is the same size as what it was before to prevent // windows moving to a better spot if one was filtered out. - if( m_layoutMode == LayoutRegularGrid && - m_gridSizes[screen].columns * m_gridSizes[screen].rows && - windows.size() < m_gridSizes[screen].columns * m_gridSizes[screen].rows && - windows.size() > ( m_gridSizes[screen].columns - 1) * m_gridSizes[screen].rows && - windows.size() > m_gridSizes[screen].columns * ( m_gridSizes[screen].rows - 1 ) && - !m_tabBoxEnabled ) + if (m_layoutMode == LayoutRegularGrid && + m_gridSizes[screen].columns * m_gridSizes[screen].rows && + windows.size() < m_gridSizes[screen].columns * m_gridSizes[screen].rows && + windows.size() > (m_gridSizes[screen].columns - 1) * m_gridSizes[screen].rows && + windows.size() > m_gridSizes[screen].columns *(m_gridSizes[screen].rows - 1) && + !m_tabBoxEnabled) continue; // No point continuing if there is no windows to process - if( !windows.count() ) + if (!windows.count()) continue; - calculateWindowTransformations( windows, screen, m_motionManager ); - } + calculateWindowTransformations(windows, screen, m_motionManager); + } // Resize text frames if required QFontMetrics* metrics = NULL; // All fonts are the same - foreach( EffectWindow *w, m_motionManager.managedWindows() ) - { - if( !metrics ) - metrics = new QFontMetrics( m_windowData[w].textFrame->font() ); - QRect geom = m_motionManager.targetGeometry( w ).toRect(); - QString string = metrics->elidedText( w->caption(), Qt::ElideRight, geom.width() * 0.9 ); - if( string != m_windowData[w].textFrame->text() ) - m_windowData[w].textFrame->setText( string ); - } - delete metrics; + foreach (EffectWindow * w, m_motionManager.managedWindows()) { + if (!metrics) + metrics = new QFontMetrics(m_windowData[w].textFrame->font()); + QRect geom = m_motionManager.targetGeometry(w).toRect(); + QString string = metrics->elidedText(w->caption(), Qt::ElideRight, geom.width() * 0.9); + if (string != m_windowData[w].textFrame->text()) + m_windowData[w].textFrame->setText(string); } + delete metrics; +} -void PresentWindowsEffect::calculateWindowTransformations( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager, bool external ) - { - if( m_layoutMode == LayoutRegularGrid || m_tabBoxEnabled ) // Force the grid for window switching - calculateWindowTransformationsClosest( windowlist, screen, motionManager ); - else if( m_layoutMode == LayoutFlexibleGrid ) - calculateWindowTransformationsKompose( windowlist, screen, motionManager ); +void PresentWindowsEffect::calculateWindowTransformations(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager, bool external) +{ + if (m_layoutMode == LayoutRegularGrid || m_tabBoxEnabled) // Force the grid for window switching + calculateWindowTransformationsClosest(windowlist, screen, motionManager); + else if (m_layoutMode == LayoutFlexibleGrid) + calculateWindowTransformationsKompose(windowlist, screen, motionManager); else - calculateWindowTransformationsNatural( windowlist, screen, motionManager ); + calculateWindowTransformationsNatural(windowlist, screen, motionManager); // If called externally we don't need to remember this data - if( external ) + if (external) m_windowData.clear(); - } +} -void PresentWindowsEffect::calculateWindowTransformationsClosest( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ) - { +void PresentWindowsEffect::calculateWindowTransformationsClosest(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager) +{ // This layout mode requires at least one window visible - if( windowlist.count() == 0 ) + if (windowlist.count() == 0) return; - QRect area = effects->clientArea( ScreenArea, screen, effects->currentDesktop() ); - if( m_showPanel ) // reserve space for the panel - area = effects->clientArea( MaximizeArea, screen, effects->currentDesktop() ); - int columns = int( ceil( sqrt( double( windowlist.count() )))); - int rows = int( ceil( windowlist.count() / double( columns ))); + QRect area = effects->clientArea(ScreenArea, screen, effects->currentDesktop()); + if (m_showPanel) // reserve space for the panel + area = effects->clientArea(MaximizeArea, screen, effects->currentDesktop()); + int columns = int(ceil(sqrt(double(windowlist.count())))); + int rows = int(ceil(windowlist.count() / double(columns))); // Remember the size for later // If we are using this layout externally we don't need to remember m_gridSizes. - if( m_gridSizes.size() != 0 ) - { + if (m_gridSizes.size() != 0) { m_gridSizes[screen].columns = columns; m_gridSizes[screen].rows = rows; - } + } // Assign slots - foreach( EffectWindow *w, windowlist ) - m_windowData[w].slot = -1; - if( m_tabBoxEnabled ) - { // Rearrange in the correct order. As rearrangeWindows() is only ever - // called once so we can use effects->currentTabBoxWindow() here. - int selectedWindow = qMax( 0, windowlist.indexOf( effects->currentTabBoxWindow() )); + foreach (EffectWindow * w, windowlist) + m_windowData[w].slot = -1; + if (m_tabBoxEnabled) { + // Rearrange in the correct order. As rearrangeWindows() is only ever + // called once so we can use effects->currentTabBoxWindow() here. + int selectedWindow = qMax(0, windowlist.indexOf(effects->currentTabBoxWindow())); int slot = 0; - for( int i = selectedWindow; i < windowlist.count(); i++ ) + for (int i = selectedWindow; i < windowlist.count(); i++) m_windowData[windowlist[i]].slot = slot++; - for( int i = selectedWindow - 1; i >= 0; i-- ) + for (int i = selectedWindow - 1; i >= 0; i--) m_windowData[windowlist[i]].slot = slot++; - } - else - { - for(;;) - { + } else { + for (;;) { // Assign each window to the closest available slot - assignSlots( windowlist, area, columns, rows ); + assignSlots(windowlist, area, columns, rows); // Leave only the closest window in each slot, remove further conflicts - getBestAssignments( windowlist ); + getBestAssignments(windowlist); bool allAssigned = true; - foreach( EffectWindow *w, windowlist ) - if( m_windowData[w].slot == -1 ) - { - allAssigned = false; - break; - } - if( allAssigned ) + foreach (EffectWindow * w, windowlist) + if (m_windowData[w].slot == -1) { + allAssigned = false; break; } - } - - int slotWidth = area.width() / columns; - int slotHeight = area.height() / rows; - foreach( EffectWindow *w, windowlist ) - { - assert( m_windowData[w].slot != -1 ); - - // Work out where the slot is - QRect target( - area.x() + ( m_windowData[w].slot % columns ) * slotWidth, - area.y() + ( m_windowData[w].slot / columns ) * slotHeight, - slotWidth, slotHeight ); - target.adjust( 10, 10, -10, -10 ); // Borders - double scale; - if( target.width() / double( w->width() ) < target.height() / double( w->height() )) - { // Center vertically - scale = target.width() / double( w->width() ); - target.moveTop( target.top() + ( target.height() - int( w->height() * scale )) / 2 ); - target.setHeight( int( w->height() * scale )); - } - else - { // Center horizontally - scale = target.height() / double( w->height() ); - target.moveLeft( target.left() + ( target.width() - int( w->width() * scale )) / 2 ); - target.setWidth( int( w->width() * scale )); - } - // Don't scale the windows too much - if( scale > 2.0 || ( scale > 1.0 && ( w->width() > 300 || w->height() > 300 ))) - { - scale = ( w->width() > 300 || w->height() > 300 ) ? 1.0 : 2.0; - target = QRect( - target.center().x() - int( w->width() * scale ) / 2, - target.center().y() - int( w->height() * scale ) / 2, - scale * w->width(), scale * w->height() ); - } - motionManager.moveWindow( w, target ); + if (allAssigned) + break; } } -void PresentWindowsEffect::calculateWindowTransformationsKompose( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ) - { + int slotWidth = area.width() / columns; + int slotHeight = area.height() / rows; + foreach (EffectWindow * w, windowlist) { + assert(m_windowData[w].slot != -1); + + // Work out where the slot is + QRect target( + area.x() + (m_windowData[w].slot % columns) * slotWidth, + area.y() + (m_windowData[w].slot / columns) * slotHeight, + slotWidth, slotHeight); + target.adjust(10, 10, -10, -10); // Borders + double scale; + if (target.width() / double(w->width()) < target.height() / double(w->height())) { + // Center vertically + scale = target.width() / double(w->width()); + target.moveTop(target.top() + (target.height() - int(w->height() * scale)) / 2); + target.setHeight(int(w->height() * scale)); + } else { + // Center horizontally + scale = target.height() / double(w->height()); + target.moveLeft(target.left() + (target.width() - int(w->width() * scale)) / 2); + target.setWidth(int(w->width() * scale)); + } + // Don't scale the windows too much + if (scale > 2.0 || (scale > 1.0 && (w->width() > 300 || w->height() > 300))) { + scale = (w->width() > 300 || w->height() > 300) ? 1.0 : 2.0; + target = QRect( + target.center().x() - int(w->width() * scale) / 2, + target.center().y() - int(w->height() * scale) / 2, + scale * w->width(), scale * w->height()); + } + motionManager.moveWindow(w, target); + } +} + +void PresentWindowsEffect::calculateWindowTransformationsKompose(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager) +{ // This layout mode requires at least one window visible - if( windowlist.count() == 0 ) + if (windowlist.count() == 0) return; - QRect availRect = effects->clientArea( ScreenArea, screen, effects->currentDesktop() ); - if( m_showPanel ) // reserve space for the panel - availRect = effects->clientArea( MaximizeArea, screen, effects->currentDesktop() ); - qSort( windowlist ); // The location of the windows should not depend on the stacking order + QRect availRect = effects->clientArea(ScreenArea, screen, effects->currentDesktop()); + if (m_showPanel) // reserve space for the panel + availRect = effects->clientArea(MaximizeArea, screen, effects->currentDesktop()); + qSort(windowlist); // The location of the windows should not depend on the stacking order // Following code is taken from Kompose 0.5.4, src/komposelayout.cpp @@ -1111,42 +1017,37 @@ void PresentWindowsEffect::calculateWindowTransformationsKompose( EffectWindowLi int rows, columns; double parentRatio = availRect.width() / (double)availRect.height(); // Use more columns than rows when parent's width > parent's height - if ( parentRatio > 1 ) - { - columns = (int)ceil( sqrt((double)windowlist.count()) ); - rows = (int)ceil( (double)windowlist.count() / (double)columns ); - } - else - { - rows = (int)ceil( sqrt((double)windowlist.count()) ); - columns = (int)ceil( (double)windowlist.count() / (double)rows ); + if (parentRatio > 1) { + columns = (int)ceil(sqrt((double)windowlist.count())); + rows = (int)ceil((double)windowlist.count() / (double)columns); + } else { + rows = (int)ceil(sqrt((double)windowlist.count())); + columns = (int)ceil((double)windowlist.count() / (double)rows); } //kDebug(1212) << "Using " << rows << " rows & " << columns << " columns for " << windowlist.count() << " clients"; // Calculate width & height - int w = (availRect.width() - (columns+1) * spacing ) / columns; - int h = (availRect.height() - (rows+1) * spacing ) / rows; + int w = (availRect.width() - (columns + 1) * spacing) / columns; + int h = (availRect.height() - (rows + 1) * spacing) / rows; - EffectWindowList::iterator it( windowlist.begin() ); + EffectWindowList::iterator it(windowlist.begin()); QList geometryRects; QList maxRowHeights; // Process rows - for ( int i=0; i 0 ) - { + if (addW > 0) { usableW = w + addW; - } } + } - if ( ratio == -1 ) - { + if (ratio == -1) { widgetw = w; widgeth = h; - } - else - { - double widthByHeight = widthForHeight( window, usableH ); - double heightByWidth = heightForWidth( window, usableW ); - if ( (ratio >= 1.0 && heightByWidth <= usableH) || - (ratio < 1.0 && widthByHeight > usableW) ) - { + } else { + double widthByHeight = widthForHeight(window, usableH); + double heightByWidth = heightForWidth(window, usableW); + if ((ratio >= 1.0 && heightByWidth <= usableH) || + (ratio < 1.0 && widthByHeight > usableW)) { widgetw = usableW; widgeth = (int)heightByWidth; - } - else if ( (ratio < 1.0 && widthByHeight <= usableW) || - (ratio >= 1.0 && heightByWidth > usableH) ) - { + } else if ((ratio < 1.0 && widthByHeight <= usableW) || + (ratio >= 1.0 && heightByWidth > usableH)) { widgeth = usableH; widgetw = (int)widthByHeight; - } + } // Don't upscale large-ish windows - if( widgetw > window->width() && ( window->width() > 300 || window->height() > 300 )) - { + if (widgetw > window->width() && (window->width() > 300 || window->height() > 300)) { widgetw = window->width(); widgeth = window->height(); - } } + } // Set the Widget's size int alignmentXoffset = 0; int alignmentYoffset = 0; - if ( i==0 && h > widgeth ) + if (i == 0 && h > widgeth) alignmentYoffset = h - widgeth; - if ( j==0 && w > widgetw ) + if (j == 0 && w > widgetw) alignmentXoffset = w - widgetw; - QRect geom( availRect.x() + j * (w + spacing) + spacing + alignmentXoffset + xOffsetFromLastCol, - availRect.y() + i * (h + spacing) + spacing + alignmentYoffset, - widgetw, widgeth ); + QRect geom(availRect.x() + j *(w + spacing) + spacing + alignmentXoffset + xOffsetFromLastCol, + availRect.y() + i *(h + spacing) + spacing + alignmentYoffset, + widgetw, widgeth); geometryRects.append(geom); - // Set the x offset for the next column - if (alignmentXoffset==0) - xOffsetFromLastCol += widgetw-w; + // Set the x offset for the next column + if (alignmentXoffset == 0) + xOffsetFromLastCol += widgetw - w; if (maxHeightInRow < widgeth) maxHeightInRow = widgeth; } @@ -1221,102 +1112,93 @@ void PresentWindowsEffect::calculateWindowTransformationsKompose( EffectWindowLi } int topOffset = 0; - for( int i = 0; i < rows; i++ ) - { - for( int j = 0; j < columns; j++ ) - { - int pos = i*columns + j; - if(pos >= windowlist.count()) + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + int pos = i * columns + j; + if (pos >= windowlist.count()) break; EffectWindow* window = windowlist[pos]; QRect target = geometryRects[pos]; - target.setY( target.y() + topOffset ); + target.setY(target.y() + topOffset); m_windowData[window].slot = pos; - motionManager.moveWindow( window, target ); + motionManager.moveWindow(window, target); //kDebug(1212) << "Window '" << window->caption() << "' gets moved to (" << // mWindowData[window].area.left() << "; " << mWindowData[window].area.right() << // "), scale: " << mWindowData[window].scale << endl; - } - if ( maxRowHeights[i]-h > 0 ) - topOffset += maxRowHeights[i]-h; } + if (maxRowHeights[i] - h > 0) + topOffset += maxRowHeights[i] - h; } +} -void PresentWindowsEffect::calculateWindowTransformationsNatural( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ) - { +void PresentWindowsEffect::calculateWindowTransformationsNatural(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager) +{ // If windows do not overlap they scale into nothingness, fix by resetting. To reproduce // just have a single window on a Xinerama screen or have two windows that do not touch. // TODO: Work out why this happens, is most likely a bug in the manager. - foreach( EffectWindow *w, windowlist ) - if( motionManager.transformedGeometry( w ) == w->geometry() ) - motionManager.reset( w ); + foreach (EffectWindow * w, windowlist) + if (motionManager.transformedGeometry(w) == w->geometry()) + motionManager.reset(w); - if( windowlist.count() == 1 ) - { + if (windowlist.count() == 1) { // Just move the window to its original location to save time - if( effects->clientArea( FullScreenArea, windowlist[0] ).contains( windowlist[0]->geometry() ) ) - { - motionManager.moveWindow( windowlist[0], windowlist[0]->geometry() ); + if (effects->clientArea(FullScreenArea, windowlist[0]).contains(windowlist[0]->geometry())) { + motionManager.moveWindow(windowlist[0], windowlist[0]->geometry()); return; - } } + } // As we are using pseudo-random movement (See "slot") we need to make sure the list // is always sorted the same way no matter which window is currently active. - qSort( windowlist ); + qSort(windowlist); - QRect area = effects->clientArea( ScreenArea, screen, effects->currentDesktop() ); - if( m_showPanel ) // reserve space for the panel - area = effects->clientArea( MaximizeArea, screen, effects->currentDesktop() ); + QRect area = effects->clientArea(ScreenArea, screen, effects->currentDesktop()); + if (m_showPanel) // reserve space for the panel + area = effects->clientArea(MaximizeArea, screen, effects->currentDesktop()); QRect bounds = area; int direction = 0; QHash targets; QHash directions; - foreach( EffectWindow *w, windowlist ) - { - bounds = bounds.united( w->geometry() ); + foreach (EffectWindow * w, windowlist) { + bounds = bounds.united(w->geometry()); targets[w] = w->geometry(); // Reuse the unused "slot" as a preferred direction attribute. This is used when the window // is on the edge of the screen to try to use as much screen real estate as possible. directions[w] = direction; direction++; - if( direction == 4 ) + if (direction == 4) direction = 0; - } - + } + // Iterate over all windows, if two overlap push them apart _slightly_ as we try to // brute-force the most optimal positions over many iterations. bool overlap; - do - { + do { overlap = false; - foreach( EffectWindow *w, windowlist ) - { - foreach( EffectWindow *e, windowlist ) - { - if( w != e && targets[w].adjusted( -5, -5, 5, 5 ).intersects( - targets[e].adjusted( -5, -5, 5, 5 ))) - { + foreach (EffectWindow * w, windowlist) { + foreach (EffectWindow * e, windowlist) { + if (w != e && targets[w].adjusted(-5, -5, 5, 5).intersects( + targets[e].adjusted(-5, -5, 5, 5))) { overlap = true; // Determine pushing direction - QPoint diff( targets[e].center() - targets[w].center() ); + QPoint diff(targets[e].center() - targets[w].center()); // Prevent dividing by zero and non-movement - if( diff.x() == 0 && diff.y() == 0 ) - diff.setX( 1 ); + if (diff.x() == 0 && diff.y() == 0) + diff.setX(1); // Try to keep screen aspect ratio - //if( bounds.height() / bounds.width() > area.height() / area.width() ) + //if ( bounds.height() / bounds.width() > area.height() / area.width() ) // diff.setY( diff.y() / 2 ); //else // diff.setX( diff.x() / 2 ); // Approximate a vector of between 10px and 20px in magnitude in the same direction - diff *= m_accuracy / double( diff.manhattanLength() ); + diff *= m_accuracy / double(diff.manhattanLength()); // Move both windows apart - targets[w].translate( -diff ); - targets[e].translate( diff ); + targets[w].translate(-diff); + targets[e].translate(diff); // Try to keep the bounding rect the same aspect as the screen so that more // screen real estate is utilised. We do this by splitting the screen into nine @@ -1328,781 +1210,718 @@ void PresentWindowsEffect::calculateWindowTransformationsNatural( EffectWindowLi // in some situations. We need to do this even when expanding later just in case // all windows are the same size. // (We are using an old bounding rect for this, hopefully it doesn't matter) - int xSection = ( targets[w].x() - bounds.x() ) / ( bounds.width() / 3 ); - int ySection = ( targets[w].y() - bounds.y() ) / ( bounds.height() / 3 ); - diff = QPoint( 0, 0 ); - if( xSection != 1 || ySection != 1 ) // Remove this if you want the center to pull as well - { - if( xSection == 1 ) - xSection = ( directions[w] / 2 ? 2 : 0 ); - if( ySection == 1 ) - ySection = ( directions[w] % 2 ? 2 : 0 ); - } - if( xSection == 0 && ySection == 0 ) - diff = QPoint( bounds.topLeft() - targets[w].center() ); - if( xSection == 2 && ySection == 0 ) - diff = QPoint( bounds.topRight() - targets[w].center() ); - if( xSection == 2 && ySection == 2 ) - diff = QPoint( bounds.bottomRight() - targets[w].center() ); - if( xSection == 0 && ySection == 2 ) - diff = QPoint( bounds.bottomLeft() - targets[w].center() ); - if( diff.x() != 0 || diff.y() != 0 ) - { - diff *= m_accuracy / double( diff.manhattanLength() ); - targets[w].translate( diff ); - } - - // Update bounding rect - bounds = bounds.united( targets[w] ); - bounds = bounds.united( targets[e] ); + int xSection = (targets[w].x() - bounds.x()) / (bounds.width() / 3); + int ySection = (targets[w].y() - bounds.y()) / (bounds.height() / 3); + diff = QPoint(0, 0); + if (xSection != 1 || ySection != 1) { // Remove this if you want the center to pull as well + if (xSection == 1) + xSection = (directions[w] / 2 ? 2 : 0); + if (ySection == 1) + ySection = (directions[w] % 2 ? 2 : 0); } + if (xSection == 0 && ySection == 0) + diff = QPoint(bounds.topLeft() - targets[w].center()); + if (xSection == 2 && ySection == 0) + diff = QPoint(bounds.topRight() - targets[w].center()); + if (xSection == 2 && ySection == 2) + diff = QPoint(bounds.bottomRight() - targets[w].center()); + if (xSection == 0 && ySection == 2) + diff = QPoint(bounds.bottomLeft() - targets[w].center()); + if (diff.x() != 0 || diff.y() != 0) { + diff *= m_accuracy / double(diff.manhattanLength()); + targets[w].translate(diff); + } + + // Update bounding rect + bounds = bounds.united(targets[w]); + bounds = bounds.united(targets[e]); } } - } while( overlap ); + } + } while (overlap); // Work out scaling by getting the most top-left and most bottom-right window coords. // The 20's and 10's are so that the windows don't touch the edge of the screen. double scale; - if( bounds == area ) + if (bounds == area) scale = 1.0; // Don't add borders to the screen - else if( area.width() / double( bounds.width() ) < area.height() / double( bounds.height() )) - scale = ( area.width() - 20 ) / double( bounds.width() ); + else if (area.width() / double(bounds.width()) < area.height() / double(bounds.height())) + scale = (area.width() - 20) / double(bounds.width()); else - scale = ( area.height() - 20 ) / double( bounds.height() ); + scale = (area.height() - 20) / double(bounds.height()); // Make bounding rect fill the screen size for later steps bounds = QRect( - bounds.x() - ( area.width() - 20 - bounds.width() * scale ) / 2 - 10 / scale, - bounds.y() - ( area.height() - 20 - bounds.height() * scale ) / 2 - 10 / scale, - area.width() / scale, - area.height() / scale - ); + bounds.x() - (area.width() - 20 - bounds.width() * scale) / 2 - 10 / scale, + bounds.y() - (area.height() - 20 - bounds.height() * scale) / 2 - 10 / scale, + area.width() / scale, + area.height() / scale + ); // Move all windows back onto the screen and set their scale - foreach( EffectWindow *w, windowlist ) - targets[w] = QRect( - ( targets[w].x() - bounds.x() ) * scale + area.x(), - ( targets[w].y() - bounds.y() ) * scale + area.y(), - targets[w].width() * scale, - targets[w].height() * scale - ); + foreach (EffectWindow * w, windowlist) + targets[w] = QRect( + (targets[w].x() - bounds.x()) * scale + area.x(), + (targets[w].y() - bounds.y()) * scale + area.y(), + targets[w].width() * scale, + targets[w].height() * scale + ); // Try to fill the gaps by enlarging windows if they have the space - if( m_fillGaps ) - { + if (m_fillGaps) { // Don't expand onto or over the border - QRegion borderRegion( area.adjusted( -200, -200, 200, 200 )); - borderRegion ^= area.adjusted( 10 / scale, 10 / scale, -10 / scale, -10 / scale ); - + QRegion borderRegion(area.adjusted(-200, -200, 200, 200)); + borderRegion ^= area.adjusted(10 / scale, 10 / scale, -10 / scale, -10 / scale); + bool moved; - do - { + do { moved = false; - foreach( EffectWindow *w, windowlist ) - { + foreach (EffectWindow * w, windowlist) { QRect oldRect; // This may cause some slight distortion if the windows are enlarged a large amount int widthDiff = m_accuracy; - int heightDiff = heightForWidth( w, targets[w].width() + widthDiff ) - targets[w].height(); + int heightDiff = heightForWidth(w, targets[w].width() + widthDiff) - targets[w].height(); int xDiff = widthDiff / 2; // Also move a bit in the direction of the enlarge, allows the int yDiff = heightDiff / 2; // center windows to be enlarged if there is gaps on the side. - + // Attempt enlarging to the top-right oldRect = targets[w]; targets[w] = QRect( - targets[w].x() + xDiff, - targets[w].y() - yDiff - heightDiff, - targets[w].width() + widthDiff, - targets[w].height() + heightDiff - ); - if( isOverlappingAny( w, targets, borderRegion )) + targets[w].x() + xDiff, + targets[w].y() - yDiff - heightDiff, + targets[w].width() + widthDiff, + targets[w].height() + heightDiff + ); + if (isOverlappingAny(w, targets, borderRegion)) targets[w] = oldRect; else moved = true; - + // Attempt enlarging to the bottom-right oldRect = targets[w]; targets[w] = QRect( - targets[w].x() + xDiff, - targets[w].y() + yDiff, - targets[w].width() + widthDiff, - targets[w].height() + heightDiff - ); - if( isOverlappingAny( w, targets, borderRegion )) + targets[w].x() + xDiff, + targets[w].y() + yDiff, + targets[w].width() + widthDiff, + targets[w].height() + heightDiff + ); + if (isOverlappingAny(w, targets, borderRegion)) targets[w] = oldRect; else moved = true; - + // Attempt enlarging to the bottom-left oldRect = targets[w]; targets[w] = QRect( - targets[w].x() - xDiff - widthDiff, - targets[w].y() + yDiff, - targets[w].width() + widthDiff, - targets[w].height() + heightDiff - ); - if( isOverlappingAny( w, targets, borderRegion )) + targets[w].x() - xDiff - widthDiff, + targets[w].y() + yDiff, + targets[w].width() + widthDiff, + targets[w].height() + heightDiff + ); + if (isOverlappingAny(w, targets, borderRegion)) targets[w] = oldRect; else moved = true; - + // Attempt enlarging to the top-left oldRect = targets[w]; targets[w] = QRect( - targets[w].x() - xDiff - widthDiff, - targets[w].y() - yDiff - heightDiff, - targets[w].width() + widthDiff, - targets[w].height() + heightDiff - ); - if( isOverlappingAny( w, targets, borderRegion )) + targets[w].x() - xDiff - widthDiff, + targets[w].y() - yDiff - heightDiff, + targets[w].width() + widthDiff, + targets[w].height() + heightDiff + ); + if (isOverlappingAny(w, targets, borderRegion)) targets[w] = oldRect; else moved = true; - } - } while( moved ); + } + } while (moved); // The expanding code above can actually enlarge windows over 1.0/2.0 scale, we don't like this // We can't add this to the loop above as it would cause a never-ending loop so we have to make // do with the less-than-optimal space usage with using this method. - foreach( EffectWindow *w, windowlist ) - { - double scale = targets[w].width() / double( w->width() ); - if( scale > 2.0 || ( scale > 1.0 && ( w->width() > 300 || w->height() > 300 ))) - { - scale = ( w->width() > 300 || w->height() > 300 ) ? 1.0 : 2.0; - targets[w] = QRect( - targets[w].center().x() - int( w->width() * scale ) / 2, - targets[w].center().y() - int( w->height() * scale ) / 2, - w->width() * scale, - w->height() * scale ); - } + foreach (EffectWindow * w, windowlist) { + double scale = targets[w].width() / double(w->width()); + if (scale > 2.0 || (scale > 1.0 && (w->width() > 300 || w->height() > 300))) { + scale = (w->width() > 300 || w->height() > 300) ? 1.0 : 2.0; + targets[w] = QRect( + targets[w].center().x() - int(w->width() * scale) / 2, + targets[w].center().y() - int(w->height() * scale) / 2, + w->width() * scale, + w->height() * scale); } } + } // Notify the motion manager of the targets - foreach( EffectWindow *w, windowlist ) - motionManager.moveWindow( w, targets[w] ); - } + foreach (EffectWindow * w, windowlist) + motionManager.moveWindow(w, targets[w]); +} //----------------------------------------------------------------------------- // Helper functions for window rearranging -void PresentWindowsEffect::assignSlots( EffectWindowList windowlist, const QRect &area, int columns, int rows ) - { +void PresentWindowsEffect::assignSlots(EffectWindowList windowlist, const QRect &area, int columns, int rows) +{ QVector< bool > taken; - taken.fill( false, columns * rows ); - foreach( EffectWindow* w, windowlist ) - if( m_windowData[w].slot != -1 ) - taken[ m_windowData[w].slot ] = true; + taken.fill(false, columns * rows); + foreach (EffectWindow * w, windowlist) + if (m_windowData[w].slot != -1) + taken[ m_windowData[w].slot ] = true; int slotWidth = area.width() / columns; int slotHeight = area.height() / rows; - foreach( EffectWindow *w, windowlist ) - { + foreach (EffectWindow * w, windowlist) { WindowData *wData = &m_windowData[w]; - if( wData->slot != -1 ) + if (wData->slot != -1) continue; // it already has a slot QPoint pos = w->geometry().center(); - if( pos.x() < area.left() ) - pos.setX( area.left() ); - if( pos.x() > area.right() ) - pos.setX( area.right() ); - if( pos.y() < area.top() ) - pos.setY( area.top() ); - if( pos.y() > area.bottom() ) - pos.setY( area.bottom() ); + if (pos.x() < area.left()) + pos.setX(area.left()); + if (pos.x() > area.right()) + pos.setX(area.right()); + if (pos.y() < area.top()) + pos.setY(area.top()); + if (pos.y() > area.bottom()) + pos.setY(area.bottom()); int distance = INT_MAX; - for( int x = 0; x < columns; x++ ) - for( int y = 0; y < rows; y++ ) - { + for (int x = 0; x < columns; x++) + for (int y = 0; y < rows; y++) { int slot = x + y * columns; - if( taken[slot] ) + if (taken[slot]) continue; - int xdiff = pos.x() - ( area.x() + slotWidth * x + slotWidth / 2 ); - int ydiff = pos.y() - ( area.y() + slotHeight * y + slotHeight / 2 ); - int dist = int( sqrt( double( xdiff * xdiff + ydiff * ydiff ))); - if( dist < distance ) - { + int xdiff = pos.x() - (area.x() + slotWidth * x + slotWidth / 2); + int ydiff = pos.y() - (area.y() + slotHeight * y + slotHeight / 2); + int dist = int(sqrt(double(xdiff * xdiff + ydiff * ydiff))); + if (dist < distance) { distance = dist; wData->slot = slot; wData->slot_distance = distance; - } } - } - } - -void PresentWindowsEffect::getBestAssignments( EffectWindowList windowlist ) - { - foreach( EffectWindow* w1, windowlist ) - { - WindowData *windowData1 = &m_windowData[w1]; - foreach( EffectWindow* w2, windowlist ) - { - WindowData *windowData2 = &m_windowData[w2]; - if( w1 != w2 && windowData1->slot == windowData2->slot && - windowData1->slot_distance >= windowData2->slot_distance ) - windowData1->slot = -1; } + } +} + +void PresentWindowsEffect::getBestAssignments(EffectWindowList windowlist) +{ + foreach (EffectWindow * w1, windowlist) { + WindowData *windowData1 = &m_windowData[w1]; + foreach (EffectWindow * w2, windowlist) { + WindowData *windowData2 = &m_windowData[w2]; + if (w1 != w2 && windowData1->slot == windowData2->slot && + windowData1->slot_distance >= windowData2->slot_distance) + windowData1->slot = -1; } } +} -bool PresentWindowsEffect::isOverlappingAny( EffectWindow *w, const QHash &targets, const QRegion &border ) - { - if( border.intersects( targets[w] )) +bool PresentWindowsEffect::isOverlappingAny(EffectWindow *w, const QHash &targets, const QRegion &border) +{ + if (border.intersects(targets[w])) return true; // Is there a better way to do this? QHash::const_iterator i; - for( i = targets.constBegin(); i != targets.constEnd(); ++i ) - { - if( w == i.key() ) + for (i = targets.constBegin(); i != targets.constEnd(); ++i) { + if (w == i.key()) continue; - if( targets[w].adjusted( -5, -5, 5, 5 ).intersects( - i.value().adjusted( -5, -5, 5, 5 ))) + if (targets[w].adjusted(-5, -5, 5, 5).intersects( + i.value().adjusted(-5, -5, 5, 5))) return true; - } - return false; } + return false; +} //----------------------------------------------------------------------------- // Activation -void PresentWindowsEffect::setActive( bool active, bool closingTab ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void PresentWindowsEffect::setActive(bool active, bool closingTab) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - if( m_activated == active ) + if (m_activated == active) return; - if( m_activated && m_tabBoxEnabled && !closingTab ) - { + if (m_activated && m_tabBoxEnabled && !closingTab) { effects->closeTabBox(); return; - } + } m_activated = active; - if( m_activated ) - { + if (m_activated) { m_decalOpacity = 0.0; m_highlightedWindow = NULL; m_windowFilter.clear(); m_closeView = new CloseWindowView(); - connect( m_closeView, SIGNAL(close()), SLOT(closeWindow()) ); + connect(m_closeView, SIGNAL(close()), SLOT(closeWindow())); // Add every single window to m_windowData (Just calling [w] creates it) - foreach( EffectWindow *w, effects->stackingOrder() ) - { - if( m_windowData.contains( w )) // Happens if we reactivate before the ending animation finishes + foreach (EffectWindow * w, effects->stackingOrder()) { + if (m_windowData.contains(w)) // Happens if we reactivate before the ending animation finishes continue; - m_windowData[w].visible = isVisibleWindow( w ); + m_windowData[w].visible = isVisibleWindow(w); m_windowData[w].deleted = false; m_windowData[w].referenced = false; m_windowData[w].opacity = 0.0; - if( w->isOnCurrentDesktop() && !w->isMinimized() ) + if (w->isOnCurrentDesktop() && !w->isMinimized()) m_windowData[w].opacity = 1.0; m_windowData[w].highlight = 1.0; - m_windowData[w].textFrame = effects->effectFrame( EffectFrameUnstyled, false ); + m_windowData[w].textFrame = effects->effectFrame(EffectFrameUnstyled, false); QFont font; - font.setBold( true ); - font.setPointSize( 12 ); - m_windowData[w].textFrame->setFont( font ); - m_windowData[w].iconFrame = effects->effectFrame( EffectFrameUnstyled, false ); - m_windowData[w].iconFrame->setAlignment( Qt::AlignRight | Qt::AlignBottom ); - m_windowData[w].iconFrame->setIcon( w->icon() ); - } + font.setBold(true); + font.setPointSize(12); + m_windowData[w].textFrame->setFont(font); + m_windowData[w].iconFrame = effects->effectFrame(EffectFrameUnstyled, false); + m_windowData[w].iconFrame->setAlignment(Qt::AlignRight | Qt::AlignBottom); + m_windowData[w].iconFrame->setIcon(w->icon()); + } - if( m_tabBoxEnabled ) - { - foreach( EffectWindow *w, effects->currentTabBoxWindowList() ) - { - if( !w ) + if (m_tabBoxEnabled) { + foreach (EffectWindow * w, effects->currentTabBoxWindowList()) { + if (!w) continue; - m_motionManager.manage( w ); - assert( m_windowData.contains( w )); - m_windowData[w].visible = effects->currentTabBoxWindowList().contains( w ); - } + m_motionManager.manage(w); + assert(m_windowData.contains(w)); + m_windowData[w].visible = effects->currentTabBoxWindowList().contains(w); + } // Hide windows not in the list - foreach( EffectWindow *w, effects->stackingOrder() ) - m_windowData[w].visible = isVisibleWindow( w ) && - (!isSelectableWindow( w ) || effects->currentTabBoxWindowList().contains( w )); - } - else - { + foreach (EffectWindow * w, effects->stackingOrder()) + m_windowData[w].visible = isVisibleWindow(w) && + (!isSelectableWindow(w) || effects->currentTabBoxWindowList().contains(w)); + } else { // Filter out special windows such as panels and taskbars - foreach( EffectWindow *w, effects->stackingOrder() ) - if( isSelectableWindow( w )) - m_motionManager.manage( w ); - } - if( m_motionManager.managedWindows().isEmpty() || - (( m_motionManager.managedWindows().count() == 1 ) && m_motionManager.managedWindows().first()->isOnCurrentDesktop() && - ( m_ignoreMinimized || !m_motionManager.managedWindows().first()->isMinimized() ) )) - { // No point triggering if there is nothing to do + foreach (EffectWindow * w, effects->stackingOrder()) + if (isSelectableWindow(w)) + m_motionManager.manage(w); + } + if (m_motionManager.managedWindows().isEmpty() || + ((m_motionManager.managedWindows().count() == 1) && m_motionManager.managedWindows().first()->isOnCurrentDesktop() && + (m_ignoreMinimized || !m_motionManager.managedWindows().first()->isMinimized()))) { + // No point triggering if there is nothing to do m_activated = false; DataHash::iterator i = m_windowData.begin(); - while( i != m_windowData.end() ) - { + while (i != m_windowData.end()) { delete i.value().textFrame; delete i.value().iconFrame; i++; - } + } m_windowData.clear(); m_motionManager.unmanageAll(); return; - } + } // Create temporary input window to catch mouse events - m_input = effects->createFullScreenInputWindow( this, Qt::PointingHandCursor ); - m_hasKeyboardGrab = effects->grabKeyboard( this ); - effects->setActiveFullScreenEffect( this ); + m_input = effects->createFullScreenInputWindow(this, Qt::PointingHandCursor); + m_hasKeyboardGrab = effects->grabKeyboard(this); + effects->setActiveFullScreenEffect(this); m_gridSizes.clear(); - for( int i = 0; i < effects->numScreens(); i++ ) - m_gridSizes.append( GridSize() ); + for (int i = 0; i < effects->numScreens(); i++) + m_gridSizes.append(GridSize()); rearrangeWindows(); - if( m_tabBoxEnabled ) - setHighlightedWindow( effects->currentTabBoxWindow() ); + if (m_tabBoxEnabled) + setHighlightedWindow(effects->currentTabBoxWindow()); else - setHighlightedWindow( effects->activeWindow() ); + setHighlightedWindow(effects->activeWindow()); - foreach( EffectWindow *w, effects->stackingOrder() ) - { - if( w->isDock() ) - { - w->setData( WindowForceBlurRole, QVariant( true ) ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + if (w->isDock()) { + w->setData(WindowForceBlurRole, QVariant(true)); } } - else - { + } else { // Fade in/out all windows EffectWindow *activeWindow = effects->activeWindow(); - if( m_tabBoxEnabled ) + if (m_tabBoxEnabled) activeWindow = effects->currentTabBoxWindow(); int desktop = effects->currentDesktop(); - if( activeWindow && !activeWindow->isOnAllDesktops() ) + if (activeWindow && !activeWindow->isOnAllDesktops()) desktop = activeWindow->desktop(); - foreach( EffectWindow *w, effects->stackingOrder() ) - { - assert( m_windowData.contains( w )); - m_windowData[w].visible = ( w->isOnDesktop( desktop ) || w->isOnAllDesktops() ) && - !w->isMinimized() && ( w->visibleInClientGroup() || m_windowData[w].visible ); - } + foreach (EffectWindow * w, effects->stackingOrder()) { + assert(m_windowData.contains(w)); + m_windowData[w].visible = (w->isOnDesktop(desktop) || w->isOnAllDesktops()) && + !w->isMinimized() && (w->visibleInClientGroup() || m_windowData[w].visible); + } delete m_closeView; m_closeView = 0; // Move all windows back to their original position - foreach( EffectWindow *w, m_motionManager.managedWindows() ) - m_motionManager.moveWindow( w, w->geometry() ); + foreach (EffectWindow * w, m_motionManager.managedWindows()) + m_motionManager.moveWindow(w, w->geometry()); m_filterFrame->free(); m_windowFilter.clear(); m_selectedWindows.clear(); - effects->destroyInputWindow( m_input ); - if( m_hasKeyboardGrab ) + effects->destroyInputWindow(m_input); + if (m_hasKeyboardGrab) effects->ungrabKeyboard(); m_hasKeyboardGrab = false; // destroy atom on manager window - if( m_managerWindow ) - { - if( m_mode == ModeSelectedDesktop ) - m_managerWindow->deleteProperty( m_atomDesktop ); - else if( m_mode == ModeWindowGroup ) - m_managerWindow->deleteProperty( m_atomWindows ); + if (m_managerWindow) { + if (m_mode == ModeSelectedDesktop) + m_managerWindow->deleteProperty(m_atomDesktop); + else if (m_mode == ModeWindowGroup) + m_managerWindow->deleteProperty(m_atomWindows); m_managerWindow = NULL; - } } - effects->addRepaintFull(); // Trigger the first repaint } + effects->addRepaintFull(); // Trigger the first repaint +} //----------------------------------------------------------------------------- // Filter box void PresentWindowsEffect::updateFilterFrame() - { - QRect area = effects->clientArea( ScreenArea, effects->activeScreen(), effects->currentDesktop() ); - m_filterFrame->setPosition( QPoint( area.x() + area.width() / 2, area.y() + area.height() / 2 )); - m_filterFrame->setText( i18n( "Filter:\n%1", m_windowFilter )); - } +{ + QRect area = effects->clientArea(ScreenArea, effects->activeScreen(), effects->currentDesktop()); + m_filterFrame->setPosition(QPoint(area.x() + area.width() / 2, area.y() + area.height() / 2)); + m_filterFrame->setText(i18n("Filter:\n%1", m_windowFilter)); +} //----------------------------------------------------------------------------- // Helper functions -bool PresentWindowsEffect::isSelectableWindow( EffectWindow *w ) - { - if( w->isSpecialWindow() || w->isUtility() ) +bool PresentWindowsEffect::isSelectableWindow(EffectWindow *w) +{ + if (w->isSpecialWindow() || w->isUtility()) return false; - if( w->isDeleted() ) + if (w->isDeleted()) return false; - if( !w->acceptsFocus() ) + if (!w->acceptsFocus()) return false; - if( !w->visibleInClientGroup() ) + if (!w->visibleInClientGroup()) return false; - if( w->isSkipSwitcher() ) + if (w->isSkipSwitcher()) return false; - if( w == effects->findWindow( m_closeView->winId() ) ) + if (w == effects->findWindow(m_closeView->winId())) return false; - if( m_tabBoxEnabled ) + if (m_tabBoxEnabled) return true; - if ( m_ignoreMinimized && w->isMinimized() ) + if (m_ignoreMinimized && w->isMinimized()) return false; - switch( m_mode ) - { - default: - case ModeAllDesktops: - return true; - case ModeCurrentDesktop: - return w->isOnCurrentDesktop(); - case ModeSelectedDesktop: - return w->isOnDesktop( m_desktop ); - case ModeWindowGroup: - return m_selectedWindows.contains( w ); - case ModeWindowClass: - return m_class == w->windowClass(); - } - } - -bool PresentWindowsEffect::isVisibleWindow( EffectWindow *w ) - { - if( w->isDesktop() ) + switch(m_mode) { + default: + case ModeAllDesktops: return true; - return isSelectableWindow( w ); + case ModeCurrentDesktop: + return w->isOnCurrentDesktop(); + case ModeSelectedDesktop: + return w->isOnDesktop(m_desktop); + case ModeWindowGroup: + return m_selectedWindows.contains(w); + case ModeWindowClass: + return m_class == w->windowClass(); } +} -void PresentWindowsEffect::setHighlightedWindow( EffectWindow *w ) - { - if( w == m_highlightedWindow || ( w != NULL && !m_motionManager.isManaging( w ))) +bool PresentWindowsEffect::isVisibleWindow(EffectWindow *w) +{ + if (w->isDesktop()) + return true; + return isSelectableWindow(w); +} + +void PresentWindowsEffect::setHighlightedWindow(EffectWindow *w) +{ + if (w == m_highlightedWindow || (w != NULL && !m_motionManager.isManaging(w))) return; m_closeView->hide(); - if( m_highlightedWindow ) + if (m_highlightedWindow) m_highlightedWindow->addRepaintFull(); // Trigger the first repaint m_highlightedWindow = w; - if( m_highlightedWindow ) + if (m_highlightedWindow) m_highlightedWindow->addRepaintFull(); // Trigger the first repaint - if( m_tabBoxEnabled && m_highlightedWindow ) - effects->setTabBoxWindow( w ); + if (m_tabBoxEnabled && m_highlightedWindow) + effects->setTabBoxWindow(w); updateCloseWindow(); - } +} void PresentWindowsEffect::updateCloseWindow() - { - if ( m_doNotCloseWindows ) +{ + if (m_doNotCloseWindows) return; - if( m_closeView->isVisible() ) + if (m_closeView->isVisible()) return; - if( !m_highlightedWindow ) - { + if (!m_highlightedWindow) { m_closeView->hide(); return; - } - const QRectF rect = m_motionManager.targetGeometry( m_highlightedWindow ); - m_closeView->setGeometry( rect.x() + rect.width() - m_closeView->sceneRect().width(), rect.y(), - m_closeView->sceneRect().width(), m_closeView->sceneRect().height() ); - if( rect.contains( effects->cursorPos() ) ) + } + const QRectF rect = m_motionManager.targetGeometry(m_highlightedWindow); + m_closeView->setGeometry(rect.x() + rect.width() - m_closeView->sceneRect().width(), rect.y(), + m_closeView->sceneRect().width(), m_closeView->sceneRect().height()); + if (rect.contains(effects->cursorPos())) m_closeView->delayedShow(); else m_closeView->hide(); - } +} void PresentWindowsEffect::closeWindow() - { - if( m_highlightedWindow ) +{ + if (m_highlightedWindow) m_highlightedWindow->closeWindow(); - } +} -EffectWindow* PresentWindowsEffect::relativeWindow( EffectWindow *w, int xdiff, int ydiff, bool wrap ) const - { // TODO: Is it possible to select hidden windows? +EffectWindow* PresentWindowsEffect::relativeWindow(EffectWindow *w, int xdiff, int ydiff, bool wrap) const +{ + // TODO: Is it possible to select hidden windows? EffectWindow* next; - QRect area = effects->clientArea( FullArea, 0, effects->currentDesktop() ); + QRect area = effects->clientArea(FullArea, 0, effects->currentDesktop()); QRect detectRect; // Detect across the width of the desktop - if( xdiff != 0 ) - { - if( xdiff > 0 ) - { // Detect right - for( int i = 0; i < xdiff; i++ ) - { - QRectF wArea = m_motionManager.transformedGeometry( w ); - detectRect = QRect( 0, wArea.y(), area.width(), wArea.height() ); + if (xdiff != 0) { + if (xdiff > 0) { + // Detect right + for (int i = 0; i < xdiff; i++) { + QRectF wArea = m_motionManager.transformedGeometry(w); + detectRect = QRect(0, wArea.y(), area.width(), wArea.height()); next = NULL; - foreach( EffectWindow* e, m_motionManager.managedWindows() ) - { - if( !m_windowData[e].visible ) + foreach (EffectWindow * e, m_motionManager.managedWindows()) { + if (!m_windowData[e].visible) continue; - QRectF eArea = m_motionManager.transformedGeometry( e ); - if( eArea.intersects( detectRect ) && - eArea.x() > wArea.x() ) - { - if( next == NULL ) + QRectF eArea = m_motionManager.transformedGeometry(e); + if (eArea.intersects(detectRect) && + eArea.x() > wArea.x()) { + if (next == NULL) next = e; - else - { - QRectF nArea = m_motionManager.transformedGeometry( next ); - if( eArea.x() < nArea.x() ) + else { + QRectF nArea = m_motionManager.transformedGeometry(next); + if (eArea.x() < nArea.x()) next = e; - } } } - if( next == NULL ) - { - if( wrap ) // We are at the right-most window, now get the left-most one to wrap - return relativeWindow( w, -1000, 0, false ); + } + if (next == NULL) { + if (wrap) // We are at the right-most window, now get the left-most one to wrap + return relativeWindow(w, -1000, 0, false); break; // No more windows to the right - } - w = next; } - return w; + w = next; } - else - { // Detect left - for( int i = 0; i < -xdiff; i++ ) - { - QRectF wArea = m_motionManager.transformedGeometry( w ); - detectRect = QRect( 0, wArea.y(), area.width(), wArea.height() ); + return w; + } else { + // Detect left + for (int i = 0; i < -xdiff; i++) { + QRectF wArea = m_motionManager.transformedGeometry(w); + detectRect = QRect(0, wArea.y(), area.width(), wArea.height()); next = NULL; - foreach( EffectWindow* e, m_motionManager.managedWindows() ) - { - if( !m_windowData[e].visible ) + foreach (EffectWindow * e, m_motionManager.managedWindows()) { + if (!m_windowData[e].visible) continue; - QRectF eArea = m_motionManager.transformedGeometry( e ); - if( eArea.intersects( detectRect ) && - eArea.x() + eArea.width() < wArea.x() + wArea.width() ) - { - if( next == NULL ) + QRectF eArea = m_motionManager.transformedGeometry(e); + if (eArea.intersects(detectRect) && + eArea.x() + eArea.width() < wArea.x() + wArea.width()) { + if (next == NULL) next = e; - else - { - QRectF nArea = m_motionManager.transformedGeometry( next ); - if( eArea.x() + eArea.width() > nArea.x() + nArea.width() ) + else { + QRectF nArea = m_motionManager.transformedGeometry(next); + if (eArea.x() + eArea.width() > nArea.x() + nArea.width()) next = e; - } } } - if( next == NULL ) - { - if( wrap ) // We are at the left-most window, now get the right-most one to wrap - return relativeWindow( w, 1000, 0, false ); - break; // No more windows to the left - } - w = next; } - return w; + if (next == NULL) { + if (wrap) // We are at the left-most window, now get the right-most one to wrap + return relativeWindow(w, 1000, 0, false); + break; // No more windows to the left + } + w = next; } + return w; } + } // Detect across the height of the desktop - if( ydiff != 0 ) - { - if( ydiff > 0 ) - { // Detect down - for( int i = 0; i < ydiff; i++ ) - { - QRectF wArea = m_motionManager.transformedGeometry( w ); - detectRect = QRect( wArea.x(), 0, wArea.width(), area.height() ); + if (ydiff != 0) { + if (ydiff > 0) { + // Detect down + for (int i = 0; i < ydiff; i++) { + QRectF wArea = m_motionManager.transformedGeometry(w); + detectRect = QRect(wArea.x(), 0, wArea.width(), area.height()); next = NULL; - foreach( EffectWindow* e, m_motionManager.managedWindows() ) - { - if( !m_windowData[e].visible ) + foreach (EffectWindow * e, m_motionManager.managedWindows()) { + if (!m_windowData[e].visible) continue; - QRectF eArea = m_motionManager.transformedGeometry( e ); - if( eArea.intersects( detectRect ) && - eArea.y() > wArea.y() ) - { - if( next == NULL ) + QRectF eArea = m_motionManager.transformedGeometry(e); + if (eArea.intersects(detectRect) && + eArea.y() > wArea.y()) { + if (next == NULL) next = e; - else - { - QRectF nArea = m_motionManager.transformedGeometry( next ); - if( eArea.y() < nArea.y() ) + else { + QRectF nArea = m_motionManager.transformedGeometry(next); + if (eArea.y() < nArea.y()) next = e; - } } } - if( next == NULL ) - { - if( wrap ) // We are at the bottom-most window, now get the top-most one to wrap - return relativeWindow( w, 0, -1000, false ); + } + if (next == NULL) { + if (wrap) // We are at the bottom-most window, now get the top-most one to wrap + return relativeWindow(w, 0, -1000, false); break; // No more windows to the bottom - } - w = next; } - return w; + w = next; } - else - { // Detect up - for( int i = 0; i < -ydiff; i++ ) - { - QRectF wArea = m_motionManager.transformedGeometry( w ); - detectRect = QRect( wArea.x(), 0, wArea.width(), area.height() ); + return w; + } else { + // Detect up + for (int i = 0; i < -ydiff; i++) { + QRectF wArea = m_motionManager.transformedGeometry(w); + detectRect = QRect(wArea.x(), 0, wArea.width(), area.height()); next = NULL; - foreach( EffectWindow* e, m_motionManager.managedWindows() ) - { - if( !m_windowData[e].visible ) + foreach (EffectWindow * e, m_motionManager.managedWindows()) { + if (!m_windowData[e].visible) continue; - QRectF eArea = m_motionManager.transformedGeometry( e ); - if( eArea.intersects( detectRect ) && - eArea.y() + eArea.height() < wArea.y() + wArea.height() ) - { - if( next == NULL ) + QRectF eArea = m_motionManager.transformedGeometry(e); + if (eArea.intersects(detectRect) && + eArea.y() + eArea.height() < wArea.y() + wArea.height()) { + if (next == NULL) next = e; - else - { - QRectF nArea = m_motionManager.transformedGeometry( next ); - if( eArea.y() + eArea.height() > nArea.y() + nArea.height() ) + else { + QRectF nArea = m_motionManager.transformedGeometry(next); + if (eArea.y() + eArea.height() > nArea.y() + nArea.height()) next = e; - } } } - if( next == NULL ) - { - if( wrap ) // We are at the top-most window, now get the bottom-most one to wrap - return relativeWindow( w, 0, 1000, false ); - break; // No more windows to the top - } - w = next; } - return w; + if (next == NULL) { + if (wrap) // We are at the top-most window, now get the bottom-most one to wrap + return relativeWindow(w, 0, 1000, false); + break; // No more windows to the top + } + w = next; } + return w; } + } abort(); // Should never get here - } +} EffectWindow* PresentWindowsEffect::findFirstWindow() const - { +{ EffectWindow *topLeft = NULL; QRectF topLeftGeometry; - foreach( EffectWindow *w, m_motionManager.managedWindows() ) - { - QRectF geometry = m_motionManager.transformedGeometry( w ); - if( m_windowData[w].visible == false ) + foreach (EffectWindow * w, m_motionManager.managedWindows()) { + QRectF geometry = m_motionManager.transformedGeometry(w); + if (m_windowData[w].visible == false) continue; // Not visible - if( m_windowData[w].deleted ) + if (m_windowData[w].deleted) continue; // Window has been closed - if( topLeft == NULL ) - { + if (topLeft == NULL) { topLeft = w; topLeftGeometry = geometry; - } - else if( geometry.x() < topLeftGeometry.x() || geometry.y() < topLeftGeometry.y() ) - { + } else if (geometry.x() < topLeftGeometry.x() || geometry.y() < topLeftGeometry.y()) { topLeft = w; topLeftGeometry = geometry; - } } + } return topLeft; - } +} -void PresentWindowsEffect::globalShortcutChanged( const QKeySequence& seq ) - { - shortcut = KShortcut( seq ); - } +void PresentWindowsEffect::globalShortcutChanged(const QKeySequence& seq) +{ + shortcut = KShortcut(seq); +} -void PresentWindowsEffect::globalShortcutChangedAll( const QKeySequence& seq ) - { - shortcutAll = KShortcut( seq ); - } +void PresentWindowsEffect::globalShortcutChangedAll(const QKeySequence& seq) +{ + shortcutAll = KShortcut(seq); +} -void PresentWindowsEffect::globalShortcutChangedClass( const QKeySequence& seq ) - { - shortcutClass = KShortcut( seq ); - } +void PresentWindowsEffect::globalShortcutChangedClass(const QKeySequence& seq) +{ + shortcutClass = KShortcut(seq); +} /************************************************ * CloseWindowView ************************************************/ -CloseWindowView::CloseWindowView( QWidget* parent ) +CloseWindowView::CloseWindowView(QWidget* parent) : QGraphicsView(parent) - , m_delayedShowTimer( new QTimer( this )) - { - setWindowFlags( Qt::X11BypassWindowManagerHint ); - setAttribute( Qt::WA_TranslucentBackground ); - setFrameShape( QFrame::NoFrame ); + , m_delayedShowTimer(new QTimer(this)) +{ + setWindowFlags(Qt::X11BypassWindowManagerHint); + setAttribute(Qt::WA_TranslucentBackground); + setFrameShape(QFrame::NoFrame); QPalette pal = palette(); - pal.setColor( backgroundRole(), Qt::transparent ); - setPalette( pal ); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); + pal.setColor(backgroundRole(), Qt::transparent); + setPalette(pal); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // setup the scene - QGraphicsScene* scene = new QGraphicsScene( this ); + QGraphicsScene* scene = new QGraphicsScene(this); m_closeButton = new Plasma::PushButton(); - m_closeButton->setIcon( KIcon( "window-close" ) ); - scene->addItem( m_closeButton ); - connect( m_closeButton, SIGNAL(clicked()), SIGNAL(close())); + m_closeButton->setIcon(KIcon("window-close")); + scene->addItem(m_closeButton); + connect(m_closeButton, SIGNAL(clicked()), SIGNAL(close())); QGraphicsLinearLayout *layout = new QGraphicsLinearLayout; - layout->addItem( m_closeButton ); + layout->addItem(m_closeButton); QGraphicsWidget *form = new QGraphicsWidget; - form->setLayout( layout ); + form->setLayout(layout); form->setGeometry(0, 0, 32, 32); - scene->addItem( form ); + scene->addItem(form); - m_frame = new Plasma::FrameSvg( this ); - m_frame->setImagePath( "dialogs/background" ); - m_frame->setCacheAllRenderedFrames( true ); - m_frame->setEnabledBorders( Plasma::FrameSvg::AllBorders ); + m_frame = new Plasma::FrameSvg(this); + m_frame->setImagePath("dialogs/background"); + m_frame->setCacheAllRenderedFrames(true); + m_frame->setEnabledBorders(Plasma::FrameSvg::AllBorders); qreal left, top, right, bottom; - m_frame->getMargins( left, top, right, bottom ); + m_frame->getMargins(left, top, right, bottom); qreal width = form->size().width() + left + right; qreal height = form->size().height() + top + bottom; - m_frame->resizeFrame( QSizeF( width, height ) ); - Plasma::WindowEffects::enableBlurBehind( winId(), true, m_frame->mask() ); - Plasma::WindowEffects::overrideShadow( winId(), true ); - form->setPos( left, top ); - scene->setSceneRect( QRectF( QPointF( 0, 0 ), QSizeF( width, height ) ) ); - setScene( scene ); + m_frame->resizeFrame(QSizeF(width, height)); + Plasma::WindowEffects::enableBlurBehind(winId(), true, m_frame->mask()); + Plasma::WindowEffects::overrideShadow(winId(), true); + form->setPos(left, top); + scene->setSceneRect(QRectF(QPointF(0, 0), QSizeF(width, height))); + setScene(scene); // setup the timer - m_delayedShowTimer->setSingleShot( true ); - m_delayedShowTimer->setInterval( 500 ); - connect( m_delayedShowTimer, SIGNAL(timeout()), SLOT(show())); - } + m_delayedShowTimer->setSingleShot(true); + m_delayedShowTimer->setInterval(500); + connect(m_delayedShowTimer, SIGNAL(timeout()), SLOT(show())); +} -void CloseWindowView::windowInputMouseEvent( QMouseEvent* e ) - { - if( m_delayedShowTimer->isActive() ) +void CloseWindowView::windowInputMouseEvent(QMouseEvent* e) +{ + if (m_delayedShowTimer->isActive()) return; - if( e->type() == QEvent::MouseMove ) - { - mouseMoveEvent( e ); - } - else if( e->type() == QEvent::MouseButtonPress ) - { - mousePressEvent( e ); - } - else if( e->type() == QEvent::MouseButtonDblClick ) - { - mouseDoubleClickEvent( e ); - } - else if( e->type() == QEvent::MouseButtonRelease ) - { - mouseReleaseEvent( e ); - } + if (e->type() == QEvent::MouseMove) { + mouseMoveEvent(e); + } else if (e->type() == QEvent::MouseButtonPress) { + mousePressEvent(e); + } else if (e->type() == QEvent::MouseButtonDblClick) { + mouseDoubleClickEvent(e); + } else if (e->type() == QEvent::MouseButtonRelease) { + mouseReleaseEvent(e); } +} -void CloseWindowView::drawBackground( QPainter* painter, const QRectF& rect ) - { - Q_UNUSED( rect ) - painter->setRenderHint( QPainter::Antialiasing ); - m_frame->paintFrame( painter ); - } +void CloseWindowView::drawBackground(QPainter* painter, const QRectF& rect) +{ + Q_UNUSED(rect) + painter->setRenderHint(QPainter::Antialiasing); + m_frame->paintFrame(painter); +} void CloseWindowView::hide() - { +{ m_delayedShowTimer->stop(); QWidget::hide(); - } +} void CloseWindowView::delayedShow() - { - if( isVisible() || m_delayedShowTimer->isActive() ) +{ + if (isVisible() || m_delayedShowTimer->isActive()) return; m_delayedShowTimer->start(); - } +} } // namespace diff --git a/effects/presentwindows/presentwindows.h b/effects/presentwindows/presentwindows.h index 43151bd3d..ea042f946 100644 --- a/effects/presentwindows/presentwindows.h +++ b/effects/presentwindows/presentwindows.h @@ -38,24 +38,24 @@ namespace KWin { class CloseWindowView : public QGraphicsView - { +{ Q_OBJECT - public: - CloseWindowView( QWidget* parent = 0 ); - void windowInputMouseEvent( QMouseEvent* e ); - virtual void drawBackground( QPainter* painter, const QRectF& rect ); +public: + CloseWindowView(QWidget* parent = 0); + void windowInputMouseEvent(QMouseEvent* e); + virtual void drawBackground(QPainter* painter, const QRectF& rect); - void delayedShow(); - void hide(); + void delayedShow(); + void hide(); - Q_SIGNALS: - void close(); +Q_SIGNALS: + void close(); - private: - Plasma::PushButton* m_closeButton; - Plasma::FrameSvg* m_frame; - QTimer* m_delayedShowTimer; - }; +private: + Plasma::PushButton* m_closeButton; + Plasma::FrameSvg* m_frame; + QTimer* m_delayedShowTimer; +}; /** * Expose-like effect which shows all windows on current desktop side-by-side, @@ -63,209 +63,213 @@ class CloseWindowView : public QGraphicsView **/ class PresentWindowsEffect : public QObject, public Effect - { +{ Q_OBJECT - private: - // Structures - struct WindowData - { - bool visible; - bool deleted; - bool referenced; - double opacity; - double highlight; - int slot; - int slot_distance; - EffectFrame* textFrame; - EffectFrame* iconFrame; - }; - typedef QHash DataHash; - struct GridSize - { - int columns; - int rows; - }; - - public: - PresentWindowsEffect(); - virtual ~PresentWindowsEffect(); - - virtual void reconfigure( ReconfigureFlags ); - virtual void* proxy(); - - // Screen painting - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData &data ); - virtual void postPaintScreen(); - - // Window painting - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ); - - // User interaction - virtual void windowAdded( EffectWindow *w ); - virtual void windowClosed( EffectWindow *w ); - virtual void windowDeleted( EffectWindow *w ); - virtual void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - virtual bool borderActivated( ElectricBorder border ); - virtual void windowInputMouseEvent( Window w, QEvent *e ); - virtual void grabbedKeyboardEvent( QKeyEvent *e ); - - // Tab box - virtual void tabBoxAdded( int mode ); - virtual void tabBoxClosed(); - virtual void tabBoxUpdated(); - virtual void tabBoxKeyEvent( QKeyEvent* event ); - - // atoms - virtual void propertyNotify( EffectWindow* w, long atom ); - - enum { LayoutNatural, LayoutRegularGrid, LayoutFlexibleGrid }; // Layout modes - enum PresentWindowsMode - { - ModeAllDesktops, // Shows windows of all desktops - ModeCurrentDesktop, // Shows windows on current desktop - ModeSelectedDesktop, // Shows windows of selected desktop via property (m_desktop) - ModeWindowGroup, // Shows windows selected via property - ModeWindowClass // Shows all windows of same class as selected class - }; - enum WindowMouseAction - { - WindowNoAction = 0, // Nothing - WindowActivateAction = 1, // Activates the window and deactivates the effect - WindowExitAction = 2, // Deactivates the effect without activating new window - WindowToCurrentDesktopAction = 3, // Brings window to current desktop - WindowToAllDesktopsAction = 4, // Brings window to all desktops - WindowMinimizeAction = 5, // Minimize the window - WindowCloseAction = 6 // Closes the window - }; - enum DesktopMouseAction - { - DesktopNoAction = 0, // nothing - DesktopActivateAction = 1, // Activates the window and deactivates the effect - DesktopExitAction = 2, // Deactivates the effect without activating new window - DesktopShowDesktopAction = 3 // Minimizes all windows - }; - - public slots: - void setActive( bool active, bool closingTab = false ); // HACK: closingTab shouldn't be needed - void toggleActive() { m_mode = ModeCurrentDesktop; setActive( !m_activated ); } - void toggleActiveAllDesktops() { m_mode = ModeAllDesktops; setActive( !m_activated ); } - void toggleActiveClass(); - - // slots for global shortcut changed - // needed to toggle the effect - void globalShortcutChanged( const QKeySequence& seq ); - void globalShortcutChangedAll( const QKeySequence& seq ); - void globalShortcutChangedClass( const QKeySequence& seq ); - - private slots: - void closeWindow(); - - protected: - // Window rearranging - void rearrangeWindows(); - void calculateWindowTransformations( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager, bool external = false ); - void calculateWindowTransformationsClosest( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ); - void calculateWindowTransformationsKompose( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ); - void calculateWindowTransformationsNatural( EffectWindowList windowlist, int screen, - WindowMotionManager& motionManager ); - - // Helper functions for window rearranging - inline double aspectRatio( EffectWindow *w ) - { return w->width() / double( w->height() ); } - inline int widthForHeight( EffectWindow *w, int height ) - { return int(( height / double( w->height() )) * w->width() ); } - inline int heightForWidth( EffectWindow *w, int width ) - { return int(( width / double( w->width() )) * w->height() ); } - void assignSlots( EffectWindowList windowlist, const QRect &area, int columns, int rows ); - void getBestAssignments( EffectWindowList windowlist ); - bool isOverlappingAny( EffectWindow *w, const QHash &targets, const QRegion &border ); - - // Filter box - void updateFilterFrame(); - - // Helper functions - bool isSelectableWindow( EffectWindow *w ); - bool isVisibleWindow( EffectWindow *w ); - void setHighlightedWindow( EffectWindow *w ); - EffectWindow* relativeWindow( EffectWindow *w, int xdiff, int ydiff, bool wrap ) const; - EffectWindow* findFirstWindow() const; - void updateCloseWindow(); - - // Helper functions for mouse actions - void mouseActionWindow( WindowMouseAction& action ); - void mouseActionDesktop( DesktopMouseAction& action ); - - private: - PresentWindowsEffectProxy m_proxy; - friend class PresentWindowsEffectProxy; - - // User configuration settings - QList m_borderActivate; - QList m_borderActivateAll; - int m_layoutMode; - bool m_showCaptions; - bool m_showIcons; - bool m_doNotCloseWindows; - bool m_tabBoxAllowed; - bool m_tabBoxAlternativeAllowed; - int m_accuracy; - bool m_fillGaps; - double m_fadeDuration; - bool m_showPanel; - - // Activation - bool m_activated; - bool m_ignoreMinimized; - double m_decalOpacity; - Window m_input; - bool m_hasKeyboardGrab; - bool m_tabBoxEnabled; - PresentWindowsMode m_mode; - int m_desktop; - EffectWindowList m_selectedWindows; - EffectWindow *m_managerWindow; - QString m_class; - - // Window data - WindowMotionManager m_motionManager; - DataHash m_windowData; - EffectWindow *m_highlightedWindow; - - // Grid layout info - QList m_gridSizes; - - // Filter box - EffectFrame* m_filterFrame; - QString m_windowFilter; - - // Shortcut - needed to toggle the effect - KShortcut shortcut; - KShortcut shortcutAll; - KShortcut shortcutClass; - - // Atoms - // Present windows for all windows of given desktop - // -1 for all desktops - long m_atomDesktop; - // Present windows for group of window ids - long m_atomWindows; - - // Mouse Actions - WindowMouseAction m_leftButtonWindow; - WindowMouseAction m_middleButtonWindow; - WindowMouseAction m_rightButtonWindow; - DesktopMouseAction m_leftButtonDesktop; - DesktopMouseAction m_middleButtonDesktop; - DesktopMouseAction m_rightButtonDesktop; - - CloseWindowView* m_closeView; - EffectWindow* m_closeWindow; +private: + // Structures + struct WindowData { + bool visible; + bool deleted; + bool referenced; + double opacity; + double highlight; + int slot; + int slot_distance; + EffectFrame* textFrame; + EffectFrame* iconFrame; }; + typedef QHash DataHash; + struct GridSize { + int columns; + int rows; + }; + +public: + PresentWindowsEffect(); + virtual ~PresentWindowsEffect(); + + virtual void reconfigure(ReconfigureFlags); + virtual void* proxy(); + + // Screen painting + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData &data); + virtual void postPaintScreen(); + + // Window painting + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data); + + // User interaction + virtual void windowAdded(EffectWindow *w); + virtual void windowClosed(EffectWindow *w); + virtual void windowDeleted(EffectWindow *w); + virtual void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + virtual bool borderActivated(ElectricBorder border); + virtual void windowInputMouseEvent(Window w, QEvent *e); + virtual void grabbedKeyboardEvent(QKeyEvent *e); + + // Tab box + virtual void tabBoxAdded(int mode); + virtual void tabBoxClosed(); + virtual void tabBoxUpdated(); + virtual void tabBoxKeyEvent(QKeyEvent* event); + + // atoms + virtual void propertyNotify(EffectWindow* w, long atom); + + enum { LayoutNatural, LayoutRegularGrid, LayoutFlexibleGrid }; // Layout modes + enum PresentWindowsMode { + ModeAllDesktops, // Shows windows of all desktops + ModeCurrentDesktop, // Shows windows on current desktop + ModeSelectedDesktop, // Shows windows of selected desktop via property (m_desktop) + ModeWindowGroup, // Shows windows selected via property + ModeWindowClass // Shows all windows of same class as selected class + }; + enum WindowMouseAction { + WindowNoAction = 0, // Nothing + WindowActivateAction = 1, // Activates the window and deactivates the effect + WindowExitAction = 2, // Deactivates the effect without activating new window + WindowToCurrentDesktopAction = 3, // Brings window to current desktop + WindowToAllDesktopsAction = 4, // Brings window to all desktops + WindowMinimizeAction = 5, // Minimize the window + WindowCloseAction = 6 // Closes the window + }; + enum DesktopMouseAction { + DesktopNoAction = 0, // nothing + DesktopActivateAction = 1, // Activates the window and deactivates the effect + DesktopExitAction = 2, // Deactivates the effect without activating new window + DesktopShowDesktopAction = 3 // Minimizes all windows + }; + +public slots: + void setActive(bool active, bool closingTab = false); // HACK: closingTab shouldn't be needed + void toggleActive() { + m_mode = ModeCurrentDesktop; + setActive(!m_activated); + } + void toggleActiveAllDesktops() { + m_mode = ModeAllDesktops; + setActive(!m_activated); + } + void toggleActiveClass(); + + // slots for global shortcut changed + // needed to toggle the effect + void globalShortcutChanged(const QKeySequence& seq); + void globalShortcutChangedAll(const QKeySequence& seq); + void globalShortcutChangedClass(const QKeySequence& seq); + +private slots: + void closeWindow(); + +protected: + // Window rearranging + void rearrangeWindows(); + void calculateWindowTransformations(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager, bool external = false); + void calculateWindowTransformationsClosest(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager); + void calculateWindowTransformationsKompose(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager); + void calculateWindowTransformationsNatural(EffectWindowList windowlist, int screen, + WindowMotionManager& motionManager); + + // Helper functions for window rearranging + inline double aspectRatio(EffectWindow *w) { + return w->width() / double(w->height()); + } + inline int widthForHeight(EffectWindow *w, int height) { + return int((height / double(w->height())) * w->width()); + } + inline int heightForWidth(EffectWindow *w, int width) { + return int((width / double(w->width())) * w->height()); + } + void assignSlots(EffectWindowList windowlist, const QRect &area, int columns, int rows); + void getBestAssignments(EffectWindowList windowlist); + bool isOverlappingAny(EffectWindow *w, const QHash &targets, const QRegion &border); + + // Filter box + void updateFilterFrame(); + + // Helper functions + bool isSelectableWindow(EffectWindow *w); + bool isVisibleWindow(EffectWindow *w); + void setHighlightedWindow(EffectWindow *w); + EffectWindow* relativeWindow(EffectWindow *w, int xdiff, int ydiff, bool wrap) const; + EffectWindow* findFirstWindow() const; + void updateCloseWindow(); + + // Helper functions for mouse actions + void mouseActionWindow(WindowMouseAction& action); + void mouseActionDesktop(DesktopMouseAction& action); + +private: + PresentWindowsEffectProxy m_proxy; + friend class PresentWindowsEffectProxy; + + // User configuration settings + QList m_borderActivate; + QList m_borderActivateAll; + int m_layoutMode; + bool m_showCaptions; + bool m_showIcons; + bool m_doNotCloseWindows; + bool m_tabBoxAllowed; + bool m_tabBoxAlternativeAllowed; + int m_accuracy; + bool m_fillGaps; + double m_fadeDuration; + bool m_showPanel; + + // Activation + bool m_activated; + bool m_ignoreMinimized; + double m_decalOpacity; + Window m_input; + bool m_hasKeyboardGrab; + bool m_tabBoxEnabled; + PresentWindowsMode m_mode; + int m_desktop; + EffectWindowList m_selectedWindows; + EffectWindow *m_managerWindow; + QString m_class; + + // Window data + WindowMotionManager m_motionManager; + DataHash m_windowData; + EffectWindow *m_highlightedWindow; + + // Grid layout info + QList m_gridSizes; + + // Filter box + EffectFrame* m_filterFrame; + QString m_windowFilter; + + // Shortcut - needed to toggle the effect + KShortcut shortcut; + KShortcut shortcutAll; + KShortcut shortcutClass; + + // Atoms + // Present windows for all windows of given desktop + // -1 for all desktops + long m_atomDesktop; + // Present windows for group of window ids + long m_atomWindows; + + // Mouse Actions + WindowMouseAction m_leftButtonWindow; + WindowMouseAction m_middleButtonWindow; + WindowMouseAction m_rightButtonWindow; + DesktopMouseAction m_leftButtonDesktop; + DesktopMouseAction m_middleButtonDesktop; + DesktopMouseAction m_rightButtonDesktop; + + CloseWindowView* m_closeView; + EffectWindow* m_closeWindow; +}; } // namespace diff --git a/effects/presentwindows/presentwindows_config.cpp b/effects/presentwindows/presentwindows_config.cpp index 1197f9699..1d6572cde 100644 --- a/effects/presentwindows/presentwindows_config.cpp +++ b/effects/presentwindows/presentwindows_config.cpp @@ -35,174 +35,174 @@ KWIN_EFFECT_CONFIG_FACTORY PresentWindowsEffectConfigForm::PresentWindowsEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } PresentWindowsEffectConfig::PresentWindowsEffectConfig(QWidget* parent, const QVariantList& args) - : KCModule( EffectFactory::componentData(), parent, args ) - { - m_ui = new PresentWindowsEffectConfigForm( this ); + : KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new PresentWindowsEffectConfigForm(this); - QVBoxLayout* layout = new QVBoxLayout( this ); + QVBoxLayout* layout = new QVBoxLayout(this); - layout->addWidget( m_ui ); + layout->addWidget(m_ui); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); - m_actionCollection->setConfigGroup( "PresentWindows" ); - m_actionCollection->setConfigGlobal( true ); + m_actionCollection->setConfigGroup("PresentWindows"); + m_actionCollection->setConfigGlobal(true); - KAction* a = (KAction*) m_actionCollection->addAction( "ExposeAll" ); - a->setText( i18n( "Toggle Present Windows (All desktops)" )); - a->setProperty( "isConfigurationAction", true ); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F10 )); + KAction* a = (KAction*) m_actionCollection->addAction("ExposeAll"); + a->setText(i18n("Toggle Present Windows (All desktops)")); + a->setProperty("isConfigurationAction", true); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F10)); - KAction* b = (KAction*) m_actionCollection->addAction( "Expose" ); - b->setText( i18n( "Toggle Present Windows (Current desktop)" )); - b->setProperty( "isConfigurationAction", true ); - b->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F9 )); + KAction* b = (KAction*) m_actionCollection->addAction("Expose"); + b->setText(i18n("Toggle Present Windows (Current desktop)")); + b->setProperty("isConfigurationAction", true); + b->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F9)); - KAction* c = ( KAction* )m_actionCollection->addAction( "ExposeClass" ); - c->setText( i18n( "Toggle Present Windows (Window class)" )); - c->setProperty( "isConfigurationAction", true ); - c->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::Key_F7 )); + KAction* c = (KAction*)m_actionCollection->addAction("ExposeClass"); + c->setText(i18n("Toggle Present Windows (Window class)")); + c->setProperty("isConfigurationAction", true); + c->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::Key_F7)); - m_ui->shortcutEditor->addCollection( m_actionCollection ); + m_ui->shortcutEditor->addCollection(m_actionCollection); - connect( m_ui->layoutCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->displayTitleBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->displayIconBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->allowClosing, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->ignoreMinimizedBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->showPanelBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->accuracySlider, SIGNAL( valueChanged( int )), this, SLOT( changed() )); - connect( m_ui->fillGapsBox, SIGNAL( stateChanged( int )), this, SLOT( changed() )); - connect( m_ui->shortcutEditor, SIGNAL( keyChange() ), this, SLOT( changed() )); - connect( m_ui->leftButtonWindowCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->middleButtonWindowCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->rightButtonWindowCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->leftButtonDesktopCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->middleButtonDesktopCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); - connect( m_ui->rightButtonDesktopCombo, SIGNAL( currentIndexChanged( int )), this, SLOT( changed() )); + connect(m_ui->layoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->displayTitleBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->displayIconBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->allowClosing, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->ignoreMinimizedBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->showPanelBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->accuracySlider, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->fillGapsBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->shortcutEditor, SIGNAL(keyChange()), this, SLOT(changed())); + connect(m_ui->leftButtonWindowCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->middleButtonWindowCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->rightButtonWindowCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->leftButtonDesktopCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->middleButtonDesktopCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->rightButtonDesktopCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); load(); - } +} PresentWindowsEffectConfig::~PresentWindowsEffectConfig() - { +{ // If save() is called undoChanges() has no effect m_ui->shortcutEditor->undoChanges(); - } +} void PresentWindowsEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "PresentWindows" ); - - int layoutMode = conf.readEntry( "LayoutMode", int( PresentWindowsEffect::LayoutNatural )); - m_ui->layoutCombo->setCurrentIndex( layoutMode ); + KConfigGroup conf = EffectsHandler::effectConfig("PresentWindows"); - bool displayTitle = conf.readEntry( "DrawWindowCaptions", true ); - m_ui->displayTitleBox->setChecked( displayTitle ); + int layoutMode = conf.readEntry("LayoutMode", int(PresentWindowsEffect::LayoutNatural)); + m_ui->layoutCombo->setCurrentIndex(layoutMode); - bool displayIcon = conf.readEntry( "DrawWindowIcons", true ); - m_ui->displayIconBox->setChecked( displayIcon ); + bool displayTitle = conf.readEntry("DrawWindowCaptions", true); + m_ui->displayTitleBox->setChecked(displayTitle); - bool allowClosing = conf.readEntry( "AllowClosingWindows", true ); - m_ui->allowClosing->setChecked( allowClosing ); + bool displayIcon = conf.readEntry("DrawWindowIcons", true); + m_ui->displayIconBox->setChecked(displayIcon); - bool ignoreMinimized = conf.readEntry( "IgnoreMinimized", false ); - m_ui->ignoreMinimizedBox->setChecked( ignoreMinimized ); + bool allowClosing = conf.readEntry("AllowClosingWindows", true); + m_ui->allowClosing->setChecked(allowClosing); - bool showPanel = conf.readEntry( "ShowPanel", false ); - m_ui->showPanelBox->setChecked( showPanel ); + bool ignoreMinimized = conf.readEntry("IgnoreMinimized", false); + m_ui->ignoreMinimizedBox->setChecked(ignoreMinimized); - int accuracy = conf.readEntry( "Accuracy", 1 ); - m_ui->accuracySlider->setSliderPosition( accuracy ); + bool showPanel = conf.readEntry("ShowPanel", false); + m_ui->showPanelBox->setChecked(showPanel); - bool fillGaps = conf.readEntry( "FillGaps", true ); - m_ui->fillGapsBox->setChecked( fillGaps ); + int accuracy = conf.readEntry("Accuracy", 1); + m_ui->accuracySlider->setSliderPosition(accuracy); - int leftButtonWindow = conf.readEntry( "LeftButtonWindow", int( PresentWindowsEffect::WindowActivateAction )); - m_ui->leftButtonWindowCombo->setCurrentIndex( leftButtonWindow ); - int middleButtonWindow = conf.readEntry( "MiddleButtonWindow", int( PresentWindowsEffect::WindowNoAction )); - m_ui->middleButtonWindowCombo->setCurrentIndex( middleButtonWindow ); - int rightButtonWindow = conf.readEntry( "RightButtonWindow", int( PresentWindowsEffect::WindowExitAction )); - m_ui->rightButtonWindowCombo->setCurrentIndex( rightButtonWindow ); + bool fillGaps = conf.readEntry("FillGaps", true); + m_ui->fillGapsBox->setChecked(fillGaps); - int leftButtonDesktop = conf.readEntry( "LeftButtonDesktop", int( PresentWindowsEffect::DesktopExitAction )); - m_ui->leftButtonDesktopCombo->setCurrentIndex( leftButtonDesktop ); - int middleButtonDesktop = conf.readEntry( "MiddleButtonDesktop", int( PresentWindowsEffect::DesktopNoAction )); - m_ui->middleButtonDesktopCombo->setCurrentIndex( middleButtonDesktop ); - int rightButtonDesktop = conf.readEntry( "RightButtonDesktop", int( PresentWindowsEffect::DesktopNoAction )); - m_ui->rightButtonDesktopCombo->setCurrentIndex( rightButtonDesktop ); + int leftButtonWindow = conf.readEntry("LeftButtonWindow", int(PresentWindowsEffect::WindowActivateAction)); + m_ui->leftButtonWindowCombo->setCurrentIndex(leftButtonWindow); + int middleButtonWindow = conf.readEntry("MiddleButtonWindow", int(PresentWindowsEffect::WindowNoAction)); + m_ui->middleButtonWindowCombo->setCurrentIndex(middleButtonWindow); + int rightButtonWindow = conf.readEntry("RightButtonWindow", int(PresentWindowsEffect::WindowExitAction)); + m_ui->rightButtonWindowCombo->setCurrentIndex(rightButtonWindow); + + int leftButtonDesktop = conf.readEntry("LeftButtonDesktop", int(PresentWindowsEffect::DesktopExitAction)); + m_ui->leftButtonDesktopCombo->setCurrentIndex(leftButtonDesktop); + int middleButtonDesktop = conf.readEntry("MiddleButtonDesktop", int(PresentWindowsEffect::DesktopNoAction)); + m_ui->middleButtonDesktopCombo->setCurrentIndex(middleButtonDesktop); + int rightButtonDesktop = conf.readEntry("RightButtonDesktop", int(PresentWindowsEffect::DesktopNoAction)); + m_ui->rightButtonDesktopCombo->setCurrentIndex(rightButtonDesktop); emit changed(false); - } +} void PresentWindowsEffectConfig::save() - { +{ KCModule::save(); - KConfigGroup conf = EffectsHandler::effectConfig( "PresentWindows" ); + KConfigGroup conf = EffectsHandler::effectConfig("PresentWindows"); int layoutMode = m_ui->layoutCombo->currentIndex(); - conf.writeEntry( "LayoutMode", layoutMode ); + conf.writeEntry("LayoutMode", layoutMode); - conf.writeEntry( "DrawWindowCaptions", m_ui->displayTitleBox->isChecked() ); - conf.writeEntry( "DrawWindowIcons", m_ui->displayIconBox->isChecked() ); - conf.writeEntry( "AllowClosingWindows", m_ui->allowClosing->isChecked() ); - conf.writeEntry( "IgnoreMinimized", m_ui->ignoreMinimizedBox->isChecked() ); - conf.writeEntry( "ShowPanel", m_ui->showPanelBox->isChecked() ); + conf.writeEntry("DrawWindowCaptions", m_ui->displayTitleBox->isChecked()); + conf.writeEntry("DrawWindowIcons", m_ui->displayIconBox->isChecked()); + conf.writeEntry("AllowClosingWindows", m_ui->allowClosing->isChecked()); + conf.writeEntry("IgnoreMinimized", m_ui->ignoreMinimizedBox->isChecked()); + conf.writeEntry("ShowPanel", m_ui->showPanelBox->isChecked()); int accuracy = m_ui->accuracySlider->value(); - conf.writeEntry( "Accuracy", accuracy ); + conf.writeEntry("Accuracy", accuracy); - conf.writeEntry( "FillGaps", m_ui->fillGapsBox->isChecked() ); + conf.writeEntry("FillGaps", m_ui->fillGapsBox->isChecked()); int leftButtonWindow = m_ui->leftButtonWindowCombo->currentIndex(); - conf.writeEntry( "LeftButtonWindow", leftButtonWindow ); + conf.writeEntry("LeftButtonWindow", leftButtonWindow); int middleButtonWindow = m_ui->middleButtonWindowCombo->currentIndex(); - conf.writeEntry( "MiddleButtonWindow", middleButtonWindow ); + conf.writeEntry("MiddleButtonWindow", middleButtonWindow); int rightButtonWindow = m_ui->rightButtonWindowCombo->currentIndex(); - conf.writeEntry( "RightButtonWindow", rightButtonWindow ); + conf.writeEntry("RightButtonWindow", rightButtonWindow); int leftButtonDesktop = m_ui->leftButtonDesktopCombo->currentIndex(); - conf.writeEntry( "LeftButtonDesktop", leftButtonDesktop ); + conf.writeEntry("LeftButtonDesktop", leftButtonDesktop); int middleButtonDesktop = m_ui->middleButtonDesktopCombo->currentIndex(); - conf.writeEntry( "MiddleButtonDesktop", middleButtonDesktop ); + conf.writeEntry("MiddleButtonDesktop", middleButtonDesktop); int rightButtonDesktop = m_ui->rightButtonDesktopCombo->currentIndex(); - conf.writeEntry( "RightButtonDesktop", rightButtonDesktop ); + conf.writeEntry("RightButtonDesktop", rightButtonDesktop); m_ui->shortcutEditor->save(); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "presentwindows" ); - } + EffectsHandler::sendReloadMessage("presentwindows"); +} void PresentWindowsEffectConfig::defaults() - { - m_ui->layoutCombo->setCurrentIndex( int( PresentWindowsEffect::LayoutNatural )); - m_ui->displayTitleBox->setChecked( true ); - m_ui->displayIconBox->setChecked( true ); - m_ui->allowClosing->setChecked( true ); - m_ui->ignoreMinimizedBox->setChecked( false ); - m_ui->showPanelBox->setChecked( false ); - m_ui->accuracySlider->setSliderPosition( 1 ); - m_ui->fillGapsBox->setChecked( true ); +{ + m_ui->layoutCombo->setCurrentIndex(int(PresentWindowsEffect::LayoutNatural)); + m_ui->displayTitleBox->setChecked(true); + m_ui->displayIconBox->setChecked(true); + m_ui->allowClosing->setChecked(true); + m_ui->ignoreMinimizedBox->setChecked(false); + m_ui->showPanelBox->setChecked(false); + m_ui->accuracySlider->setSliderPosition(1); + m_ui->fillGapsBox->setChecked(true); m_ui->shortcutEditor->allDefault(); - m_ui->leftButtonWindowCombo->setCurrentIndex( int( PresentWindowsEffect::WindowActivateAction )); - m_ui->middleButtonWindowCombo->setCurrentIndex( int( PresentWindowsEffect::WindowNoAction )); - m_ui->rightButtonWindowCombo->setCurrentIndex( int( PresentWindowsEffect::WindowExitAction )); - m_ui->leftButtonDesktopCombo->setCurrentIndex( int( PresentWindowsEffect::DesktopExitAction )); - m_ui->middleButtonDesktopCombo->setCurrentIndex( int( PresentWindowsEffect::DesktopNoAction )); - m_ui->rightButtonDesktopCombo->setCurrentIndex( int( PresentWindowsEffect::DesktopNoAction )); + m_ui->leftButtonWindowCombo->setCurrentIndex(int(PresentWindowsEffect::WindowActivateAction)); + m_ui->middleButtonWindowCombo->setCurrentIndex(int(PresentWindowsEffect::WindowNoAction)); + m_ui->rightButtonWindowCombo->setCurrentIndex(int(PresentWindowsEffect::WindowExitAction)); + m_ui->leftButtonDesktopCombo->setCurrentIndex(int(PresentWindowsEffect::DesktopExitAction)); + m_ui->middleButtonDesktopCombo->setCurrentIndex(int(PresentWindowsEffect::DesktopNoAction)); + m_ui->rightButtonDesktopCombo->setCurrentIndex(int(PresentWindowsEffect::DesktopNoAction)); emit changed(true); - } +} } // namespace diff --git a/effects/presentwindows/presentwindows_config.h b/effects/presentwindows/presentwindows_config.h index d2ca568d9..93a76c2f4 100644 --- a/effects/presentwindows/presentwindows_config.h +++ b/effects/presentwindows/presentwindows_config.h @@ -33,26 +33,26 @@ namespace KWin class PresentWindowsEffectConfigForm : public QWidget, public Ui::PresentWindowsEffectConfigForm { Q_OBJECT - public: - explicit PresentWindowsEffectConfigForm(QWidget* parent); +public: + explicit PresentWindowsEffectConfigForm(QWidget* parent); }; class PresentWindowsEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit PresentWindowsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~PresentWindowsEffectConfig(); +public: + explicit PresentWindowsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~PresentWindowsEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - PresentWindowsEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + PresentWindowsEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/presentwindows/presentwindows_proxy.cpp b/effects/presentwindows/presentwindows_proxy.cpp index 1703d1511..5c4937e53 100644 --- a/effects/presentwindows/presentwindows_proxy.cpp +++ b/effects/presentwindows/presentwindows_proxy.cpp @@ -24,19 +24,19 @@ along with this program. If not, see . namespace KWin { -PresentWindowsEffectProxy::PresentWindowsEffectProxy( PresentWindowsEffect* effect ) - : m_effect( effect ) - { - } +PresentWindowsEffectProxy::PresentWindowsEffectProxy(PresentWindowsEffect* effect) + : m_effect(effect) +{ +} PresentWindowsEffectProxy::~PresentWindowsEffectProxy() - { - } +{ +} void PresentWindowsEffectProxy::calculateWindowTransformations(EffectWindowList windows, int screen, WindowMotionManager& manager) - { - return m_effect->calculateWindowTransformations( windows, screen, manager, true ); - } +{ + return m_effect->calculateWindowTransformations(windows, screen, manager, true); +} } // namespace diff --git a/effects/presentwindows/presentwindows_proxy.h b/effects/presentwindows/presentwindows_proxy.h index 54f2913aa..efcd81ffe 100644 --- a/effects/presentwindows/presentwindows_proxy.h +++ b/effects/presentwindows/presentwindows_proxy.h @@ -28,16 +28,16 @@ namespace KWin class PresentWindowsEffect; class PresentWindowsEffectProxy - { - public: - PresentWindowsEffectProxy( PresentWindowsEffect* effect ); - ~PresentWindowsEffectProxy(); +{ +public: + PresentWindowsEffectProxy(PresentWindowsEffect* effect); + ~PresentWindowsEffectProxy(); - void calculateWindowTransformations(EffectWindowList windows, int screen, WindowMotionManager& manager); + void calculateWindowTransformations(EffectWindowList windows, int screen, WindowMotionManager& manager); - private: - PresentWindowsEffect* m_effect; - }; +private: + PresentWindowsEffect* m_effect; +}; } // namespace diff --git a/effects/resize/resize.cpp b/effects/resize/resize.cpp index 51e8d2251..51b4a2334 100644 --- a/effects/resize/resize.cpp +++ b/effects/resize/resize.cpp @@ -33,61 +33,57 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( resize, ResizeEffect ) +KWIN_EFFECT(resize, ResizeEffect) ResizeEffect::ResizeEffect() - : m_active( false ) - , m_resizeWindow( 0 ) - { - reconfigure( ReconfigureAll ); - } + : m_active(false) + , m_resizeWindow(0) +{ + reconfigure(ReconfigureAll); +} ResizeEffect::~ResizeEffect() - { - } +{ +} -void ResizeEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( m_active ) - { +void ResizeEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (m_active) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void ResizeEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( m_active && w == m_resizeWindow ) +void ResizeEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (m_active && w == m_resizeWindow) data.mask |= PAINT_WINDOW_TRANSFORMED; - effects->prePaintWindow( w, data, time ); - } + effects->prePaintWindow(w, data, time); +} -void ResizeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( m_active && w == m_resizeWindow ) - { - if( m_features & TextureScale ) - { +void ResizeEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (m_active && w == m_resizeWindow) { + if (m_features & TextureScale) { data.xTranslate += m_currentGeometry.x() - m_originalGeometry.x(); data.xScale *= m_currentGeometry.width(); data.xScale /= m_originalGeometry.width(); data.yTranslate += m_currentGeometry.y() - m_originalGeometry.y(); data.yScale *= m_currentGeometry.height(); data.yScale /= m_originalGeometry.height(); - } - effects->paintWindow( w, mask, region, data ); + } + effects->paintWindow(w, mask, region, data); - if( m_features & Outline ) - { - QRegion intersection = m_originalGeometry.intersected( m_currentGeometry ); - QRegion paintRegion = QRegion(m_originalGeometry).united( m_currentGeometry ).subtracted( intersection ); + if (m_features & Outline) { + QRegion intersection = m_originalGeometry.intersected(m_currentGeometry); + QRegion paintRegion = QRegion(m_originalGeometry).united(m_currentGeometry).subtracted(intersection); float alpha = 0.8f; - QColor color = KColorScheme( QPalette::Normal, KColorScheme::Selection ).background().color(); + QColor color = KColorScheme(QPalette::Normal, KColorScheme::Selection).background().color(); #ifdef KWIN_HAVE_OPENGL_COMPOSITING if (effects->compositingType() == OpenGLCompositing) { #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); @@ -95,13 +91,13 @@ void ResizeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Windo if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); color.setAlphaF(alpha); vbo->setColor(color); QVector verts; - verts.reserve(paintRegion.rects().count()*12); - foreach( const QRect &r, paintRegion.rects() ) { + verts.reserve(paintRegion.rects().count() * 12); + foreach (const QRect & r, paintRegion.rects()) { verts << r.x() + r.width() << r.y(); verts << r.x() << r.y(); verts << r.x() << r.y() + r.height(); @@ -109,7 +105,7 @@ void ResizeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Windo verts << r.x() + r.width() << r.y() + r.height(); verts << r.x() + r.width() << r.y(); } - vbo->setData(verts.count()/2, 2, verts.data(), NULL); + vbo->setData(verts.count() / 2, 2, verts.data(), NULL); vbo->render(GL_TRIANGLES); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); @@ -122,64 +118,58 @@ void ResizeEffect::paintWindow( EffectWindow* w, int mask, QRegion region, Windo #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( effects->compositingType() == XRenderCompositing) - { + if (effects->compositingType() == XRenderCompositing) { XRenderColor col; - col.alpha = int( alpha * 0xffff ); - col.red = int( alpha * 0xffff * color.red() / 255 ); - col.green = int( alpha * 0xffff * color.green() / 255 ); - col.blue= int( alpha * 0xffff * color.blue() / 255 ); - foreach( const QRect &r, paintRegion.rects() ) - XRenderFillRectangle( display(), PictOpOver, effects->xrenderBufferPicture(), - &col, r.x(), r.y(), r.width(), r.height()); - } -#endif + col.alpha = int(alpha * 0xffff); + col.red = int(alpha * 0xffff * color.red() / 255); + col.green = int(alpha * 0xffff * color.green() / 255); + col.blue = int(alpha * 0xffff * color.blue() / 255); + foreach (const QRect & r, paintRegion.rects()) + XRenderFillRectangle(display(), PictOpOver, effects->xrenderBufferPicture(), + &col, r.x(), r.y(), r.width(), r.height()); } +#endif } - else - effects->paintWindow( w, mask, region, data ); - } + } else + effects->paintWindow(w, mask, region, data); +} -void ResizeEffect::reconfigure( ReconfigureFlags ) - { +void ResizeEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = effects->effectConfig("Resize"); m_features = 0; - if ( conf.readEntry( "TextureScale", true ) ) + if (conf.readEntry("TextureScale", true)) m_features |= TextureScale; - if ( conf.readEntry( "Outline", false ) ) + if (conf.readEntry("Outline", false)) m_features |= Outline; - } +} -void ResizeEffect::windowUserMovedResized( EffectWindow* w, bool first, bool last ) - { - if( first && last ) - { +void ResizeEffect::windowUserMovedResized(EffectWindow* w, bool first, bool last) +{ + if (first && last) { // not interested in maximized return; - } - if( first && w->isUserResize() && !w->isUserMove() ) - { + } + if (first && w->isUserResize() && !w->isUserMove()) { m_active = true; m_resizeWindow = w; m_originalGeometry = w->geometry(); m_currentGeometry = w->geometry(); w->addRepaintFull(); - } - if( m_active && w == m_resizeWindow && last ) - { + } + if (m_active && w == m_resizeWindow && last) { m_active = false; m_resizeWindow = NULL; effects->addRepaintFull(); - } } +} -void ResizeEffect::windowMoveResizeGeometryUpdate( EffectWindow* c, const QRect& geometry ) - { - if( m_active && c == m_resizeWindow ) - { +void ResizeEffect::windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry) +{ + if (m_active && c == m_resizeWindow) { m_currentGeometry = geometry; effects->addRepaintFull(); - } } +} } // namespace diff --git a/effects/resize/resize.h b/effects/resize/resize.h index 9575fbcd2..cc59d719e 100644 --- a/effects/resize/resize.h +++ b/effects/resize/resize.h @@ -28,25 +28,27 @@ namespace KWin class ResizeEffect : public Effect - { - public: - ResizeEffect(); - ~ResizeEffect(); - virtual inline bool provides( Effect::Feature ef ) { return ef == Effect::Resize; } - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void reconfigure( ReconfigureFlags ); - virtual void windowUserMovedResized( EffectWindow *w, bool first, bool last ); - virtual void windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry); +{ +public: + ResizeEffect(); + ~ResizeEffect(); + virtual inline bool provides(Effect::Feature ef) { + return ef == Effect::Resize; + } + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void reconfigure(ReconfigureFlags); + virtual void windowUserMovedResized(EffectWindow *w, bool first, bool last); + virtual void windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry); - private: - enum Feature { TextureScale = 1<<0, Outline = 1<<1 }; - bool m_active; - int m_features; - EffectWindow* m_resizeWindow; - QRect m_currentGeometry, m_originalGeometry; - }; +private: + enum Feature { TextureScale = 1 << 0, Outline = 1 << 1 }; + bool m_active; + int m_features; + EffectWindow* m_resizeWindow; + QRect m_currentGeometry, m_originalGeometry; +}; } diff --git a/effects/resize/resize_config.cpp b/effects/resize/resize_config.cpp index 748e78875..2c5effa92 100644 --- a/effects/resize/resize_config.cpp +++ b/effects/resize/resize_config.cpp @@ -30,16 +30,16 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY ResizeEffectConfigForm::ResizeEffectConfigForm(QWidget* parent) : QWidget(parent) - { - setupUi( this ); - } +{ + setupUi(this); +} ResizeEffectConfig::ResizeEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { - m_ui = new ResizeEffectConfigForm( this ); + KCModule(EffectFactory::componentData(), parent, args) +{ + m_ui = new ResizeEffectConfigForm(this); - QVBoxLayout* layout = new QVBoxLayout( this ); + QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(m_ui); @@ -47,37 +47,37 @@ ResizeEffectConfig::ResizeEffectConfig(QWidget* parent, const QVariantList& args connect(m_ui->outlineBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); load(); - } +} void ResizeEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "Resize" ); - m_ui->scaleBox->setChecked(conf.readEntry( "TextureScale", true )); - m_ui->outlineBox->setChecked(conf.readEntry( "Outline" , false )); + KConfigGroup conf = EffectsHandler::effectConfig("Resize"); + m_ui->scaleBox->setChecked(conf.readEntry("TextureScale", true)); + m_ui->outlineBox->setChecked(conf.readEntry("Outline" , false)); - emit changed( false ); - } + emit changed(false); +} void ResizeEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "Resize" ); - conf.writeEntry( "TextureScale", m_ui->scaleBox->isChecked() ); - conf.writeEntry( "Outline", m_ui->outlineBox->isChecked() ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("Resize"); + conf.writeEntry("TextureScale", m_ui->scaleBox->isChecked()); + conf.writeEntry("Outline", m_ui->outlineBox->isChecked()); conf.sync(); - emit changed( false ); - EffectsHandler::sendReloadMessage( "resize" ); - } + emit changed(false); + EffectsHandler::sendReloadMessage("resize"); +} void ResizeEffectConfig::defaults() - { - m_ui->scaleBox->setChecked( true ); - m_ui->outlineBox->setChecked( false ); - emit changed( true ); - } +{ + m_ui->scaleBox->setChecked(true); + m_ui->outlineBox->setChecked(false); + emit changed(true); +} } // namespace diff --git a/effects/resize/resize_config.h b/effects/resize/resize_config.h index a5710f467..ae66343a4 100644 --- a/effects/resize/resize_config.h +++ b/effects/resize/resize_config.h @@ -32,24 +32,24 @@ namespace KWin class ResizeEffectConfigForm : public QWidget, public Ui::ResizeEffectConfigForm { Q_OBJECT - public: - explicit ResizeEffectConfigForm(QWidget* parent = 0); +public: + explicit ResizeEffectConfigForm(QWidget* parent = 0); }; class ResizeEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit ResizeEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit ResizeEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - ResizeEffectConfigForm* m_ui; - }; +private: + ResizeEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/scalein/scalein.cpp b/effects/scalein/scalein.cpp index 30a2fd174..dd1a1a2bb 100644 --- a/effects/scalein/scalein.cpp +++ b/effects/scalein/scalein.cpp @@ -23,71 +23,68 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( scalein, ScaleInEffect ) +KWIN_EFFECT(scalein, ScaleInEffect) -void ScaleInEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !mTimeLineWindows.isEmpty() ) +void ScaleInEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!mTimeLineWindows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void ScaleInEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( mTimeLineWindows.contains( w ) ) - { - mTimeLineWindows[ w ].setCurveShape( TimeLine::EaseOutCurve ); - mTimeLineWindows[ w ].addTime( time ); - if( mTimeLineWindows[ w ].value() < 1 ) +void ScaleInEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (mTimeLineWindows.contains(w)) { + mTimeLineWindows[ w ].setCurveShape(TimeLine::EaseOutCurve); + mTimeLineWindows[ w ].addTime(time); + if (mTimeLineWindows[ w ].value() < 1) data.setTransformed(); else - mTimeLineWindows.remove( w ); - } - effects->prePaintWindow( w, data, time ); + mTimeLineWindows.remove(w); } + effects->prePaintWindow(w, data, time); +} -void ScaleInEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( mTimeLineWindows.contains( w ) && isScaleWindow( w ) ) - { +void ScaleInEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (mTimeLineWindows.contains(w) && isScaleWindow(w)) { data.opacity *= mTimeLineWindows[ w ].value(); data.xScale *= mTimeLineWindows[ w ].value(); data.yScale *= mTimeLineWindows[ w ].value(); - data.xTranslate += int( w->width() / 2 * ( 1 - mTimeLineWindows[ w ].value() ) ); - data.yTranslate += int( w->height() / 2 * ( 1 - mTimeLineWindows[ w ].value() ) ); - } - effects->paintWindow( w, mask, region, data ); + data.xTranslate += int(w->width() / 2 * (1 - mTimeLineWindows[ w ].value())); + data.yTranslate += int(w->height() / 2 * (1 - mTimeLineWindows[ w ].value())); } + effects->paintWindow(w, mask, region, data); +} -bool ScaleInEffect::isScaleWindow( EffectWindow* w ) - { - const void* e = w->data( WindowAddedGrabRole ).value(); +bool ScaleInEffect::isScaleWindow(EffectWindow* w) +{ + const void* e = w->data(WindowAddedGrabRole).value(); // TODO: isSpecialWindow is rather generic, maybe tell windowtypes separately? - if ( w->isPopupMenu() || w->isSpecialWindow() || w->isUtility() || ( e && e != this )) + if (w->isPopupMenu() || w->isSpecialWindow() || w->isUtility() || (e && e != this)) return false; return true; - } +} -void ScaleInEffect::postPaintWindow( EffectWindow* w ) - { - if( mTimeLineWindows.contains( w ) ) +void ScaleInEffect::postPaintWindow(EffectWindow* w) +{ + if (mTimeLineWindows.contains(w)) w->addRepaintFull(); // trigger next animation repaint - effects->postPaintWindow( w ); - } + effects->postPaintWindow(w); +} -void ScaleInEffect::windowAdded( EffectWindow* c ) - { - if( c->isOnCurrentDesktop()) - { - mTimeLineWindows[ c ].setDuration( animationTime( 250 )); - mTimeLineWindows[ c ].setProgress( 0.0 ); +void ScaleInEffect::windowAdded(EffectWindow* c) +{ + if (c->isOnCurrentDesktop()) { + mTimeLineWindows[ c ].setDuration(animationTime(250)); + mTimeLineWindows[ c ].setProgress(0.0); c->addRepaintFull(); - } } +} -void ScaleInEffect::windowClosed( EffectWindow* c ) - { - mTimeLineWindows.remove( c ); - } +void ScaleInEffect::windowClosed(EffectWindow* c) +{ + mTimeLineWindows.remove(c); +} } // namespace diff --git a/effects/scalein/scalein.h b/effects/scalein/scalein.h index 7b79a5069..bf378c409 100644 --- a/effects/scalein/scalein.h +++ b/effects/scalein/scalein.h @@ -28,19 +28,19 @@ namespace KWin class ScaleInEffect : public Effect - { - public: - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - // TODO react also on virtual desktop changes - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - private: - bool isScaleWindow ( EffectWindow* w ); - QHash< const EffectWindow*, TimeLine > mTimeLineWindows; - }; +{ +public: + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + // TODO react also on virtual desktop changes + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); +private: + bool isScaleWindow(EffectWindow* w); + QHash< const EffectWindow*, TimeLine > mTimeLineWindows; +}; } // namespace diff --git a/effects/screenshot/screenshot.cpp b/effects/screenshot/screenshot.cpp index 03ddeab7e..5fc09ec44 100644 --- a/effects/screenshot/screenshot.cpp +++ b/effects/screenshot/screenshot.cpp @@ -31,142 +31,129 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( screenshot, ScreenShotEffect ) -KWIN_EFFECT_SUPPORTED( screenshot, ScreenShotEffect::supported() ) +KWIN_EFFECT(screenshot, ScreenShotEffect) +KWIN_EFFECT_SUPPORTED(screenshot, ScreenShotEffect::supported()) bool ScreenShotEffect::supported() - { +{ return effects->compositingType() == KWin::OpenGLCompositing && GLRenderTarget::supported(); - } +} ScreenShotEffect::ScreenShotEffect() - : m_scheduledScreenshot( 0 ) - { - QDBusConnection::sessionBus().registerObject( "/Screenshot", this, QDBusConnection::ExportScriptableContents ); - QDBusConnection::sessionBus().registerService( "org.kde.kwin.Screenshot" ); - } + : m_scheduledScreenshot(0) +{ + QDBusConnection::sessionBus().registerObject("/Screenshot", this, QDBusConnection::ExportScriptableContents); + QDBusConnection::sessionBus().registerService("org.kde.kwin.Screenshot"); +} ScreenShotEffect::~ScreenShotEffect() - { - QDBusConnection::sessionBus().unregisterObject( "/Screenshot" ); - QDBusConnection::sessionBus().unregisterService( "org.kde.kwin.Screenshot" ); - } +{ + QDBusConnection::sessionBus().unregisterObject("/Screenshot"); + QDBusConnection::sessionBus().unregisterService("org.kde.kwin.Screenshot"); +} void ScreenShotEffect::postPaintScreen() - { +{ effects->postPaintScreen(); - if( m_scheduledScreenshot ) - { + if (m_scheduledScreenshot) { int w = displayWidth(); int h = displayHeight(); - if( !GLTexture::NPOTTextureSupported() ) - { - w = nearestPowerOfTwo( w ); - h = nearestPowerOfTwo( h ); - } - GLTexture* offscreenTexture = new GLTexture( w, h ); - offscreenTexture->setFilter( GL_LINEAR ); - offscreenTexture->setWrapMode( GL_CLAMP_TO_EDGE ); - GLRenderTarget* target = new GLRenderTarget( offscreenTexture ); - if( target->valid() ) - { - WindowPaintData d( m_scheduledScreenshot ); + if (!GLTexture::NPOTTextureSupported()) { + w = nearestPowerOfTwo(w); + h = nearestPowerOfTwo(h); + } + GLTexture* offscreenTexture = new GLTexture(w, h); + offscreenTexture->setFilter(GL_LINEAR); + offscreenTexture->setWrapMode(GL_CLAMP_TO_EDGE); + GLRenderTarget* target = new GLRenderTarget(offscreenTexture); + if (target->valid()) { + WindowPaintData d(m_scheduledScreenshot); double left = 0; double top = 0; double right = m_scheduledScreenshot->width(); double bottom = m_scheduledScreenshot->height(); - if( m_scheduledScreenshot->hasDecoration() && m_type & INCLUDE_DECORATION ) - { - foreach( const WindowQuad& quad, d.quads ) - { + if (m_scheduledScreenshot->hasDecoration() && m_type & INCLUDE_DECORATION) { + foreach (const WindowQuad & quad, d.quads) { // we need this loop to include the decoration padding left = qMin(left, quad.left()); top = qMin(top, quad.top()); right = qMax(right, quad.right()); bottom = qMax(bottom, quad.bottom()); - } } - else if( m_scheduledScreenshot->hasDecoration() ) - { + } else if (m_scheduledScreenshot->hasDecoration()) { WindowQuadList newQuads; left = m_scheduledScreenshot->width(); top = m_scheduledScreenshot->height(); right = 0; bottom = 0; - foreach( const WindowQuad& quad, d.quads ) - { - if( quad.type() == WindowQuadContents ) - { + foreach (const WindowQuad & quad, d.quads) { + if (quad.type() == WindowQuadContents) { newQuads << quad; left = qMin(left, quad.left()); top = qMin(top, quad.top()); right = qMax(right, quad.right()); bottom = qMax(bottom, quad.bottom()); - } } - d.quads = newQuads; } + d.quads = newQuads; + } int width = right - left; int height = bottom - top; d.xTranslate = -m_scheduledScreenshot->x() - left; d.yTranslate = -m_scheduledScreenshot->y() - top; // render window into offscreen texture int mask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT; - effects->pushRenderTarget( target ); + effects->pushRenderTarget(target); glClearColor(0.0, 0.0, 0.0, 0.0); - glClear( GL_COLOR_BUFFER_BIT ); + glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.0, 0.0, 0.0, 1.0); - effects->drawWindow( m_scheduledScreenshot, mask, QRegion( 0, 0, width, height ), d ); + effects->drawWindow(m_scheduledScreenshot, mask, QRegion(0, 0, width, height), d); // copy content from framebuffer into image - QImage img( QSize( width, height ), QImage::Format_ARGB32 ); + QImage img(QSize(width, height), QImage::Format_ARGB32); glReadPixels(0, offscreenTexture->height() - height, width, height, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)img.bits()); effects->popRenderTarget(); - ScreenShotEffect::convertFromGLImage( img, width, height ); - if( m_type & INCLUDE_CURSOR ) - { - grabPointerImage( img, m_scheduledScreenshot->x() + left, m_scheduledScreenshot->y() + top ); - } - m_lastScreenshot = QPixmap::fromImage( img ); - emit screenshotCreated( m_lastScreenshot.handle() ); + ScreenShotEffect::convertFromGLImage(img, width, height); + if (m_type & INCLUDE_CURSOR) { + grabPointerImage(img, m_scheduledScreenshot->x() + left, m_scheduledScreenshot->y() + top); } + m_lastScreenshot = QPixmap::fromImage(img); + emit screenshotCreated(m_lastScreenshot.handle()); + } delete offscreenTexture; delete target; m_scheduledScreenshot = NULL; - } } +} void ScreenShotEffect::screenshotWindowUnderCursor(int mask) - { +{ m_type = (ScreenShotType)mask; const QPoint cursor = effects->cursorPos(); - foreach( EffectWindow* w, effects->stackingOrder() ) - { - if( w->geometry().contains( cursor ) && w->isOnCurrentDesktop() && !w->isMinimized() ) - { + foreach (EffectWindow * w, effects->stackingOrder()) { + if (w->geometry().contains(cursor) && w->isOnCurrentDesktop() && !w->isMinimized()) { m_scheduledScreenshot = w; - } - } - if( m_scheduledScreenshot ) - { - m_scheduledScreenshot->addRepaintFull(); } } + if (m_scheduledScreenshot) { + m_scheduledScreenshot->addRepaintFull(); + } +} -void ScreenShotEffect::grabPointerImage( QImage& snapshot, int offsetx, int offsety ) +void ScreenShotEffect::grabPointerImage(QImage& snapshot, int offsetx, int offsety) // Uses the X11_EXTENSIONS_XFIXES_H extension to grab the pointer image, and overlays it onto the snapshot. { - XFixesCursorImage *xcursorimg = XFixesGetCursorImage( QX11Info::display() ); - if ( !xcursorimg ) - return; + XFixesCursorImage *xcursorimg = XFixesGetCursorImage(QX11Info::display()); + if (!xcursorimg) + return; //Annoyingly, xfixes specifies the data to be 32bit, but places it in an unsigned long * //which can be 64 bit. So we need to iterate over a 64bit structure to put it in a 32bit //structure. - QVarLengthArray< quint32 > pixels( xcursorimg->width * xcursorimg->height ); + QVarLengthArray< quint32 > pixels(xcursorimg->width * xcursorimg->height); for (int i = 0; i < xcursorimg->width * xcursorimg->height; ++i) pixels[i] = xcursorimg->pixels[i] & 0xffffffff; QImage qcursorimg((uchar *) pixels.data(), xcursorimg->width, xcursorimg->height, - QImage::Format_ARGB32_Premultiplied); + QImage::Format_ARGB32_Premultiplied); QPainter painter(&snapshot); painter.drawImage(QPointF(xcursorimg->x - xcursorimg->xhot - offsetx, xcursorimg->y - xcursorimg ->yhot - offsety), qcursorimg); @@ -182,7 +169,7 @@ void ScreenShotEffect::convertFromGLImage(QImage &img, int w, int h) if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { // OpenGL gives RGBA; Qt wants ARGB uint *p = (uint*)img.bits(); - uint *end = p + w*h; + uint *end = p + w * h; while (p < end) { uint a = *p << 24; *p = (*p >> 8) | a; @@ -192,10 +179,10 @@ void ScreenShotEffect::convertFromGLImage(QImage &img, int w, int h) // OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB for (int y = 0; y < h; y++) { uint *q = (uint*)img.scanLine(y); - for (int x=0; x < w; ++x) { + for (int x = 0; x < w; ++x) { const uint pixel = *q; *q = ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) - | (pixel & 0xff00ff00); + | (pixel & 0xff00ff00); q++; } diff --git a/effects/screenshot/screenshot.h b/effects/screenshot/screenshot.h index b1d98e8fb..0b0271250 100644 --- a/effects/screenshot/screenshot.h +++ b/effects/screenshot/screenshot.h @@ -29,33 +29,32 @@ namespace KWin { class ScreenShotEffect : public QObject, public Effect - { +{ Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Screenshot") - public: - enum ScreenShotType - { - INCLUDE_DECORATION = 1 << 0, - INCLUDE_CURSOR = 1 << 1 - }; - ScreenShotEffect(); - virtual ~ScreenShotEffect(); - virtual void postPaintScreen(); - - static bool supported(); - static void convertFromGLImage(QImage &img, int w, int h); - public Q_SLOTS: - Q_SCRIPTABLE void screenshotWindowUnderCursor( int mask = 0 ); - - Q_SIGNALS: - Q_SCRIPTABLE void screenshotCreated( qulonglong handle ); - - private: - void grabPointerImage( QImage& snapshot, int offsetx, int offsety ); - EffectWindow *m_scheduledScreenshot; - ScreenShotType m_type; - QPixmap m_lastScreenshot; +public: + enum ScreenShotType { + INCLUDE_DECORATION = 1 << 0, + INCLUDE_CURSOR = 1 << 1 }; + ScreenShotEffect(); + virtual ~ScreenShotEffect(); + virtual void postPaintScreen(); + + static bool supported(); + static void convertFromGLImage(QImage &img, int w, int h); +public Q_SLOTS: + Q_SCRIPTABLE void screenshotWindowUnderCursor(int mask = 0); + +Q_SIGNALS: + Q_SCRIPTABLE void screenshotCreated(qulonglong handle); + +private: + void grabPointerImage(QImage& snapshot, int offsetx, int offsety); + EffectWindow *m_scheduledScreenshot; + ScreenShotType m_type; + QPixmap m_lastScreenshot; +}; } // namespace diff --git a/effects/sheet/sheet.cpp b/effects/sheet/sheet.cpp index a13038429..86d9663af 100644 --- a/effects/sheet/sheet.cpp +++ b/effects/sheet/sheet.cpp @@ -28,169 +28,156 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( sheet, SheetEffect ) -KWIN_EFFECT_SUPPORTED( sheet, SheetEffect::supported() ) +KWIN_EFFECT(sheet, SheetEffect) +KWIN_EFFECT_SUPPORTED(sheet, SheetEffect::supported()) static const int IsSheetWindow = 0x22A982D5; SheetEffect::SheetEffect() - { - reconfigure( ReconfigureAll ); - } +{ + reconfigure(ReconfigureAll); +} bool SheetEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void SheetEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "Sheet" ); - duration = animationTime( conf, "AnimationTime", 500 ); - } +void SheetEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("Sheet"); + duration = animationTime(conf, "AnimationTime", 500); +} -void SheetEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !windows.isEmpty() ) - { +void SheetEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!windows.isEmpty()) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; screenTime = time; + } + effects->prePaintScreen(data, time); +} + +void SheetEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + InfoMap::iterator info = windows.find(w); + if (info != windows.end()) { + data.setTransformed(); + if (info->added) + info->timeLine.addTime(screenTime); + else if (info->closed) { + info->timeLine.removeTime(screenTime); + if (info->deleted) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } - effects->prePaintScreen( data, time ); } -void SheetEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - InfoMap::iterator info = windows.find( w ); - if( info != windows.end() ) - { - data.setTransformed(); - if( info->added ) - info->timeLine.addTime( screenTime ); - else if( info->closed ) - { - info->timeLine.removeTime( screenTime ); - if( info->deleted ) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); - } - } - - effects->prePaintWindow( w, data, time ); - + effects->prePaintWindow(w, data, time); + // if the window isn't to be painted, then let's make sure // to track its progress - if( info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect() ) + if (info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect()) w->addRepaintFull(); - } +} -void SheetEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - InfoMap::const_iterator info = windows.constFind( w ); - if( info != windows.constEnd() ) - { +void SheetEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + InfoMap::const_iterator info = windows.constFind(w); + if (info != windows.constEnd()) { const double progress = info->timeLine.value(); RotationData rot; rot.axis = RotationData::XAxis; - rot.angle = 60.0 * ( 1.0 - progress ); + rot.angle = 60.0 * (1.0 - progress); data.rotation = &rot; data.yScale *= progress; data.zScale *= progress; - data.yTranslate -= (w->y() - info->parentY) * ( 1.0 - progress ); - } - effects->paintWindow( w, mask, region, data ); + data.yTranslate -= (w->y() - info->parentY) * (1.0 - progress); } + effects->paintWindow(w, mask, region, data); +} -void SheetEffect::postPaintWindow( EffectWindow* w ) - { - InfoMap::iterator info = windows.find( w ); - if( info != windows.end() ) - { - if( info->added && info->timeLine.value() == 1.0 ) - { - windows.remove( w ); +void SheetEffect::postPaintWindow(EffectWindow* w) +{ + InfoMap::iterator info = windows.find(w); + if (info != windows.end()) { + if (info->added && info->timeLine.value() == 1.0) { + windows.remove(w); effects->addRepaintFull(); - } - else if( info->closed && info->timeLine.value() == 0.0 ) - { + } else if (info->closed && info->timeLine.value() == 0.0) { info->closed = false; - if( info->deleted ) - { - windows.remove( w ); + if (info->deleted) { + windows.remove(w); w->unrefWindow(); - } - effects->addRepaintFull(); } - if( info->added || info->closed ) - w->addRepaintFull(); + effects->addRepaintFull(); } - effects->postPaintWindow( w ); + if (info->added || info->closed) + w->addRepaintFull(); } + effects->postPaintWindow(w); +} -void SheetEffect::windowAdded( EffectWindow* w ) - { - if( !isSheetWindow( w ) ) +void SheetEffect::windowAdded(EffectWindow* w) +{ + if (!isSheetWindow(w)) return; - w->setData( IsSheetWindow, true ); - - InfoMap::iterator it = windows.find( w ); - WindowInfo *info = ( it == windows.end() ) ? &windows[w] : &it.value(); + w->setData(IsSheetWindow, true); + + InfoMap::iterator it = windows.find(w); + WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = true; info->closed = false; info->deleted = false; - info->timeLine.setDuration( duration ); + info->timeLine.setDuration(duration); const EffectWindowList stack = effects->stackingOrder(); // find parent - foreach( EffectWindow* window, stack ) - { - if( window->findModal() == w ) - { + foreach (EffectWindow * window, stack) { + if (window->findModal() == w) { info->parentY = window->y(); break; - } } - w->addRepaintFull(); } + w->addRepaintFull(); +} -void SheetEffect::windowClosed( EffectWindow* w ) - { - if( !isSheetWindow( w ) ) +void SheetEffect::windowClosed(EffectWindow* w) +{ + if (!isSheetWindow(w)) return; - + w->refWindow(); - - InfoMap::iterator it = windows.find( w ); - WindowInfo *info = ( it == windows.end() ) ? &windows[w] : &it.value(); + + InfoMap::iterator it = windows.find(w); + WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = false; info->closed = true; info->deleted = true; - info->timeLine.setDuration( duration ); - info->timeLine.setProgress( 1.0 ); + info->timeLine.setDuration(duration); + info->timeLine.setProgress(1.0); bool found = false; // find parent const EffectWindowList stack = effects->stackingOrder(); - foreach( EffectWindow* window, stack ) - { - if( window->findModal() == w ) - { + foreach (EffectWindow * window, stack) { + if (window->findModal() == w) { info->parentY = window->y(); found = true; break; - } } - if( !found ) + } + if (!found) info->parentY = 0; w->addRepaintFull(); - } +} -void SheetEffect::windowDeleted( EffectWindow* w ) - { - windows.remove( w ); - } +void SheetEffect::windowDeleted(EffectWindow* w) +{ + windows.remove(w); +} -bool SheetEffect::isSheetWindow( EffectWindow* w ) - { - return ( w->isModal() || w->data( IsSheetWindow ).toBool() ); - } +bool SheetEffect::isSheetWindow(EffectWindow* w) +{ + return (w->isModal() || w->data(IsSheetWindow).toBool()); +} } // namespace diff --git a/effects/sheet/sheet.h b/effects/sheet/sheet.h index 4327b3d39..233f736bf 100644 --- a/effects/sheet/sheet.h +++ b/effects/sheet/sheet.h @@ -29,45 +29,44 @@ namespace KWin class SheetEffect : public Effect - { - public: - SheetEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); +{ +public: + SheetEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); - static bool supported(); - private: - class WindowInfo; - typedef QMap< const EffectWindow*, WindowInfo > InfoMap; - bool isSheetWindow( EffectWindow* w ); - InfoMap windows; - float duration; - int screenTime; - }; + static bool supported(); +private: + class WindowInfo; + typedef QMap< const EffectWindow*, WindowInfo > InfoMap; + bool isSheetWindow(EffectWindow* w); + InfoMap windows; + float duration; + int screenTime; +}; class SheetEffect::WindowInfo - { - public: - WindowInfo() - : deleted( false ) - , added( false ) - , closed( false ) - , parentY( 0 ) - { - } - bool deleted; - bool added; - bool closed; - TimeLine timeLine; - int parentY; - }; +{ +public: + WindowInfo() + : deleted(false) + , added(false) + , closed(false) + , parentY(0) { + } + bool deleted; + bool added; + bool closed; + TimeLine timeLine; + int parentY; +}; } // namespace diff --git a/effects/showfps/showfps.cpp b/effects/showfps/showfps.cpp index 2d96cf42f..dd12b7f0b 100644 --- a/effects/showfps/showfps.cpp +++ b/effects/showfps/showfps.cpp @@ -43,153 +43,149 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( showfps, ShowFpsEffect ) +KWIN_EFFECT(showfps, ShowFpsEffect) const int FPS_WIDTH = 10; const int MAX_TIME = 100; ShowFpsEffect::ShowFpsEffect() - : paints_pos( 0 ) - , frames_pos( 0 ) + : paints_pos(0) + , frames_pos(0) #ifdef KWIN_HAVE_OPENGL_COMPOSITING , fpsText(0) #endif - { - for( int i = 0; - i < NUM_PAINTS; - ++i ) - { +{ + for (int i = 0; + i < NUM_PAINTS; + ++i) { paints[ i ] = 0; paint_size[ i ] = 0; - } - for( int i = 0; - i < MAX_FPS; - ++i ) - frames[ i ] = 0; - reconfigure( ReconfigureAll ); } + for (int i = 0; + i < MAX_FPS; + ++i) + frames[ i ] = 0; + reconfigure(ReconfigureAll); +} -void ShowFpsEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup config( KGlobal::config(), "EffectShowFps" ); - alpha = config.readEntry( "Alpha", 0.5 ); - x = config.readEntry( "X", -10000 ); - y = config.readEntry( "Y", 0 ); - if( x == -10000 ) // there's no -0 :( - x = displayWidth() - 2*NUM_PAINTS - FPS_WIDTH; - else if ( x < 0 ) - x = displayWidth() - 2*NUM_PAINTS - FPS_WIDTH - x; - if( y == -10000 ) +void ShowFpsEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup config(KGlobal::config(), "EffectShowFps"); + alpha = config.readEntry("Alpha", 0.5); + x = config.readEntry("X", -10000); + y = config.readEntry("Y", 0); + if (x == -10000) // there's no -0 :( + x = displayWidth() - 2 * NUM_PAINTS - FPS_WIDTH; + else if (x < 0) + x = displayWidth() - 2 * NUM_PAINTS - FPS_WIDTH - x; + if (y == -10000) y = displayHeight() - MAX_TIME; - else if ( y < 0 ) + else if (y < 0) y = displayHeight() - MAX_TIME - y; - fps_rect = QRect( x, y, FPS_WIDTH + 2*NUM_PAINTS, MAX_TIME ); - + fps_rect = QRect(x, y, FPS_WIDTH + 2 * NUM_PAINTS, MAX_TIME); + config = effects->effectConfig("ShowFps"); int textPosition = config.readEntry("TextPosition", int(INSIDE_GRAPH)); textFont = config.readEntry("TextFont", QFont()); textColor = config.readEntry("TextColor", QColor()); double textAlpha = config.readEntry("TextAlpha", 1.0); - - if(!textColor.isValid()) + + if (!textColor.isValid()) textColor = QPalette().color(QPalette::Active, QPalette::WindowText); textColor.setAlphaF(textAlpha); - - switch(textPosition) - { - case TOP_LEFT: - fpsTextRect = QRect(0, 0, 100, 100); - textAlign = Qt::AlignTop|Qt::AlignLeft; - break; - case TOP_RIGHT: - fpsTextRect = QRect(displayWidth()-100, 0, 100, 100); - textAlign = Qt::AlignTop|Qt::AlignRight; - break; - case BOTTOM_LEFT: - fpsTextRect = QRect(0, displayHeight()-100, 100, 100); - textAlign = Qt::AlignBottom|Qt::AlignLeft; - break; - case BOTTOM_RIGHT: - fpsTextRect = QRect(displayWidth()-100, displayHeight()-100, 100, 100); - textAlign = Qt::AlignBottom|Qt::AlignRight; - break; - case NOWHERE: - fpsTextRect = QRect(); - break; - case INSIDE_GRAPH: - default: - fpsTextRect = QRect(x, y, FPS_WIDTH + NUM_PAINTS, MAX_TIME); - textAlign = Qt::AlignTop|Qt::AlignRight; - break; - } + + switch(textPosition) { + case TOP_LEFT: + fpsTextRect = QRect(0, 0, 100, 100); + textAlign = Qt::AlignTop | Qt::AlignLeft; + break; + case TOP_RIGHT: + fpsTextRect = QRect(displayWidth() - 100, 0, 100, 100); + textAlign = Qt::AlignTop | Qt::AlignRight; + break; + case BOTTOM_LEFT: + fpsTextRect = QRect(0, displayHeight() - 100, 100, 100); + textAlign = Qt::AlignBottom | Qt::AlignLeft; + break; + case BOTTOM_RIGHT: + fpsTextRect = QRect(displayWidth() - 100, displayHeight() - 100, 100, 100); + textAlign = Qt::AlignBottom | Qt::AlignRight; + break; + case NOWHERE: + fpsTextRect = QRect(); + break; + case INSIDE_GRAPH: + default: + fpsTextRect = QRect(x, y, FPS_WIDTH + NUM_PAINTS, MAX_TIME); + textAlign = Qt::AlignTop | Qt::AlignRight; + break; } - -void ShowFpsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( time == 0 ) { +} + +void ShowFpsEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (time == 0) { // TODO optimized away } t.start(); frames[ frames_pos ] = t.minute() * 60000 + t.second() * 1000 + t.msec(); - if( ++frames_pos == MAX_FPS ) + if (++frames_pos == MAX_FPS) frames_pos = 0; - effects->prePaintScreen( data, time ); + effects->prePaintScreen(data, time); data.paint += fps_rect; paint_size[ paints_pos ] = 0; - } +} -void ShowFpsEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - effects->paintWindow( w, mask, region, data ); +void ShowFpsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + effects->paintWindow(w, mask, region, data); // Take intersection of region and actual window's rect, minus the fps area // (since we keep repainting it) and count the pixels. - QRegion r2 = region & QRect( w->x(), w->y(), w->width(), w->height() ); + QRegion r2 = region & QRect(w->x(), w->y(), w->width(), w->height()); r2 -= fps_rect; int winsize = 0; - foreach( const QRect& r, r2.rects()) - winsize += r.width() * r.height(); + foreach (const QRect & r, r2.rects()) + winsize += r.width() * r.height(); paint_size[ paints_pos ] += winsize; - } +} -void ShowFpsEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); +void ShowFpsEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); int fps = 0; - for( int i = 0; - i < MAX_FPS; - ++i ) - if( abs( t.minute() * 60000 + t.second() * 1000 + t.msec() - frames[ i ] ) < 1000 ) + for (int i = 0; + i < MAX_FPS; + ++i) + if (abs(t.minute() * 60000 + t.second() * 1000 + t.msec() - frames[ i ]) < 1000) ++fps; // count all frames in the last second - if( fps > MAX_TIME ) + if (fps > MAX_TIME) fps = MAX_TIME; // keep it the same height #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == OpenGLCompositing) - { - paintGL( fps ); + if (effects->compositingType() == OpenGLCompositing) { + paintGL(fps); glFinish(); // make sure all rendering is done - } + } #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( effects->compositingType() == XRenderCompositing) - { - paintXrender( fps ); - XSync( display(), False ); // make sure all rendering is done - } -#endif + if (effects->compositingType() == XRenderCompositing) { + paintXrender(fps); + XSync(display(), False); // make sure all rendering is done } +#endif +} #ifdef KWIN_HAVE_OPENGL_COMPOSITING -void ShowFpsEffect::paintGL( int fps ) - { +void ShowFpsEffect::paintGL(int fps) +{ int x = this->x; int y = this->y; #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // TODO painting first the background white and then the contents // means that the contents also blend with the background, I guess if (ShaderManager::instance()->isValid()) { @@ -202,12 +198,12 @@ void ShowFpsEffect::paintGL( int fps ) vbo->setColor(color); QVector verts; verts.reserve(12); - verts << x + 2*NUM_PAINTS + FPS_WIDTH << y; + verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y; verts << x << y; verts << x << y + MAX_TIME; verts << x << y + MAX_TIME; - verts << x + 2*NUM_PAINTS + FPS_WIDTH << y + MAX_TIME; - verts << x + 2*NUM_PAINTS + FPS_WIDTH << y; + verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y + MAX_TIME; + verts << x + 2 * NUM_PAINTS + FPS_WIDTH << y; vbo->setData(6, 2, verts.constData(), NULL); vbo->render(GL_TRIANGLES); y += MAX_TIME; // paint up from the bottom @@ -228,27 +224,26 @@ void ShowFpsEffect::paintGL( int fps ) color.setBlue(0); vbo->setColor(color); QVector vertices; - for( int i = 10; - i < MAX_TIME; - i += 10 ) - { + for (int i = 10; + i < MAX_TIME; + i += 10) { vertices << x << y - i; vertices << x + FPS_WIDTH << y - i; } - vbo->setData(vertices.size()/2, 2, vertices.constData(), NULL); + vbo->setData(vertices.size() / 2, 2, vertices.constData(), NULL); vbo->render(GL_LINES); x += FPS_WIDTH; // Paint FPS graph - paintFPSGraph( x, y ); + paintFPSGraph(x, y); x += NUM_PAINTS; // Paint amount of rendered pixels graph - paintDrawSizeGraph( x, y ); + paintDrawSizeGraph(x, y); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } - + // Paint FPS numerical value paintFPSText(fps); @@ -257,7 +252,7 @@ void ShowFpsEffect::paintGL( int fps ) #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif - } +} #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING @@ -266,61 +261,59 @@ void ShowFpsEffect::paintGL( int fps ) - differently specified rectangles (X: width/height, O: x2,y2) - XRender uses pre-multiplied alpha */ -void ShowFpsEffect::paintXrender( int fps ) - { - Pixmap pixmap = XCreatePixmap( display(), rootWindow(), FPS_WIDTH, MAX_TIME, 32 ); - XRenderPicture p( pixmap, 32 ); - XFreePixmap( display(), pixmap ); +void ShowFpsEffect::paintXrender(int fps) +{ + Pixmap pixmap = XCreatePixmap(display(), rootWindow(), FPS_WIDTH, MAX_TIME, 32); + XRenderPicture p(pixmap, 32); + XFreePixmap(display(), pixmap); XRenderColor col; - col.alpha = int( alpha * 0xffff ); - col.red = int( alpha * 0xffff ); // white - col.green = int( alpha * 0xffff ); - col.blue= int( alpha * 0xffff ); - XRenderFillRectangle( display(), PictOpSrc, p, &col, 0, 0, FPS_WIDTH, MAX_TIME ); + col.alpha = int(alpha * 0xffff); + col.red = int(alpha * 0xffff); // white + col.green = int(alpha * 0xffff); + col.blue = int(alpha * 0xffff); + XRenderFillRectangle(display(), PictOpSrc, p, &col, 0, 0, FPS_WIDTH, MAX_TIME); col.red = 0; // blue col.green = 0; - col.blue = int( alpha * 0xffff ); - XRenderFillRectangle( display(), PictOpSrc, p, &col, 0, MAX_TIME - fps, FPS_WIDTH, fps ); + col.blue = int(alpha * 0xffff); + XRenderFillRectangle(display(), PictOpSrc, p, &col, 0, MAX_TIME - fps, FPS_WIDTH, fps); col.red = 0; // black col.green = 0; col.blue = 0; - for( int i = 10; - i < MAX_TIME; - i += 10 ) - { - XRenderFillRectangle( display(), PictOpSrc, p, &col, 0, MAX_TIME - i, FPS_WIDTH, 1 ); - } - XRenderComposite( display(), alpha != 1.0 ? PictOpOver : PictOpSrc, p, None, - effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, FPS_WIDTH, MAX_TIME ); + for (int i = 10; + i < MAX_TIME; + i += 10) { + XRenderFillRectangle(display(), PictOpSrc, p, &col, 0, MAX_TIME - i, FPS_WIDTH, 1); + } + XRenderComposite(display(), alpha != 1.0 ? PictOpOver : PictOpSrc, p, None, + effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, FPS_WIDTH, MAX_TIME); // Paint FPS graph - paintFPSGraph( x + FPS_WIDTH, y ); + paintFPSGraph(x + FPS_WIDTH, y); // Paint amount of rendered pixels graph - paintDrawSizeGraph( x + FPS_WIDTH + MAX_TIME, y ); - } + paintDrawSizeGraph(x + FPS_WIDTH + MAX_TIME, y); +} #endif void ShowFpsEffect::paintFPSGraph(int x, int y) - { +{ // Paint FPS graph QList lines; lines << 10 << 20 << 50; QList values; - for( int i = 0; - i < NUM_PAINTS; - ++i ) - { - values.append( paints[ ( i + paints_pos ) % NUM_PAINTS ] ); - } - paintGraph( x, y, values, lines, true ); + for (int i = 0; + i < NUM_PAINTS; + ++i) { + values.append(paints[(i + paints_pos) % NUM_PAINTS ]); } + paintGraph(x, y, values, lines, true); +} void ShowFpsEffect::paintDrawSizeGraph(int x, int y) { int max_drawsize = 0; - for( int i = 0; i < NUM_PAINTS; i++) - max_drawsize = qMax(max_drawsize, paint_size[ i ] ); + for (int i = 0; i < NUM_PAINTS; i++) + max_drawsize = qMax(max_drawsize, paint_size[ i ]); // Log of min/max values shown on graph const float max_pixels_log = 7.2f; @@ -330,31 +323,28 @@ void ShowFpsEffect::paintDrawSizeGraph(int x, int y) float drawscale = (MAX_TIME - minh) / (max_pixels_log - min_pixels_log); QList drawlines; - for( int logh = (int)min_pixels_log; logh <= max_pixels_log; logh++ ) - drawlines.append( (int)(( logh - min_pixels_log ) * drawscale ) + minh ); + for (int logh = (int)min_pixels_log; logh <= max_pixels_log; logh++) + drawlines.append((int)((logh - min_pixels_log) * drawscale) + minh); QList drawvalues; - for( int i = 0; - i < NUM_PAINTS; - ++i ) - { - int value = paint_size[ ( i + paints_pos ) % NUM_PAINTS ]; + for (int i = 0; + i < NUM_PAINTS; + ++i) { + int value = paint_size[(i + paints_pos) % NUM_PAINTS ]; int h = 0; - if( value > 0) - { - h = (int)(( log10( (double)value ) - min_pixels_log ) * drawscale ); - h = qMin( qMax( 0, h ) + minh, MAX_TIME ); - } - drawvalues.append( h ); + if (value > 0) { + h = (int)((log10((double)value) - min_pixels_log) * drawscale); + h = qMin(qMax(0, h) + minh, MAX_TIME); } - paintGraph( x, y, drawvalues, drawlines, false ); + drawvalues.append(h); } + paintGraph(x, y, drawvalues, drawlines, false); +} -void ShowFpsEffect::paintGraph( int x, int y, QList values, QList lines, bool colorize) - { +void ShowFpsEffect::paintGraph(int x, int y, QList values, QList lines, bool colorize) +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == OpenGLCompositing) - { + if (effects->compositingType() == OpenGLCompositing) { QColor color(0, 0, 0); color.setAlphaF(alpha); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); @@ -362,12 +352,11 @@ void ShowFpsEffect::paintGraph( int x, int y, QList values, QList line vbo->setColor(color); QVector verts; // First draw the lines - foreach( int h, lines) - { + foreach (int h, lines) { verts << x << y - h; verts << x + values.count() << y - h; - } - vbo->setData(verts.size()/2, 2, verts.constData(), NULL); + } + vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); // Then the graph values int lastValue = 0; @@ -376,15 +365,15 @@ void ShowFpsEffect::paintGraph( int x, int y, QList values, QList line int value = values[ i ]; if (colorize && value != lastValue) { if (!verts.isEmpty()) { - vbo->setData(verts.size()/2, 2, verts.constData(), NULL); + vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); } verts.clear(); if (value <= 10) { color = QColor(0, 255, 0); } else if (value <= 20) { - color= QColor(255, 255, 0); - } else if( value <= 50 ) { + color = QColor(255, 255, 0); + } else if (value <= 50) { color = QColor(255, 0, 0); } else { color = QColor(0, 0, 0); @@ -396,84 +385,78 @@ void ShowFpsEffect::paintGraph( int x, int y, QList values, QList line lastValue = value; } if (!verts.isEmpty()) { - vbo->setData(verts.size()/2, 2, verts.constData(), NULL); + vbo->setData(verts.size() / 2, 2, verts.constData(), NULL); vbo->render(GL_LINES); } - } + } #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( effects->compositingType() == XRenderCompositing) - { - Pixmap pixmap = XCreatePixmap( display(), rootWindow(), values.count(), MAX_TIME, 32 ); - XRenderPicture p( pixmap, 32 ); - XFreePixmap( display(), pixmap ); + if (effects->compositingType() == XRenderCompositing) { + Pixmap pixmap = XCreatePixmap(display(), rootWindow(), values.count(), MAX_TIME, 32); + XRenderPicture p(pixmap, 32); + XFreePixmap(display(), pixmap); XRenderColor col; - col.alpha = int( alpha * 0xffff ); + col.alpha = int(alpha * 0xffff); // Draw background - col.red = col.green = col.blue = int( alpha * 0xffff ); // white - XRenderFillRectangle( display(), PictOpSrc, p, &col, 0, 0, values.count(), MAX_TIME ); + col.red = col.green = col.blue = int(alpha * 0xffff); // white + XRenderFillRectangle(display(), PictOpSrc, p, &col, 0, 0, values.count(), MAX_TIME); // Then the values - col.red = col.green = col.blue = int( alpha * 0x8000 ); // grey - for( int i = 0; i < values.count(); i++ ) - { + col.red = col.green = col.blue = int(alpha * 0x8000); // grey + for (int i = 0; i < values.count(); i++) { int value = values[ i ]; - if( colorize ) - { - if( value <= 10 ) - { // green + if (colorize) { + if (value <= 10) { + // green col.red = 0; - col.green = int( alpha * 0xffff ); + col.green = int(alpha * 0xffff); col.blue = 0; - } - else if( value <= 20 ) - { // yellow - col.red = int( alpha * 0xffff ); - col.green = int( alpha * 0xffff ); + } else if (value <= 20) { + // yellow + col.red = int(alpha * 0xffff); + col.green = int(alpha * 0xffff); col.blue = 0; - } - else if( value <= 50 ) - { // red - col.red = int( alpha * 0xffff ); + } else if (value <= 50) { + // red + col.red = int(alpha * 0xffff); col.green = 0; col.blue = 0; - } - else - { // black + } else { + // black col.red = 0; col.green = 0; col.blue = 0; - } } - XRenderFillRectangle( display(), PictOpSrc, p, &col, - values.count() - i, MAX_TIME - value, 1, value ); } + XRenderFillRectangle(display(), PictOpSrc, p, &col, + values.count() - i, MAX_TIME - value, 1, value); + } // Then the lines col.red = col.green = col.blue = 0; // black - foreach( int h, lines) - XRenderFillRectangle( display(), PictOpSrc, p, &col, 0, MAX_TIME - h, values.count(), 1 ); + foreach (int h, lines) + XRenderFillRectangle(display(), PictOpSrc, p, &col, 0, MAX_TIME - h, values.count(), 1); // Finally render the pixmap onto screen - XRenderComposite( display(), alpha != 1.0 ? PictOpOver : PictOpSrc, p, None, - effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, values.count(), MAX_TIME ); - } -#endif + XRenderComposite(display(), alpha != 1.0 ? PictOpOver : PictOpSrc, p, None, + effects->xrenderBufferPicture(), 0, 0, 0, 0, x, y, values.count(), MAX_TIME); } +#endif +} void ShowFpsEffect::postPaintScreen() - { +{ effects->postPaintScreen(); paints[ paints_pos ] = t.elapsed(); - if( ++paints_pos == NUM_PAINTS ) + if (++paints_pos == NUM_PAINTS) paints_pos = 0; - effects->addRepaint( fps_rect ); - } + effects->addRepaint(fps_rect); +} void ShowFpsEffect::paintFPSText(int fps) - { - if( !fpsTextRect.isValid()) +{ + if (!fpsTextRect.isValid()) return; #ifdef KWIN_HAVE_OPENGL_COMPOSITING QImage im(100, 100, QImage::Format_ARGB32); @@ -482,7 +465,7 @@ void ShowFpsEffect::paintFPSText(int fps) painter.setFont(textFont); painter.setPen(textColor); painter.drawText(QRect(0, 0, 100, 100), textAlign, QString::number(fps)); - if(fpsText) + if (fpsText) delete fpsText; fpsText = new GLTexture(im); fpsText->bind(); @@ -497,6 +480,6 @@ void ShowFpsEffect::paintFPSText(int fps) fpsText->unbind(); effects->addRepaint(fpsTextRect); #endif - } +} } // namespace diff --git a/effects/showfps/showfps.h b/effects/showfps/showfps.h index c62602c8d..a4a24c8ee 100644 --- a/effects/showfps/showfps.h +++ b/effects/showfps/showfps.h @@ -30,47 +30,47 @@ namespace KWin class ShowFpsEffect : public Effect - { - public: - ShowFpsEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintScreen(); - enum { INSIDE_GRAPH, NOWHERE, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; // fps text position - private: +{ +public: + ShowFpsEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintScreen(); + enum { INSIDE_GRAPH, NOWHERE, TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; // fps text position +private: #ifdef KWIN_HAVE_OPENGL_COMPOSITING - void paintGL( int fps ); + void paintGL(int fps); #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - void paintXrender( int fps ); + void paintXrender(int fps); #endif - void paintFPSGraph(int x, int y); - void paintDrawSizeGraph(int x, int y); - void paintGraph( int x, int y, QList values, QList lines, bool colorize); - void paintFPSText(int fps); - QTime t; - enum { NUM_PAINTS = 100 }; // remember time needed to paint this many paints - int paints[ NUM_PAINTS ]; // time needed to paint - int paint_size[ NUM_PAINTS ]; // number of pixels painted - int paints_pos; // position in the queue - enum { MAX_FPS = 200 }; - int frames[ MAX_FPS ]; // (sec*1000+msec) of the time the frame was done - int frames_pos; // position in the queue - double alpha; - int x; - int y; - QRect fps_rect; + void paintFPSGraph(int x, int y); + void paintDrawSizeGraph(int x, int y); + void paintGraph(int x, int y, QList values, QList lines, bool colorize); + void paintFPSText(int fps); + QTime t; + enum { NUM_PAINTS = 100 }; // remember time needed to paint this many paints + int paints[ NUM_PAINTS ]; // time needed to paint + int paint_size[ NUM_PAINTS ]; // number of pixels painted + int paints_pos; // position in the queue + enum { MAX_FPS = 200 }; + int frames[ MAX_FPS ]; // (sec*1000+msec) of the time the frame was done + int frames_pos; // position in the queue + double alpha; + int x; + int y; + QRect fps_rect; #ifdef KWIN_HAVE_OPENGL_COMPOSITING - GLTexture *fpsText; + GLTexture *fpsText; #endif - int textPosition; - QFont textFont; - QColor textColor; - QRect fpsTextRect; - int textAlign; - }; + int textPosition; + QFont textFont; + QColor textColor; + QRect fpsTextRect; + int textAlign; +}; } // namespace diff --git a/effects/showfps/showfps_config.cpp b/effects/showfps/showfps_config.cpp index 91161472c..dcbe93bc0 100644 --- a/effects/showfps/showfps_config.cpp +++ b/effects/showfps/showfps_config.cpp @@ -32,7 +32,7 @@ KWIN_EFFECT_CONFIG_FACTORY ShowFpsEffectConfig::ShowFpsEffectConfig(QWidget* parent, const QVariantList& args) : KCModule(EffectFactory::componentData(), parent, args) - { +{ m_ui = new Ui::ShowFpsEffectConfigForm; m_ui->setupUi(this); @@ -42,38 +42,38 @@ ShowFpsEffectConfig::ShowFpsEffectConfig(QWidget* parent, const QVariantList& ar connect(m_ui->textAlpha, SIGNAL(valueChanged(double)), this, SLOT(changed())); load(); - } - +} + ShowFpsEffectConfig::~ShowFpsEffectConfig() - { +{ delete m_ui; - } - +} + void ShowFpsEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("ShowFps"); int position = conf.readEntry("TextPosition", int(ShowFpsEffect::INSIDE_GRAPH)); - if(position > -1) + if (position > -1) m_ui->textPosition->setCurrentIndex(position); QFont font = conf.readEntry("TextFont", QFont()); m_ui->textFont->setFont(font); QColor color = conf.readEntry("TextColor", QColor()); - if(color.isValid()) + if (color.isValid()) m_ui->textColor->setColor(color); double alpha = conf.readEntry("TextAlpha", 1.0); m_ui->textAlpha->setValue(alpha); emit changed(false); - } - +} + void ShowFpsEffectConfig::save() - { +{ KCModule::save(); KConfigGroup conf = EffectsHandler::effectConfig("ShowFps"); @@ -94,17 +94,17 @@ void ShowFpsEffectConfig::save() emit changed(false); EffectsHandler::sendReloadMessage("showfps"); - } - +} + void ShowFpsEffectConfig::defaults() - { +{ m_ui->textPosition->setCurrentIndex(0); m_ui->textFont->setFont(QFont()); m_ui->textColor->setColor(QColor()); m_ui->textAlpha->setValue(1.0); emit changed(true); - } +} } // namespace diff --git a/effects/showfps/showfps_config.h b/effects/showfps/showfps_config.h index 6cf4711f3..b1846222a 100644 --- a/effects/showfps/showfps_config.h +++ b/effects/showfps/showfps_config.h @@ -30,20 +30,20 @@ namespace KWin { class ShowFpsEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit ShowFpsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~ShowFpsEffectConfig(); +public: + explicit ShowFpsEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~ShowFpsEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - Ui::ShowFpsEffectConfigForm *m_ui; - }; +private: + Ui::ShowFpsEffectConfigForm *m_ui; +}; } // namespace diff --git a/effects/showpaint/showpaint.cpp b/effects/showpaint/showpaint.cpp index a8256ba8c..7dc9ebec4 100644 --- a/effects/showpaint/showpaint.cpp +++ b/effects/showpaint/showpaint.cpp @@ -38,47 +38,48 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( showpaint, ShowPaintEffect ) +KWIN_EFFECT(showpaint, ShowPaintEffect) static QColor colors[] = { Qt::red, Qt::green, Qt::blue, Qt::cyan, Qt::magenta, - Qt::yellow, Qt::gray }; + Qt::yellow, Qt::gray + }; ShowPaintEffect::ShowPaintEffect() - : color_index( 0 ) - { - } + : color_index(0) +{ +} ShowPaintEffect::~ShowPaintEffect() { } -void ShowPaintEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { +void ShowPaintEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ painted = QRegion(); - effects->paintScreen( mask, region, data ); + effects->paintScreen(mask, region, data); #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == OpenGLCompositing) + if (effects->compositingType() == OpenGLCompositing) paintGL(); #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( effects->compositingType() == XRenderCompositing) + if (effects->compositingType() == XRenderCompositing) paintXrender(); #endif - if( ++color_index == sizeof( colors ) / sizeof( colors[ 0 ] )) + if (++color_index == sizeof(colors) / sizeof(colors[ 0 ])) color_index = 0; - } +} -void ShowPaintEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void ShowPaintEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ painted |= region; - effects->paintWindow( w, mask, region, data ); - } + effects->paintWindow(w, mask, region, data); +} void ShowPaintEffect::paintGL() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); @@ -86,14 +87,14 @@ void ShowPaintEffect::paintGL() if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); QColor color = colors[ color_index ]; color.setAlphaF(0.2); vbo->setColor(color); QVector verts; - verts.reserve(painted.rects().count()*12); - foreach (const QRect &r, painted.rects()) { + verts.reserve(painted.rects().count() * 12); + foreach (const QRect & r, painted.rects()) { verts << r.x() + r.width() << r.y(); verts << r.x() << r.y(); verts << r.x() << r.y() + r.height(); @@ -101,32 +102,32 @@ void ShowPaintEffect::paintGL() verts << r.x() + r.width() << r.y() + r.height(); verts << r.x() + r.width() << r.y(); } - vbo->setData(verts.count()/2, 2, verts.data(), NULL); + vbo->setData(verts.count() / 2, 2, verts.data(), NULL); vbo->render(GL_TRIANGLES); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } - glDisable( GL_BLEND ); + glDisable(GL_BLEND); #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif #endif - } +} void ShowPaintEffect::paintXrender() - { +{ #ifdef KWIN_HAVE_XRENDER_COMPOSITING XRenderColor col; float alpha = 0.2; const QColor& color = colors[ color_index ]; - col.alpha = int( alpha * 0xffff ); - col.red = int( alpha * 0xffff * color.red() / 255 ); - col.green = int( alpha * 0xffff * color.green() / 255 ); - col.blue= int( alpha * 0xffff * color.blue() / 255 ); - foreach( const QRect &r, painted.rects()) - XRenderFillRectangle( display(), PictOpOver, effects->xrenderBufferPicture(), - &col, r.x(), r.y(), r.width(), r.height()); + col.alpha = int(alpha * 0xffff); + col.red = int(alpha * 0xffff * color.red() / 255); + col.green = int(alpha * 0xffff * color.green() / 255); + col.blue = int(alpha * 0xffff * color.blue() / 255); + foreach (const QRect & r, painted.rects()) + XRenderFillRectangle(display(), PictOpOver, effects->xrenderBufferPicture(), + &col, r.x(), r.y(), r.width(), r.height()); #endif - } +} } // namespace diff --git a/effects/showpaint/showpaint.h b/effects/showpaint/showpaint.h index 26055c35b..83c48390e 100644 --- a/effects/showpaint/showpaint.h +++ b/effects/showpaint/showpaint.h @@ -28,18 +28,18 @@ namespace KWin class ShowPaintEffect : public Effect - { - public: - ShowPaintEffect(); - ~ShowPaintEffect(); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - private: - void paintGL(); - void paintXrender(); - QRegion painted; // what's painted in one pass - int color_index; - }; +{ +public: + ShowPaintEffect(); + ~ShowPaintEffect(); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); +private: + void paintGL(); + void paintXrender(); + QRegion painted; // what's painted in one pass + int color_index; +}; } // namespace diff --git a/effects/slide/slide.cpp b/effects/slide/slide.cpp index d77f21758..8e5efaa63 100644 --- a/effects/slide/slide.cpp +++ b/effects/slide/slide.cpp @@ -26,228 +26,208 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( slide, SlideEffect ) +KWIN_EFFECT(slide, SlideEffect) SlideEffect::SlideEffect() - : slide( false ) - { + : slide(false) +{ mTimeLine.setCurveShape(TimeLine::EaseInOutCurve); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} -void SlideEffect::reconfigure( ReconfigureFlags ) - { - mTimeLine.setDuration( animationTime( 250 )); - } +void SlideEffect::reconfigure(ReconfigureFlags) +{ + mTimeLine.setDuration(animationTime(250)); +} -void SlideEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( slide ) - { +void SlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (slide) { mTimeLine.addTime(time); // PAINT_SCREEN_BACKGROUND_FIRST is needed because screen will be actually painted more than once, // so with normal screen painting second screen paint would erase parts of the first paint - if( mTimeLine.value() != 1 ) + if (mTimeLine.value() != 1) data.mask |= PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST; - else - { + else { slide = false; mTimeLine.setProgress(0); - effects->setActiveFullScreenEffect( NULL ); - } + effects->setActiveFullScreenEffect(NULL); } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} -void SlideEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( slide ) - { - if( w->isOnAllDesktops()) - { - if( slide_painting_sticky ) +void SlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (slide) { + if (w->isOnAllDesktops()) { + if (slide_painting_sticky) data.setTransformed(); else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - else if( w->isOnDesktop( painting_desktop )) - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } else if (w->isOnDesktop(painting_desktop)) + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); else - w->disablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); - } - effects->prePaintWindow( w, data, time ); + w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); + } + effects->prePaintWindow(w, data, time); +} + +void SlideEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (mTimeLine.value() == 0) { + effects->paintScreen(mask, region, data); + return; } -void SlideEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( mTimeLine.value() == 0 ) - { - effects->paintScreen( mask, region, data ); - return; - } - /* Transformations are done by remembering starting position of the change and the progress of it, the destination is computed from the current desktop. Positions of desktops are done using their topleft corner. */ - QPoint destPos = desktopRect( effects->currentDesktop() ).topLeft(); + QPoint destPos = desktopRect(effects->currentDesktop()).topLeft(); QPoint diffPos = destPos - slide_start_pos; int w = 0; int h = 0; - if( effects->optionRollOverDesktops()) - { + if (effects->optionRollOverDesktops()) { w = effects->workspaceWidth(); h = effects->workspaceHeight(); // wrap around if shorter - if( diffPos.x() > 0 && diffPos.x() > w / 2 ) - diffPos.setX( diffPos.x() - w ); - if( diffPos.x() < 0 && abs( diffPos.x()) > w / 2 ) - diffPos.setX( diffPos.x() + w ); - if( diffPos.y() > 0 && diffPos.y() > h / 2 ) - diffPos.setY( diffPos.y() - h ); - if( diffPos.y() < 0 && abs( diffPos.y()) > h / 2 ) - diffPos.setY( diffPos.y() + h ); - } + if (diffPos.x() > 0 && diffPos.x() > w / 2) + diffPos.setX(diffPos.x() - w); + if (diffPos.x() < 0 && abs(diffPos.x()) > w / 2) + diffPos.setX(diffPos.x() + w); + if (diffPos.y() > 0 && diffPos.y() > h / 2) + diffPos.setY(diffPos.y() - h); + if (diffPos.y() < 0 && abs(diffPos.y()) > h / 2) + diffPos.setY(diffPos.y() + h); + } QPoint currentPos = slide_start_pos + mTimeLine.value() * diffPos; - QSize displaySize( displayWidth(), displayHeight()); - QRegion currentRegion = QRect( currentPos, displaySize ); - if( effects->optionRollOverDesktops()) - { - currentRegion |= ( currentRegion & QRect( -w, 0, w, h )).translated( w, 0 ); - currentRegion |= ( currentRegion & QRect( 0, -h, w, h )).translated( 0, h ); - currentRegion |= ( currentRegion & QRect( w, 0, w, h )).translated( -w, 0 ); - currentRegion |= ( currentRegion & QRect( 0, h, w, h )).translated( 0, -h ); - } + QSize displaySize(displayWidth(), displayHeight()); + QRegion currentRegion = QRect(currentPos, displaySize); + if (effects->optionRollOverDesktops()) { + currentRegion |= (currentRegion & QRect(-w, 0, w, h)).translated(w, 0); + currentRegion |= (currentRegion & QRect(0, -h, w, h)).translated(0, h); + currentRegion |= (currentRegion & QRect(w, 0, w, h)).translated(-w, 0); + currentRegion |= (currentRegion & QRect(0, h, w, h)).translated(0, -h); + } bool do_sticky = true; - for( int desktop = 1; - desktop <= effects->numberOfDesktops(); - ++desktop ) - { - QRect rect = desktopRect( desktop ); - if( currentRegion.contains( rect )) // part of the desktop needs painting - { + for (int desktop = 1; + desktop <= effects->numberOfDesktops(); + ++desktop) { + QRect rect = desktopRect(desktop); + if (currentRegion.contains(rect)) { // part of the desktop needs painting painting_desktop = desktop; slide_painting_sticky = do_sticky; slide_painting_diff = rect.topLeft() - currentPos; - if( effects->optionRollOverDesktops()) - { - if( slide_painting_diff.x() > displayWidth()) - slide_painting_diff.setX( slide_painting_diff.x() - w ); - if( slide_painting_diff.x() < -displayWidth()) - slide_painting_diff.setX( slide_painting_diff.x() + w ); - if( slide_painting_diff.y() > displayHeight()) - slide_painting_diff.setY( slide_painting_diff.y() - h ); - if( slide_painting_diff.y() < -displayHeight()) - slide_painting_diff.setY( slide_painting_diff.y() + h ); - } + if (effects->optionRollOverDesktops()) { + if (slide_painting_diff.x() > displayWidth()) + slide_painting_diff.setX(slide_painting_diff.x() - w); + if (slide_painting_diff.x() < -displayWidth()) + slide_painting_diff.setX(slide_painting_diff.x() + w); + if (slide_painting_diff.y() > displayHeight()) + slide_painting_diff.setY(slide_painting_diff.y() - h); + if (slide_painting_diff.y() < -displayHeight()) + slide_painting_diff.setY(slide_painting_diff.y() + h); + } do_sticky = false; // paint on-all-desktop windows only once ScreenPaintData d = data; d.xTranslate += slide_painting_diff.x(); d.yTranslate += slide_painting_diff.y(); // TODO mask parts that are not visible? - effects->paintScreen( mask, region, d ); - } + effects->paintScreen(mask, region, d); } } +} -void SlideEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - if( slide ) - { // don't move windows on all desktops (compensate screen transformation) - if( w->isOnAllDesktops()) // TODO also fix 'Workspace::movingClient' - { +void SlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + if (slide) { + // don't move windows on all desktops (compensate screen transformation) + if (w->isOnAllDesktops()) { // TODO also fix 'Workspace::movingClient' data.xTranslate -= slide_painting_diff.x(); data.yTranslate -= slide_painting_diff.y(); - } } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} void SlideEffect::postPaintScreen() - { - if( slide ) +{ + if (slide) effects->addRepaintFull(); effects->postPaintScreen(); - } +} // Gives a position of the given desktop when all desktops are arranged in a grid -QRect SlideEffect::desktopRect( int desktop ) const - { - QRect rect( 0, 0, displayWidth(), displayHeight() ); - rect.translate( effects->desktopCoords( desktop )); +QRect SlideEffect::desktopRect(int desktop) const +{ + QRect rect(0, 0, displayWidth(), displayHeight()); + rect.translate(effects->desktopCoords(desktop)); return rect; - } +} -void SlideEffect::desktopChanged( int old ) - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) +void SlideEffect::desktopChanged(int old) +{ + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; - - if( slide ) // old slide still in progress - { - QPoint diffPos = desktopRect( old ).topLeft() - slide_start_pos; + + if (slide) { // old slide still in progress + QPoint diffPos = desktopRect(old).topLeft() - slide_start_pos; int w = 0; int h = 0; - if( effects->optionRollOverDesktops()) - { + if (effects->optionRollOverDesktops()) { w = effects->workspaceWidth(); h = effects->workspaceHeight(); // wrap around if shorter - if( diffPos.x() > 0 && diffPos.x() > w / 2 ) - diffPos.setX( diffPos.x() - w ); - if( diffPos.x() < 0 && abs( diffPos.x()) > w / 2 ) - diffPos.setX( diffPos.x() + w ); - if( diffPos.y() > 0 && diffPos.y() > h / 2 ) - diffPos.setY( diffPos.y() - h ); - if( diffPos.y() < 0 && abs( diffPos.y()) > h / 2 ) - diffPos.setY( diffPos.y() + h ); - } + if (diffPos.x() > 0 && diffPos.x() > w / 2) + diffPos.setX(diffPos.x() - w); + if (diffPos.x() < 0 && abs(diffPos.x()) > w / 2) + diffPos.setX(diffPos.x() + w); + if (diffPos.y() > 0 && diffPos.y() > h / 2) + diffPos.setY(diffPos.y() - h); + if (diffPos.y() < 0 && abs(diffPos.y()) > h / 2) + diffPos.setY(diffPos.y() + h); + } QPoint currentPos = slide_start_pos + mTimeLine.value() * diffPos; - QRegion currentRegion = QRect( currentPos, QSize( displayWidth(), displayHeight())); - if( effects->optionRollOverDesktops()) - { - currentRegion |= ( currentRegion & QRect( -w, 0, w, h )).translated( w, 0 ); - currentRegion |= ( currentRegion & QRect( 0, -h, w, h )).translated( 0, h ); - currentRegion |= ( currentRegion & QRect( w, 0, w, h )).translated( -w, 0 ); - currentRegion |= ( currentRegion & QRect( 0, h, w, h )).translated( 0, -h ); - } - QRect rect = desktopRect( effects->currentDesktop() ); - if( currentRegion.contains( rect )) - { // current position is in new current desktop (e.g. quickly changing back), - // don't do full progress - if( abs( currentPos.x() - rect.x()) > abs( currentPos.y() - rect.y())) - mTimeLine.setProgress(1 - abs( currentPos.x() - rect.x()) / double( displayWidth())); + QRegion currentRegion = QRect(currentPos, QSize(displayWidth(), displayHeight())); + if (effects->optionRollOverDesktops()) { + currentRegion |= (currentRegion & QRect(-w, 0, w, h)).translated(w, 0); + currentRegion |= (currentRegion & QRect(0, -h, w, h)).translated(0, h); + currentRegion |= (currentRegion & QRect(w, 0, w, h)).translated(-w, 0); + currentRegion |= (currentRegion & QRect(0, h, w, h)).translated(0, -h); + } + QRect rect = desktopRect(effects->currentDesktop()); + if (currentRegion.contains(rect)) { + // current position is in new current desktop (e.g. quickly changing back), + // don't do full progress + if (abs(currentPos.x() - rect.x()) > abs(currentPos.y() - rect.y())) + mTimeLine.setProgress(1 - abs(currentPos.x() - rect.x()) / double(displayWidth())); else - mTimeLine.setProgress(1 - abs( currentPos.y() - rect.y()) / double( displayHeight())); - } - else // current position is not on current desktop, do full progress + mTimeLine.setProgress(1 - abs(currentPos.y() - rect.y()) / double(displayHeight())); + } else // current position is not on current desktop, do full progress mTimeLine.setProgress(0); diffPos = rect.topLeft() - currentPos; - if( mTimeLine.value() <= 0 ) - { + if (mTimeLine.value() <= 0) { // Compute starting point for this new move (given current and end positions) - slide_start_pos = rect.topLeft() - diffPos * 1 / ( 1 - mTimeLine.value() ); - } - else - { // at the end, stop + slide_start_pos = rect.topLeft() - diffPos * 1 / (1 - mTimeLine.value()); + } else { + // at the end, stop slide = false; mTimeLine.setProgress(0); - effects->setActiveFullScreenEffect( NULL ); - } + effects->setActiveFullScreenEffect(NULL); } - else - { - if( effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this ) + } else { + if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; mTimeLine.setProgress(0); - slide_start_pos = desktopRect( old ).topLeft(); + slide_start_pos = desktopRect(old).topLeft(); slide = true; - effects->setActiveFullScreenEffect( this ); - } - effects->addRepaintFull(); + effects->setActiveFullScreenEffect(this); } + effects->addRepaintFull(); +} } // namespace diff --git a/effects/slide/slide.h b/effects/slide/slide.h index d112abae9..5befbeecd 100644 --- a/effects/slide/slide.h +++ b/effects/slide/slide.h @@ -30,27 +30,27 @@ namespace KWin class SlideEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - SlideEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void desktopChanged( int old ); - private: - QRect desktopRect( int desktop ) const; - TimeLine mTimeLine; - int painting_desktop; - bool slide; - QPoint slide_start_pos; - bool slide_painting_sticky; - QPoint slide_painting_diff; +public: + SlideEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void desktopChanged(int old); +private: + QRect desktopRect(int desktop) const; + TimeLine mTimeLine; + int painting_desktop; + bool slide; + QPoint slide_start_pos; + bool slide_painting_sticky; + QPoint slide_painting_diff; - }; +}; } // namespace diff --git a/effects/slideback/slideback.cpp b/effects/slideback/slideback.cpp index a3189401c..9b23d9c84 100644 --- a/effects/slideback/slideback.cpp +++ b/effects/slideback/slideback.cpp @@ -26,121 +26,102 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( slideback, SlideBackEffect ) +KWIN_EFFECT(slideback, SlideBackEffect) SlideBackEffect::SlideBackEffect() - { +{ updateStackingOrder(); disabled = false; unminimizedWindow = NULL; - } - -static inline bool windowsShareDesktop( EffectWindow *w1, EffectWindow *w2 ) - { +} + +static inline bool windowsShareDesktop(EffectWindow *w1, EffectWindow *w2) +{ return w1->isOnAllDesktops() || w2->isOnAllDesktops() || w1->desktop() == w2->desktop(); +} + +void SlideBackEffect::windowActivated(EffectWindow* w) +{ + if (w == NULL || w->keepAbove()) { // plasma popups, yakuake etc... + return; } -void SlideBackEffect::windowActivated( EffectWindow* w ) - { - if( w == NULL || w->keepAbove()) // plasma popups, yakuake etc... - { - return; - } - - if( disabled || effects->activeFullScreenEffect() ) // TabBox or PresentWindows/Cube in progress - { + if (disabled || effects->activeFullScreenEffect()) { // TabBox or PresentWindows/Cube in progress updateStackingOrder(); disabled = false; return; - } + } - if( !isWindowUsable( w ) || !stackingOrderChanged() || !isWindowOnTop( w ) ) // Focus changed but stacking still the same - { + if (!isWindowUsable(w) || !stackingOrderChanged() || !isWindowOnTop(w)) { // Focus changed but stacking still the same updateStackingOrder(); return; - } + } - if( unminimizedWindow == w ){ // A window was activated by being unminimized. Don't trigger SlideBack. + if (unminimizedWindow == w) { // A window was activated by being unminimized. Don't trigger SlideBack. unminimizedWindow = NULL; updateStackingOrder(); return; } - - if( clientItemShown == w ) - { + + if (clientItemShown == w) { clientItemShown = NULL; updateStackingOrder(); return; - } - if( clientItemHidden == w ) - { + } + if (clientItemHidden == w) { clientItemHidden = NULL; updateStackingOrder(); return; - } + } // Determine all windows on top of the activated one bool currentFound = false; - foreach( EffectWindow *tmp, oldStackingOrder ) - { - if( !currentFound ) - { - if( tmp == w ) - { + foreach (EffectWindow * tmp, oldStackingOrder) { + if (!currentFound) { + if (tmp == w) { currentFound = true; + } + } else { + if (isWindowUsable(tmp) && windowsShareDesktop(tmp, w)) { + // Do we have to move it? + if (intersects(w, tmp->geometry())) { + QRect slideRect; + slideRect = getSlideDestination(getModalGroupGeometry(w), tmp->geometry()); + effects->setElevatedWindow(tmp, true); + elevatedList.append(tmp); + motionManager.manage(tmp); + motionManager.moveWindow(tmp, slideRect); + destinationList.insert(tmp, slideRect); + coveringWindows.append(tmp); + } else { + //Does it intersect with a moved (elevated) window and do we have to elevate it too? + foreach (EffectWindow * elevatedWindow, elevatedList) { + if (tmp->geometry().intersects(elevatedWindow->geometry())) { + effects->setElevatedWindow(tmp, true); + elevatedList.append(tmp); + break; + } + } + } } - else - { - if( isWindowUsable( tmp ) && windowsShareDesktop( tmp, w ) ) - { - // Do we have to move it? - if( intersects( w, tmp->geometry() ) ) - { - QRect slideRect; - slideRect = getSlideDestination( getModalGroupGeometry( w ), tmp->geometry() ); - effects->setElevatedWindow( tmp, true ); - elevatedList.append( tmp ); - motionManager.manage( tmp ); - motionManager.moveWindow( tmp, slideRect ); - destinationList.insert( tmp, slideRect ); - coveringWindows.append( tmp ); - } - else - { - //Does it intersect with a moved (elevated) window and do we have to elevate it too? - foreach( EffectWindow *elevatedWindow, elevatedList ) - { - if( tmp->geometry().intersects( elevatedWindow->geometry() ) ) - { - effects->setElevatedWindow( tmp, true ); - elevatedList.append( tmp ); - break; - } - } - - } - } - if( tmp->isDock() || tmp->keepAbove() ) - { - effects->setElevatedWindow( tmp, true ); - elevatedList.append( tmp ); - } + if (tmp->isDock() || tmp->keepAbove()) { + effects->setElevatedWindow(tmp, true); + elevatedList.append(tmp); } } + } // If a window is minimized it could happen that the panels stay elevated without any windows sliding. // clear all elevation settings - if( !motionManager.managingWindows() ) - { - foreach( EffectWindow* tmp, elevatedList ) - { - effects->setElevatedWindow( tmp, false ); - } + if (!motionManager.managingWindows()) { + foreach (EffectWindow * tmp, elevatedList) { + effects->setElevatedWindow(tmp, false); } - updateStackingOrder(); } + updateStackingOrder(); +} -QRect SlideBackEffect::getSlideDestination( const QRect &windowUnderGeometry, const QRect &windowOverGeometry) - { +QRect SlideBackEffect::getSlideDestination(const QRect &windowUnderGeometry, const QRect &windowOverGeometry) +{ // Determine the shortest way: int leftSlide = windowUnderGeometry.left() - windowOverGeometry.right() - 20; int rightSlide = windowUnderGeometry.right() - windowOverGeometry.left() + 20; @@ -148,289 +129,245 @@ QRect SlideBackEffect::getSlideDestination( const QRect &windowUnderGeometry, co int downSlide = windowUnderGeometry.bottom() - windowOverGeometry.top() + 20; int horizSlide = leftSlide; - if( qAbs( horizSlide ) > qAbs( rightSlide ) ) - { + if (qAbs(horizSlide) > qAbs(rightSlide)) { horizSlide = rightSlide; - } + } int vertSlide = upSlide; - if( qAbs( vertSlide ) > qAbs( downSlide ) ) - { - vertSlide = downSlide; - } + if (qAbs(vertSlide) > qAbs(downSlide)) { + vertSlide = downSlide; + } QRect slideRect = windowOverGeometry; - if( qAbs( horizSlide ) < qAbs( vertSlide ) ) - { - slideRect.moveLeft( slideRect.x() + horizSlide ); - } - else - { - slideRect.moveTop( slideRect.y() + vertSlide ); - } - return slideRect; + if (qAbs(horizSlide) < qAbs(vertSlide)) { + slideRect.moveLeft(slideRect.x() + horizSlide); + } else { + slideRect.moveTop(slideRect.y() + vertSlide); } + return slideRect; +} void SlideBackEffect::updateStackingOrder() - { - usableOldStackingOrder = usableWindows( effects->stackingOrder() ); +{ + usableOldStackingOrder = usableWindows(effects->stackingOrder()); oldStackingOrder = effects->stackingOrder(); - } +} -void SlideBackEffect::prePaintScreen( ScreenPrePaintData &data, int time ) - { - if( motionManager.managingWindows() ) - { - motionManager.calculate( time ); +void SlideBackEffect::prePaintScreen(ScreenPrePaintData &data, int time) +{ + if (motionManager.managingWindows()) { + motionManager.calculate(time); data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; - } - effects->prePaintScreen( data, time ); } + effects->prePaintScreen(data, time); +} void SlideBackEffect::postPaintScreen() - { - if( motionManager.areWindowsMoving() ) - { +{ + if (motionManager.areWindowsMoving()) { effects->addRepaintFull(); - } + } effects->postPaintScreen(); - } +} -void SlideBackEffect::prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ) - { - if( motionManager.isManaging( w ) ) - { +void SlideBackEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) +{ + if (motionManager.isManaging(w)) { data.setTransformed(); - } - - effects->prePaintWindow( w, data, time ); } -void SlideBackEffect::paintWindow( EffectWindow *w, int mask, QRegion region, WindowPaintData &data ) - { - if( stackingOrderChanged() && ( w == newTopWindow() ) && !disabled ) - { + effects->prePaintWindow(w, data, time); +} + +void SlideBackEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) +{ + if (stackingOrderChanged() && (w == newTopWindow()) && !disabled) { /* This can happen because of two reasons: - a window has received the focus earlier without being raised and is raised now. -> call windowActivated() now - paintWindow() is called with a new stackingOrder before activateWindow(). Bug? -> don't draw the overlapping content;*/ - foreach( EffectWindow *tmp, oldStackingOrder ) - { - if( oldStackingOrder.lastIndexOf( tmp ) > oldStackingOrder.lastIndexOf( w ) && isWindowUsable( tmp ) && windowsShareDesktop( tmp, w ) ) - { - kDebug( 1212 ) << "screw detected. region:" << region << "clipping:" << tmp->geometry() ; - clippedRegions << region.subtracted( tmp->geometry() ); - PaintClipper::push( clippedRegions.last() ); + foreach (EffectWindow * tmp, oldStackingOrder) { + if (oldStackingOrder.lastIndexOf(tmp) > oldStackingOrder.lastIndexOf(w) && isWindowUsable(tmp) && windowsShareDesktop(tmp, w)) { + kDebug(1212) << "screw detected. region:" << region << "clipping:" << tmp->geometry() ; + clippedRegions << region.subtracted(tmp->geometry()); + PaintClipper::push(clippedRegions.last()); // region = region.subtracted( tmp->geometry() ); - } } + } // Finally call windowActivated in case a already active window is raised. - windowActivated( w ); - } - if( motionManager.isManaging( w ) ) - { - motionManager.apply( w, data ); - } - effects->paintWindow( w, mask, region, data ); - for ( int i = clippedRegions.count() - 1; i > -1; --i ) - PaintClipper::pop( clippedRegions.at(i) ); - clippedRegions.clear(); + windowActivated(w); } + if (motionManager.isManaging(w)) { + motionManager.apply(w, data); + } + effects->paintWindow(w, mask, region, data); + for (int i = clippedRegions.count() - 1; i > -1; --i) + PaintClipper::pop(clippedRegions.at(i)); + clippedRegions.clear(); +} -void SlideBackEffect::postPaintWindow( EffectWindow* w ) - { - if( motionManager.isManaging( w ) ) - { - if( destinationList.contains( w ) ) - { +void SlideBackEffect::postPaintWindow(EffectWindow* w) +{ + if (motionManager.isManaging(w)) { + if (destinationList.contains(w)) { // has window reched its destination? - if(( qAbs( motionManager.transformedGeometry( w ).x() - destinationList[w].x() ) < 1 ) && - ( qAbs( motionManager.transformedGeometry( w ).y() - destinationList[w].y() ) < 1 ) ) - { + if ((qAbs(motionManager.transformedGeometry(w).x() - destinationList[w].x()) < 1) && + (qAbs(motionManager.transformedGeometry(w).y() - destinationList[w].y()) < 1)) { // If we are still intersecting with the activeWindow it is moving. slide to somewhere else // restore the stacking order of all windows not intersecting any more except panels - if( coveringWindows.contains( w ) ) - { + if (coveringWindows.contains(w)) { EffectWindowList tmpList; - foreach( EffectWindow *tmp, elevatedList ) - { + foreach (EffectWindow * tmp, elevatedList) { QRect elevatedGeometry = tmp->geometry(); - if( motionManager.isManaging( tmp ) ) - { - elevatedGeometry = motionManager.transformedGeometry( tmp ).toAlignedRect(); - } - if( effects->activeWindow() && !tmp->isDock() && !tmp->keepAbove() && effects->activeWindow()->geometry().intersects( elevatedGeometry ) ) - { - QRect newDestination; - newDestination = getSlideDestination( getModalGroupGeometry( effects->activeWindow() ), elevatedGeometry ); - if( !motionManager.isManaging( tmp ) ) - { - motionManager.manage( tmp ); - } - motionManager.moveWindow( tmp, newDestination ); - destinationList[tmp] = newDestination; - } - else - { - if( !tmp->isDock() ) - { - bool keepElevated = false; - foreach( EffectWindow *elevatedWindow, tmpList) - { - if( tmp->geometry().intersects( elevatedWindow->geometry() ) ) - { - keepElevated = true; - } - } - if( !keepElevated ) - { - effects->setElevatedWindow( tmp, false ); - elevatedList.removeAll( tmp ); - } - } - } - tmpList.append(tmp); + if (motionManager.isManaging(tmp)) { + elevatedGeometry = motionManager.transformedGeometry(tmp).toAlignedRect(); } + if (effects->activeWindow() && !tmp->isDock() && !tmp->keepAbove() && effects->activeWindow()->geometry().intersects(elevatedGeometry)) { + QRect newDestination; + newDestination = getSlideDestination(getModalGroupGeometry(effects->activeWindow()), elevatedGeometry); + if (!motionManager.isManaging(tmp)) { + motionManager.manage(tmp); + } + motionManager.moveWindow(tmp, newDestination); + destinationList[tmp] = newDestination; + } else { + if (!tmp->isDock()) { + bool keepElevated = false; + foreach (EffectWindow * elevatedWindow, tmpList) { + if (tmp->geometry().intersects(elevatedWindow->geometry())) { + keepElevated = true; + } + } + if (!keepElevated) { + effects->setElevatedWindow(tmp, false); + elevatedList.removeAll(tmp); + } + } + } + tmpList.append(tmp); } - else - { + } else { // Move the window back where it belongs - motionManager.moveWindow( w, w->geometry() ); - destinationList.remove( w ); - } + motionManager.moveWindow(w, w->geometry()); + destinationList.remove(w); } } - else - { + } else { // is window back at its original position? - if(( qAbs( motionManager.transformedGeometry( w ).x() - w->geometry().x() ) < 1 ) && - ( qAbs( motionManager.transformedGeometry( w ).y() - w->geometry().y() ) < 1 ) ) - { - motionManager.unmanage( w ); + if ((qAbs(motionManager.transformedGeometry(w).x() - w->geometry().x()) < 1) && + (qAbs(motionManager.transformedGeometry(w).y() - w->geometry().y()) < 1)) { + motionManager.unmanage(w); effects->addRepaintFull(); - } } - if( coveringWindows.contains( w ) ) - { + } + if (coveringWindows.contains(w)) { // It could happen that there is no aciveWindow() here if the user clicks the close-button on an inactive window. // Just skip... the window will be removed in windowDeleted() later - if( effects->activeWindow() && !intersects( effects->activeWindow(), motionManager.transformedGeometry( w ).toAlignedRect() ) ) - { - coveringWindows.removeAll( w ); - if( coveringWindows.isEmpty() ) - { + if (effects->activeWindow() && !intersects(effects->activeWindow(), motionManager.transformedGeometry(w).toAlignedRect())) { + coveringWindows.removeAll(w); + if (coveringWindows.isEmpty()) { // Restore correct stacking order - foreach( EffectWindow *tmp, elevatedList ) - { - effects->setElevatedWindow( tmp, false ); - } - elevatedList.clear(); + foreach (EffectWindow * tmp, elevatedList) { + effects->setElevatedWindow(tmp, false); } + elevatedList.clear(); } } } - effects->postPaintWindow( w ); } + effects->postPaintWindow(w); +} -void SlideBackEffect::windowDeleted( EffectWindow* w ) - { - usableOldStackingOrder.removeAll( w ); - oldStackingOrder.removeAll( w ); - coveringWindows.removeAll( w ); - elevatedList.removeAll( w ); - if( motionManager.isManaging( w ) ) - { - motionManager.unmanage( w ); - } +void SlideBackEffect::windowDeleted(EffectWindow* w) +{ + usableOldStackingOrder.removeAll(w); + oldStackingOrder.removeAll(w); + coveringWindows.removeAll(w); + elevatedList.removeAll(w); + if (motionManager.isManaging(w)) { + motionManager.unmanage(w); } +} -void SlideBackEffect::windowAdded( KWin::EffectWindow* w ) - { - Q_UNUSED( w ); +void SlideBackEffect::windowAdded(KWin::EffectWindow* w) +{ + Q_UNUSED(w); updateStackingOrder(); - } +} -void SlideBackEffect::windowUnminimized( EffectWindow* w) - { +void SlideBackEffect::windowUnminimized(EffectWindow* w) +{ // SlideBack should not be triggered on an unminimized window. For this we need to store the last unminimized window. - // If a window is unminimized but not on top we need to clear the memory because the windowUnminimized() is not + // If a window is unminimized but not on top we need to clear the memory because the windowUnminimized() is not // followed by a windowActivated(). - if( isWindowOnTop( w ) ) - { + if (isWindowOnTop(w)) { unminimizedWindow = w; - } - else - { + } else { unminimizedWindow = NULL; - } } +} -void SlideBackEffect::clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ) - { +void SlideBackEffect::clientGroupItemSwitched(EffectWindow* from, EffectWindow* to) +{ clientItemShown = to; clientItemHidden = from; - } +} void SlideBackEffect::tabBoxClosed() - { +{ disabled = true; - } +} -bool SlideBackEffect::isWindowOnTop( EffectWindow* w ) - { - EffectWindowList openWindows = usableWindows( effects->stackingOrder() ); - if( !openWindows.isEmpty() && ( openWindows.last() == w ) ) - { +bool SlideBackEffect::isWindowOnTop(EffectWindow* w) +{ + EffectWindowList openWindows = usableWindows(effects->stackingOrder()); + if (!openWindows.isEmpty() && (openWindows.last() == w)) { return true; - } + } return false; - } +} -bool SlideBackEffect::isWindowUsable( EffectWindow* w ) - { - return w && ( w->isNormalWindow() || w->isDialog() ) && !w->keepAbove() && !w->isDeleted() && !w->isMinimized() - && w->visibleInClientGroup(); - } +bool SlideBackEffect::isWindowUsable(EffectWindow* w) +{ + return w && (w->isNormalWindow() || w->isDialog()) && !w->keepAbove() && !w->isDeleted() && !w->isMinimized() + && w->visibleInClientGroup(); +} -bool SlideBackEffect::intersects( EffectWindow* windowUnder, const QRect &windowOverGeometry ) - { - QRect windowUnderGeometry = getModalGroupGeometry( windowUnder ); - return windowUnderGeometry.intersects( windowOverGeometry ); - } +bool SlideBackEffect::intersects(EffectWindow* windowUnder, const QRect &windowOverGeometry) +{ + QRect windowUnderGeometry = getModalGroupGeometry(windowUnder); + return windowUnderGeometry.intersects(windowOverGeometry); +} -EffectWindowList SlideBackEffect::usableWindows( const EffectWindowList & allWindows ) - { +EffectWindowList SlideBackEffect::usableWindows(const EffectWindowList & allWindows) +{ EffectWindowList retList; - foreach( EffectWindow *tmp, allWindows ) - { - if( isWindowUsable( tmp ) ) - { - retList.append( tmp ); - } + foreach (EffectWindow * tmp, allWindows) { + if (isWindowUsable(tmp)) { + retList.append(tmp); } - return retList; } + return retList; +} bool SlideBackEffect::stackingOrderChanged() - { - return !( usableOldStackingOrder == usableWindows( effects->stackingOrder() ) ); - } +{ + return !(usableOldStackingOrder == usableWindows(effects->stackingOrder())); +} EffectWindow* SlideBackEffect::newTopWindow() - { - EffectWindowList stacking = usableWindows( effects->stackingOrder() ); +{ + EffectWindowList stacking = usableWindows(effects->stackingOrder()); return stacking.isEmpty() ? NULL : stacking.last(); - } +} -QRect SlideBackEffect::getModalGroupGeometry( EffectWindow *w ) - { +QRect SlideBackEffect::getModalGroupGeometry(EffectWindow *w) +{ QRect modalGroupGeometry = w->geometry(); - if( w->isModal() ) - { - foreach( EffectWindow *modalWindow, w->mainWindows() ) - { - modalGroupGeometry = modalGroupGeometry.united( getModalGroupGeometry( modalWindow ) ); - } + if (w->isModal()) { + foreach (EffectWindow * modalWindow, w->mainWindows()) { + modalGroupGeometry = modalGroupGeometry.united(getModalGroupGeometry(modalWindow)); } - return modalGroupGeometry; } + return modalGroupGeometry; +} } //Namespace diff --git a/effects/slideback/slideback.h b/effects/slideback/slideback.h index 78b034a96..c4a2e4c9c 100644 --- a/effects/slideback/slideback.h +++ b/effects/slideback/slideback.h @@ -28,52 +28,52 @@ namespace KWin { class SlideBackEffect - : public Effect - { - public: - SlideBackEffect(); + : public Effect +{ +public: + SlideBackEffect(); - virtual void windowActivated( EffectWindow* c ); + virtual void windowActivated(EffectWindow* c); - virtual void prePaintWindow( EffectWindow *w, WindowPrePaintData &data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); + virtual void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void postPaintScreen(); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void postPaintScreen(); - virtual void windowDeleted( EffectWindow* w ); - virtual void windowAdded( EffectWindow* w ); - virtual void windowUnminimized( EffectWindow* w ); - virtual void clientGroupItemSwitched( EffectWindow* from, EffectWindow* to ); + virtual void windowDeleted(EffectWindow* w); + virtual void windowAdded(EffectWindow* w); + virtual void windowUnminimized(EffectWindow* w); + virtual void clientGroupItemSwitched(EffectWindow* from, EffectWindow* to); - virtual void tabBoxClosed(); + virtual void tabBoxClosed(); - private: +private: - WindowMotionManager motionManager; - EffectWindowList usableOldStackingOrder; - EffectWindowList oldStackingOrder; - EffectWindowList coveringWindows; - EffectWindowList elevatedList; - EffectWindow* unminimizedWindow; - EffectWindow* clientItemShown; - EffectWindow* clientItemHidden; - QHash destinationList; - bool disabled; - QList clippedRegions; + WindowMotionManager motionManager; + EffectWindowList usableOldStackingOrder; + EffectWindowList oldStackingOrder; + EffectWindowList coveringWindows; + EffectWindowList elevatedList; + EffectWindow* unminimizedWindow; + EffectWindow* clientItemShown; + EffectWindow* clientItemHidden; + QHash destinationList; + bool disabled; + QList clippedRegions; - QRect getSlideDestination( const QRect &windowUnderGeometry, const QRect &windowOverGeometry); - void updateStackingOrder(); - bool isWindowOnTop( EffectWindow *w ); - bool isWindowUsable( EffectWindow *w ); - bool stackingOrderChanged(); - bool intersects( EffectWindow *windowUnder, const QRect &windowOverGeometry ); - EffectWindowList usableWindows( const EffectWindowList &allWindows ); - EffectWindow *newTopWindow(); - QRect getModalGroupGeometry( EffectWindow *w ); + QRect getSlideDestination(const QRect &windowUnderGeometry, const QRect &windowOverGeometry); + void updateStackingOrder(); + bool isWindowOnTop(EffectWindow *w); + bool isWindowUsable(EffectWindow *w); + bool stackingOrderChanged(); + bool intersects(EffectWindow *windowUnder, const QRect &windowOverGeometry); + EffectWindowList usableWindows(const EffectWindowList &allWindows); + EffectWindow *newTopWindow(); + QRect getModalGroupGeometry(EffectWindow *w); - }; +}; } // namespace diff --git a/effects/slidingpopups/slidingpopups.cpp b/effects/slidingpopups/slidingpopups.cpp index 4ccf36a43..12d7eceb7 100644 --- a/effects/slidingpopups/slidingpopups.cpp +++ b/effects/slidingpopups/slidingpopups.cpp @@ -25,196 +25,180 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( slidingpopups, SlidingPopupsEffect ) +KWIN_EFFECT(slidingpopups, SlidingPopupsEffect) SlidingPopupsEffect::SlidingPopupsEffect() - { - KConfigGroup conf = effects->effectConfig( "SlidingPopups" ); - mFadeInTime = animationTime( conf, "SlideInTime", 250 ); - mFadeOutTime = animationTime( conf, "SlideOutTime", 250 ); - mAtom = XInternAtom( display(), "_KDE_SLIDE", False ); - effects->registerPropertyType( mAtom, true ); +{ + KConfigGroup conf = effects->effectConfig("SlidingPopups"); + mFadeInTime = animationTime(conf, "SlideInTime", 250); + mFadeOutTime = animationTime(conf, "SlideOutTime", 250); + mAtom = XInternAtom(display(), "_KDE_SLIDE", False); + effects->registerPropertyType(mAtom, true); // TODO hackish way to announce support, make better after 4.0 unsigned char dummy = 0; - XChangeProperty( display(), rootWindow(), mAtom, mAtom, 8, PropModeReplace, &dummy, 1 ); - } + XChangeProperty(display(), rootWindow(), mAtom, mAtom, 8, PropModeReplace, &dummy, 1); +} SlidingPopupsEffect::~SlidingPopupsEffect() - { - XDeleteProperty( display(), rootWindow(), mAtom ); - effects->registerPropertyType( mAtom, false ); - } +{ + XDeleteProperty(display(), rootWindow(), mAtom); + effects->registerPropertyType(mAtom, false); +} -void SlidingPopupsEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( !mAppearingWindows.isEmpty() || !mDisappearingWindows.isEmpty() ) +void SlidingPopupsEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (!mAppearingWindows.isEmpty() || !mDisappearingWindows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS; - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void SlidingPopupsEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { - if( mAppearingWindows.contains( w ) ) - { - mAppearingWindows[ w ].addTime( time ); - if( mAppearingWindows[ w ].value() < 1 ) +void SlidingPopupsEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ + if (mAppearingWindows.contains(w)) { + mAppearingWindows[ w ].addTime(time); + if (mAppearingWindows[ w ].value() < 1) data.setTransformed(); else - mAppearingWindows.remove( w ); - } - else if( mDisappearingWindows.contains( w ) ) - { + mAppearingWindows.remove(w); + } else if (mDisappearingWindows.contains(w)) { data.setTransformed(); - w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); + w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); - mDisappearingWindows[ w ].addTime( time ); - } - effects->prePaintWindow( w, data, time ); + mDisappearingWindows[ w ].addTime(time); } + effects->prePaintWindow(w, data, time); +} -void SlidingPopupsEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { +void SlidingPopupsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ bool animating = false; bool appearing = false; QRegion clippedRegion = region; - if( mAppearingWindows.contains( w ) ) - { + if (mAppearingWindows.contains(w)) { appearing = true; animating = true; - } - else if( mDisappearingWindows.contains( w ) && w->isDeleted() ) - { + } else if (mDisappearingWindows.contains(w) && w->isDeleted()) { appearing = false; animating = true; - } + } - if( animating ) - { + if (animating) { qreal progress; - if( appearing ) + if (appearing) progress = 1.0 - mAppearingWindows[ w ].value(); - else - { - if( mDisappearingWindows.contains( w )) + else { + if (mDisappearingWindows.contains(w)) progress = mDisappearingWindows[ w ].value(); else progress = 1.0; - } + } const int start = mWindowsData[ w ].start; - switch (mWindowsData[ w ].from) - { - case West: - data.xTranslate += (start - w->width()) * progress; - clippedRegion = clippedRegion.subtracted(QRegion(start - w->width(), w->y(), w->width(), w->height() ) ); - break; - case North: - data.yTranslate += (start - w->height()) * progress; - clippedRegion = clippedRegion.subtracted(QRegion( w->x(), start - w->height(), w->width(), w->height() ) ); - break; - case East: - data.xTranslate += (start - w->x()) * progress; - clippedRegion = clippedRegion.subtracted(QRegion( w->x()+w->width(), w->y(), w->width(), w->height() ) ); - break; - case South: - default: - data.yTranslate += (start - w->y()) * progress; - clippedRegion = clippedRegion.subtracted(QRegion( w->x(), start, w->width(), w->height() ) ); - } + switch(mWindowsData[ w ].from) { + case West: + data.xTranslate += (start - w->width()) * progress; + clippedRegion = clippedRegion.subtracted(QRegion(start - w->width(), w->y(), w->width(), w->height())); + break; + case North: + data.yTranslate += (start - w->height()) * progress; + clippedRegion = clippedRegion.subtracted(QRegion(w->x(), start - w->height(), w->width(), w->height())); + break; + case East: + data.xTranslate += (start - w->x()) * progress; + clippedRegion = clippedRegion.subtracted(QRegion(w->x() + w->width(), w->y(), w->width(), w->height())); + break; + case South: + default: + data.yTranslate += (start - w->y()) * progress; + clippedRegion = clippedRegion.subtracted(QRegion(w->x(), start, w->width(), w->height())); } - - effects->paintWindow( w, mask, clippedRegion, data ); } -void SlidingPopupsEffect::postPaintWindow( EffectWindow* w ) - { - if( mAppearingWindows.contains( w ) || mDisappearingWindows.contains( w ) ) + effects->paintWindow(w, mask, clippedRegion, data); +} + +void SlidingPopupsEffect::postPaintWindow(EffectWindow* w) +{ + if (mAppearingWindows.contains(w) || mDisappearingWindows.contains(w)) w->addRepaintFull(); // trigger next animation repaint - effects->postPaintWindow( w ); - if( mDisappearingWindows.contains( w ) && mDisappearingWindows[ w ].value() >= 1 ) - { - mDisappearingWindows.remove( w ); + effects->postPaintWindow(w); + if (mDisappearingWindows.contains(w) && mDisappearingWindows[ w ].value() >= 1) { + mDisappearingWindows.remove(w); w->unrefWindow(); - effects->addRepaint( w->geometry() ); - } + effects->addRepaint(w->geometry()); } +} -void SlidingPopupsEffect::windowAdded( EffectWindow* w ) - { - propertyNotify( w, mAtom ); - if( w->isOnCurrentDesktop() && mWindowsData.contains( w ) ) - { - mAppearingWindows[ w ].setDuration( mWindowsData[ w ].fadeInDuration ); - mAppearingWindows[ w ].setProgress( 0.0 ); - mAppearingWindows[ w ].setCurveShape( TimeLine::EaseOutCurve ); +void SlidingPopupsEffect::windowAdded(EffectWindow* w) +{ + propertyNotify(w, mAtom); + if (w->isOnCurrentDesktop() && mWindowsData.contains(w)) { + mAppearingWindows[ w ].setDuration(mWindowsData[ w ].fadeInDuration); + mAppearingWindows[ w ].setProgress(0.0); + mAppearingWindows[ w ].setCurveShape(TimeLine::EaseOutCurve); // Tell other windowAdded() effects to ignore this window - w->setData( WindowAddedGrabRole, QVariant::fromValue( static_cast( this ))); + w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); w->addRepaintFull(); - } } +} -void SlidingPopupsEffect::windowClosed( EffectWindow* w ) - { - propertyNotify( w, mAtom ); - if( w->isOnCurrentDesktop() && !w->isMinimized() && mWindowsData.contains( w ) ) - { +void SlidingPopupsEffect::windowClosed(EffectWindow* w) +{ + propertyNotify(w, mAtom); + if (w->isOnCurrentDesktop() && !w->isMinimized() && mWindowsData.contains(w)) { w->refWindow(); - mAppearingWindows.remove( w ); - mDisappearingWindows[ w ].setDuration( mWindowsData[ w ].fadeOutDuration ); - mDisappearingWindows[ w ].setProgress( 0.0 ); - mDisappearingWindows[ w ].setCurveShape( TimeLine::EaseOutCurve ); + mAppearingWindows.remove(w); + mDisappearingWindows[ w ].setDuration(mWindowsData[ w ].fadeOutDuration); + mDisappearingWindows[ w ].setProgress(0.0); + mDisappearingWindows[ w ].setCurveShape(TimeLine::EaseOutCurve); // Tell other windowClosed() effects to ignore this window - w->setData( WindowClosedGrabRole, QVariant::fromValue( static_cast( this ))); + w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); w->addRepaintFull(); - } } +} -void SlidingPopupsEffect::windowDeleted( EffectWindow* w ) - { - mAppearingWindows.remove( w ); - mDisappearingWindows.remove( w ); - mWindowsData.remove( w ); - effects->addRepaint( w->geometry() ); - } +void SlidingPopupsEffect::windowDeleted(EffectWindow* w) +{ + mAppearingWindows.remove(w); + mDisappearingWindows.remove(w); + mWindowsData.remove(w); + effects->addRepaint(w->geometry()); +} -void SlidingPopupsEffect::propertyNotify( EffectWindow* w, long a ) - { - if( !w || a != mAtom ) +void SlidingPopupsEffect::propertyNotify(EffectWindow* w, long a) +{ + if (!w || a != mAtom) return; - QByteArray data = w->readProperty( mAtom, mAtom, 32 ); + QByteArray data = w->readProperty(mAtom, mAtom, 32); - if( data.length() < 1 ) - { + if (data.length() < 1) { // Property was removed, thus also remove the effect for window - mAppearingWindows.remove( w ); - mDisappearingWindows.remove( w ); - mWindowsData.remove( w ); + mAppearingWindows.remove(w); + mDisappearingWindows.remove(w); + mWindowsData.remove(w); return; - } + } - long* d = reinterpret_cast< long* >( data.data()); + long* d = reinterpret_cast< long* >(data.data()); Data animData; animData.start = d[ 0 ]; animData.from = (Position)d[ 1 ]; - if( data.length() >= (int)(sizeof( long ) * 3) ) - { + if (data.length() >= (int)(sizeof(long) * 3)) { animData.fadeInDuration = d[2]; - if( data.length() >= (int)(sizeof( long ) * 4) ) + if (data.length() >= (int)(sizeof(long) * 4)) animData.fadeOutDuration = d[3]; else animData.fadeOutDuration = d[2]; - } - else - { - animData.fadeInDuration = animationTime( mFadeInTime ); - animData.fadeOutDuration = animationTime( mFadeOutTime ); - } - mWindowsData[ w ] = animData; + } else { + animData.fadeInDuration = animationTime(mFadeInTime); + animData.fadeOutDuration = animationTime(mFadeOutTime); } + mWindowsData[ w ] = animData; +} } // namespace diff --git a/effects/slidingpopups/slidingpopups.h b/effects/slidingpopups/slidingpopups.h index 6cbbb69e6..c341ba710 100644 --- a/effects/slidingpopups/slidingpopups.h +++ b/effects/slidingpopups/slidingpopups.h @@ -29,42 +29,40 @@ namespace KWin class SlidingPopupsEffect : public Effect - { - public: - SlidingPopupsEffect(); - ~SlidingPopupsEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void postPaintWindow( EffectWindow* w ); - // TODO react also on virtual desktop changes - virtual void windowAdded( EffectWindow* c ); - virtual void windowClosed( EffectWindow* c ); - virtual void windowDeleted( EffectWindow* c ); - virtual void propertyNotify( EffectWindow* w, long a ); - private: - enum Position - { - West = 0, - North = 1, - East = 2, - South = 3 - }; - struct Data - { - int start; //point in screen coordinates where the window starts - //to animate, from decides if this point is an x or an y - Position from; - int fadeInDuration; - int fadeOutDuration; - }; - long mAtom; - QHash< const EffectWindow*, TimeLine > mAppearingWindows; - QHash< const EffectWindow*, TimeLine > mDisappearingWindows; - QHash< const EffectWindow*, Data > mWindowsData; - int mFadeInTime; - int mFadeOutTime; +{ +public: + SlidingPopupsEffect(); + ~SlidingPopupsEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void postPaintWindow(EffectWindow* w); + // TODO react also on virtual desktop changes + virtual void windowAdded(EffectWindow* c); + virtual void windowClosed(EffectWindow* c); + virtual void windowDeleted(EffectWindow* c); + virtual void propertyNotify(EffectWindow* w, long a); +private: + enum Position { + West = 0, + North = 1, + East = 2, + South = 3 }; + struct Data { + int start; //point in screen coordinates where the window starts + //to animate, from decides if this point is an x or an y + Position from; + int fadeInDuration; + int fadeOutDuration; + }; + long mAtom; + QHash< const EffectWindow*, TimeLine > mAppearingWindows; + QHash< const EffectWindow*, TimeLine > mDisappearingWindows; + QHash< const EffectWindow*, Data > mWindowsData; + int mFadeInTime; + int mFadeOutTime; +}; } // namespace diff --git a/effects/snaphelper/snaphelper.cpp b/effects/snaphelper/snaphelper.cpp index f4d9adb2d..8337d1435 100644 --- a/effects/snaphelper/snaphelper.cpp +++ b/effects/snaphelper/snaphelper.cpp @@ -26,62 +26,61 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( snaphelper, SnapHelperEffect ) -KWIN_EFFECT_SUPPORTED( snaphelper, SnapHelperEffect::supported() ) +KWIN_EFFECT(snaphelper, SnapHelperEffect) +KWIN_EFFECT_SUPPORTED(snaphelper, SnapHelperEffect::supported()) SnapHelperEffect::SnapHelperEffect() - : m_active( false ) - , m_window( NULL ) - { - m_timeline.setCurveShape( TimeLine::LinearCurve ); - reconfigure( ReconfigureAll ); + : m_active(false) + , m_window(NULL) +{ + m_timeline.setCurveShape(TimeLine::LinearCurve); + reconfigure(ReconfigureAll); - /*if( effects->compositingType() == XRenderCompositing ) + /*if ( effects->compositingType() == XRenderCompositing ) { XGCValues gcattr; // TODO: Foreground color gcattr.line_width = 4; m_gc = XCreateGC( display(), rootWindow(), GCLineWidth, &gcattr ); }*/ - } +} SnapHelperEffect::~SnapHelperEffect() - { - //if( effects->compositingType() == XRenderCompositing ) +{ + //if ( effects->compositingType() == XRenderCompositing ) // XFreeGC( display(), m_gc ); - } +} -void SnapHelperEffect::reconfigure( ReconfigureFlags ) - { - m_timeline.setDuration( animationTime( 250 )); - } +void SnapHelperEffect::reconfigure(ReconfigureFlags) +{ + m_timeline.setDuration(animationTime(250)); +} bool SnapHelperEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void SnapHelperEffect::prePaintScreen( ScreenPrePaintData &data, int time ) - { +void SnapHelperEffect::prePaintScreen(ScreenPrePaintData &data, int time) +{ double oldValue = m_timeline.value(); - if( m_active ) - m_timeline.addTime( time ); + if (m_active) + m_timeline.addTime(time); else - m_timeline.removeTime( time ); - if( oldValue != m_timeline.value() ) + m_timeline.removeTime(time); + if (oldValue != m_timeline.value()) effects->addRepaintFull(); - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} void SnapHelperEffect::postPaintScreen() - { +{ effects->postPaintScreen(); - if( m_timeline.value() != 0.0 ) - { // Display the guide - if( effects->compositingType() == OpenGLCompositing ) - { + if (m_timeline.value() != 0.0) { + // Display the guide + if (effects->compositingType() == OpenGLCompositing) { #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); @@ -89,8 +88,8 @@ void SnapHelperEffect::postPaintScreen() if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->pushShader(ShaderManager::ColorShader); } - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); QColor color; color.setRedF(0.5); @@ -98,11 +97,11 @@ void SnapHelperEffect::postPaintScreen() color.setBlueF(0.5); color.setAlphaF(m_timeline.value() * 0.5); vbo->setColor(color); - glLineWidth( 4.0 ); + glLineWidth(4.0); QVector verts; - verts.reserve(effects->numScreens()*24); + verts.reserve(effects->numScreens() * 24); for (int i = 0; i < effects->numScreens(); i++) { - const QRect& rect = effects->clientArea( ScreenArea, i, 0 ); + const QRect& rect = effects->clientArea(ScreenArea, i, 0); int midX = rect.x() + rect.width() / 2; int midY = rect.y() + rect.height() / 2 ; int halfWidth = m_window->width() / 2; @@ -125,21 +124,21 @@ void SnapHelperEffect::postPaintScreen() verts << midX - halfWidth << midY + halfHeight - 2; verts << midX - halfWidth << midY - halfHeight - 2; } - vbo->setData(verts.count()/2, 2, verts.data(), NULL); + vbo->setData(verts.count() / 2, 2, verts.data(), NULL); vbo->render(GL_LINES); if (ShaderManager::instance()->isValid()) { ShaderManager::instance()->popShader(); } - glDisable( GL_BLEND ); - glLineWidth( 1.0 ); + glDisable(GL_BLEND); + glLineWidth(1.0); #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif - } - /*if( effects->compositingType() == XRenderCompositing ) + } + /*if ( effects->compositingType() == XRenderCompositing ) { // TODO - for( int i = 0; i < effects->numScreens(); i++ ) + for ( int i = 0; i < effects->numScreens(); i++ ) { const QRect& rect = effects->clientArea( ScreenArea, i, 0 ); int midX = rect.x() + rect.width() / 2; @@ -181,34 +180,29 @@ void SnapHelperEffect::postPaintScreen() XDrawSegments( display(), effects->xrenderBufferPicture(), m_gc, segments, 6 ); } }*/ - } - else if( m_window ) - { - if( m_window->isDeleted() ) + } else if (m_window) { + if (m_window->isDeleted()) m_window->unrefWindow(); m_window = NULL; - } } +} -void SnapHelperEffect::windowClosed( EffectWindow* w ) - { - if( m_window == w ) - { +void SnapHelperEffect::windowClosed(EffectWindow* w) +{ + if (m_window == w) { m_window->refWindow(); m_active = false; - } } +} -void SnapHelperEffect::windowUserMovedResized( EffectWindow* w, bool first, bool last ) - { - if( first && !last && w->isMovable() ) - { +void SnapHelperEffect::windowUserMovedResized(EffectWindow* w, bool first, bool last) +{ + if (first && !last && w->isMovable()) { m_active = true; m_window = w; effects->addRepaintFull(); - } - else if( last ) + } else if (last) m_active = false; - } +} } // namespace diff --git a/effects/snaphelper/snaphelper.h b/effects/snaphelper/snaphelper.h index c5ed6e8ca..1b1566f28 100644 --- a/effects/snaphelper/snaphelper.h +++ b/effects/snaphelper/snaphelper.h @@ -28,26 +28,26 @@ namespace KWin class SnapHelperEffect : public Effect - { - public: - SnapHelperEffect(); - ~SnapHelperEffect(); +{ +public: + SnapHelperEffect(); + ~SnapHelperEffect(); - virtual void reconfigure( ReconfigureFlags ); + virtual void reconfigure(ReconfigureFlags); - virtual void prePaintScreen( ScreenPrePaintData &data, int time ); - virtual void postPaintScreen(); - virtual void windowClosed( EffectWindow* w ); - virtual void windowUserMovedResized( EffectWindow* w, bool first, bool last ); + virtual void prePaintScreen(ScreenPrePaintData &data, int time); + virtual void postPaintScreen(); + virtual void windowClosed(EffectWindow* w); + virtual void windowUserMovedResized(EffectWindow* w, bool first, bool last); - static bool supported(); + static bool supported(); - private: - bool m_active; - EffectWindow* m_window; - TimeLine m_timeline; - //GC m_gc; - }; +private: + bool m_active; + EffectWindow* m_window; + TimeLine m_timeline; + //GC m_gc; +}; } // namespace diff --git a/effects/startupfeedback/startupfeedback.cpp b/effects/startupfeedback/startupfeedback.cpp index f2ffe9585..d1b3ad5cd 100644 --- a/effects/startupfeedback/startupfeedback.cpp +++ b/effects/startupfeedback/startupfeedback.cpp @@ -38,8 +38,8 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( startupfeedback, StartupFeedbackEffect ) -KWIN_EFFECT_SUPPORTED( startupfeedback, StartupFeedbackEffect::supported() ) +KWIN_EFFECT(startupfeedback, StartupFeedbackEffect) +KWIN_EFFECT_SUPPORTED(startupfeedback, StartupFeedbackEffect::supported()) // number of key frames for bouncing animation static const int BOUNCE_FRAMES = 20; @@ -54,81 +54,73 @@ static const int BLINKING_FRAME_DURATION = 100; // duration of one blinking animation static const int BLINKING_DURATION = BLINKING_FRAME_DURATION * BLINKING_FRAMES; //const int color_to_pixmap[] = { 0, 1, 2, 3, 2, 1 }; -static const int FRAME_TO_BOUNCE_YOFFSET[] = - { +static const int FRAME_TO_BOUNCE_YOFFSET[] = { -5, -1, 2, 5, 8, 10, 12, 13, 15, 15, 15, 15, 14, 12, 10, 8, 5, 2, -1, -5 - }; -static const QSize BOUNCE_SIZES[] = - { +}; +static const QSize BOUNCE_SIZES[] = { QSize(16, 16), QSize(14, 18), QSize(12, 20), QSize(18, 14), QSize(20, 12) - }; -static const int FRAME_TO_BOUNCE_TEXTURE[] = - { +}; +static const int FRAME_TO_BOUNCE_TEXTURE[] = { 0, 0, 0, 1, 2, 2, 1, 0, 3, 4, 4, 3, 0, 1, 2, 2, 1, 0, 0, 0 - }; -static const int FRAME_TO_BLINKING_COLOR[] = - { +}; +static const int FRAME_TO_BLINKING_COLOR[] = { 0, 1, 2, 3, 2, 1 - }; -static const QColor BLINKING_COLORS[] = - { +}; +static const QColor BLINKING_COLORS[] = { Qt::black, Qt::darkGray, Qt::lightGray, Qt::white, Qt::white - }; +}; StartupFeedbackEffect::StartupFeedbackEffect() - : m_startupInfo( new KStartupInfo( KStartupInfo::CleanOnCantDetect, this ) ) - , m_selection( new KSelectionOwner( "_KDE_STARTUP_FEEDBACK", -1, this )) - , m_active( false ) - , m_frame( 0 ) - , m_progress( 0 ) - , m_texture( 0 ) - , m_type( BouncingFeedback ) - , m_blinkingShader( 0 ) - { - for( int i=0; i<5; ++i ) - { + : m_startupInfo(new KStartupInfo(KStartupInfo::CleanOnCantDetect, this)) + , m_selection(new KSelectionOwner("_KDE_STARTUP_FEEDBACK", -1, this)) + , m_active(false) + , m_frame(0) + , m_progress(0) + , m_texture(0) + , m_type(BouncingFeedback) + , m_blinkingShader(0) +{ + for (int i = 0; i < 5; ++i) { m_bouncingTextures[i] = 0; - } - m_selection->claim( true ); - connect( m_startupInfo, SIGNAL(gotNewStartup(KStartupInfoId,KStartupInfoData)), SLOT(gotNewStartup(KStartupInfoId,KStartupInfoData))); - connect( m_startupInfo, SIGNAL(gotRemoveStartup(KStartupInfoId,KStartupInfoData)), SLOT(gotRemoveStartup(KStartupInfoId,KStartupInfoData))); - connect( m_startupInfo, SIGNAL(gotStartupChange(KStartupInfoId,KStartupInfoData)), SLOT(gotStartupChange(KStartupInfoId,KStartupInfoData))); - reconfigure( ReconfigureAll ); } + m_selection->claim(true); + connect(m_startupInfo, SIGNAL(gotNewStartup(KStartupInfoId, KStartupInfoData)), SLOT(gotNewStartup(KStartupInfoId, KStartupInfoData))); + connect(m_startupInfo, SIGNAL(gotRemoveStartup(KStartupInfoId, KStartupInfoData)), SLOT(gotRemoveStartup(KStartupInfoId, KStartupInfoData))); + connect(m_startupInfo, SIGNAL(gotStartupChange(KStartupInfoId, KStartupInfoData)), SLOT(gotStartupChange(KStartupInfoId, KStartupInfoData))); + reconfigure(ReconfigureAll); +} StartupFeedbackEffect::~StartupFeedbackEffect() - { - if( m_active ) - { +{ + if (m_active) { effects->stopMousePolling(); - } - for( int i=0; i<5; ++i ) - { + } + for (int i = 0; i < 5; ++i) { delete m_bouncingTextures[i]; - } + } delete m_texture; delete m_blinkingShader; - } +} bool StartupFeedbackEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} -void StartupFeedbackEffect::reconfigure( Effect::ReconfigureFlags flags ) - { - Q_UNUSED( flags ) - KConfig conf( "klaunchrc", KConfig::NoGlobals ); - KConfigGroup c = conf.group( "FeedbackStyle" ); - const bool busyCursor = c.readEntry( "BusyCursor", true ); +void StartupFeedbackEffect::reconfigure(Effect::ReconfigureFlags flags) +{ + Q_UNUSED(flags) + KConfig conf("klaunchrc", KConfig::NoGlobals); + KConfigGroup c = conf.group("FeedbackStyle"); + const bool busyCursor = c.readEntry("BusyCursor", true); - c = conf.group( "BusyCursorSettings" ); - m_startupInfo->setTimeout( c.readEntry( "Timeout", 30 ) ); - const bool busyBlinking = c.readEntry( "Blinking", false ); - const bool busyBouncing = c.readEntry( "Bouncing", true ); - if( !busyCursor ) + c = conf.group("BusyCursorSettings"); + m_startupInfo->setTimeout(c.readEntry("Timeout", 30)); + const bool busyBlinking = c.readEntry("Blinking", false); + const bool busyBouncing = c.readEntry("Bouncing", true); + if (!busyCursor) m_type = NoFeedback; - else if( busyBouncing ) + else if (busyBouncing) m_type = BouncingFeedback; else if (busyBlinking) { m_type = BlinkingFeedback; @@ -140,51 +132,45 @@ void StartupFeedbackEffect::reconfigure( Effect::ReconfigureFlags flags ) if (m_blinkingShader->isValid()) { kDebug(1212) << "Blinking Shader is valid"; } else { - kDebug(1212) << "Blinking Shader is not valid"; + kDebug(1212) << "Blinking Shader is not valid"; } } - } - else + } else m_type = PassiveFeedback; - if( m_active ) - { + if (m_active) { stop(); - start( m_startups[ m_currentStartup ] ); - } + start(m_startups[ m_currentStartup ]); } +} -void StartupFeedbackEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( m_active ) - { +void StartupFeedbackEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (m_active) { // need the unclipped version - switch( m_type ) - { + switch(m_type) { case BouncingFeedback: m_progress = (m_progress + time) % BOUNCE_DURATION; - m_frame = qRound( (qreal)m_progress / (qreal)BOUNCE_FRAME_DURATION ); + m_frame = qRound((qreal)m_progress / (qreal)BOUNCE_FRAME_DURATION); break; case BlinkingFeedback: m_progress = (m_progress + time) % BLINKING_DURATION; - m_frame = qRound( (qreal)m_progress / (qreal)BLINKING_FRAME_DURATION ); + m_frame = qRound((qreal)m_progress / (qreal)BLINKING_FRAME_DURATION); break; default: break; // nothing - } - m_currentGeometry = feedbackRect(); - data.paint.unite( m_currentGeometry ); } - effects->prePaintScreen( data, time ); + m_currentGeometry = feedbackRect(); + data.paint.unite(m_currentGeometry); } + effects->prePaintScreen(data, time); +} -void StartupFeedbackEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - if( m_active ) - { +void StartupFeedbackEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + if (m_active) { GLTexture* texture; - switch( m_type ) - { + switch(m_type) { case BouncingFeedback: texture = m_bouncingTextures[ FRAME_TO_BOUNCE_TEXTURE[ m_frame ]]; break; @@ -194,12 +180,12 @@ void StartupFeedbackEffect::paintScreen( int mask, QRegion region, ScreenPaintDa break; default: return; // safety - } + } #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); texture->bind(); bool useShader = false; if (m_type == BlinkingFeedback) { @@ -212,145 +198,136 @@ void StartupFeedbackEffect::paintScreen( int mask, QRegion region, ScreenPaintDa #ifndef KWIN_HAVE_OPENGLES // texture transformation float color[4] = { blinkingColor.redF(), blinkingColor.greenF(), blinkingColor.blueF(), 1.0f }; - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); - glColor4fv( color ); - glActiveTexture( GL_TEXTURE1 ); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); + glColor4fv(color); + glActiveTexture(GL_TEXTURE1); texture->bind(); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE ); - glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE ); - glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS ); - glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); - glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_CONSTANT ); - glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color ); - glActiveTexture( GL_TEXTURE0 ); - glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color ); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_CONSTANT); + glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color); + glActiveTexture(GL_TEXTURE0); + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color); #endif } } else if (ShaderManager::instance()->isValid()) { useShader = true; ShaderManager::instance()->pushShader(ShaderManager::SimpleShader); } - texture->render( m_currentGeometry, m_currentGeometry ); + texture->render(m_currentGeometry, m_currentGeometry); if (useShader) { ShaderManager::instance()->popShader(); } - if( m_type == BlinkingFeedback && !useShader ) - { + if (m_type == BlinkingFeedback && !useShader) { #ifndef KWIN_HAVE_OPENGLES // resture states - glActiveTexture( GL_TEXTURE1 ); + glActiveTexture(GL_TEXTURE1); texture->unbind(); - glActiveTexture( GL_TEXTURE0 ); - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); - glColor4f( 0.0f, 0.0f, 0.0f, 0.0f ); + glActiveTexture(GL_TEXTURE0); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glColor4f(0.0f, 0.0f, 0.0f, 0.0f); #endif - } + } texture->unbind(); - glDisable( GL_BLEND ); + glDisable(GL_BLEND); #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif - } } +} void StartupFeedbackEffect::postPaintScreen() - { - if( m_active ) - { - switch( m_type ) - { +{ + if (m_active) { + switch(m_type) { case BouncingFeedback: // fall through case BlinkingFeedback: // repaint the icon - effects->addRepaint( m_currentGeometry ); + effects->addRepaint(m_currentGeometry); break; case PassiveFeedback: // fall through default: // no need to repaint - no change break; - } } - effects->postPaintScreen(); } + effects->postPaintScreen(); +} void StartupFeedbackEffect::mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, - Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers) - { - Q_UNUSED( pos ) - Q_UNUSED( oldpos ) - Q_UNUSED( buttons ) - Q_UNUSED( oldbuttons ) - Q_UNUSED( modifiers ) - Q_UNUSED( oldmodifiers ) - if( m_active ) - { - effects->addRepaint( m_currentGeometry ); - effects->addRepaint( feedbackRect() ); - } + Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers) +{ + Q_UNUSED(pos) + Q_UNUSED(oldpos) + Q_UNUSED(buttons) + Q_UNUSED(oldbuttons) + Q_UNUSED(modifiers) + Q_UNUSED(oldmodifiers) + if (m_active) { + effects->addRepaint(m_currentGeometry); + effects->addRepaint(feedbackRect()); } +} -void StartupFeedbackEffect::gotNewStartup( const KStartupInfoId& id, const KStartupInfoData& data ) - { +void StartupFeedbackEffect::gotNewStartup(const KStartupInfoId& id, const KStartupInfoData& data) +{ const QString& icon = data.findIcon(); m_currentStartup = id; m_startups[ id ] = icon; - start( icon ); - } + start(icon); +} -void StartupFeedbackEffect::gotRemoveStartup( const KStartupInfoId& id, const KStartupInfoData& data ) - { - m_startups.remove( id ); - if( m_startups.count() == 0 ) - { +void StartupFeedbackEffect::gotRemoveStartup(const KStartupInfoId& id, const KStartupInfoData& data) +{ + m_startups.remove(id); + if (m_startups.count() == 0) { m_currentStartup = KStartupInfoId(); // null stop(); return; - } + } m_currentStartup = m_startups.begin().key(); - start( m_startups[ m_currentStartup ] ); - } + start(m_startups[ m_currentStartup ]); +} -void StartupFeedbackEffect::gotStartupChange( const KStartupInfoId& id, const KStartupInfoData& data ) - { - if( m_currentStartup == id ) - { +void StartupFeedbackEffect::gotStartupChange(const KStartupInfoId& id, const KStartupInfoData& data) +{ + if (m_currentStartup == id) { const QString& icon = data.findIcon(); - if( !icon.isEmpty() && icon != m_startups[ m_currentStartup ] ) - { + if (!icon.isEmpty() && icon != m_startups[ m_currentStartup ]) { m_startups[ id ] = icon; - start( icon ); - } + start(icon); } } +} -void StartupFeedbackEffect::start( const QString& icon ) - { - if( m_type == NoFeedback ) +void StartupFeedbackEffect::start(const QString& icon) +{ + if (m_type == NoFeedback) return; - if ( !m_active ) + if (!m_active) effects->startMousePolling(); m_active = true; - QPixmap iconPixmap = KIconLoader::global()->loadIcon( icon, KIconLoader::Small, 0, - KIconLoader::DefaultState, QStringList(), 0, true ); // return null pixmap if not found - if( iconPixmap.isNull() ) - iconPixmap = SmallIcon( "system-run" ); - prepareTextures( iconPixmap ); + QPixmap iconPixmap = KIconLoader::global()->loadIcon(icon, KIconLoader::Small, 0, + KIconLoader::DefaultState, QStringList(), 0, true); // return null pixmap if not found + if (iconPixmap.isNull()) + iconPixmap = SmallIcon("system-run"); + prepareTextures(iconPixmap); effects->addRepaintFull(); - } +} void StartupFeedbackEffect::stop() - { - if ( m_active ) +{ + if (m_active) effects->stopMousePolling(); m_active = false; - switch( m_type ) - { + switch(m_type) { case BouncingFeedback: - for( int i=0; i<5; ++i ) - { + for (int i = 0; i < 5; ++i) { delete m_bouncingTextures[i]; m_bouncingTextures[i] = 0; - } + } break; case BlinkingFeedback: case PassiveFeedback: @@ -361,79 +338,76 @@ void StartupFeedbackEffect::stop() return; // don't want the full repaint default: break; // impossible - } - effects->addRepaintFull(); } + effects->addRepaintFull(); +} -void StartupFeedbackEffect::prepareTextures( const QPixmap& pix ) - { - switch( m_type ) - { +void StartupFeedbackEffect::prepareTextures(const QPixmap& pix) +{ + switch(m_type) { case BouncingFeedback: - for( int i=0; i<5; ++i ) - { + for (int i = 0; i < 5; ++i) { delete m_bouncingTextures[i]; - m_bouncingTextures[i] = new GLTexture( scalePixmap( pix, BOUNCE_SIZES[i] ) ); - } + m_bouncingTextures[i] = new GLTexture(scalePixmap(pix, BOUNCE_SIZES[i])); + } break; case BlinkingFeedback: case PassiveFeedback: - m_texture = new GLTexture( pix ); + m_texture = new GLTexture(pix); break; default: // for safety m_active = false; break; - } } +} -QImage StartupFeedbackEffect::scalePixmap( const QPixmap& pm, const QSize& size ) const - { - QImage scaled = pm.toImage().scaled( size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation ); - if( scaled.format() != QImage::Format_ARGB32_Premultiplied && scaled.format() != QImage::Format_ARGB32 ) - scaled = scaled.convertToFormat( QImage::Format_ARGB32 ); +QImage StartupFeedbackEffect::scalePixmap(const QPixmap& pm, const QSize& size) const +{ + QImage scaled = pm.toImage().scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + if (scaled.format() != QImage::Format_ARGB32_Premultiplied && scaled.format() != QImage::Format_ARGB32) + scaled = scaled.convertToFormat(QImage::Format_ARGB32); - QImage result(20, 20, QImage::Format_ARGB32 ); - QPainter p( &result ); - p.setCompositionMode( QPainter::CompositionMode_Source ); - p.fillRect( result.rect(), Qt::transparent ); - p.drawImage( (20 - size.width()) / 2, (20 - size.height()) / 2, scaled, 0, 0, size.width(), size.height() ); + QImage result(20, 20, QImage::Format_ARGB32); + QPainter p(&result); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(result.rect(), Qt::transparent); + p.drawImage((20 - size.width()) / 2, (20 - size.height()) / 2, scaled, 0, 0, size.width(), size.height()); return result; - } +} QRect StartupFeedbackEffect::feedbackRect() const - { +{ int cursorSize = 0; - cursorSize = XcursorGetDefaultSize( QX11Info::display()); + cursorSize = XcursorGetDefaultSize(QX11Info::display()); int xDiff; - if( cursorSize <= 16 ) + if (cursorSize <= 16) xDiff = 8 + 7; - else if( cursorSize <= 32 ) + else if (cursorSize <= 32) xDiff = 16 + 7; - else if( cursorSize <= 48 ) + else if (cursorSize <= 48) xDiff = 24 + 7; else xDiff = 32 + 7; int yDiff = xDiff; GLTexture* texture; int yOffset = 0; - switch( m_type ) - { - case BouncingFeedback: - texture = m_bouncingTextures[ FRAME_TO_BOUNCE_TEXTURE[ m_frame ]]; - yOffset = FRAME_TO_BOUNCE_YOFFSET[ m_frame ]; - break; - case BlinkingFeedback: // fall through - case PassiveFeedback: - texture = m_texture; - break; - default: - // nothing - break; - } - const QPoint cursorPos = effects->cursorPos() + QPoint( xDiff, yDiff + yOffset ); - const QRect rect( cursorPos, texture->size() ); - return rect; + switch(m_type) { + case BouncingFeedback: + texture = m_bouncingTextures[ FRAME_TO_BOUNCE_TEXTURE[ m_frame ]]; + yOffset = FRAME_TO_BOUNCE_YOFFSET[ m_frame ]; + break; + case BlinkingFeedback: // fall through + case PassiveFeedback: + texture = m_texture; + break; + default: + // nothing + break; } + const QPoint cursorPos = effects->cursorPos() + QPoint(xDiff, yDiff + yOffset); + const QRect rect(cursorPos, texture->size()); + return rect; +} } // namespace diff --git a/effects/startupfeedback/startupfeedback.h b/effects/startupfeedback/startupfeedback.h index bef68e6ae..0e4ae0785 100644 --- a/effects/startupfeedback/startupfeedback.h +++ b/effects/startupfeedback/startupfeedback.h @@ -31,52 +31,51 @@ class GLTexture; class StartupFeedbackEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - StartupFeedbackEffect(); - virtual ~StartupFeedbackEffect(); +public: + StartupFeedbackEffect(); + virtual ~StartupFeedbackEffect(); - virtual void reconfigure( ReconfigureFlags flags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void mouseChanged( const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); + virtual void reconfigure(ReconfigureFlags flags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); - static bool supported(); + static bool supported(); - private Q_SLOTS: - void gotNewStartup( const KStartupInfoId& id, const KStartupInfoData& data ); - void gotRemoveStartup (const KStartupInfoId& id, const KStartupInfoData& data ); - void gotStartupChange( const KStartupInfoId& id, const KStartupInfoData& data ); +private Q_SLOTS: + void gotNewStartup(const KStartupInfoId& id, const KStartupInfoData& data); + void gotRemoveStartup(const KStartupInfoId& id, const KStartupInfoData& data); + void gotStartupChange(const KStartupInfoId& id, const KStartupInfoData& data); - private: - enum FeedbackType - { - NoFeedback, - BouncingFeedback, - BlinkingFeedback, - PassiveFeedback - }; - void start( const QString& icon ); - void stop(); - QImage scalePixmap( const QPixmap& pm, const QSize& size ) const; - void prepareTextures( const QPixmap& pix ); - QRect feedbackRect() const; - - KStartupInfo* m_startupInfo; - KSelectionOwner* m_selection; - KStartupInfoId m_currentStartup; - QMap< KStartupInfoId, QString > m_startups; // QString == pixmap - bool m_active; - int m_frame; - int m_progress; - GLTexture* m_bouncingTextures[5]; - GLTexture* m_texture; // for passive and blinking - FeedbackType m_type; - QRect m_currentGeometry; - GLShader *m_blinkingShader; +private: + enum FeedbackType { + NoFeedback, + BouncingFeedback, + BlinkingFeedback, + PassiveFeedback }; + void start(const QString& icon); + void stop(); + QImage scalePixmap(const QPixmap& pm, const QSize& size) const; + void prepareTextures(const QPixmap& pix); + QRect feedbackRect() const; + + KStartupInfo* m_startupInfo; + KSelectionOwner* m_selection; + KStartupInfoId m_currentStartup; + QMap< KStartupInfoId, QString > m_startups; // QString == pixmap + bool m_active; + int m_frame; + int m_progress; + GLTexture* m_bouncingTextures[5]; + GLTexture* m_texture; // for passive and blinking + FeedbackType m_type; + QRect m_currentGeometry; + GLShader *m_blinkingShader; +}; } // namespace #endif diff --git a/effects/taskbarthumbnail/taskbarthumbnail.cpp b/effects/taskbarthumbnail/taskbarthumbnail.cpp index 4f1572f91..ca030dbc7 100644 --- a/effects/taskbarthumbnail/taskbarthumbnail.cpp +++ b/effects/taskbarthumbnail/taskbarthumbnail.cpp @@ -24,7 +24,7 @@ along with this program. If not, see . #include #ifdef KWIN_HAVE_OPENGL_COMPOSITING - #include +#include #endif // This effect shows a preview inside a window that has a special property set @@ -34,131 +34,126 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( taskbarthumbnail, TaskbarThumbnailEffect ) +KWIN_EFFECT(taskbarthumbnail, TaskbarThumbnailEffect) TaskbarThumbnailEffect::TaskbarThumbnailEffect() - { - atom = XInternAtom( display(), "_KDE_WINDOW_PREVIEW", False ); - effects->registerPropertyType( atom, true ); +{ + atom = XInternAtom(display(), "_KDE_WINDOW_PREVIEW", False); + effects->registerPropertyType(atom, true); // TODO hackish way to announce support, make better after 4.0 unsigned char dummy = 0; - XChangeProperty( display(), rootWindow(), atom, atom, 8, PropModeReplace, &dummy, 1 ); - } + XChangeProperty(display(), rootWindow(), atom, atom, 8, PropModeReplace, &dummy, 1); +} TaskbarThumbnailEffect::~TaskbarThumbnailEffect() - { - XDeleteProperty( display(), rootWindow(), atom ); - effects->registerPropertyType( atom, false ); - } +{ + XDeleteProperty(display(), rootWindow(), atom); + effects->registerPropertyType(atom, false); +} -void TaskbarThumbnailEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { +void TaskbarThumbnailEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ if (thumbnails.count() > 0) { - data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS; + data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS; } effects->prePaintScreen(data, time); - } +} -void TaskbarThumbnailEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void TaskbarThumbnailEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ // TODO what if of the windows is translucent and one not? change data.mask? - effects->prePaintWindow( w, data, time ); - } + effects->prePaintWindow(w, data, time); +} -void TaskbarThumbnailEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { - effects->paintWindow( w, mask, region, data ); // paint window first - if( thumbnails.contains( w )) - { // paint thumbnails on it +void TaskbarThumbnailEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ + effects->paintWindow(w, mask, region, data); // paint window first + if (thumbnails.contains(w)) { + // paint thumbnails on it int mask = PAINT_WINDOW_TRANSFORMED; - if( data.opacity == 1.0 ) + if (data.opacity == 1.0) mask |= PAINT_WINDOW_OPAQUE; else mask |= PAINT_WINDOW_TRANSLUCENT; mask |= PAINT_WINDOW_LANCZOS; - foreach( const Data &thumb, thumbnails.values( w )) - { - EffectWindow* thumbw = effects->findWindow( thumb.window ); - if( thumbw == NULL ) + foreach (const Data & thumb, thumbnails.values(w)) { + EffectWindow* thumbw = effects->findWindow(thumb.window); + if (thumbw == NULL) continue; - WindowPaintData thumbData( thumbw ); + WindowPaintData thumbData(thumbw); thumbData.opacity *= data.opacity; QRect r; #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == KWin::OpenGLCompositing ) - { - if ( data.shader ) - { + if (effects->compositingType() == KWin::OpenGLCompositing) { + if (data.shader) { // there is a shader - update texture width and height int texw = thumbw->width(); int texh = thumbw->height(); - if( !GLTexture::NPOTTextureSupported() ) - { - kWarning( 1212 ) << "NPOT textures not supported, wasting some memory" ; - texw = nearestPowerOfTwo( texw ); - texh = nearestPowerOfTwo( texh ); - } - thumbData.shader = data.shader; - thumbData.shader->setTextureWidth( (float)texw ); - thumbData.shader->setTextureHeight( (float)texh ); + if (!GLTexture::NPOTTextureSupported()) { + kWarning(1212) << "NPOT textures not supported, wasting some memory" ; + texw = nearestPowerOfTwo(texw); + texh = nearestPowerOfTwo(texh); } - } // if ( effects->compositingType() == KWin::OpenGLCompositing ) + thumbData.shader = data.shader; + thumbData.shader->setTextureWidth((float)texw); + thumbData.shader->setTextureHeight((float)texh); + } + } // if ( effects->compositingType() == KWin::OpenGLCompositing ) #endif - setPositionTransformations( thumbData, r, - thumbw, thumb.rect.translated( w->pos()), Qt::KeepAspectRatio ); - effects->drawWindow( thumbw, mask, r, thumbData ); - } + setPositionTransformations(thumbData, r, + thumbw, thumb.rect.translated(w->pos()), Qt::KeepAspectRatio); + effects->drawWindow(thumbw, mask, r, thumbData); } - } // End of function + } +} // End of function -void TaskbarThumbnailEffect::windowDamaged( EffectWindow* w, const QRect& damage ) - { - Q_UNUSED( damage ); +void TaskbarThumbnailEffect::windowDamaged(EffectWindow* w, const QRect& damage) +{ + Q_UNUSED(damage); // Update the thumbnail if the window was damaged - foreach( EffectWindow* window, thumbnails.uniqueKeys() ) - foreach( const Data &thumb, thumbnails.values( window )) - if( w == effects->findWindow( thumb.window )) - effects->addRepaint( thumb.rect.translated( window->pos() )); - } + foreach (EffectWindow * window, thumbnails.uniqueKeys()) + foreach (const Data & thumb, thumbnails.values(window)) + if (w == effects->findWindow(thumb.window)) + effects->addRepaint(thumb.rect.translated(window->pos())); +} -void TaskbarThumbnailEffect::windowAdded( EffectWindow* w ) - { - propertyNotify( w, atom ); // read initial value - } +void TaskbarThumbnailEffect::windowAdded(EffectWindow* w) +{ + propertyNotify(w, atom); // read initial value +} -void TaskbarThumbnailEffect::windowDeleted( EffectWindow* w ) - { - thumbnails.remove( w ); - } +void TaskbarThumbnailEffect::windowDeleted(EffectWindow* w) +{ + thumbnails.remove(w); +} -void TaskbarThumbnailEffect::propertyNotify( EffectWindow* w, long a ) - { - if( !w || a != atom ) +void TaskbarThumbnailEffect::propertyNotify(EffectWindow* w, long a) +{ + if (!w || a != atom) return; - thumbnails.remove( w ); - QByteArray data = w->readProperty( atom, atom, 32 ); - if( data.length() < 1 ) + thumbnails.remove(w); + QByteArray data = w->readProperty(atom, atom, 32); + if (data.length() < 1) return; - long* d = reinterpret_cast< long* >( data.data()); - int len = data.length() / sizeof( d[ 0 ] ); + long* d = reinterpret_cast< long* >(data.data()); + int len = data.length() / sizeof(d[ 0 ]); int pos = 0; int cnt = d[ 0 ]; ++pos; - for( int i = 0; - i < cnt; - ++i ) - { + for (int i = 0; + i < cnt; + ++i) { int size = d[ pos ]; - if( len - pos < size ) + if (len - pos < size) return; // format error ++pos; Data data; data.window = d[ pos ]; - data.rect = QRect( d[ pos + 1 ], d[ pos + 2 ], d[ pos + 3 ], d[ pos + 4 ] ); - thumbnails.insert( w, data ); + data.rect = QRect(d[ pos + 1 ], d[ pos + 2 ], d[ pos + 3 ], d[ pos + 4 ]); + thumbnails.insert(w, data); pos += size; - } } +} } // namespace diff --git a/effects/taskbarthumbnail/taskbarthumbnail.h b/effects/taskbarthumbnail/taskbarthumbnail.h index 667b68954..08f12ac64 100644 --- a/effects/taskbarthumbnail/taskbarthumbnail.h +++ b/effects/taskbarthumbnail/taskbarthumbnail.h @@ -30,27 +30,26 @@ namespace KWin class TaskbarThumbnailEffect : public QObject, public Effect - { - public: - TaskbarThumbnailEffect(); - virtual ~TaskbarThumbnailEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowDamaged( EffectWindow* w, const QRect& damage ); - virtual void windowAdded( EffectWindow* w ); - virtual void windowDeleted( EffectWindow* w ); - virtual void propertyNotify( EffectWindow* w, long atom ); - private: - struct Data - { - Window window; // thumbnail of this window - QRect rect; - }; - long atom; - QMultiHash< EffectWindow*, Data > thumbnails; - EffectWindowList damagedWindows; +{ +public: + TaskbarThumbnailEffect(); + virtual ~TaskbarThumbnailEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowDamaged(EffectWindow* w, const QRect& damage); + virtual void windowAdded(EffectWindow* w); + virtual void windowDeleted(EffectWindow* w); + virtual void propertyNotify(EffectWindow* w, long atom); +private: + struct Data { + Window window; // thumbnail of this window + QRect rect; }; + long atom; + QMultiHash< EffectWindow*, Data > thumbnails; + EffectWindowList damagedWindows; +}; } // namespace diff --git a/effects/thumbnailaside/thumbnailaside.cpp b/effects/thumbnailaside/thumbnailaside.cpp index 9fd79a860..32276ffde 100644 --- a/effects/thumbnailaside/thumbnailaside.cpp +++ b/effects/thumbnailaside/thumbnailaside.cpp @@ -29,154 +29,145 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( thumbnailaside, ThumbnailAsideEffect ) +KWIN_EFFECT(thumbnailaside, ThumbnailAsideEffect) ThumbnailAsideEffect::ThumbnailAsideEffect() - { - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = (KAction*)actionCollection->addAction( "ToggleCurrentThumbnail" ); - a->setText( i18n("Toggle Thumbnail for Current Window" )); +{ + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = (KAction*)actionCollection->addAction("ToggleCurrentThumbnail"); + a->setText(i18n("Toggle Thumbnail for Current Window")); a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::META + Qt::Key_T)); connect(a, SIGNAL(triggered(bool)), this, SLOT(toggleCurrentThumbnail())); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} -void ThumbnailAsideEffect::reconfigure( ReconfigureFlags ) - { +void ThumbnailAsideEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("ThumbnailAside"); maxwidth = conf.readEntry("MaxWidth", 200); spacing = conf.readEntry("Spacing", 10); opacity = conf.readEntry("Opacity", 50) / 100.0; - screen = conf.readEntry("Screen",-1); // Xinerama screen TODO add gui option + screen = conf.readEntry("Screen", -1); // Xinerama screen TODO add gui option arrange(); - } +} -void ThumbnailAsideEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); - foreach( const Data& d, windows ) - { - if( region.contains( d.rect )) - { - WindowPaintData data( d.window ); +void ThumbnailAsideEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); + foreach (const Data & d, windows) { + if (region.contains(d.rect)) { + WindowPaintData data(d.window); data.opacity = opacity; QRect region; - setPositionTransformations( data, region, d.window, d.rect, Qt::KeepAspectRatio ); - effects->drawWindow( d.window, PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSLUCENT | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, - region, data ); - } + setPositionTransformations(data, region, d.window, d.rect, Qt::KeepAspectRatio); + effects->drawWindow(d.window, PAINT_WINDOW_OPAQUE | PAINT_WINDOW_TRANSLUCENT | PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_LANCZOS, + region, data); } } +} -void ThumbnailAsideEffect::windowDamaged( EffectWindow* w, const QRect& ) - { - foreach( const Data& d, windows ) - { - if( d.window == w ) - effects->addRepaint( d.rect ); - } +void ThumbnailAsideEffect::windowDamaged(EffectWindow* w, const QRect&) +{ + foreach (const Data & d, windows) { + if (d.window == w) + effects->addRepaint(d.rect); } +} -void ThumbnailAsideEffect::windowGeometryShapeChanged( EffectWindow* w, const QRect& old ) - { - foreach( const Data& d, windows ) - { - if( d.window == w ) - { - if( w->size() == old.size()) - effects->addRepaint( d.rect ); +void ThumbnailAsideEffect::windowGeometryShapeChanged(EffectWindow* w, const QRect& old) +{ + foreach (const Data & d, windows) { + if (d.window == w) { + if (w->size() == old.size()) + effects->addRepaint(d.rect); else arrange(); return; - } } } +} -void ThumbnailAsideEffect::windowClosed( EffectWindow* w ) - { - removeThumbnail( w ); - } +void ThumbnailAsideEffect::windowClosed(EffectWindow* w) +{ + removeThumbnail(w); +} void ThumbnailAsideEffect::toggleCurrentThumbnail() - { +{ EffectWindow* active = effects->activeWindow(); - if( active == NULL ) + if (active == NULL) return; - if( windows.contains( active )) - removeThumbnail( active ); + if (windows.contains(active)) + removeThumbnail(active); else - addThumbnail( active ); - } + addThumbnail(active); +} -void ThumbnailAsideEffect::addThumbnail( EffectWindow* w ) - { +void ThumbnailAsideEffect::addThumbnail(EffectWindow* w) +{ repaintAll(); // repaint old areas Data d; d.window = w; d.index = windows.count(); windows[ w ] = d; arrange(); - } +} -void ThumbnailAsideEffect::removeThumbnail( EffectWindow* w ) - { - if( !windows.contains( w )) +void ThumbnailAsideEffect::removeThumbnail(EffectWindow* w) +{ + if (!windows.contains(w)) return; repaintAll(); // repaint old areas int index = windows[ w ].index; - windows.remove( w ); - for( QHash< EffectWindow*, Data >::Iterator it = windows.begin(); - it != windows.end(); - ++it ) - { + windows.remove(w); + for (QHash< EffectWindow*, Data >::Iterator it = windows.begin(); + it != windows.end(); + ++it) { Data& d = *it; - if( d.index > index ) + if (d.index > index) --d.index; - } - arrange(); } + arrange(); +} void ThumbnailAsideEffect::arrange() - { - if( windows.size() == 0 ) +{ + if (windows.size() == 0) return; int height = 0; - QVector< int > pos( windows.size()); + QVector< int > pos(windows.size()); int mwidth = 0; - foreach( const Data& d, windows ) - { + foreach (const Data & d, windows) { height += d.window->height(); - mwidth = qMax( mwidth, d.window->width()); + mwidth = qMax(mwidth, d.window->width()); pos[ d.index ] = d.window->height(); - } - QRect area = effects->clientArea( MaximizeArea, screen, effects->currentDesktop()); - double scale = area.height() / double( height ); - scale = qMin( scale, maxwidth / double( mwidth )); // don't be wider than maxwidth pixels + } + QRect area = effects->clientArea(MaximizeArea, screen, effects->currentDesktop()); + double scale = area.height() / double(height); + scale = qMin(scale, maxwidth / double(mwidth)); // don't be wider than maxwidth pixels int add = 0; - for( int i = 0; - i < windows.size(); - ++i ) - { - pos[ i ] = int( pos[ i ] * scale ); + for (int i = 0; + i < windows.size(); + ++i) { + pos[ i ] = int(pos[ i ] * scale); pos[ i ] += spacing + add; // compute offset of each item add = pos[ i ]; - } - for( QHash< EffectWindow*, Data >::Iterator it = windows.begin(); - it != windows.end(); - ++it ) - { - Data& d = *it; - int width = int( d.window->width() * scale ); - d.rect = QRect( area.right() - width, area.bottom() - pos[ d.index ], width, int( d.window->height() * scale )); - } - repaintAll(); } + for (QHash< EffectWindow*, Data >::Iterator it = windows.begin(); + it != windows.end(); + ++it) { + Data& d = *it; + int width = int(d.window->width() * scale); + d.rect = QRect(area.right() - width, area.bottom() - pos[ d.index ], width, int(d.window->height() * scale)); + } + repaintAll(); +} void ThumbnailAsideEffect::repaintAll() - { - foreach( const Data& d, windows ) - effects->addRepaint( d.rect ); - } +{ + foreach (const Data & d, windows) + effects->addRepaint(d.rect); +} } // namespace diff --git a/effects/thumbnailaside/thumbnailaside.h b/effects/thumbnailaside/thumbnailaside.h index d0ad1f154..ccb1907be 100644 --- a/effects/thumbnailaside/thumbnailaside.h +++ b/effects/thumbnailaside/thumbnailaside.h @@ -38,34 +38,33 @@ namespace KWin class ThumbnailAsideEffect : public QObject , public Effect - { +{ Q_OBJECT - public: - ThumbnailAsideEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void windowDamaged( EffectWindow* w, const QRect& damage ); - virtual void windowGeometryShapeChanged( EffectWindow* w, const QRect& old ); - virtual void windowClosed( EffectWindow* w ); - private slots: - void toggleCurrentThumbnail(); - private: - void addThumbnail( EffectWindow* w ); - void removeThumbnail( EffectWindow* w ); - void arrange(); - void repaintAll(); - struct Data - { - EffectWindow* window; // the same like the key in the hash (makes code simpler) - int index; - QRect rect; - }; - QHash< EffectWindow*, Data > windows; - int maxwidth; - int spacing; - double opacity; - int screen; +public: + ThumbnailAsideEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void windowDamaged(EffectWindow* w, const QRect& damage); + virtual void windowGeometryShapeChanged(EffectWindow* w, const QRect& old); + virtual void windowClosed(EffectWindow* w); +private slots: + void toggleCurrentThumbnail(); +private: + void addThumbnail(EffectWindow* w); + void removeThumbnail(EffectWindow* w); + void arrange(); + void repaintAll(); + struct Data { + EffectWindow* window; // the same like the key in the hash (makes code simpler) + int index; + QRect rect; }; + QHash< EffectWindow*, Data > windows; + int maxwidth; + int spacing; + double opacity; + int screen; +}; } // namespace diff --git a/effects/thumbnailaside/thumbnailaside_config.cpp b/effects/thumbnailaside/thumbnailaside_config.cpp index 346cec613..ce700781b 100644 --- a/effects/thumbnailaside/thumbnailaside_config.cpp +++ b/effects/thumbnailaside/thumbnailaside_config.cpp @@ -39,12 +39,12 @@ KWIN_EFFECT_CONFIG_FACTORY ThumbnailAsideEffectConfigForm::ThumbnailAsideEffectConfigForm(QWidget* parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } ThumbnailAsideEffectConfig::ThumbnailAsideEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new ThumbnailAsideEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -57,28 +57,28 @@ ThumbnailAsideEffectConfig::ThumbnailAsideEffectConfig(QWidget* parent, const QV connect(m_ui->spinOpacity, SIGNAL(valueChanged(int)), this, SLOT(changed())); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); m_actionCollection->setConfigGroup("ThumbnailAside"); m_actionCollection->setConfigGlobal(true); - KAction* a = (KAction*)m_actionCollection->addAction( "ToggleCurrentThumbnail" ); - a->setText( i18n("Toggle Thumbnail for Current Window" )); + KAction* a = (KAction*)m_actionCollection->addAction("ToggleCurrentThumbnail"); + a->setText(i18n("Toggle Thumbnail for Current Window")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::CTRL + Qt::Key_T)); m_ui->editor->addCollection(m_actionCollection); - } +} ThumbnailAsideEffectConfig::~ThumbnailAsideEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts m_ui->editor->undoChanges(); - } +} void ThumbnailAsideEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("ThumbnailAside"); @@ -93,10 +93,10 @@ void ThumbnailAsideEffectConfig::load() m_ui->spinOpacity->setValue(opacity); emit changed(false); - } +} void ThumbnailAsideEffectConfig::save() - { +{ kDebug(1212) << "Saving config of ThumbnailAside" ; //KCModule::save(); @@ -112,19 +112,19 @@ void ThumbnailAsideEffectConfig::save() conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "thumbnailaside" ); - } + EffectsHandler::sendReloadMessage("thumbnailaside"); +} void ThumbnailAsideEffectConfig::defaults() - { +{ m_ui->spinWidth->setValue(200); m_ui->spinSpacing->setValue(10); m_ui->spinOpacity->setValue(50); m_ui->editor->allDefault(); emit changed(true); - - } + +} } // namespace diff --git a/effects/thumbnailaside/thumbnailaside_config.h b/effects/thumbnailaside/thumbnailaside_config.h index e4eb5651d..9e59a275a 100644 --- a/effects/thumbnailaside/thumbnailaside_config.h +++ b/effects/thumbnailaside/thumbnailaside_config.h @@ -33,25 +33,25 @@ namespace KWin class ThumbnailAsideEffectConfigForm : public QWidget, public Ui::ThumbnailAsideEffectConfigForm { Q_OBJECT - public: - explicit ThumbnailAsideEffectConfigForm(QWidget* parent); +public: + explicit ThumbnailAsideEffectConfigForm(QWidget* parent); }; class ThumbnailAsideEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit ThumbnailAsideEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual ~ThumbnailAsideEffectConfig(); +public: + explicit ThumbnailAsideEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + virtual ~ThumbnailAsideEffectConfig(); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - ThumbnailAsideEffectConfigForm* m_ui; - KActionCollection* m_actionCollection; - }; +private: + ThumbnailAsideEffectConfigForm* m_ui; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/trackmouse/trackmouse.cpp b/effects/trackmouse/trackmouse.cpp index aa364d2a2..4c351edbf 100644 --- a/effects/trackmouse/trackmouse.cpp +++ b/effects/trackmouse/trackmouse.cpp @@ -40,82 +40,78 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( trackmouse, TrackMouseEffect ) +KWIN_EFFECT(trackmouse, TrackMouseEffect) const int STARS = 5; const int DIST = 50; TrackMouseEffect::TrackMouseEffect() - : active( false ) - , angle( 0 ) - , texture( NULL ) - { + : active(false) + , angle(0) + , texture(NULL) +{ mousePolling = false; - actionCollection = new KActionCollection( this ); - action = static_cast< KAction* >( actionCollection->addAction( "TrackMouse" )); - action->setText( i18n( "Track mouse" ) ); - action->setGlobalShortcut( KShortcut() ); + actionCollection = new KActionCollection(this); + action = static_cast< KAction* >(actionCollection->addAction("TrackMouse")); + action->setText(i18n("Track mouse")); + action->setGlobalShortcut(KShortcut()); - connect( action, SIGNAL( triggered( bool ) ), this, SLOT( toggle() ) ); - reconfigure( ReconfigureAll ); - } + connect(action, SIGNAL(triggered(bool)), this, SLOT(toggle())); + reconfigure(ReconfigureAll); +} TrackMouseEffect::~TrackMouseEffect() - { - if( mousePolling ) +{ + if (mousePolling) effects->stopMousePolling(); delete texture; - } +} -void TrackMouseEffect::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "TrackMouse" ); - bool shift = conf.readEntry( "Shift", false ); - bool alt = conf.readEntry( "Alt", false ); - bool control = conf.readEntry( "Control", true ); - bool meta = conf.readEntry( "Meta", true ); +void TrackMouseEffect::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("TrackMouse"); + bool shift = conf.readEntry("Shift", false); + bool alt = conf.readEntry("Alt", false); + bool control = conf.readEntry("Control", true); + bool meta = conf.readEntry("Meta", true); modifier = 0; - if( meta ) + if (meta) modifier |= Qt::MetaModifier; - if( control ) + if (control) modifier |= Qt::ControlModifier; - if( alt ) + if (alt) modifier |= Qt::AltModifier; - if( shift ) + if (shift) modifier |= Qt::ShiftModifier; - if( modifier != 0 && action != NULL ) - { - if( !mousePolling ) + if (modifier != 0 && action != NULL) { + if (!mousePolling) effects->startMousePolling(); mousePolling = true; - } - else if( action != NULL ) - { - if( mousePolling ) + } else if (action != NULL) { + if (mousePolling) effects->stopMousePolling(); mousePolling = false; - } } +} -void TrackMouseEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( active ) { +void TrackMouseEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (active) { QTime t = QTime::currentTime(); angle = ((t.second() % 4) * 90.0) + (t.msec() / 1000.0 * 90.0); } - effects->prePaintScreen( data, time ); - } + effects->prePaintScreen(data, time); +} -void TrackMouseEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - effects->paintScreen( mask, region, data ); // paint normal screen - if( !active ) +void TrackMouseEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + effects->paintScreen(mask, region, data); // paint normal screen + if (!active) return; #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( texture ) - { + if (texture) { #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif bool useShader = false; if (ShaderManager::instance()->isValid()) { @@ -123,15 +119,14 @@ void TrackMouseEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d ShaderManager::instance()->pushShader(ShaderManager::SimpleShader); } texture->bind(); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - for( int i = 0; - i < STARS; - ++i ) - { - QRect r = starRect( i ); - texture->render( region, r ); - } + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + for (int i = 0; + i < STARS; + ++i) { + QRect r = starRect(i); + texture->render(region, r); + } texture->unbind(); glDisable(GL_BLEND); if (ShaderManager::instance()->isValid()) { @@ -139,86 +134,79 @@ void TrackMouseEffect::paintScreen( int mask, QRegion region, ScreenPaintData& d } #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); -#endif - } #endif } +#endif +} void TrackMouseEffect::postPaintScreen() - { - if( active ) - { - for( int i = 0; - i < STARS; - ++i ) - effects->addRepaint( starRect( i )); - } - effects->postPaintScreen(); +{ + if (active) { + for (int i = 0; + i < STARS; + ++i) + effects->addRepaint(starRect(i)); } + effects->postPaintScreen(); +} void TrackMouseEffect::toggle() - { - if( mousePolling ) +{ + if (mousePolling) return; - if( !active ) - { - if( texture == NULL ) + if (!active) { + if (texture == NULL) loadTexture(); - if( texture == NULL ) + if (texture == NULL) return; active = true; angle = 0; - } - else + } else active = false; - for( int i = 0; i < STARS; ++i ) - effects->addRepaint( starRect( i )); - } + for (int i = 0; i < STARS; ++i) + effects->addRepaint(starRect(i)); +} -void TrackMouseEffect::mouseChanged( const QPoint&, const QPoint&, Qt::MouseButtons, - Qt::MouseButtons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers ) - { - if( modifier != 0 && modifiers == modifier ) - { - if( !active ) - { - if( texture == NULL ) +void TrackMouseEffect::mouseChanged(const QPoint&, const QPoint&, Qt::MouseButtons, + Qt::MouseButtons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers) +{ + if (modifier != 0 && modifiers == modifier) { + if (!active) { + if (texture == NULL) loadTexture(); - if( texture == NULL ) + if (texture == NULL) return; active = true; angle = 0; - } - for( int i = 0; i < STARS; ++i ) - effects->addRepaint( starRect( i )); } - else if( active ) - { - for( int i = 0; i < STARS; ++i ) - effects->addRepaint( starRect( i )); + for (int i = 0; i < STARS; ++i) + effects->addRepaint(starRect(i)); + } else if (active) { + for (int i = 0; i < STARS; ++i) + effects->addRepaint(starRect(i)); active = false; - } } +} -QRect TrackMouseEffect::starRect( int num ) const - { +QRect TrackMouseEffect::starRect(int num) const +{ int a = angle + 360 / STARS * num; - int x = cursorPos().x() + int( DIST * cos( a * ( 2 * M_PI / 360 ))); - int y = cursorPos().y() + int( DIST * sin( a * ( 2 * M_PI / 360 ))); - return QRect( QPoint( x - textureSize.width() / 2, - y - textureSize.height() / 2 ), textureSize ); - } + int x = cursorPos().x() + int(DIST * cos(a * (2 * M_PI / 360))); + int y = cursorPos().y() + int(DIST * sin(a * (2 * M_PI / 360))); + return QRect(QPoint(x - textureSize.width() / 2, + y - textureSize.height() / 2), textureSize); +} void TrackMouseEffect::loadTexture() - { +{ #ifdef KWIN_HAVE_OPENGL_COMPOSITING - QString file = KGlobal::dirs()->findResource( "appdata", "trackmouse.png" ); - if( file.isEmpty()) + QString file = KGlobal::dirs()->findResource("appdata", "trackmouse.png"); + if (file.isEmpty()) return; - QImage im( file ); - texture = new GLTexture( im ); + QImage im(file); + texture = new GLTexture(im); textureSize = im.size(); #endif - } +} } // namespace diff --git a/effects/trackmouse/trackmouse.h b/effects/trackmouse/trackmouse.h index c90510f22..6ef2c889a 100644 --- a/effects/trackmouse/trackmouse.h +++ b/effects/trackmouse/trackmouse.h @@ -32,31 +32,31 @@ class GLTexture; class TrackMouseEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - TrackMouseEffect(); - virtual ~TrackMouseEffect(); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - virtual void reconfigure( ReconfigureFlags ); - private slots: - void toggle(); - private: - QRect starRect( int num ) const; - void loadTexture(); - bool active, mousePolling; - int angle; - GLTexture* texture; - QSize textureSize; - KActionCollection* actionCollection; - KAction* action; - Qt::KeyboardModifiers modifier; - }; +public: + TrackMouseEffect(); + virtual ~TrackMouseEffect(); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); + virtual void reconfigure(ReconfigureFlags); +private slots: + void toggle(); +private: + QRect starRect(int num) const; + void loadTexture(); + bool active, mousePolling; + int angle; + GLTexture* texture; + QSize textureSize; + KActionCollection* actionCollection; + KAction* action; + Qt::KeyboardModifiers modifier; +}; } // namespace diff --git a/effects/trackmouse/trackmouse_config.cpp b/effects/trackmouse/trackmouse_config.cpp index fe25ad534..52ea00f29 100644 --- a/effects/trackmouse/trackmouse_config.cpp +++ b/effects/trackmouse/trackmouse_config.cpp @@ -37,95 +37,92 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY -TrackMouseEffectConfigForm::TrackMouseEffectConfigForm( QWidget* parent ) : QWidget( parent ) - { - setupUi( this ); - } +TrackMouseEffectConfigForm::TrackMouseEffectConfigForm(QWidget* parent) : QWidget(parent) +{ + setupUi(this); +} -TrackMouseEffectConfig::TrackMouseEffectConfig( QWidget* parent, const QVariantList& args ) : - KCModule( EffectFactory::componentData(), parent, args ) - { +TrackMouseEffectConfig::TrackMouseEffectConfig(QWidget* parent, const QVariantList& args) : + KCModule(EffectFactory::componentData(), parent, args) +{ - m_ui = new TrackMouseEffectConfigForm( this ); - QVBoxLayout* layout = new QVBoxLayout( this ); - layout->addWidget( m_ui ); - connect( m_ui->editor, SIGNAL( keyChange() ), this, SLOT( changed() ) ); - connect( m_ui->alt, SIGNAL( stateChanged( int ) ), this, SLOT( changed() ) ); - connect( m_ui->control, SIGNAL( stateChanged( int ) ), this, SLOT( changed() ) ); - connect( m_ui->meta, SIGNAL( stateChanged( int ) ), this, SLOT( changed() ) ); - connect( m_ui->shift, SIGNAL( stateChanged( int ) ), this, SLOT( changed() ) ); - connect( m_ui->alt, SIGNAL( toggled( bool ) ), this, SLOT( enableEditor( bool ) ) ); - connect( m_ui->control, SIGNAL( toggled( bool ) ), this, SLOT( enableEditor( bool ) ) ); - connect( m_ui->meta, SIGNAL( toggled( bool ) ), this, SLOT( enableEditor( bool ) ) ); - connect( m_ui->shift, SIGNAL( toggled( bool ) ), this, SLOT( enableEditor( bool ) ) ); - m_actionCollection = new KActionCollection( this, KComponentData( "kwin" ) ); - m_actionCollection->setConfigGroup( "TrackMouse" ); - m_actionCollection->setConfigGlobal( true ); + m_ui = new TrackMouseEffectConfigForm(this); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_ui); + connect(m_ui->editor, SIGNAL(keyChange()), this, SLOT(changed())); + connect(m_ui->alt, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->control, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->meta, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->shift, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->alt, SIGNAL(toggled(bool)), this, SLOT(enableEditor(bool))); + connect(m_ui->control, SIGNAL(toggled(bool)), this, SLOT(enableEditor(bool))); + connect(m_ui->meta, SIGNAL(toggled(bool)), this, SLOT(enableEditor(bool))); + connect(m_ui->shift, SIGNAL(toggled(bool)), this, SLOT(enableEditor(bool))); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); + m_actionCollection->setConfigGroup("TrackMouse"); + m_actionCollection->setConfigGlobal(true); - action = static_cast< KAction* >( m_actionCollection->addAction( "TrackMouse" ) ); - action->setText( i18n( "Track mouse" ) ); + action = static_cast< KAction* >(m_actionCollection->addAction("TrackMouse")); + action->setText(i18n("Track mouse")); action->setProperty("isConfigurationAction", true); - action->setGlobalShortcut( KShortcut() ); + action->setGlobalShortcut(KShortcut()); - m_ui->editor->addCollection( m_actionCollection ); + m_ui->editor->addCollection(m_actionCollection); load(); - } +} TrackMouseEffectConfig::~TrackMouseEffectConfig() - { +{ m_ui->editor->undoChanges(); - } +} void TrackMouseEffectConfig::load() - { +{ KCModule::load(); - KConfigGroup conf = EffectsHandler::effectConfig( "TrackMouse" ); - m_ui->meta->setChecked( conf.readEntry( "Meta", true ) ); - m_ui->control->setChecked( conf.readEntry( "Control", true ) ); - m_ui->alt->setChecked( conf.readEntry( "Alt", false ) ); - m_ui->shift->setChecked( conf.readEntry( "Shift", false ) ); - emit changed( false ); - } + KConfigGroup conf = EffectsHandler::effectConfig("TrackMouse"); + m_ui->meta->setChecked(conf.readEntry("Meta", true)); + m_ui->control->setChecked(conf.readEntry("Control", true)); + m_ui->alt->setChecked(conf.readEntry("Alt", false)); + m_ui->shift->setChecked(conf.readEntry("Shift", false)); + emit changed(false); +} void TrackMouseEffectConfig::save() - { - KConfigGroup conf = EffectsHandler::effectConfig( "TrackMouse" ); - conf.writeEntry( "Shift", m_ui->shift->isChecked() ); - conf.writeEntry( "Alt", m_ui->alt->isChecked() ); - conf.writeEntry( "Control", m_ui->control->isChecked() ); - conf.writeEntry( "Meta", m_ui->meta->isChecked() ); +{ + KConfigGroup conf = EffectsHandler::effectConfig("TrackMouse"); + conf.writeEntry("Shift", m_ui->shift->isChecked()); + conf.writeEntry("Alt", m_ui->alt->isChecked()); + conf.writeEntry("Control", m_ui->control->isChecked()); + conf.writeEntry("Meta", m_ui->meta->isChecked()); m_ui->editor->save(); conf.sync(); - emit changed( false ); - EffectsHandler::sendReloadMessage( "trackmouse" ); - } + emit changed(false); + EffectsHandler::sendReloadMessage("trackmouse"); +} void TrackMouseEffectConfig::defaults() - { +{ m_ui->editor->allDefault(); - m_ui->meta->setChecked( true ); - m_ui->control->setChecked( true ); - m_ui->alt->setChecked( false ); - m_ui->shift->setChecked( false ); - emit changed( true ); - } + m_ui->meta->setChecked(true); + m_ui->control->setChecked(true); + m_ui->alt->setChecked(false); + m_ui->shift->setChecked(false); + emit changed(true); +} -void TrackMouseEffectConfig::enableEditor( bool enabled ) - { - if( !enabled && !m_ui->alt->isChecked() && !m_ui->shift->isChecked() && !m_ui->meta->isChecked() && !m_ui->control->isChecked() ) - { - m_ui->editor->setEnabled( true ); - emit changed( true ); - } - else if( enabled && ( m_ui->alt->isChecked() || m_ui->shift->isChecked() || m_ui->meta->isChecked() || m_ui->control->isChecked() ) ) - { - m_ui->editor->setEnabled( false ); - action->setGlobalShortcut( KShortcut(), KAction::ShortcutTypes( KAction::ActiveShortcut | KAction::DefaultShortcut), KAction::NoAutoloading ); +void TrackMouseEffectConfig::enableEditor(bool enabled) +{ + if (!enabled && !m_ui->alt->isChecked() && !m_ui->shift->isChecked() && !m_ui->meta->isChecked() && !m_ui->control->isChecked()) { + m_ui->editor->setEnabled(true); + emit changed(true); + } else if (enabled && (m_ui->alt->isChecked() || m_ui->shift->isChecked() || m_ui->meta->isChecked() || m_ui->control->isChecked())) { + m_ui->editor->setEnabled(false); + action->setGlobalShortcut(KShortcut(), KAction::ShortcutTypes(KAction::ActiveShortcut | KAction::DefaultShortcut), KAction::NoAutoloading); emit changed(true); - } - emit changed( true ); } + emit changed(true); +} } // namespace diff --git a/effects/trackmouse/trackmouse_config.h b/effects/trackmouse/trackmouse_config.h index 918a9ab6b..59db12341 100644 --- a/effects/trackmouse/trackmouse_config.h +++ b/effects/trackmouse/trackmouse_config.h @@ -33,30 +33,30 @@ namespace KWin { class TrackMouseEffectConfigForm : public QWidget, public Ui::TrackMouseEffectConfigForm - { - Q_OBJECT - public: - explicit TrackMouseEffectConfigForm( QWidget* parent ); - }; +{ + Q_OBJECT +public: + explicit TrackMouseEffectConfigForm(QWidget* parent); +}; class TrackMouseEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit TrackMouseEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - ~TrackMouseEffectConfig(); +public: + explicit TrackMouseEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + ~TrackMouseEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); - private slots: - virtual void enableEditor( bool ); - private: - TrackMouseEffectConfigForm* m_ui; - KAction *action; - KActionCollection* m_actionCollection; - }; +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); +private slots: + virtual void enableEditor(bool); +private: + TrackMouseEffectConfigForm* m_ui; + KAction *action; + KActionCollection* m_actionCollection; +}; } // namespace diff --git a/effects/translucency/translucency.cpp b/effects/translucency/translucency.cpp index 9687a4094..bb685c0af 100644 --- a/effects/translucency/translucency.cpp +++ b/effects/translucency/translucency.cpp @@ -25,213 +25,188 @@ along with this program. If not, see . namespace KWin { -KWIN_EFFECT( translucency, TranslucencyEffect ) +KWIN_EFFECT(translucency, TranslucencyEffect) TranslucencyEffect::TranslucencyEffect() - : fadeout( NULL ) - , current( NULL ) - , previous( NULL ) - { - reconfigure( ReconfigureAll ); + : fadeout(NULL) + , current(NULL) + , previous(NULL) +{ + reconfigure(ReconfigureAll); active = effects->activeWindow(); - } +} -void TranslucencyEffect::reconfigure( ReconfigureFlags ) - { +void TranslucencyEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = effects->effectConfig("Translucency"); - decoration = conf.readEntry( "Decoration", 1.0 ); - moveresize = conf.readEntry( "MoveResize", 0.8 ); - dialogs = conf.readEntry( "Dialogs", 1.0 ); - inactive = conf.readEntry( "Inactive", 1.0 ); - comboboxpopups = conf.readEntry( "ComboboxPopups", 1.0 ); - menus = conf.readEntry( "Menus", 1.0 ); - individualmenuconfig = conf.readEntry( "IndividualMenuConfig", false ); - if( individualmenuconfig ) - { - dropdownmenus = conf.readEntry( "DropdownMenus", 1.0 ); - popupmenus = conf.readEntry( "PopupMenus", 1.0 ); - tornoffmenus = conf.readEntry( "TornOffMenus", 1.0 ); - } - else - { + decoration = conf.readEntry("Decoration", 1.0); + moveresize = conf.readEntry("MoveResize", 0.8); + dialogs = conf.readEntry("Dialogs", 1.0); + inactive = conf.readEntry("Inactive", 1.0); + comboboxpopups = conf.readEntry("ComboboxPopups", 1.0); + menus = conf.readEntry("Menus", 1.0); + individualmenuconfig = conf.readEntry("IndividualMenuConfig", false); + if (individualmenuconfig) { + dropdownmenus = conf.readEntry("DropdownMenus", 1.0); + popupmenus = conf.readEntry("PopupMenus", 1.0); + tornoffmenus = conf.readEntry("TornOffMenus", 1.0); + } else { dropdownmenus = menus; popupmenus = menus; tornoffmenus = menus; - } - moveresize_timeline.setCurveShape( TimeLine::EaseOutCurve ); - moveresize_timeline.setDuration( animationTime( conf, "Duration", 800 ) ); - activeinactive_timeline.setCurveShape( TimeLine::EaseInOutCurve ); - activeinactive_timeline.setDuration( animationTime( conf, "Duration", 800 ) ); + } + moveresize_timeline.setCurveShape(TimeLine::EaseOutCurve); + moveresize_timeline.setDuration(animationTime(conf, "Duration", 800)); + activeinactive_timeline.setCurveShape(TimeLine::EaseInOutCurve); + activeinactive_timeline.setDuration(animationTime(conf, "Duration", 800)); // Repaint the screen just in case the user changed the inactive opacity effects->addRepaintFull(); - } +} -void TranslucencyEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) - { +void TranslucencyEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) +{ moveresize_timeline.addTime(time); activeinactive_timeline.addTime(time); - if( decoration != 1.0 && w->hasDecoration()) - { + if (decoration != 1.0 && w->hasDecoration()) { data.mask |= PAINT_WINDOW_TRANSLUCENT; // don't clear PAINT_WINDOW_OPAQUE, contents are not affected - data.clip &= w->contentsRect().translated( w->pos()); // decoration cannot clip - } - if( inactive != 1.0 && isInactive( w )) + data.clip &= w->contentsRect().translated(w->pos()); // decoration cannot clip + } + if (inactive != 1.0 && isInactive(w)) data.setTranslucent(); - if(( moveresize != 1.0 && ( w->isUserMove() || w->isUserResize())) - || ( dialogs != 1.0 && w->isDialog())) - { + if ((moveresize != 1.0 && (w->isUserMove() || w->isUserResize())) + || (dialogs != 1.0 && w->isDialog())) { data.setTranslucent(); - } - if( ( dropdownmenus != 1.0 && w->isDropdownMenu() ) - || ( popupmenus != 1.0 && w->isPopupMenu() ) - || ( tornoffmenus != 1.0 && w->isMenu() ) - || ( comboboxpopups != 1.0 && w->isComboBox() ) ) - { + } + if ((dropdownmenus != 1.0 && w->isDropdownMenu()) + || (popupmenus != 1.0 && w->isPopupMenu()) + || (tornoffmenus != 1.0 && w->isMenu()) + || (comboboxpopups != 1.0 && w->isComboBox())) { data.setTranslucent(); - } - - effects->prePaintWindow( w, data, time ); } -void TranslucencyEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) - { + effects->prePaintWindow(w, data, time); +} + +void TranslucencyEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) +{ // We keep track of the windows that was last active so we know // which one to fade out and which ones to paint as fully inactive - if ( w == active && w != current ) - { + if (w == active && w != current) { previous = current; current = w; - } + } - if ( w->isDesktop() || w->isDock() ) - { - effects->paintWindow( w, mask, region, data ); + if (w->isDesktop() || w->isDock()) { + effects->paintWindow(w, mask, region, data); return; - } + } // Handling active and inactive windows - if( inactive != 1.0 && isInactive(w) ) - { + if (inactive != 1.0 && isInactive(w)) { data.opacity *= inactive; - if ( w == previous ) - { + if (w == previous) { data.opacity *= (inactive + ((1.0 - inactive) * (1.0 - activeinactive_timeline.value()))); - if ( activeinactive_timeline.value() < 1.0 ) + if (activeinactive_timeline.value() < 1.0) w->addRepaintFull(); - } } - else - { + } else { // Fading in - if ( !isInactive(w) && !w->isDesktop() ) - { + if (!isInactive(w) && !w->isDesktop()) { data.opacity *= (inactive + ((1.0 - inactive) * activeinactive_timeline.value())); - if ( activeinactive_timeline.value() < 1.0 ) + if (activeinactive_timeline.value() < 1.0) w->addRepaintFull(); - } + } // decoration and dialogs - if( decoration != 1.0 && w->hasDecoration()) + if (decoration != 1.0 && w->hasDecoration()) data.decoration_opacity *= decoration; - if( dialogs != 1.0 && w->isDialog()) + if (dialogs != 1.0 && w->isDialog()) data.opacity *= dialogs; // Handling moving and resizing - if( moveresize != 1.0 && !w->isDesktop() && !w->isDock()) - { + if (moveresize != 1.0 && !w->isDesktop() && !w->isDock()) { double progress = moveresize_timeline.value(); - if ( w->isUserMove() || w->isUserResize() ) - { // Fading to translucent - data.opacity *= (moveresize + ((1.0 - moveresize) * ( 1.0 - progress ))); - if (progress < 1.0 && progress > 0.0) - { + if (w->isUserMove() || w->isUserResize()) { + // Fading to translucent + data.opacity *= (moveresize + ((1.0 - moveresize) * (1.0 - progress))); + if (progress < 1.0 && progress > 0.0) { w->addRepaintFull(); - if ( fadeout != w ) + if (fadeout != w) fadeout = w; - } } - else - { // Fading back to more opaque - if( w == fadeout && !w->isUserMove() && !w->isUserResize() ) - { + } else { + // Fading back to more opaque + if (w == fadeout && !w->isUserMove() && !w->isUserResize()) { data.opacity *= (moveresize + ((1.0 - moveresize) * (progress))); - if ( progress == 1.0 || progress == 0.0) + if (progress == 1.0 || progress == 0.0) fadeout = NULL; else w->addRepaintFull(); - } } } + } // Menus and combos - if( dropdownmenus != 1.0 && w->isDropdownMenu() ) + if (dropdownmenus != 1.0 && w->isDropdownMenu()) data.opacity *= dropdownmenus; - if( popupmenus != 1.0 && w->isPopupMenu() ) + if (popupmenus != 1.0 && w->isPopupMenu()) data.opacity *= popupmenus; - if( tornoffmenus != 1.0 && w->isMenu() ) + if (tornoffmenus != 1.0 && w->isMenu()) data.opacity *= tornoffmenus; - if( comboboxpopups != 1.0 && w->isComboBox() ) + if (comboboxpopups != 1.0 && w->isComboBox()) data.opacity *= comboboxpopups; - } - effects->paintWindow( w, mask, region, data ); } + effects->paintWindow(w, mask, region, data); +} -bool TranslucencyEffect::isInactive( const EffectWindow* w ) const - { - if( active == w || w->isDock() || !w->isManaged() ) +bool TranslucencyEffect::isInactive(const EffectWindow* w) const +{ + if (active == w || w->isDock() || !w->isManaged()) return false; - if( NULL != active && NULL != active->group() ) - if (active->group() == w->group() ) + if (NULL != active && NULL != active->group()) + if (active->group() == w->group()) return false; - if( !w->isNormalWindow() && !w->isDialog() && !w->isDock() ) + if (!w->isNormalWindow() && !w->isDialog() && !w->isDock()) return false; return true; - } +} -void TranslucencyEffect::windowUserMovedResized( EffectWindow* w, bool first, bool last ) - { - if( moveresize != 1.0 && ( first || last )) - { +void TranslucencyEffect::windowUserMovedResized(EffectWindow* w, bool first, bool last) +{ + if (moveresize != 1.0 && (first || last)) { moveresize_timeline.setProgress(0.0); w->addRepaintFull(); - } } +} -void TranslucencyEffect::windowActivated( EffectWindow* w ) - { - if( inactive != 1.0 ) - { +void TranslucencyEffect::windowActivated(EffectWindow* w) +{ + if (inactive != 1.0) { activeinactive_timeline.setProgress(0.0); - if( NULL != active && active != w ) - { - if( ( NULL == w || w->group() != active->group() ) && - NULL != active->group() ) - { + if (NULL != active && active != w) { + if ((NULL == w || w->group() != active->group()) && + NULL != active->group()) { // Active group has changed. so repaint old group - foreach( EffectWindow *tmp, active->group()->members() ) - tmp->addRepaintFull(); - } - else + foreach (EffectWindow * tmp, active->group()->members()) + tmp->addRepaintFull(); + } else active->addRepaintFull(); - } - - if( NULL != w ) - { - if (NULL != w->group() ) - { - // Repaint windows in new group - foreach( EffectWindow *tmp, w->group()->members() ) - tmp->addRepaintFull(); - } - else - w->addRepaintFull(); - } } - active = w; + + if (NULL != w) { + if (NULL != w->group()) { + // Repaint windows in new group + foreach (EffectWindow * tmp, w->group()->members()) + tmp->addRepaintFull(); + } else + w->addRepaintFull(); + } } + active = w; +} } // namespace diff --git a/effects/translucency/translucency.h b/effects/translucency/translucency.h index cb17044e6..219679452 100644 --- a/effects/translucency/translucency.h +++ b/effects/translucency/translucency.h @@ -28,36 +28,36 @@ namespace KWin class TranslucencyEffect : public Effect - { - public: - TranslucencyEffect(); - virtual void reconfigure( ReconfigureFlags ); - virtual void windowUserMovedResized( EffectWindow* c, bool first, bool last ); - virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); - virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); - virtual void windowActivated( EffectWindow* w ); - private: - bool isInactive( const EffectWindow *w ) const; - bool individualmenuconfig; +{ +public: + TranslucencyEffect(); + virtual void reconfigure(ReconfigureFlags); + virtual void windowUserMovedResized(EffectWindow* c, bool first, bool last); + virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); + virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); + virtual void windowActivated(EffectWindow* w); +private: + bool isInactive(const EffectWindow *w) const; + bool individualmenuconfig; - double decoration; - double moveresize; - double dialogs; - double inactive; - double comboboxpopups; - double menus; - double dropdownmenus; - double popupmenus; - double tornoffmenus; + double decoration; + double moveresize; + double dialogs; + double inactive; + double comboboxpopups; + double menus; + double dropdownmenus; + double popupmenus; + double tornoffmenus; - EffectWindow* fadeout; - EffectWindow* current; - EffectWindow* previous; - EffectWindow* active; + EffectWindow* fadeout; + EffectWindow* current; + EffectWindow* previous; + EffectWindow* active; - TimeLine moveresize_timeline; - TimeLine activeinactive_timeline; - }; + TimeLine moveresize_timeline; + TimeLine activeinactive_timeline; +}; } // namespace diff --git a/effects/translucency/translucency_config.cpp b/effects/translucency/translucency_config.cpp index 2d1fc9ea4..ba711d7e5 100644 --- a/effects/translucency/translucency_config.cpp +++ b/effects/translucency/translucency_config.cpp @@ -35,13 +35,13 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY TranslucencyEffectConfigForm::TranslucencyEffectConfigForm(QWidget* parent) : QWidget(parent) - { +{ setupUi(this); - } +} TranslucencyEffectConfig::TranslucencyEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new TranslucencyEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(m_ui); @@ -59,66 +59,66 @@ TranslucencyEffectConfig::TranslucencyEffectConfig(QWidget* parent, const QVaria connect(m_ui->duration, SIGNAL(valueChanged(int)), this, SLOT(changed())); load(); - } +} void TranslucencyEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("Translucency"); - m_ui->decorations->setValue( (int)( conf.readEntry( "Decoration", 1.0 ) * 100 ) ); - m_ui->moveresize->setValue( (int)( conf.readEntry( "MoveResize", 0.8 ) * 100 ) ); - m_ui->dialogs->setValue( (int)( conf.readEntry( "Dialogs", 1.0 ) * 100 ) ); - m_ui->inactive->setValue( (int)( conf.readEntry( "Inactive", 1.0 ) * 100 ) ); - m_ui->comboboxpopup->setValue( (int)( conf.readEntry( "ComboboxPopups", 1.0) * 100 ) ); - m_ui->menus->setValue( (int)( conf.readEntry( "Menus", 1.0) * 100 ) ); - m_ui->individualmenuconfig->setChecked( ( conf.readEntry( "IndividualMenuConfig", false ) ) ); - m_ui->dropdownmenus->setValue( (int)( conf.readEntry( "DropdownMenus", 1.0) * 100 ) ); - m_ui->popupmenus->setValue( (int)( conf.readEntry( "PopupMenus", 1.0) * 100 ) ); - m_ui->tornoffmenus->setValue( (int)( conf.readEntry( "TornOffMenus", 1.0) * 100 ) ); - m_ui->duration->setValue( conf.readEntry( "Duration", 0) ); + m_ui->decorations->setValue((int)(conf.readEntry("Decoration", 1.0) * 100)); + m_ui->moveresize->setValue((int)(conf.readEntry("MoveResize", 0.8) * 100)); + m_ui->dialogs->setValue((int)(conf.readEntry("Dialogs", 1.0) * 100)); + m_ui->inactive->setValue((int)(conf.readEntry("Inactive", 1.0) * 100)); + m_ui->comboboxpopup->setValue((int)(conf.readEntry("ComboboxPopups", 1.0) * 100)); + m_ui->menus->setValue((int)(conf.readEntry("Menus", 1.0) * 100)); + m_ui->individualmenuconfig->setChecked((conf.readEntry("IndividualMenuConfig", false))); + m_ui->dropdownmenus->setValue((int)(conf.readEntry("DropdownMenus", 1.0) * 100)); + m_ui->popupmenus->setValue((int)(conf.readEntry("PopupMenus", 1.0) * 100)); + m_ui->tornoffmenus->setValue((int)(conf.readEntry("TornOffMenus", 1.0) * 100)); + m_ui->duration->setValue(conf.readEntry("Duration", 0)); m_ui->duration->setSuffix(ki18np(" millisecond", " milliseconds")); emit changed(false); - } +} void TranslucencyEffectConfig::save() - { +{ KCModule::save(); KConfigGroup conf = EffectsHandler::effectConfig("Translucency"); - conf.writeEntry( "Decoration", m_ui->decorations->value() / 100.0 ); - conf.writeEntry( "MoveResize", m_ui->moveresize->value() / 100.0 ); - conf.writeEntry( "Dialogs", m_ui->dialogs->value() / 100.0 ); - conf.writeEntry( "Inactive", m_ui->inactive->value() / 100.0 ); - conf.writeEntry( "ComboboxPopups", m_ui->comboboxpopup->value() / 100.0 ); - conf.writeEntry( "Menus", m_ui->menus->value() / 100.0 ); - conf.writeEntry( "IndividualMenuConfig", m_ui->individualmenuconfig->isChecked() ); - conf.writeEntry( "DropdownMenus", m_ui->dropdownmenus->value() / 100.0 ); - conf.writeEntry( "PopupMenus", m_ui->popupmenus->value() / 100.0 ); - conf.writeEntry( "TornOffMenus", m_ui->tornoffmenus->value() / 100.0 ); - conf.writeEntry( "Duration", m_ui->duration->value() ); + conf.writeEntry("Decoration", m_ui->decorations->value() / 100.0); + conf.writeEntry("MoveResize", m_ui->moveresize->value() / 100.0); + conf.writeEntry("Dialogs", m_ui->dialogs->value() / 100.0); + conf.writeEntry("Inactive", m_ui->inactive->value() / 100.0); + conf.writeEntry("ComboboxPopups", m_ui->comboboxpopup->value() / 100.0); + conf.writeEntry("Menus", m_ui->menus->value() / 100.0); + conf.writeEntry("IndividualMenuConfig", m_ui->individualmenuconfig->isChecked()); + conf.writeEntry("DropdownMenus", m_ui->dropdownmenus->value() / 100.0); + conf.writeEntry("PopupMenus", m_ui->popupmenus->value() / 100.0); + conf.writeEntry("TornOffMenus", m_ui->tornoffmenus->value() / 100.0); + conf.writeEntry("Duration", m_ui->duration->value()); conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "translucency" ); - } + EffectsHandler::sendReloadMessage("translucency"); +} void TranslucencyEffectConfig::defaults() - { - m_ui->decorations->setValue( 100 ); - m_ui->moveresize->setValue( 80 ); - m_ui->dialogs->setValue( 100 ); - m_ui->inactive->setValue( 100 ); - m_ui->comboboxpopup->setValue( 100 ); - m_ui->menus->setValue( 100 ); - m_ui->individualmenuconfig->setChecked( false ); - m_ui->dropdownmenus->setValue( 100 ); - m_ui->popupmenus->setValue( 100 ); - m_ui->tornoffmenus->setValue( 100 ); - m_ui->duration->setValue( 0 ); +{ + m_ui->decorations->setValue(100); + m_ui->moveresize->setValue(80); + m_ui->dialogs->setValue(100); + m_ui->inactive->setValue(100); + m_ui->comboboxpopup->setValue(100); + m_ui->menus->setValue(100); + m_ui->individualmenuconfig->setChecked(false); + m_ui->dropdownmenus->setValue(100); + m_ui->popupmenus->setValue(100); + m_ui->tornoffmenus->setValue(100); + m_ui->duration->setValue(0); emit changed(true); - } +} } // namespace diff --git a/effects/translucency/translucency_config.h b/effects/translucency/translucency_config.h index bb802d708..a43d3e7ed 100644 --- a/effects/translucency/translucency_config.h +++ b/effects/translucency/translucency_config.h @@ -31,23 +31,23 @@ namespace KWin class TranslucencyEffectConfigForm : public QWidget, public Ui::TranslucencyEffectConfigForm { Q_OBJECT - public: - explicit TranslucencyEffectConfigForm(QWidget* parent); +public: + explicit TranslucencyEffectConfigForm(QWidget* parent); }; class TranslucencyEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit TranslucencyEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); +public: + explicit TranslucencyEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual void save(); - virtual void load(); - virtual void defaults(); + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - TranslucencyEffectConfigForm* m_ui; - }; +private: + TranslucencyEffectConfigForm* m_ui; +}; } // namespace diff --git a/effects/windowgeometry/windowgeometry.cpp b/effects/windowgeometry/windowgeometry.cpp index 1c7316c38..b125d01e9 100644 --- a/effects/windowgeometry/windowgeometry.cpp +++ b/effects/windowgeometry/windowgeometry.cpp @@ -28,109 +28,104 @@ along with this program. If not, see . using namespace KWin; -KWIN_EFFECT( windowgeometry, WindowGeometry ) +KWIN_EFFECT(windowgeometry, WindowGeometry) WindowGeometry::WindowGeometry() - { +{ iAmActivated = true; iAmActive = false; myResizeWindow = 0L; myResizeString = i18nc("Window geometry display, %1 and %2 are the new size," - " %3 and %4 are pixel increments - avoid reformatting or suffixes like 'px'", + " %3 and %4 are pixel increments - avoid reformatting or suffixes like 'px'", "Width: %1 (%3)\nHeight: %2 (%4)"); myCoordString[0] = i18nc("Window geometry display, %1 and %2 are the cartesian x and y coordinates" - " - avoid reformatting or suffixes like 'px'", + " - avoid reformatting or suffixes like 'px'", "X: %1\nY: %2"); myCoordString[1] = i18nc("Window geometry display, %1 and %2 are the cartesian x and y coordinates," - " %3 and %4 are the resp. increments - avoid reformatting or suffixes like 'px'", + " %3 and %4 are the resp. increments - avoid reformatting or suffixes like 'px'", "X: %1 (%3)\nY: %2 (%4)"); - reconfigure( ReconfigureAll ); + reconfigure(ReconfigureAll); QFont fnt; fnt.setBold(true); fnt.setPointSize(12); - for ( int i = 0; i < 3; ++i ) - { - myMeasure[i] = effects->effectFrame( EffectFrameUnstyled, false ); - myMeasure[i]->setFont( fnt ); - } - myMeasure[0]->setAlignment( Qt::AlignLeft|Qt::AlignTop ); - myMeasure[1]->setAlignment( Qt::AlignCenter ); - myMeasure[2]->setAlignment( Qt::AlignRight|Qt::AlignBottom ); - - KActionCollection* actionCollection = new KActionCollection( this ); - KAction* a = static_cast< KAction* >( actionCollection->addAction( "WindowGeometry" )); - a->setText( i18n("Toggle window geometry display (effect only)" )); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_F11 )); - connect( a, SIGNAL( triggered(bool) ), this, SLOT( toggle() ) ); + for (int i = 0; i < 3; ++i) { + myMeasure[i] = effects->effectFrame(EffectFrameUnstyled, false); + myMeasure[i]->setFont(fnt); } + myMeasure[0]->setAlignment(Qt::AlignLeft | Qt::AlignTop); + myMeasure[1]->setAlignment(Qt::AlignCenter); + myMeasure[2]->setAlignment(Qt::AlignRight | Qt::AlignBottom); + + KActionCollection* actionCollection = new KActionCollection(this); + KAction* a = static_cast< KAction* >(actionCollection->addAction("WindowGeometry")); + a->setText(i18n("Toggle window geometry display (effect only)")); + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_F11)); + connect(a, SIGNAL(triggered(bool)), this, SLOT(toggle())); +} WindowGeometry::~WindowGeometry() - { - for ( int i = 0; i < 3; ++i ) +{ + for (int i = 0; i < 3; ++i) delete myMeasure[i]; - } +} -void WindowGeometry::reconfigure( ReconfigureFlags ) - { - KConfigGroup conf = effects->effectConfig( "WindowGeometry" ); - iHandleMoves = conf.readEntry( "Move", true ); - iHandleResizes = conf.readEntry( "Resize", true ); - } +void WindowGeometry::reconfigure(ReconfigureFlags) +{ + KConfigGroup conf = effects->effectConfig("WindowGeometry"); + iHandleMoves = conf.readEntry("Move", true); + iHandleResizes = conf.readEntry("Resize", true); +} void WindowGeometry::paintScreen(int mask, QRegion region, ScreenPaintData &data) - { - effects->paintScreen( mask, region, data ); - if ( iAmActivated && iAmActive ) - { - for ( int i = 0; i < 3; ++i ) +{ + effects->paintScreen(mask, region, data); + if (iAmActivated && iAmActive) { + for (int i = 0; i < 3; ++i) myMeasure[i]->render(infiniteRegion(), 1.0, .66); - } } +} void WindowGeometry::toggle() - { +{ iAmActivated = !iAmActivated; - } +} -void WindowGeometry::windowUserMovedResized( EffectWindow* w, bool first, bool last ) - { - if (first && last) // "maximized" +void WindowGeometry::windowUserMovedResized(EffectWindow* w, bool first, bool last) +{ + if (first && last) // "maximized" return; - if ( first ) - { - if ( !iAmActivated ) + if (first) { + if (!iAmActivated) return; - if ( w->isUserResize() && !iHandleResizes ) + if (w->isUserResize() && !iHandleResizes) return; - if ( w->isUserMove() && !iHandleMoves) + if (w->isUserMove() && !iHandleMoves) return; - + iAmActive = true; myResizeWindow = w; myOriginalGeometry = w->geometry(); myCurrentGeometry = w->geometry(); - effects->addRepaint( myCurrentGeometry.adjusted(-20, -20, 20, 20) ); - } + effects->addRepaint(myCurrentGeometry.adjusted(-20, -20, 20, 20)); + } - if ( iAmActive && w == myResizeWindow && last ) - { + if (iAmActive && w == myResizeWindow && last) { iAmActive = false; myResizeWindow = 0L; - effects->addRepaint( myCurrentGeometry.adjusted(-20, -20, 20, 20) ); - } + effects->addRepaint(myCurrentGeometry.adjusted(-20, -20, 20, 20)); + } } static inline QString number(int n) - { - if ( n >= 0 ) +{ + if (n >= 0) return '+' + QString::number(n); return QString::number(n); // "-" is auto-applied - } - +} -void WindowGeometry::windowMoveResizeGeometryUpdate( EffectWindow* w, const QRect& geometry ) + +void WindowGeometry::windowMoveResizeGeometryUpdate(EffectWindow* w, const QRect& geometry) { - if ( iAmActivated && iAmActive && w == myResizeWindow ) - { + if (iAmActivated && iAmActive && w == myResizeWindow) { myCurrentGeometry = geometry; const QRect &r = geometry; const QRect &r2 = myOriginalGeometry; @@ -138,42 +133,40 @@ void WindowGeometry::windowMoveResizeGeometryUpdate( EffectWindow* w, const QRec // sufficient for moves, resizes calculated otherwise int dx = r.x() - r2.x(); int dy = r.y() - r2.y(); - + // upper left ---------------------- - if ( w->isUserResize() ) - myMeasure[0]->setText( myCoordString[1].arg( r.x() ).arg( r.y() ).arg( number(dx) ).arg( number(dy) ) ); + if (w->isUserResize()) + myMeasure[0]->setText(myCoordString[1].arg(r.x()).arg(r.y()).arg(number(dx)).arg(number(dy))); else - myMeasure[0]->setText( myCoordString[0].arg( r.x() ).arg( r.y() ) ); - myMeasure[0]->setPosition( geometry.topLeft() ); - + myMeasure[0]->setText(myCoordString[0].arg(r.x()).arg(r.y())); + myMeasure[0]->setPosition(geometry.topLeft()); + // center ---------------------- - if ( w->isUserResize() ) - { + if (w->isUserResize()) { // calc width for center element, otherwise the current dx/dx remains right dx = r.width() - r2.width(); dy = r.height() - r2.height(); - + // TODO: i hate this. anyone got a nice idea to invoke the stringbuilder or otherwise avoid // dogslow QString::arg() system here? - myMeasure[1]->setText( myResizeString.arg( r.width() ).arg( r.height() ).arg( number(dx) ).arg( number(dy) ) ); - + myMeasure[1]->setText(myResizeString.arg(r.width()).arg(r.height()).arg(number(dx)).arg(number(dy))); + // calc width for bottomright element, superfluous otherwise dx = r.right() - r2.right(); dy = r.bottom() - r2.bottom(); - } - else - myMeasure[1]->setText( myCoordString[0].arg( number(dx) ).arg( number(dy) ) ); + } else + myMeasure[1]->setText(myCoordString[0].arg(number(dx)).arg(number(dy))); - myMeasure[1]->setPosition( geometry.center() ); + myMeasure[1]->setPosition(geometry.center()); // lower right ---------------------- - if ( w->isUserResize() ) - myMeasure[2]->setText( myCoordString[1].arg( r.right() ).arg( r.bottom() ).arg( number(dx) ).arg( number(dy) ) ); + if (w->isUserResize()) + myMeasure[2]->setText(myCoordString[1].arg(r.right()).arg(r.bottom()).arg(number(dx)).arg(number(dy))); else - myMeasure[2]->setText( myCoordString[0].arg( r.right() ).arg( r.bottom() ) ); - myMeasure[2]->setPosition( geometry.bottomRight() ); + myMeasure[2]->setText(myCoordString[0].arg(r.right()).arg(r.bottom())); + myMeasure[2]->setPosition(geometry.bottomRight()); - effects->addRepaint( geometry.adjusted(-20, -20, 20, 20) ); - } + effects->addRepaint(geometry.adjusted(-20, -20, 20, 20)); } +} diff --git a/effects/windowgeometry/windowgeometry.h b/effects/windowgeometry/windowgeometry.h index f3556f4f0..985420208 100644 --- a/effects/windowgeometry/windowgeometry.h +++ b/effects/windowgeometry/windowgeometry.h @@ -33,11 +33,13 @@ public: WindowGeometry(); ~WindowGeometry(); - inline bool provides( Effect::Feature ef ) { return ef == Effect::GeometryTip; } - void reconfigure( ReconfigureFlags ); + inline bool provides(Effect::Feature ef) { + return ef == Effect::GeometryTip; + } + void reconfigure(ReconfigureFlags); void paintScreen(int mask, QRegion region, ScreenPaintData &data); - void windowUserMovedResized( EffectWindow* w, bool first, bool last ); - void windowMoveResizeGeometryUpdate( EffectWindow* c, const QRect& geometry ); + void windowUserMovedResized(EffectWindow* w, bool first, bool last); + void windowMoveResizeGeometryUpdate(EffectWindow* c, const QRect& geometry); private slots: void toggle(); diff --git a/effects/windowgeometry/windowgeometry_config.cpp b/effects/windowgeometry/windowgeometry_config.cpp index 50c9c33f6..be48b1c25 100644 --- a/effects/windowgeometry/windowgeometry_config.cpp +++ b/effects/windowgeometry/windowgeometry_config.cpp @@ -30,62 +30,62 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY WindowGeometryConfigForm::WindowGeometryConfigForm(QWidget* parent) : QWidget(parent) - { +{ setupUi(this); - } +} WindowGeometryConfig::WindowGeometryConfig(QWidget* parent, const QVariantList& args) : KCModule(KWin::EffectFactory::componentData(), parent, args) - { +{ QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(myUi = new WindowGeometryConfigForm(this)); // Shortcut config. The shortcut belongs to the component "kwin"! - myActionCollection = new KActionCollection( this, KComponentData("kwin") ); - KAction* a = (KAction*)myActionCollection->addAction( "WindowGeometry" ); - a->setText( i18n("Toggle KWin composited geometry display" )); + myActionCollection = new KActionCollection(this, KComponentData("kwin")); + KAction* a = (KAction*)myActionCollection->addAction("WindowGeometry"); + a->setText(i18n("Toggle KWin composited geometry display")); a->setProperty("isConfigurationAction", true); - a->setGlobalShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_F11 )); - + a->setGlobalShortcut(KShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_F11)); + myUi->shortcuts->addCollection(myActionCollection); connect(myUi->shortcuts, SIGNAL(keyChange()), this, SLOT(changed())); connect(myUi->handleMove, SIGNAL(toggled(bool)), this, SLOT(changed())); connect(myUi->handleResize, SIGNAL(toggled(bool)), this, SLOT(changed())); - } +} WindowGeometryConfig::~WindowGeometryConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts myUi->shortcuts->undoChanges(); - } +} void WindowGeometryConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("WindowGeometry"); - myUi->handleMove->setChecked( conf.readEntry("Move", true) ); - myUi->handleResize->setChecked( conf.readEntry("Resize", true) ); + myUi->handleMove->setChecked(conf.readEntry("Move", true)); + myUi->handleResize->setChecked(conf.readEntry("Resize", true)); emit changed(false); - } +} void WindowGeometryConfig::save() - { +{ KConfigGroup conf = EffectsHandler::effectConfig("WindowGeometry"); conf.writeEntry("Move", myUi->handleMove->isChecked()); conf.writeEntry("Resize", myUi->handleResize->isChecked()); myUi->shortcuts->save(); // undo() will restore to this state from now on conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "windowgeometry" ); - } + EffectsHandler::sendReloadMessage("windowgeometry"); +} void WindowGeometryConfig::defaults() - { - myUi->handleMove->setChecked( true ); - myUi->handleResize->setChecked( true ); +{ + myUi->handleMove->setChecked(true); + myUi->handleResize->setChecked(true); myUi->shortcuts->allDefault(); emit changed(true); - } +} } //namespace #include "windowgeometry_config.moc" diff --git a/effects/wobblywindows/wobblywindows.cpp b/effects/wobblywindows/wobblywindows.cpp index 6730ff431..badd18ad0 100644 --- a/effects/wobblywindows/wobblywindows.cpp +++ b/effects/wobblywindows/wobblywindows.cpp @@ -52,8 +52,7 @@ static const qreal MINACCELERATION = 0.0; static const qreal MAXACCELERATION = 1000.0; static const qreal STOPACCELERATION = 5.0; -struct ParameterSet -{ +struct ParameterSet { qreal stiffness; qreal drag; qreal move_factor; @@ -73,8 +72,7 @@ struct ParameterSet bool closeEffectEnabled; }; -static const ParameterSet set_0 = -{ +static const ParameterSet set_0 = { 0.15, 0.80, 0.10, @@ -91,8 +89,7 @@ static const ParameterSet set_0 = false }; -static const ParameterSet set_1 = -{ +static const ParameterSet set_1 = { 0.10, 0.85, 0.10, @@ -109,8 +106,7 @@ static const ParameterSet set_1 = false }; -static const ParameterSet set_2 = -{ +static const ParameterSet set_2 = { 0.06, 0.90, 0.10, @@ -127,8 +123,7 @@ static const ParameterSet set_2 = false }; -static const ParameterSet set_3 = -{ +static const ParameterSet set_3 = { 0.03, 0.92, 0.20, @@ -145,8 +140,7 @@ static const ParameterSet set_3 = false }; -static const ParameterSet set_4 = -{ +static const ParameterSet set_4 = { 0.01, 0.97, 0.25, @@ -170,49 +164,42 @@ KWIN_EFFECT_SUPPORTED(wobblywindows, WobblyWindowsEffect::supported()) WobblyWindowsEffect::WobblyWindowsEffect() { - reconfigure( ReconfigureAll ); + reconfigure(ReconfigureAll); } WobblyWindowsEffect::~WobblyWindowsEffect() { - if (!windows.empty()) - { + if (!windows.empty()) { // we should be empty at this point... // emit a warning and clean the list. kDebug(1212) << "Windows list not empty. Left items : " << windows.count(); QHash< const EffectWindow*, WindowWobblyInfos >::iterator i; - for (i = windows.begin(); i != windows.end(); ++i) - { + for (i = windows.begin(); i != windows.end(); ++i) { freeWobblyInfo(i.value()); } } } -void WobblyWindowsEffect::reconfigure( ReconfigureFlags ) +void WobblyWindowsEffect::reconfigure(ReconfigureFlags) { KConfigGroup conf = effects->effectConfig("Wobbly"); QString settingsMode = conf.readEntry("Settings", "Auto"); - if (settingsMode != "Custom") - { + if (settingsMode != "Custom") { unsigned int wobblynessLevel = conf.readEntry("WobblynessLevel", 0); - if (wobblynessLevel > 4) - { + if (wobblynessLevel > 4) { kDebug(1212) << "Wrong value for \"WobblynessLevel\" : " << wobblynessLevel; wobblynessLevel = 4; } setParameterSet(pset[wobblynessLevel]); - - if (conf.readEntry("AdvancedMode", false)) - { + + if (conf.readEntry("AdvancedMode", false)) { m_stiffness = conf.readEntry("Stiffness", STIFFNESS * 100.0) / 100.0; m_drag = conf.readEntry("Drag", DRAG * 100.0) / 100.0; m_move_factor = conf.readEntry("MoveFactor", MOVEFACTOR * 100.0) / 100.0; } - } - else // Custom method, read all values from config file. - { + } else { // Custom method, read all values from config file. m_stiffness = conf.readEntry("Stiffness", STIFFNESS); m_drag = conf.readEntry("Drag", DRAG); m_move_factor = conf.readEntry("MoveFactor", MOVEFACTOR); @@ -238,18 +225,18 @@ void WobblyWindowsEffect::reconfigure( ReconfigureFlags ) #if defined VERBOSE_MODE kDebug(1212) << "Parameters :\n" << - "move : " << m_moveEffectEnabled << ", open : " << m_openEffectEnabled << ", close : " << m_closeEffectEnabled << "\n" - "grid(" << m_stiffness << ", " << m_drag << ", " << m_move_factor << ")\n" << - "velocity(" << m_minVelocity << ", " << m_maxVelocity << ", " << m_stopVelocity << ")\n" << - "acceleration(" << m_minAcceleration << ", " << m_maxAcceleration << ", " << m_stopAcceleration << ")\n" << - "tesselation(" << m_xTesselation << ", " << m_yTesselation << ")"; + "move : " << m_moveEffectEnabled << ", open : " << m_openEffectEnabled << ", close : " << m_closeEffectEnabled << "\n" + "grid(" << m_stiffness << ", " << m_drag << ", " << m_move_factor << ")\n" << + "velocity(" << m_minVelocity << ", " << m_maxVelocity << ", " << m_stopVelocity << ")\n" << + "acceleration(" << m_minAcceleration << ", " << m_maxAcceleration << ", " << m_stopAcceleration << ")\n" << + "tesselation(" << m_xTesselation << ", " << m_yTesselation << ")"; #endif } bool WobblyWindowsEffect::supported() - { +{ return effects->compositingType() == OpenGLCompositing; - } +} void WobblyWindowsEffect::setParameterSet(const ParameterSet& pset) { @@ -297,8 +284,7 @@ void WobblyWindowsEffect::prePaintScreen(ScreenPrePaintData& data, int time) // We need to mark the screen windows as transformed. Otherwise the whole // screen won't be repainted, resulting in artefacts. // Could we just set a subset of the screen to be repainted ? - if (windows.count() != 0) - { + if (windows.count() != 0) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS; m_updateRegion = QRegion(); @@ -309,23 +295,20 @@ void WobblyWindowsEffect::prePaintScreen(ScreenPrePaintData& data, int time) const qreal maxTime = 10.0; void WobblyWindowsEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { - if (windows.contains(w)) - { + if (windows.contains(w)) { data.setTransformed(); data.quads = data.quads.makeRegularGrid(m_xTesselation, m_yTesselation); bool stop = false; qreal updateTime = time; - while (!stop && (updateTime > maxTime)) - { + while (!stop && (updateTime > maxTime)) { #if defined VERBOSE_MODE kDebug(1212) << "loop time " << updateTime << " / " << time; #endif stop = !updateWindowWobblyDatas(w, maxTime); updateTime -= maxTime; } - if (!stop && updateTime > 0) - { + if (!stop && updateTime > 0) { updateWindowWobblyDatas(w, updateTime); } } @@ -335,8 +318,7 @@ void WobblyWindowsEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& da void WobblyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { - if(windows.contains(w)) - { + if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; int tx = w->geometry().x(); int ty = w->geometry().y(); @@ -344,10 +326,8 @@ void WobblyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, double top = 0.0; double right = w->width(); double bottom = w->height(); - for (int i = 0; i < data.quads.count(); ++i) - { - for(int j = 0; j < 4; ++j) - { + for (int i = 0; i < data.quads.count(); ++i) { + for (int j = 0; j < 4; ++j) { WindowVertex& v = data.quads[i][j]; Pair oldPos = {tx + v.x(), ty + v.y()}; Pair newPos = computeBezierPoint(wwi, oldPos); @@ -359,7 +339,7 @@ void WobblyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, bottom = qMax(bottom, data.quads[i].bottom()); } m_updateRegion = m_updateRegion.united(QRect(w->x() + left, w->y() + top, - right - left, bottom-top)); + right - left, bottom - top)); } // Call the next effect. @@ -368,8 +348,7 @@ void WobblyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, void WobblyWindowsEffect::postPaintScreen() { - if (!windows.isEmpty()) - { + if (!windows.isEmpty()) { effects->addRepaint(m_updateRegion); } @@ -382,44 +361,36 @@ void WobblyWindowsEffect::windowUserMovedResized(EffectWindow* w, bool first, bo if (!m_moveEffectEnabled || w->isSpecialWindow()) return; - if (first) - { - if(last && m_moveWobble && m_resizeWobble) - { + if (first) { + if (last && m_moveWobble && m_resizeWobble) { // both first and last - a step change like Maximize stepMovedResized(w); - } - else if ((w->isUserMove() && m_moveWobble) || (w->isUserResize() && m_resizeWobble)) - { + } else if ((w->isUserMove() && m_moveWobble) || (w->isUserResize() && m_resizeWobble)) { startMovedResized(w); } } - if (last) - { - if (windows.contains(w)) - { + if (last) { + if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; wwi.status = Free; } } - if (windows.contains(w)) - { + if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; QRect rect = w->geometry(); - if(rect.y()!=wwi.resize_original_rect.y()) wwi.can_wobble_top = true; - if(rect.x()!=wwi.resize_original_rect.x()) wwi.can_wobble_left = true; - if(rect.right()!=wwi.resize_original_rect.right()) wwi.can_wobble_right = true; - if(rect.bottom()!=wwi.resize_original_rect.bottom()) wwi.can_wobble_bottom = true; + if (rect.y() != wwi.resize_original_rect.y()) wwi.can_wobble_top = true; + if (rect.x() != wwi.resize_original_rect.x()) wwi.can_wobble_left = true; + if (rect.right() != wwi.resize_original_rect.right()) wwi.can_wobble_right = true; + if (rect.bottom() != wwi.resize_original_rect.bottom()) wwi.can_wobble_bottom = true; } } void WobblyWindowsEffect::startMovedResized(EffectWindow* w) { - if (!windows.contains(w)) - { + if (!windows.contains(w)) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); windows[w] = new_wwi; @@ -429,20 +400,17 @@ void WobblyWindowsEffect::startMovedResized(EffectWindow* w) wwi.status = Moving; const QRectF& rect = w->geometry(); - qreal x_increment = rect.width() / (wwi.width-1.0); - qreal y_increment = rect.height() / (wwi.height-1.0); + qreal x_increment = rect.width() / (wwi.width - 1.0); + qreal y_increment = rect.height() / (wwi.height - 1.0); Pair picked = {cursorPos().x(), cursorPos().y()}; int indx = (picked.x - rect.x()) / x_increment + 0.5; int indy = (picked.y - rect.y()) / y_increment + 0.5; - int pickedPointIndex = indy*wwi.width + indx; - if (pickedPointIndex < 0) - { + int pickedPointIndex = indy * wwi.width + indx; + if (pickedPointIndex < 0) { kDebug(1212) << "Picked index == " << pickedPointIndex << " with (" << cursorPos().x() << "," << cursorPos().y() << ")"; pickedPointIndex = 0; - } - else if (static_cast(pickedPointIndex) > wwi.count - 1) - { + } else if (static_cast(pickedPointIndex) > wwi.count - 1) { kDebug(1212) << "Picked index == " << pickedPointIndex << " with (" << cursorPos().x() << "," << cursorPos().y() << ")"; pickedPointIndex = wwi.count - 1; } @@ -451,15 +419,12 @@ void WobblyWindowsEffect::startMovedResized(EffectWindow* w) #endif wwi.constraint[pickedPointIndex] = true; - if (w->isUserResize()) - { + if (w->isUserResize()) { // on a resize, do not allow any edges to wobble until it has been moved from // its original location wwi.can_wobble_top = wwi.can_wobble_left = wwi.can_wobble_right = wwi.can_wobble_bottom = false; wwi.resize_original_rect = w->geometry(); - } - else - { + } else { wwi.can_wobble_top = wwi.can_wobble_left = wwi.can_wobble_right = wwi.can_wobble_bottom = true; } } @@ -467,8 +432,7 @@ void WobblyWindowsEffect::startMovedResized(EffectWindow* w) void WobblyWindowsEffect::stepMovedResized(EffectWindow* w) { QRect new_geometry = w->geometry(); - if (!windows.contains(w)) - { + if (!windows.contains(w)) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, new_geometry); windows[w] = new_wwi; @@ -477,24 +441,20 @@ void WobblyWindowsEffect::stepMovedResized(EffectWindow* w) WindowWobblyInfos& wwi = windows[w]; wwi.status = Free; - QRect maximized_area = effects->clientArea(MaximizeArea,w); - bool throb_direction_out = (new_geometry.top()==maximized_area.top()&&new_geometry.bottom()==maximized_area.bottom()) || - (new_geometry.left()==maximized_area.left()&&new_geometry.right()==maximized_area.right()); + QRect maximized_area = effects->clientArea(MaximizeArea, w); + bool throb_direction_out = (new_geometry.top() == maximized_area.top() && new_geometry.bottom() == maximized_area.bottom()) || + (new_geometry.left() == maximized_area.left() && new_geometry.right() == maximized_area.right()); qreal magnitude = throb_direction_out ? 10 : -30; // a small throb out when maximized, a larger throb inwards when restored - for (unsigned int j=0; jdata( WindowAddedGrabRole ).value() != this) - { - if(windows.contains(w)) - { + if (m_openEffectEnabled && w->data(WindowAddedGrabRole).value() != this) { + if (windows.contains(w)) { // could this happen ?? WindowWobblyInfos& wwi = windows[w]; wobblyOpenInit(wwi); - } - else - { + } else { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); wobblyOpenInit(new_wwi); @@ -522,24 +478,18 @@ void WobblyWindowsEffect::windowAdded(EffectWindow* w) void WobblyWindowsEffect::windowClosed(EffectWindow* w) { - if(windows.contains(w)) - { + if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; - if (m_closeEffectEnabled) - { + if (m_closeEffectEnabled) { wobblyCloseInit(wwi, w); w->refWindow(); - } - else - { + } else { freeWobblyInfo(wwi); windows.remove(w); - if( windows.isEmpty() ) + if (windows.isEmpty()) effects->addRepaintFull(); } - } - else if (m_closeEffectEnabled && w->data( WindowAddedGrabRole ).value() != this) - { + } else if (m_closeEffectEnabled && w->data(WindowAddedGrabRole).value() != this) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); wobblyCloseInit(new_wwi, w); @@ -550,16 +500,14 @@ void WobblyWindowsEffect::windowClosed(EffectWindow* w) void WobblyWindowsEffect::wobblyOpenInit(WindowWobblyInfos& wwi) const { - Pair middle = { (wwi.origin[0].x + wwi.origin[15].x)/2, (wwi.origin[0].y + wwi.origin[15].y)/2 }; + Pair middle = { (wwi.origin[0].x + wwi.origin[15].x) / 2, (wwi.origin[0].y + wwi.origin[15].y) / 2 }; - for (unsigned int j=0; j<4; ++j) - { - for (unsigned int i=0; i<4; ++i) - { - unsigned int idx = j*4 + i; + for (unsigned int j = 0; j < 4; ++j) { + for (unsigned int i = 0; i < 4; ++i) { + unsigned int idx = j * 4 + i; wwi.constraint[idx] = false; - wwi.position[idx].x = (wwi.position[idx].x + 3*middle.x)/4; - wwi.position[idx].y = (wwi.position[idx].y + 3*middle.y)/4; + wwi.position[idx].x = (wwi.position[idx].x + 3 * middle.x) / 4; + wwi.position[idx].y = (wwi.position[idx].y + 3 * middle.y) / 4; } } wwi.status = Openning; @@ -570,18 +518,16 @@ void WobblyWindowsEffect::wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* { const QRectF& rect = w->geometry(); QPointF center = rect.center(); - int x1 = (rect.x() + 3*center.x())/4; - int x2 = (rect.x() + rect.width() + 3*center.x())/4; - int y1 = (rect.y() + 3*center.y())/4; - int y2 = (rect.y() + rect.height() + 3*center.y())/4; + int x1 = (rect.x() + 3 * center.x()) / 4; + int x2 = (rect.x() + rect.width() + 3 * center.x()) / 4; + int y1 = (rect.y() + 3 * center.y()) / 4; + int y2 = (rect.y() + rect.height() + 3 * center.y()) / 4; wwi.closeRect.setCoords(x1, y1, x2, y2); // for closing, not yet used... - for (unsigned int j=0; j<4; ++j) - { - for (unsigned int i=0; i<4; ++i) - { - unsigned int idx = j*4 + i; + for (unsigned int j = 0; j < 4; ++j) { + for (unsigned int i = 0; i < 4; ++i) { + unsigned int idx = j * 4 + i; wwi.constraint[idx] = false; } } @@ -590,7 +536,7 @@ void WobblyWindowsEffect::wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* void WobblyWindowsEffect::initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) const { - wwi.count = 4*4; + wwi.count = 4 * 4; wwi.width = 4; wwi.height = 4; @@ -615,36 +561,28 @@ void WobblyWindowsEffect::initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) Pair initValue = {x, y}; static const Pair nullPair = {0.0, 0.0}; - qreal x_increment = width / (wwi.width-1.0); - qreal y_increment = height / (wwi.height-1.0); + qreal x_increment = width / (wwi.width - 1.0); + qreal y_increment = height / (wwi.height - 1.0); - for (unsigned int j=0; j<4; ++j) - { - for (unsigned int i=0; i<4; ++i) - { - unsigned int idx = j*4 + i; + for (unsigned int j = 0; j < 4; ++j) { + for (unsigned int i = 0; i < 4; ++i) { + unsigned int idx = j * 4 + i; wwi.origin[idx] = initValue; wwi.position[idx] = initValue; wwi.velocity[idx] = nullPair; wwi.constraint[idx] = false; - if (i != 4-2) // x grid count - 2, i.e. not the last point - { + if (i != 4 - 2) { // x grid count - 2, i.e. not the last point initValue.x += x_increment; - } - else - { + } else { initValue.x = width + x; } initValue.x = initValue.x; } initValue.x = x; initValue.x = initValue.x; - if (j != 4-2) // y grid count - 2, i.e. not the last point - { + if (j != 4 - 2) { // y grid count - 2, i.e. not the last point initValue.y += y_increment; - } - else - { + } else { initValue.y = height + y; } initValue.y = initValue.y; @@ -685,23 +623,21 @@ WobblyWindowsEffect::Pair WobblyWindowsEffect::computeBezierPoint(const WindowWo // compute polynomial coeff qreal px[4]; - px[0] = (1-tx)*(1-tx)*(1-tx); - px[1] = 3*(1-tx)*(1-tx)*tx; - px[2] = 3*(1-tx)*tx*tx; - px[3] = tx*tx*tx; + px[0] = (1 - tx) * (1 - tx) * (1 - tx); + px[1] = 3 * (1 - tx) * (1 - tx) * tx; + px[2] = 3 * (1 - tx) * tx * tx; + px[3] = tx * tx * tx; qreal py[4]; - py[0] = (1-ty)*(1-ty)*(1-ty); - py[1] = 3*(1-ty)*(1-ty)*ty; - py[2] = 3*(1-ty)*ty*ty; - py[3] = ty*ty*ty; + py[0] = (1 - ty) * (1 - ty) * (1 - ty); + py[1] = 3 * (1 - ty) * (1 - ty) * ty; + py[2] = 3 * (1 - ty) * ty * ty; + py[3] = ty * ty * ty; Pair res = {0.0, 0.0}; - for (unsigned int j = 0; j < 4; ++j) - { - for (unsigned int i = 0; i < 4; ++i) - { + for (unsigned int j = 0; j < 4; ++j) { + for (unsigned int i = 0; i < 4; ++i) { // this assume the grid is 4*4 res.x += px[i] * py[j] * wwi.position[i + j * wwi.width].x; res.y += px[i] * py[j] * wwi.position[i + j * wwi.width].y; @@ -716,34 +652,22 @@ namespace static inline void fixVectorBounds(WobblyWindowsEffect::Pair& vec, qreal min, qreal max) { - if (fabs(vec.x) < min) - { + if (fabs(vec.x) < min) { vec.x = 0.0; - } - else if (fabs(vec.x) > max) - { - if (vec.x > 0.0) - { + } else if (fabs(vec.x) > max) { + if (vec.x > 0.0) { vec.x = max; - } - else - { + } else { vec.x = -max; } } - if (fabs(vec.y) < min) - { + if (fabs(vec.y) < min) { vec.y = 0.0; - } - else if (fabs(vec.y) > max) - { - if (vec.y > 0.0) - { + } else if (fabs(vec.y) > max) { + if (vec.y > 0.0) { vec.y = max; - } - else - { + } else { vec.y = -max; } } @@ -751,20 +675,14 @@ static inline void fixVectorBounds(WobblyWindowsEffect::Pair& vec, qreal min, qr static inline void computeVectorBounds(WobblyWindowsEffect::Pair& vec, WobblyWindowsEffect::Pair& bound) { - if (fabs(vec.x) < bound.x) - { + if (fabs(vec.x) < bound.x) { bound.x = fabs(vec.x); - } - else if (fabs(vec.x) > bound.y) - { + } else if (fabs(vec.x) > bound.y) { bound.y = fabs(vec.x); } - if (fabs(vec.y) < bound.x) - { + if (fabs(vec.y) < bound.x) { bound.x = fabs(vec.y); - } - else if (fabs(vec.y) > bound.y) - { + } else if (fabs(vec.y) > bound.y) { bound.y = fabs(vec.y); } } @@ -776,13 +694,12 @@ bool WobblyWindowsEffect::updateWindowWobblyDatas(EffectWindow* w, qreal time) QRectF rect = w->geometry(); WindowWobblyInfos& wwi = windows[w]; - if (wwi.status == Closing) - { + if (wwi.status == Closing) { rect = wwi.closeRect; } - qreal x_length = rect.width() / (wwi.width-1.0); - qreal y_length = rect.height() / (wwi.height-1.0); + qreal x_length = rect.width() / (wwi.width - 1.0); + qreal y_length = rect.height() / (wwi.height - 1.0); #if defined VERBOSE_MODE kDebug(1212) << "time " << time; @@ -791,27 +708,19 @@ bool WobblyWindowsEffect::updateWindowWobblyDatas(EffectWindow* w, qreal time) Pair origine = {rect.x(), rect.y()}; - for (unsigned int j=0; junrefWindow(); } freeWobblyInfo(wwi); windows.remove(w); - if( windows.isEmpty() ) + if (windows.isEmpty()) effects->addRepaintFull(); return false; } @@ -1195,8 +1062,8 @@ void WobblyWindowsEffect::heightRingLinearMean(Pair** data_pointer, WindowWobbly neibourgs[1] = data[wwi.width]; neibourgs[2] = data[wwi.width+1]; - res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0*vit.x) / 6.0; - res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0*vit.y) / 6.0; + res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; + res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } @@ -1208,21 +1075,21 @@ void WobblyWindowsEffect::heightRingLinearMean(Pair** data_pointer, WindowWobbly neibourgs[1] = data[2*wwi.width-1]; neibourgs[2] = data[2*wwi.width-2]; - res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0*vit.x) / 6.0; - res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0*vit.y) / 6.0; + res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; + res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // bottom-left - { + { Pair& res = wwi.buffer[wwi.width*(wwi.height-1)]; Pair vit = data[wwi.width*(wwi.height-1)]; neibourgs[0] = data[wwi.width*(wwi.height-1)+1]; neibourgs[1] = data[wwi.width*(wwi.height-2)]; neibourgs[2] = data[wwi.width*(wwi.height-2)+1]; - res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0*vit.x) / 6.0; - res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0*vit.y) / 6.0; + res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; + res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } @@ -1234,16 +1101,15 @@ void WobblyWindowsEffect::heightRingLinearMean(Pair** data_pointer, WindowWobbly neibourgs[1] = data[wwi.width*(wwi.height-1)-1]; neibourgs[2] = data[wwi.width*(wwi.height-1)-2]; - res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0*vit.x) / 6.0; - res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0*vit.y) / 6.0; + res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; + res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // for borders // top border - for (unsigned int i=1; i windows; + QHash< const EffectWindow*, WindowWobblyInfos > windows; - QRegion m_updateRegion; + QRegion m_updateRegion; - qreal m_stiffness; - qreal m_drag; - qreal m_move_factor; + qreal m_stiffness; + qreal m_drag; + qreal m_move_factor; - // the default tesselation for windows - // use qreal instead of int as I really often need - // these values as real to do divisions. - qreal m_xTesselation; - qreal m_yTesselation; + // the default tesselation for windows + // use qreal instead of int as I really often need + // these values as real to do divisions. + qreal m_xTesselation; + qreal m_yTesselation; - qreal m_minVelocity; - qreal m_maxVelocity; - qreal m_stopVelocity; - qreal m_minAcceleration; - qreal m_maxAcceleration; - qreal m_stopAcceleration; + qreal m_minVelocity; + qreal m_maxVelocity; + qreal m_stopVelocity; + qreal m_minAcceleration; + qreal m_maxAcceleration; + qreal m_stopAcceleration; - bool m_moveEffectEnabled; - bool m_openEffectEnabled; - bool m_closeEffectEnabled; + bool m_moveEffectEnabled; + bool m_openEffectEnabled; + bool m_closeEffectEnabled; - bool m_moveWobble; // Expands m_moveEffectEnabled - bool m_resizeWobble; + bool m_moveWobble; // Expands m_moveEffectEnabled + bool m_resizeWobble; - void initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) const; - void freeWobblyInfo(WindowWobblyInfos& wwi) const; - void wobblyOpenInit(WindowWobblyInfos& wwi) const; - void wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* w) const; + void initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) const; + void freeWobblyInfo(WindowWobblyInfos& wwi) const; + void wobblyOpenInit(WindowWobblyInfos& wwi) const; + void wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* w) const; - WobblyWindowsEffect::Pair computeBezierPoint(const WindowWobblyInfos& wwi, Pair point) const; + WobblyWindowsEffect::Pair computeBezierPoint(const WindowWobblyInfos& wwi, Pair point) const; - static void heightRingLinearMean(Pair** data_pointer, WindowWobblyInfos& wwi); + static void heightRingLinearMean(Pair** data_pointer, WindowWobblyInfos& wwi); - void setParameterSet(const ParameterSet& pset); + void setParameterSet(const ParameterSet& pset); }; } // namespace KWin diff --git a/effects/wobblywindows/wobblywindows_config.cpp b/effects/wobblywindows/wobblywindows_config.cpp index 5019b49c5..8b65b4881 100644 --- a/effects/wobblywindows/wobblywindows_config.cpp +++ b/effects/wobblywindows/wobblywindows_config.cpp @@ -36,43 +36,37 @@ KWIN_EFFECT_CONFIG_FACTORY //----------------------------------------------------------------------------- // WARNING: This is (kinda) copied from wobblywindows.cpp -struct ParameterSet -{ +struct ParameterSet { int stiffness; int drag; int move_factor; }; -ParameterSet set_0 = -{ +ParameterSet set_0 = { 15, 80, 10 }; -ParameterSet set_1 = -{ +ParameterSet set_1 = { 10, 85, 10 }; -ParameterSet set_2 = -{ +ParameterSet set_2 = { 6, 90, 10 }; -ParameterSet set_3 = -{ +ParameterSet set_3 = { 3, 92, 20 }; -ParameterSet set_4 = -{ +ParameterSet set_4 = { 1, 97, 25 @@ -83,7 +77,7 @@ ParameterSet pset[5] = { set_0, set_1, set_2, set_3, set_4 }; //----------------------------------------------------------------------------- WobblyWindowsEffectConfig::WobblyWindowsEffectConfig(QWidget* parent, const QVariantList& args) : -KCModule(EffectFactory::componentData(), parent, args) + KCModule(EffectFactory::componentData(), parent, args) { m_ui.setupUi(this); @@ -113,13 +107,11 @@ void WobblyWindowsEffectConfig::load() unsigned int wobblynessLevel = 0; QString settingsMode = conf.readEntry("Settings", "Auto"); - if (settingsMode != "Custom") - { + if (settingsMode != "Custom") { wobblynessLevel = conf.readEntry("WobblynessLevel", 0); change = false; } - if (wobblynessLevel > 4) - { + if (wobblynessLevel > 4) { wobblynessLevel = 4; change = true; } @@ -173,21 +165,21 @@ void WobblyWindowsEffectConfig::defaults() } void WobblyWindowsEffectConfig::advancedChanged() - { - if(m_ui.advancedBox->isChecked()) +{ + if (m_ui.advancedBox->isChecked()) m_ui.advancedGroup->setEnabled(true); else m_ui.advancedGroup->setEnabled(false); - } +} void WobblyWindowsEffectConfig::wobblinessChanged() - { +{ ParameterSet preset = pset[m_ui.wobblinessSlider->value()]; m_ui.stiffnessSlider->setValue(preset.stiffness); m_ui.dragSlider->setValue(preset.drag); m_ui.moveFactorSlider->setValue(preset.move_factor); - } +} } // namespace diff --git a/effects/zoom/zoom.cpp b/effects/zoom/zoom.cpp index 93cd03f9c..668a384b4 100644 --- a/effects/zoom/zoom.cpp +++ b/effects/zoom/zoom.cpp @@ -42,97 +42,95 @@ namespace KWin { static int nominalCursorSize(int iconSize) - { - for(int i = 512; i > 8; i /= 2) - { - if(i < iconSize) +{ + for (int i = 512; i > 8; i /= 2) { + if (i < iconSize) return i; - if((i * .75) < iconSize) + if ((i * .75) < iconSize) return int(i * .75); - } - return 8; } + return 8; +} -KWIN_EFFECT( zoom, ZoomEffect ) +KWIN_EFFECT(zoom, ZoomEffect) ZoomEffect::ZoomEffect() : QObject() , Effect() - , zoom( 1 ) - , target_zoom( 1 ) - , polling( false ) - , zoomFactor( 1.25 ) - , mouseTracking( MouseTrackingProportional ) - , enableFocusTracking( false ) - , followFocus( true ) - , mousePointer( MousePointerScale ) - , focusDelay( 350 ) // in milliseconds - , texture( 0 ) - , xrenderPicture( 0 ) - , imageWidth( 0 ) - , imageHeight( 0 ) - , isMouseHidden( false ) - , xMove( 0 ) - , yMove( 0 ) - , moveFactor( 20.0 ) - { - KActionCollection* actionCollection = new KActionCollection( this ); + , zoom(1) + , target_zoom(1) + , polling(false) + , zoomFactor(1.25) + , mouseTracking(MouseTrackingProportional) + , enableFocusTracking(false) + , followFocus(true) + , mousePointer(MousePointerScale) + , focusDelay(350) // in milliseconds + , texture(0) + , xrenderPicture(0) + , imageWidth(0) + , imageHeight(0) + , isMouseHidden(false) + , xMove(0) + , yMove(0) + , moveFactor(20.0) +{ + KActionCollection* actionCollection = new KActionCollection(this); KAction* a = 0; - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomIn, this, SLOT( zoomIn()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomIn, this, SLOT(zoomIn()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Equal)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomOut, this, SLOT( zoomOut()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomOut, this, SLOT(zoomOut()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ActualSize, this, SLOT( actualSize()))); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ActualSize, this, SLOT(actualSize()))); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomLeft" )); - a->setText( i18n("Move Left") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomLeft")); + a->setText(i18n("Move Left")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Left)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveZoomLeft() )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveZoomLeft())); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomRight" )); - a->setText( i18n("Move Right") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomRight")); + a->setText(i18n("Move Right")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Right)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveZoomRight() )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveZoomRight())); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomUp" )); - a->setText( i18n("Move Up") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomUp")); + a->setText(i18n("Move Up")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Up)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveZoomUp() )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveZoomUp())); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomDown" )); - a->setText( i18n("Move Down") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomDown")); + a->setText(i18n("Move Down")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Down)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveZoomDown() )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveZoomDown())); - a = static_cast< KAction* >( actionCollection->addAction( "MoveMouseToFocus" )); - a->setText( i18n("Move Mouse to Focus") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveMouseToFocus")); + a->setText(i18n("Move Mouse to Focus")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_F5)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveMouseToFocus() )); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveMouseToFocus())); - a = static_cast< KAction* >( actionCollection->addAction( "MoveMouseToCenter" )); - a->setText( i18n("Move Mouse to Center") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveMouseToCenter")); + a->setText(i18n("Move Mouse to Center")); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_F6)); - connect( a, SIGNAL( triggered( bool )), this, SLOT( moveMouseToCenter() )); - - timeline.setDuration( 350 ); - timeline.setFrameRange( 0, 100 ); + connect(a, SIGNAL(triggered(bool)), this, SLOT(moveMouseToCenter())); + + timeline.setDuration(350); + timeline.setFrameRange(0, 100); connect(&timeline, SIGNAL(frameChanged(int)), this, SLOT(timelineFrameChanged(int))); - reconfigure( ReconfigureAll ); - } + reconfigure(ReconfigureAll); +} ZoomEffect::~ZoomEffect() - { +{ // switch off and free resources showCursor(); - } +} void ZoomEffect::showCursor() - { +{ #if defined(KWIN_HAVE_OPENGL_COMPOSITING) || defined(KWIN_HAVE_XRENDER_COMPOSITING) - if( isMouseHidden ) - { + if (isMouseHidden) { // show the previously hidden mouse-pointer again and free the loaded texture/picture. Display* display = QX11Info::display(); XFixesShowCursor(display, DefaultRootWindow(display)); @@ -141,77 +139,72 @@ void ZoomEffect::showCursor() delete xrenderPicture; xrenderPicture = 0; isMouseHidden = false; - } -#endif } +#endif +} void ZoomEffect::hideCursor() - { +{ #if defined(KWIN_HAVE_OPENGL_COMPOSITING) || defined(KWIN_HAVE_XRENDER_COMPOSITING) - if( !isMouseHidden ) - { - // try to load the cursor-theme into a OpenGL texture and if successful then hide the mouse-pointer + if (!isMouseHidden) { + // try to load the cursor-theme into a OpenGL texture and if successful then hide the mouse-pointer recreateTexture(); - if( texture || xrenderPicture ) - { + if (texture || xrenderPicture) { Display* display = QX11Info::display(); XFixesHideCursor(display, DefaultRootWindow(display)); isMouseHidden = true; - } } -#endif } +#endif +} void ZoomEffect::recreateTexture() - { +{ // read details about the mouse-cursor theme define per default - KConfigGroup mousecfg(KSharedConfig::openConfig( "kcminputrc" ), "Mouse" ); + KConfigGroup mousecfg(KSharedConfig::openConfig("kcminputrc"), "Mouse"); QString theme = mousecfg.readEntry("cursorTheme", QString()); QString size = mousecfg.readEntry("cursorSize", QString()); // try to find the to the theme-name matching cursor-directory. QByteArray themePath; - foreach (const QString &baseDir, QString(XcursorLibraryPath()).split(':', QString::SkipEmptyParts)) - { + foreach (const QString & baseDir, QString(XcursorLibraryPath()).split(':', QString::SkipEmptyParts)) { QDir dir(baseDir); - if(!dir.exists()) continue; - if(!theme.isEmpty() && dir.cd(theme)) - { + if (!dir.exists()) continue; + if (!theme.isEmpty() && dir.cd(theme)) { themePath = QFile::encodeName(dir.absolutePath()); break; // theme found, job is done and we can abort the search now - } - if(dir.cd("default")) // default is better then nothing, so keep it as backup - themePath = QFile::encodeName(dir.absolutePath()); } + if (dir.cd("default")) // default is better then nothing, so keep it as backup + themePath = QFile::encodeName(dir.absolutePath()); + } // fetch a reasonable size for the cursor-theme image bool ok; int iconSize = size.toInt(&ok); - if(!ok) + if (!ok) iconSize = QApplication::style()->pixelMetric(QStyle::PM_LargeIconSize); // load the cursor-theme image from the Xcursor-library XcursorImage *ximg = XcursorLibraryLoadImage("left_ptr", themePath, nominalCursorSize(iconSize)); - if (ximg) - { + if (ximg) { // turn the XcursorImage into a QImage that will be used to create the GLTexture/XRenderPicture. imageWidth = ximg->width; imageHeight = ximg->height; QImage img((uchar*)ximg->pixels, imageWidth, imageHeight, QImage::Format_ARGB32_Premultiplied); #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( effects->compositingType() == OpenGLCompositing ) + if (effects->compositingType() == OpenGLCompositing) texture = new GLTexture(img); #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( effects->compositingType() == XRenderCompositing ) + if (effects->compositingType() == XRenderCompositing) xrenderPicture = new XRenderPicture(QPixmap::fromImage(img)); #endif XcursorImageDestroy(ximg); - } } +} -void ZoomEffect::reconfigure( ReconfigureFlags ) - { +void ZoomEffect::reconfigure(ReconfigureFlags) +{ KConfigGroup conf = EffectsHandler::effectConfig("Zoom"); // On zoom-in and zoom-out change the zoom by the defined zoom-factor. zoomFactor = qMax(0.1, conf.readEntry("ZoomFactor", zoomFactor)); @@ -221,142 +214,126 @@ void ZoomEffect::reconfigure( ReconfigureFlags ) mouseTracking = MouseTrackingType(conf.readEntry("MouseTracking", int(mouseTracking))); // Enable tracking of the focused location. bool _enableFocusTracking = conf.readEntry("EnableFocusTracking", enableFocusTracking); - if(enableFocusTracking != _enableFocusTracking) - { + if (enableFocusTracking != _enableFocusTracking) { enableFocusTracking = _enableFocusTracking; - if(QDBusConnection::sessionBus().isConnected()) - { - if(enableFocusTracking) - QDBusConnection::sessionBus().connect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int,int,int,int,int,int))); + if (QDBusConnection::sessionBus().isConnected()) { + if (enableFocusTracking) + QDBusConnection::sessionBus().connect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int, int, int, int, int, int))); else - QDBusConnection::sessionBus().disconnect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int,int,int,int,int,int))); - } + QDBusConnection::sessionBus().disconnect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int, int, int, int, int, int))); } + } // When the focus changes, move the zoom area to the focused location. followFocus = conf.readEntry("EnableFollowFocus", followFocus); // The time in milliseconds to wait before a focus-event takes away a mouse-move. focusDelay = qMax(0, conf.readEntry("FocusDelay", focusDelay)); // The factor the zoom-area will be moved on touching an edge on push-mode or using the navigation KAction's. moveFactor = qMax(0.1, conf.readEntry("MoveFactor", moveFactor)); +} + +void ZoomEffect::prePaintScreen(ScreenPrePaintData& data, int time) +{ + if (zoom != target_zoom) { + double diff = time / animationTime(500.0); + if (target_zoom > zoom) + zoom = qMin(zoom * qMax(1 + diff, 1.2), target_zoom); + else + zoom = qMax(zoom * qMin(1 - diff, 0.8), target_zoom); } -void ZoomEffect::prePaintScreen( ScreenPrePaintData& data, int time ) - { - if( zoom != target_zoom ) - { - double diff = time / animationTime( 500.0 ); - if( target_zoom > zoom ) - zoom = qMin( zoom * qMax( 1 + diff, 1.2 ), target_zoom ); - else - zoom = qMax( zoom * qMin( 1 - diff, 0.8 ), target_zoom ); - } - - if( zoom == 1.0 ) - { + if (zoom == 1.0) { showCursor(); - } - else - { + } else { hideCursor(); data.mask |= PAINT_SCREEN_TRANSFORMED; - } - - effects->prePaintScreen( data, time ); } -void ZoomEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) - { - if( zoom != 1.0 ) - { + effects->prePaintScreen(data, time); +} + +void ZoomEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) +{ + if (zoom != 1.0) { data.xScale *= zoom; data.yScale *= zoom; // mouse-tracking allows navigation of the zoom-area using the mouse. - switch( mouseTracking ) - { - case MouseTrackingProportional: - data.xTranslate = - int( cursorPoint.x() * ( zoom - 1.0 ) ); - data.yTranslate = - int( cursorPoint.y() * ( zoom - 1.0 ) ); - prevPoint = cursorPoint; - break; - case MouseTrackingCentred: - data.xTranslate = qMin(0, qMax( int(displayWidth() - displayWidth() * zoom), int( displayWidth()/2 - cursorPoint.x() * zoom ))); - data.yTranslate = qMin(0, qMax( int(displayHeight() - displayHeight() * zoom), int( displayHeight()/2 - cursorPoint.y() * zoom ))); - prevPoint = cursorPoint; - break; - case MouseTrackingPush: - if( timeline.state() != QTimeLine::Running ) - { - // touching an edge of the screen moves the zoom-area in that direction. - int x = cursorPoint.x() * zoom - prevPoint.x() * ( zoom - 1.0 ); - int y = cursorPoint.y() * zoom - prevPoint.y() * ( zoom - 1.0 ); - int threshold = 1; //qMax(1, int(10.0 / zoom)); - xMove = yMove = 0; - if( x < threshold ) - xMove = - qMax(1.0, displayWidth() / zoom / moveFactor); - else if( x + threshold > displayWidth() ) - xMove = qMax(1.0, displayWidth() / zoom / moveFactor); - if( y < threshold ) - yMove = - qMax(1.0, displayHeight() / zoom / moveFactor); - else if( y + threshold > displayHeight() ) - yMove = qMax(1.0, displayHeight() / zoom / moveFactor); - if( xMove != 0 || yMove != 0 ) - { - prevPoint.setX( qMax(0, qMin(displayWidth(), prevPoint.x() + xMove)) ); - prevPoint.setY( qMax(0, qMin(displayHeight(), prevPoint.y() + yMove)) ); - timeline.start(); - } - } - // fall through - case MouseTrackingDisabled: - data.xTranslate = - int( prevPoint.x() * ( zoom - 1.0 ) ); - data.yTranslate = - int( prevPoint.y() * ( zoom - 1.0 ) ); - break; + switch(mouseTracking) { + case MouseTrackingProportional: + data.xTranslate = - int(cursorPoint.x() * (zoom - 1.0)); + data.yTranslate = - int(cursorPoint.y() * (zoom - 1.0)); + prevPoint = cursorPoint; + break; + case MouseTrackingCentred: + data.xTranslate = qMin(0, qMax(int(displayWidth() - displayWidth() * zoom), int(displayWidth() / 2 - cursorPoint.x() * zoom))); + data.yTranslate = qMin(0, qMax(int(displayHeight() - displayHeight() * zoom), int(displayHeight() / 2 - cursorPoint.y() * zoom))); + prevPoint = cursorPoint; + break; + case MouseTrackingPush: + if (timeline.state() != QTimeLine::Running) { + // touching an edge of the screen moves the zoom-area in that direction. + int x = cursorPoint.x() * zoom - prevPoint.x() * (zoom - 1.0); + int y = cursorPoint.y() * zoom - prevPoint.y() * (zoom - 1.0); + int threshold = 1; //qMax(1, int(10.0 / zoom)); + xMove = yMove = 0; + if (x < threshold) + xMove = - qMax(1.0, displayWidth() / zoom / moveFactor); + else if (x + threshold > displayWidth()) + xMove = qMax(1.0, displayWidth() / zoom / moveFactor); + if (y < threshold) + yMove = - qMax(1.0, displayHeight() / zoom / moveFactor); + else if (y + threshold > displayHeight()) + yMove = qMax(1.0, displayHeight() / zoom / moveFactor); + if (xMove != 0 || yMove != 0) { + prevPoint.setX(qMax(0, qMin(displayWidth(), prevPoint.x() + xMove))); + prevPoint.setY(qMax(0, qMin(displayHeight(), prevPoint.y() + yMove))); + timeline.start(); + } } + // fall through + case MouseTrackingDisabled: + data.xTranslate = - int(prevPoint.x() * (zoom - 1.0)); + data.yTranslate = - int(prevPoint.y() * (zoom - 1.0)); + break; + } // use the focusPoint if focus tracking is enabled - if(enableFocusTracking && followFocus) - { + if (enableFocusTracking && followFocus) { bool acceptFocus = true; - if(mouseTracking != MouseTrackingDisabled && focusDelay > 0) - { + if (mouseTracking != MouseTrackingDisabled && focusDelay > 0) { // Wait some time for the mouse before doing the switch. This serves as threshold // to prevent the focus from jumping around to much while working with the mouse. const int msecs = lastMouseEvent.msecsTo(lastFocusEvent); acceptFocus = msecs > focusDelay; - } - if(acceptFocus) - { - data.xTranslate = - int( focusPoint.x() * ( zoom - 1.0 ) ); - data.yTranslate = - int( focusPoint.y() * ( zoom - 1.0 ) ); + } + if (acceptFocus) { + data.xTranslate = - int(focusPoint.x() * (zoom - 1.0)); + data.yTranslate = - int(focusPoint.y() * (zoom - 1.0)); prevPoint = focusPoint; - } } } + } - effects->paintScreen( mask, region, data ); + effects->paintScreen(mask, region, data); - if( zoom != 1.0 && mousePointer != MousePointerHide ) - { + if (zoom != 1.0 && mousePointer != MousePointerHide) { // Draw the mouse-texture at the position matching to zoomed-in image of the desktop. Hiding the // previous mouse-cursor and drawing our own fake mouse-cursor is needed to be able to scale the // mouse-cursor up and to re-position those mouse-cursor to match to the chosen zoom-level. #ifdef KWIN_HAVE_OPENGL_COMPOSITING - if( texture ) - { + if (texture) { #ifndef KWIN_HAVE_OPENGLES - glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT); #endif texture->bind(); - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int w = imageWidth; int h = imageHeight; - if( mousePointer == MousePointerScale ) - { + if (mousePointer == MousePointerScale) { w *= zoom; h *= zoom; - } + } QPoint p = QCursor::pos(); QRect rect(p.x() * zoom + data.xTranslate, p.y() * zoom + data.yTranslate, w, h); texture->render(region, rect); @@ -365,149 +342,142 @@ void ZoomEffect::paintScreen( int mask, QRegion region, ScreenPaintData& data ) #ifndef KWIN_HAVE_OPENGLES glPopAttrib(); #endif - } + } #endif #ifdef KWIN_HAVE_XRENDER_COMPOSITING - if( xrenderPicture ) - { + if (xrenderPicture) { QPoint p = QCursor::pos(); QRect rect(p.x() * zoom + data.xTranslate, p.y() * zoom + data.yTranslate, imageWidth, imageHeight); - XRenderComposite( display(), PictOpOver, *xrenderPicture, None, effects->xrenderBufferPicture(), 0, 0, 0, 0, rect.x(), rect.y(), rect.width(), rect.height()); - } -#endif + XRenderComposite(display(), PictOpOver, *xrenderPicture, None, effects->xrenderBufferPicture(), 0, 0, 0, 0, rect.x(), rect.y(), rect.width(), rect.height()); } +#endif } +} void ZoomEffect::postPaintScreen() - { - if( zoom != target_zoom ) +{ + if (zoom != target_zoom) effects->addRepaintFull(); effects->postPaintScreen(); - } +} void ZoomEffect::zoomIn() - { +{ target_zoom *= zoomFactor; - if( !polling ) - { + if (!polling) { polling = true; effects->startMousePolling(); - } - effects->addRepaintFull(); } + effects->addRepaintFull(); +} void ZoomEffect::zoomOut() - { +{ target_zoom /= zoomFactor; - if( target_zoom < 1 ) - { + if (target_zoom < 1) { target_zoom = 1; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } } - effects->addRepaintFull(); } + effects->addRepaintFull(); +} void ZoomEffect::actualSize() - { +{ target_zoom = 1; - if( polling ) - { + if (polling) { polling = false; effects->stopMousePolling(); - } - effects->addRepaintFull(); } + effects->addRepaintFull(); +} void ZoomEffect::timelineFrameChanged(int /* frame */) - { - prevPoint.setX( qMax(0, qMin(displayWidth(), prevPoint.x() + xMove)) ); - prevPoint.setY( qMax(0, qMin(displayHeight(), prevPoint.y() + yMove)) ); +{ + prevPoint.setX(qMax(0, qMin(displayWidth(), prevPoint.x() + xMove))); + prevPoint.setY(qMax(0, qMin(displayHeight(), prevPoint.y() + yMove))); cursorPoint = prevPoint; effects->addRepaintFull(); - } +} void ZoomEffect::moveZoom(int x, int y) - { - if( timeline.state() == QTimeLine::Running ) +{ + if (timeline.state() == QTimeLine::Running) timeline.stop(); - if( x < 0 ) + if (x < 0) xMove = - qMax(1.0, displayWidth() / zoom / moveFactor); - else if( x > 0 ) + else if (x > 0) xMove = qMax(1.0, displayWidth() / zoom / moveFactor); else xMove = 0; - if( y < 0 ) + if (y < 0) yMove = - qMax(1.0, displayHeight() / zoom / moveFactor); - else if( y > 0 ) + else if (y > 0) yMove = qMax(1.0, displayHeight() / zoom / moveFactor); else yMove = 0; - + timeline.start(); - } +} void ZoomEffect::moveZoomLeft() - { +{ moveZoom(-1, 0); - } +} void ZoomEffect::moveZoomRight() - { +{ moveZoom(1, 0); - } +} void ZoomEffect::moveZoomUp() - { +{ moveZoom(0, -1); - } +} void ZoomEffect::moveZoomDown() - { +{ moveZoom(0, 1); - } +} void ZoomEffect::moveMouseToFocus() - { +{ QCursor::setPos(focusPoint.x(), focusPoint.y()); - } +} void ZoomEffect::moveMouseToCenter() - { +{ //QRect r = effects->clientArea(KWin::ScreenArea, effects->activeScreen(), effects->currentDesktop()); QRect r(0, 0, displayWidth(), displayHeight()); QCursor::setPos(r.x() + r.width() / 2, r.y() + r.height() / 2); - } +} -void ZoomEffect::mouseChanged( const QPoint& pos, const QPoint& old, Qt::MouseButtons, - Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers ) - { - if( zoom == 1.0 ) +void ZoomEffect::mouseChanged(const QPoint& pos, const QPoint& old, Qt::MouseButtons, + Qt::MouseButtons, Qt::KeyboardModifiers, Qt::KeyboardModifiers) +{ + if (zoom == 1.0) return; cursorPoint = pos; - if( pos != old ) - { + if (pos != old) { lastMouseEvent = QTime::currentTime(); effects->addRepaintFull(); - } } +} void ZoomEffect::focusChanged(int px, int py, int rx, int ry, int rwidth, int rheight) - { - if( zoom == 1.0 ) +{ + if (zoom == 1.0) return; - focusPoint = (px >= 0 && py >= 0) ? QPoint(px, py) : QPoint( rx + qMax(0, (qMin(displayWidth(), rwidth)/2)-60), ry + qMax(0, (qMin(displayHeight(), rheight)/2)-60) ); - if( enableFocusTracking ) - { + focusPoint = (px >= 0 && py >= 0) ? QPoint(px, py) : QPoint(rx + qMax(0, (qMin(displayWidth(), rwidth) / 2) - 60), ry + qMax(0, (qMin(displayHeight(), rheight) / 2) - 60)); + if (enableFocusTracking) { lastFocusEvent = QTime::currentTime(); effects->addRepaintFull(); - } } +} } // namespace diff --git a/effects/zoom/zoom.h b/effects/zoom/zoom.h index dd4daa73f..ca65a7b81 100644 --- a/effects/zoom/zoom.h +++ b/effects/zoom/zoom.h @@ -32,61 +32,61 @@ class XRenderPicture; class ZoomEffect : public QObject, public Effect - { +{ Q_OBJECT - public: - ZoomEffect(); - virtual ~ZoomEffect(); - virtual void reconfigure( ReconfigureFlags flags ); - virtual void prePaintScreen( ScreenPrePaintData& data, int time ); - virtual void paintScreen( int mask, QRegion region, ScreenPaintData& data ); - virtual void postPaintScreen(); - virtual void mouseChanged( const QPoint& pos, const QPoint& old, - Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, - Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers ); - private slots: - void zoomIn(); - void zoomOut(); - void actualSize(); - void moveZoomLeft(); - void moveZoomRight(); - void moveZoomUp(); - void moveZoomDown(); - void moveMouseToFocus(); - void moveMouseToCenter(); - void timelineFrameChanged(int frame); - void focusChanged(int px, int py, int rx, int ry, int rwidth, int rheight); - private: - void showCursor(); - void hideCursor(); - void recreateTexture(); - void moveZoom(int x, int y); - private: - double zoom; - double target_zoom; - bool polling; // Mouse polling - double zoomFactor; - enum MouseTrackingType { MouseTrackingProportional = 0, MouseTrackingCentred = 1, MouseTrackingPush = 2, MouseTrackingDisabled = 3 }; - MouseTrackingType mouseTracking; - bool enableFocusTracking; - bool followFocus; - enum MousePointerType { MousePointerScale = 0, MousePointerKeep = 1, MousePointerHide = 2 }; - MousePointerType mousePointer; - int focusDelay; - QPoint cursorPoint; - QPoint focusPoint; - QPoint prevPoint; - QTime lastMouseEvent; - QTime lastFocusEvent; - GLTexture* texture; - XRenderPicture* xrenderPicture; - int imageWidth; - int imageHeight; - bool isMouseHidden; - QTimeLine timeline; - int xMove, yMove; - double moveFactor; - }; +public: + ZoomEffect(); + virtual ~ZoomEffect(); + virtual void reconfigure(ReconfigureFlags flags); + virtual void prePaintScreen(ScreenPrePaintData& data, int time); + virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); + virtual void postPaintScreen(); + virtual void mouseChanged(const QPoint& pos, const QPoint& old, + Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, + Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); +private slots: + void zoomIn(); + void zoomOut(); + void actualSize(); + void moveZoomLeft(); + void moveZoomRight(); + void moveZoomUp(); + void moveZoomDown(); + void moveMouseToFocus(); + void moveMouseToCenter(); + void timelineFrameChanged(int frame); + void focusChanged(int px, int py, int rx, int ry, int rwidth, int rheight); +private: + void showCursor(); + void hideCursor(); + void recreateTexture(); + void moveZoom(int x, int y); +private: + double zoom; + double target_zoom; + bool polling; // Mouse polling + double zoomFactor; + enum MouseTrackingType { MouseTrackingProportional = 0, MouseTrackingCentred = 1, MouseTrackingPush = 2, MouseTrackingDisabled = 3 }; + MouseTrackingType mouseTracking; + bool enableFocusTracking; + bool followFocus; + enum MousePointerType { MousePointerScale = 0, MousePointerKeep = 1, MousePointerHide = 2 }; + MousePointerType mousePointer; + int focusDelay; + QPoint cursorPoint; + QPoint focusPoint; + QPoint prevPoint; + QTime lastMouseEvent; + QTime lastFocusEvent; + GLTexture* texture; + XRenderPicture* xrenderPicture; + int imageWidth; + int imageHeight; + bool isMouseHidden; + QTimeLine timeline; + int xMove, yMove; + double moveFactor; +}; } // namespace diff --git a/effects/zoom/zoom_config.cpp b/effects/zoom/zoom_config.cpp index 9a1e50913..3edd10cab 100644 --- a/effects/zoom/zoom_config.cpp +++ b/effects/zoom/zoom_config.cpp @@ -37,13 +37,13 @@ namespace KWin KWIN_EFFECT_CONFIG_FACTORY ZoomEffectConfigForm::ZoomEffectConfigForm(QWidget* parent) : QWidget(parent) - { +{ setupUi(this); - } +} ZoomEffectConfig::ZoomEffectConfig(QWidget* parent, const QVariantList& args) : - KCModule(EffectFactory::componentData(), parent, args) - { + KCModule(EffectFactory::componentData(), parent, args) +{ m_ui = new ZoomEffectConfigForm(this); QVBoxLayout* layout = new QVBoxLayout(this); @@ -57,71 +57,71 @@ ZoomEffectConfig::ZoomEffectConfig(QWidget* parent, const QVariantList& args) : connect(m_ui->editor, SIGNAL(keyChange()), this, SLOT(changed())); // Shortcut config. The shortcut belongs to the component "kwin"! - KActionCollection *actionCollection = new KActionCollection( this, KComponentData("kwin") ); - actionCollection->setConfigGroup( "Zoom" ); + KActionCollection *actionCollection = new KActionCollection(this, KComponentData("kwin")); + actionCollection->setConfigGroup("Zoom"); actionCollection->setConfigGlobal(true); KAction* a; - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomIn )); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomIn)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Equal)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ZoomOut )); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ZoomOut)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Minus)); - a = static_cast< KAction* >( actionCollection->addAction( KStandardAction::ActualSize )); + a = static_cast< KAction* >(actionCollection->addAction(KStandardAction::ActualSize)); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_0)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomLeft" ) ); - a->setIcon( KIcon("go-previous") ); - a->setText( i18n("Move Left") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomLeft")); + a->setIcon(KIcon("go-previous")); + a->setText(i18n("Move Left")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Left)); - - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomRight" ) ); - a->setIcon( KIcon("go-next") ); - a->setText( i18n("Move Right") ); + + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomRight")); + a->setIcon(KIcon("go-next")); + a->setText(i18n("Move Right")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Right)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomUp" ) ); - a->setIcon( KIcon("go-up") ); - a->setText( i18n("Move Up") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomUp")); + a->setIcon(KIcon("go-up")); + a->setText(i18n("Move Up")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Up)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveZoomDown" ) ); - a->setIcon( KIcon("go-down") ); - a->setText( i18n("Move Down") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveZoomDown")); + a->setIcon(KIcon("go-down")); + a->setText(i18n("Move Down")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_Down)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveMouseToFocus" ) ); - a->setIcon( KIcon("view-restore") ); - a->setText( i18n("Move Mouse to Focus") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveMouseToFocus")); + a->setIcon(KIcon("view-restore")); + a->setText(i18n("Move Mouse to Focus")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_F5)); - a = static_cast< KAction* >( actionCollection->addAction( "MoveMouseToCenter" ) ); - a->setIcon( KIcon("view-restore") ); - a->setText( i18n("Move Mouse to Center") ); + a = static_cast< KAction* >(actionCollection->addAction("MoveMouseToCenter")); + a->setIcon(KIcon("view-restore")); + a->setText(i18n("Move Mouse to Center")); a->setProperty("isConfigurationAction", true); a->setGlobalShortcut(KShortcut(Qt::META + Qt::Key_F6)); - + m_ui->editor->addCollection(actionCollection); load(); - } +} ZoomEffectConfig::~ZoomEffectConfig() - { +{ // Undo (only) unsaved changes to global key shortcuts m_ui->editor->undoChanges(); - } +} void ZoomEffectConfig::load() - { +{ KCModule::load(); KConfigGroup conf = EffectsHandler::effectConfig("Zoom"); m_ui->zoomStepsSpinBox->setValue(conf.readEntry("ZoomFactor", 1.2)); @@ -130,10 +130,10 @@ void ZoomEffectConfig::load() m_ui->focusTrackingCheckBox->setChecked(conf.readEntry("EnableFocusTracking", false)); m_ui->followFocusCheckBox->setChecked(conf.readEntry("EnableFollowFocus", true)); emit changed(false); - } +} void ZoomEffectConfig::save() - { +{ //KCModule::save(); KConfigGroup conf = EffectsHandler::effectConfig("Zoom"); conf.writeEntry("ZoomFactor", m_ui->zoomStepsSpinBox->value()); @@ -144,11 +144,11 @@ void ZoomEffectConfig::save() m_ui->editor->save(); // undo() will restore to this state from now on conf.sync(); emit changed(false); - EffectsHandler::sendReloadMessage( "zoom" ); - } + EffectsHandler::sendReloadMessage("zoom"); +} void ZoomEffectConfig::defaults() - { +{ m_ui->zoomStepsSpinBox->setValue(1.25); m_ui->mousePointerComboBox->setCurrentIndex(0); m_ui->mouseTrackingComboBox->setCurrentIndex(0); @@ -156,7 +156,7 @@ void ZoomEffectConfig::defaults() m_ui->followFocusCheckBox->setChecked(true); m_ui->editor->allDefault(); emit changed(true); - } +} } // namespace diff --git a/effects/zoom/zoom_config.h b/effects/zoom/zoom_config.h index 63a42553e..f7b4e064a 100644 --- a/effects/zoom/zoom_config.h +++ b/effects/zoom/zoom_config.h @@ -31,28 +31,28 @@ namespace KWin { class ZoomEffectConfigForm : public QWidget, public Ui::ZoomEffectConfigForm - { +{ Q_OBJECT - public: - explicit ZoomEffectConfigForm(QWidget* parent = 0); - }; +public: + explicit ZoomEffectConfigForm(QWidget* parent = 0); +}; class ZoomEffectConfig : public KCModule - { +{ Q_OBJECT - public: - explicit ZoomEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); - virtual ~ZoomEffectConfig(); +public: + explicit ZoomEffectConfig(QWidget* parent = 0, const QVariantList& args = QVariantList()); + virtual ~ZoomEffectConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private: - ZoomEffectConfigForm* m_ui; - enum MouseTracking { MouseCentred = 0, MouseProportional = 1, MouseDisabled = 2 }; - }; +private: + ZoomEffectConfigForm* m_ui; + enum MouseTracking { MouseCentred = 0, MouseProportional = 1, MouseDisabled = 2 }; +}; } // namespace diff --git a/events.cpp b/events.cpp index 81a6684be..390313f92 100644 --- a/events.cpp +++ b/events.cpp @@ -56,167 +56,161 @@ 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 ) - { - } +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 ); - } +{ + m_client->workspace()->sendClientToDesktop(m_client, desktop, true); +} -void WinInfo::changeFullscreenMonitors( NETFullscreenMonitors topology ) - { - m_client->updateFullscreenMonitors( topology ); - } +void WinInfo::changeFullscreenMonitors(NETFullscreenMonitors topology) +{ + m_client->updateFullscreenMonitors(topology); +} -void WinInfo::changeState( unsigned long state, unsigned long mask ) - { +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::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 ); + 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 ); - } + 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 ) - { +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 ); - } +{ + workspace->setNumberOfDesktops(n); +} void RootInfo::changeCurrentDesktop(int d) - { - workspace->setCurrentDesktop( 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 ) +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 ) + if (src != NET::FromApplication && src != FromTool) src = NET::FromTool; - if( src == NET::FromTool ) - workspace->activateClient( c, true ); // force - else // NET::FromApplication - { + 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 (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 + 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 ) +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 ) + if (src != NET::FromApplication && src != FromTool) src = NET::FromTool; - c->restackWindow( above, detail, src, timestamp, true ); - } + 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::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 ) +{ + 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 ) - { +{ + 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); - } + 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::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::gotPing(Window w, Time timestamp) +{ + if (Client* c = workspace->findClient(WindowMatchPredicate(w))) + c->gotPing(timestamp); +} -void RootInfo::changeShowingDesktop( bool showing ) - { - workspace->setShowingDesktop( showing ); - } +void RootInfo::changeShowingDesktop(bool showing) +{ + workspace->setShowingDesktop(showing); +} // **************************************** // Workspace @@ -225,157 +219,130 @@ void RootInfo::changeShowingDesktop( bool showing ) /*! Handles workspace specific XEvents */ -bool Workspace::workspaceEvent( XEvent * e ) - { - if ( mouse_emulation && (e->type == ButtonPress || e->type == ButtonRelease ) ) - { +bool Workspace::workspaceEvent(XEvent * e) +{ + if (mouse_emulation && (e->type == ButtonPress || e->type == ButtonRelease)) { mouse_emulation = false; ungrabXKeyboard(); - } - if( effects && static_cast< EffectsHandlerImpl* >( effects )->hasKeyboardGrab() - && ( e->type == KeyPress || e->type == KeyRelease )) + } + 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 ) - { + 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 ) + rootInfo->event(e, dirty, NETRootInfo::PROPERTIES_SIZE); + if (dirty[ NETRootInfo::PROTOCOLS ] & NET::DesktopNames) saveDesktopSettings(); - if( dirty[ NETRootInfo::PROTOCOLS2 ] & NET::WM2DesktopLayout ) + 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; + switch(e->type) { + case ButtonPress: + case ButtonRelease: + was_user_interaction = true; // fallthrough - case MotionNotify: - if ( tab_grab || control_grab ) - { - tab_box->handleMouseEvent( e ); - return true; - } - if( effects && static_cast(effects)->checkInputWindowEvent( e )) - return true; - break; - case KeyPress: - { - was_user_interaction = true; - int keyQt; - KKeyServer::xEventToQt(e, &keyQt); + case MotionNotify: + if (tab_grab || control_grab) { + tab_box->handleMouseEvent(e); + return true; + } + 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; - } - if( tab_grab || control_grab ) - { - tabBoxKeyPress( keyQt ); - return true; - } - break; - } - case KeyRelease: - was_user_interaction = true; - if( tab_grab || control_grab ) - { - tabBoxKeyRelease( e->xkey ); - return true; - } - break; - case ConfigureNotify: - if( e->xconfigure.event == rootWindow()) - x_stacking_dirty = true; - break; - }; + if (movingClient) { + movingClient->keyPressEvent(keyQt); + return true; + } + if (tab_grab || control_grab) { + tabBoxKeyPress(keyQt); + return true; + } + break; + } + case KeyRelease: + was_user_interaction = true; + if (tab_grab || control_grab) { + tabBoxKeyRelease(e->xkey); + return true; + } + 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 )) + 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 )) + } 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 )) + } 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 )) + } 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 )) + } 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() && effects ) - { + if (e->type == PropertyNotify && e->xany.window == rootWindow() && effects) { XPropertyEvent* re = &e->xproperty; - static_cast< EffectsHandlerImpl* >( effects )->propertyNotify( NULL, re->atom ); - } + static_cast< EffectsHandlerImpl* >(effects)->propertyNotify(NULL, re->atom); } - if( movingClient != NULL && movingClient->moveResizeGrabWindow() == e->xany.window - && ( e->type == MotionNotify || e->type == ButtonPress || e->type == ButtonRelease )) - { - if( movingClient->windowEvent( e )) + } + 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() + 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: - { + 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(); + 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 ) - { + // 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 @@ -384,206 +351,188 @@ bool Workspace::workspaceEvent( XEvent * e ) // 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(); - } - if( electricBorderEvent(e)) - return true; - 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 KeyPress: - if ( mouse_emulation ) - return keyPressMouseEmulation( e->xkey ); - break; - case KeyRelease: - if ( mouse_emulation ) - return false; - 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: - if( electricBorderEvent( e )) - return true; - break; - case Expose: - if( compositing() - && ( e->xexpose.window == rootWindow() // root window needs repainting - || (overlay != None && e->xexpose.window == overlay) )) // overlay needs repainting - { - addRepaint( e->xexpose.x, e->xexpose.y, e->xexpose.width, e->xexpose.height ); - } - break; - case VisibilityNotify: - if( compositing() && overlay != None && e->xvisibility.window == overlay ) - { - bool was_visible = overlay_visible; - overlay_visible = ( e->xvisibility.state != VisibilityFullyObscured ); - if( !was_visible && overlay_visible ) - { // hack for #154825 - addRepaintFull(); - QTimer::singleShot( 2000, this, SLOT( addRepaintFull())); - } - checkCompositeTimer(); - } - break; - default: - if( e->type == Extensions::randrNotifyEvent() && Extensions::randrAvailable() ) - { -#ifdef HAVE_XRANDR - XRRUpdateConfiguration( e ); -#endif - 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; + 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; } - return false; + 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(); + } + if (electricBorderEvent(e)) + return true; + 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 KeyPress: + if (mouse_emulation) + return keyPressMouseEmulation(e->xkey); + break; + case KeyRelease: + if (mouse_emulation) + return false; + 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: + if (electricBorderEvent(e)) + return true; + break; + case Expose: + if (compositing() + && (e->xexpose.window == rootWindow() // root window needs repainting + || (overlay != None && e->xexpose.window == overlay))) { // overlay needs repainting + addRepaint(e->xexpose.x, e->xexpose.y, e->xexpose.width, e->xexpose.height); + } + break; + case VisibilityNotify: + if (compositing() && overlay != None && e->xvisibility.window == overlay) { + bool was_visible = overlay_visible; + overlay_visible = (e->xvisibility.state != VisibilityFullyObscured); + if (!was_visible && overlay_visible) { + // hack for #154825 + addRepaintFull(); + QTimer::singleShot(2000, this, SLOT(addRepaintFull())); + } + checkCompositeTimer(); + } + break; + default: + if (e->type == Extensions::randrNotifyEvent() && Extensions::randrAvailable()) { +#ifdef HAVE_XRANDR + XRRUpdateConfiguration(e); +#endif + 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 )); +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; } + 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; - }; - } +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 @@ -592,172 +541,158 @@ Window Workspace::findSpecialEventWindow( XEvent* e ) /*! 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 - { +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 + info->event(e, dirty, 2); // pass through the NET stuff - if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMName ) != 0 ) + if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMName) != 0) fetchName(); - if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIconName ) != 0 ) + if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMIconName) != 0) fetchIconicName(); - if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMStrut ) != 0 - || ( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2ExtendedStrut ) != 0 ) - { - if( isTopMenu()) // the fallback mode of KMenuBar may alter the strut + if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMStrut) != 0 + || (dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2ExtendedStrut) != 0) { + if (isTopMenu()) // the fallback mode of KMenuBar may alter the strut checkWorkspacePosition(); // restore it workspace()->updateClientArea(); - } - if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0 ) + } + 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 ) - { + if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2UserTime) != 0) { workspace()->setWasUserInteraction(); - updateUserTime( info->userTime()); - } - if(( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId ) != 0 ) + updateUserTime(info->userTime()); + } + if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId) != 0) startupIdChanged(); - if( dirty[ WinInfo::PROTOCOLS ] & NET::WMIconGeometry ) - { - if( demandAttentionKNotifyTimer != NULL ) + if (dirty[ WinInfo::PROTOCOLS ] & NET::WMIconGeometry) { + if (demandAttentionKNotifyTimer != NULL) demandAttentionKNotify(); - } - if( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2Opacity ) - { - if( compositing()) - { + } + if (dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2Opacity) { + if (compositing()) { addRepaintFull(); - scene->windowOpacityChanged( this ); - if( effects ) - static_cast(effects)->windowOpacityChanged( effectWindow(), 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()); - } + scene->windowOpacityChanged(this); + if (effects) + static_cast(effects)->windowOpacityChanged(effectWindow(), 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 ) - { + } + 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(); } } - - 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->xany.window == frameId()) { #ifdef HAVE_XDAMAGE - if( e->type == Extensions::damageNotifyEvent()) - damageNotifyEvent( reinterpret_cast< XDamageNotifyEvent* >( e )); + if (e->type == Extensions::damageNotifyEvent()) + damageNotifyEvent(reinterpret_cast< XDamageNotifyEvent* >(e)); #endif - } - break; } - return true; // eat all events + break; } + return true; // eat all events +} /*! Handles map requests of the client window */ -bool Client::mapRequestEvent( XMapRequestEvent* e ) - { - if( e->window != 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, @@ -770,132 +705,125 @@ bool Client::mapRequestEvent( XMapRequestEvent* e ) // 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()) + if (e->parent == wrapperId()) return false; return true; // no messing with frame etc. - } - if( isTopMenu() && workspace()->managingTopMenus()) + } + if (isTopMenu() && workspace()->managingTopMenus()) return true; // kwin controls these // also copied in clientMessage() - if( isMinimized()) + if (isMinimized()) unminimize(); - if( isShade()) - setShade( ShadeNone ); - if( !isOnCurrentDesktop()) - { - if( workspace()->allowClientActivation( this )) - workspace()->activateClient( this ); + if (isShade()) + setShade(ShadeNone); + if (!isOnCurrentDesktop()) { + if (workspace()->allowClientActivation(this)) + workspace()->activateClient(this); else demandAttention(); - } - return true; } + return true; +} /*! Handles unmap notify events of the client window */ -void Client::unmapNotifyEvent( XUnmapEvent* e ) - { - if( e->window != window()) +void Client::unmapNotifyEvent(XUnmapEvent* e) +{ + if (e->window != window()) return; - if( e->event != wrapperId()) - { // most probably event from root window when initially reparenting + if (e->event != wrapperId()) { + // most probably event from root window when initially reparenting bool ignore = true; - if( e->event == rootWindow() && e->send_event ) + if (e->event == rootWindow() && e->send_event) ignore = false; // XWithdrawWindow() - if( ignore ) + if (ignore) return; - } - releaseWindow(); } + releaseWindow(); +} -void Client::destroyNotifyEvent( XDestroyWindowEvent* e ) - { - if( e->window != window()) +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()) +void Client::clientMessageEvent(XClientMessageEvent* e) +{ + if (e->window != window()) return; // ignore frame/wrapper // WM_STATE - if ( e->message_type == atoms->kde_wm_change_state ) - { - if( isTopMenu() && workspace()->managingTopMenus()) + if (e->message_type == atoms->kde_wm_change_state) { + if (isTopMenu() && workspace()->managingTopMenus()) return; // kwin controls these - bool avoid_animation = ( e->data.l[ 1 ] ); - if( e->data.l[ 0 ] == IconicState ) + 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 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( isTopMenu() && workspace()->managingTopMenus()) + } else if (e->message_type == atoms->wm_change_state) { + if (isTopMenu() && workspace()->managingTopMenus()) return; // kwin controls these - if ( e->data.l[0] == IconicState ) + if (e->data.l[0] == IconicState) minimize(); return; - } } +} /*! Handles configure requests of the client window */ -void Client::configureRequestEvent( XConfigureRequestEvent* e ) - { - if( e->window != window()) +void Client::configureRequestEvent(XConfigureRequestEvent* e) +{ + if (e->window != window()) return; // ignore frame/wrapper - if ( isResize() || isMove()) + 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 + 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 - || isTopMenu()) // topmenus neither - { + } + if (isSplash() // no manipulations with splashscreens either + || isTopMenu()) { // topmenus neither sendSyntheticConfigureNotify(); return; - } + } - if ( e->value_mask & CWBorderWidth ) - { + 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 ); - } + 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 & (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 ); + 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 @@ -906,114 +834,106 @@ void Client::configureRequestEvent( XConfigureRequestEvent* e ) // 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()) +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(); - break; - } + 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(); + break; } +} -void Client::enterNotifyEvent( XCrossingEvent* e ) - { - if( e->window != frameId()) +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 (e->mode == NotifyNormal || + (!options->focusPolicyIsReasonable() && + e->mode == NotifyUngrab)) { - if ( options->shadeHover ) - { + 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 (isShade()) { + shadeHoverTimer = new QTimer(this); + connect(shadeHoverTimer, SIGNAL(timeout()), this, SLOT(shadeHover())); + shadeHoverTimer->setSingleShot(true); + shadeHoverTimer->start(options->shadeHoverInterval); } + } - if ( options->focusPolicy == Options::ClickToFocus ) + if (options->focusPolicy == Options::ClickToFocus) return; - if ( options->autoRaise && !isDesktop() && - !isDock() && !isTopMenu() && workspace()->focusChangeEnabled() && - workspace()->topClientOnDesktop( workspace()->currentDesktop(), - options->separateScreenFocus ? screen() : -1 ) != this ) - { + if (options->autoRaise && !isDesktop() && + !isDock() && !isTopMenu() && 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 ); - } + 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() || isTopMenu() ) ) + QPoint currentPos(e->x_root, e->y_root); + if (options->focusPolicy != Options::FocusStrictlyUnderMouse && (isDesktop() || isDock() || isTopMenu())) 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 ); + if (options->focusPolicy != Options::FocusFollowsMouse + || currentPos != workspace()->focusMousePosition()) { + if (options->delayFocus) + workspace()->requestDelayFocus(this); else - workspace()->requestFocus( this ); - } - return; + workspace()->requestFocus(this); } + return; } +} -void Client::leaveNotifyEvent( XCrossingEvent* e ) - { - if( e->window != frameId()) +void Client::leaveNotifyEvent(XCrossingEvent* e) +{ + if (e->window != frameId()) return; // care only about leaving the whole frame - if ( e->mode == NotifyNormal ) - { - if ( !buttonDown ) - { + if (e->mode == NotifyNormal) { + if (!buttonDown) { mode = PositionCenter; updateCursor(); - } - bool lostMouse = !rect().contains( QPoint( e->x, e->y ) ); + } + 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 @@ -1021,69 +941,64 @@ void Client::leaveNotifyEvent( XCrossingEvent* e ) // 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 ) - { + 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 ) + if (XQueryPointer(display(), frameId(), &w, &child, &d1, &d2, &d3, &d4, &d5) == False + || child == None) lostMouse = true; // really lost the mouse - } - if ( lostMouse ) - { + } + 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 (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; } + 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 ] = - { +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 ); - } + }; + 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 ] = - { +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()); - } + }; + for (int i = 0; + i < 8; + ++i) + XUngrabButton(display(), AnyButton, + modifier | mods[ i ], wrapperId()); +} #undef XCapL #undef XNumL #undef XScrL @@ -1095,89 +1010,80 @@ void Client::ungrabButton( int modifier ) (Motif, AWT, Tk, ...) */ void Client::updateMouseGrab() - { - if( workspace()->globalShortcutsDisabled()) - { - XUngrabButton( display(), AnyButton, AnyModifier, wrapperId()); +{ + 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 ); + 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() - { + } + if (isActive() && !workspace()->forcedGlobalMouseGrab()) { // see Workspace::establishTabBoxGrab() // first grab all modifier combinations - XGrabButton( display(), AnyButton, AnyModifier, wrapperId(), false, - ButtonPressMask, - GrabModeSync, GrabModeAsync, - None, None ); + 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 ); + 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()); + 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 ); - } + 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()) +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() ); + 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 ); + } + 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 ) ) ) + 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. @@ -1185,229 +1091,212 @@ bool Client::eventFilter( QObject* o, QEvent* e ) // 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()->setAttribute(Qt::WA_WState_ConfigPending, false); decoration->widget()->update(); return false; - } - 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()); +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 + 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; + 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()); + 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 ) - { + if (bModKeyHeld) { was_action = true; - switch (button) - { + 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->commandAll1(); + com = options->commandWindow1(); break; case Button2: - com = options->commandAll2(); + com = options->commandWindow2(); break; case Button3: - com = options->commandAll3(); + com = options->commandWindow3(); break; case Button4: case Button5: - com = options->operationWindowMouseWheel( button == Button4 ? 120 : -120 ); + com = options->commandWindowWheel(); 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 - { + 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 (was_action) { + bool replay = performMouseCommand(com, QPoint(x_root, y_root), perform_handled); - if ( isSpecialWindow()) + if (isSpecialWindow()) replay = true; - if( w == wrapperId()) // these can come only from a grab - XAllowEvents(display(), replay? ReplayPointer : SyncPointer, CurrentTime ); //xTime()); + 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()); + if (w == wrapperId()) { // these can come only from a grab + XAllowEvents(display(), ReplayPointer, CurrentTime); //xTime()); return true; - } - if( w == decorationId()) - { - if( dynamic_cast( decoration )) + } + 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 ); + 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; } + 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 ) - { +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 + if (!wantsInput()) // we cannot be active, use it anyway active = true; - if ( button == Button1 ) + if (button == Button1) com = active ? options->commandActiveTitlebar1() : options->commandInactiveTitlebar1(); - else if ( button == Button2 ) + else if (button == Button2) com = active ? options->commandActiveTitlebar2() : options->commandInactiveTitlebar2(); - else if ( button == Button3 ) + 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 )); + 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 ); + 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 )); + 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 ); - } + 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 ) - { +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()); } + 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) +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()); + if (w == wrapperId()) { + XAllowEvents(display(), SyncPointer, CurrentTime); //xTime()); return true; - } - if( w != frameId() && w != decorationId() && w != moveResizeGrabWindow()) + } + 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 ) - { + if ((state & (Button1Mask & Button2Mask & Button3Mask)) == 0) { buttonDown = false; stopDelayedMoveResize(); - if ( moveResizeMode ) - { - finishMoveResize( false ); + 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() ) + QPoint mousepos(x_root - x + padding_left, y_root - y + padding_top); + mode = mousePosition(mousepos); + } else if (workspace()->decorationSupportsClientGrouping()) return false; updateCursor(); - } - return true; } + return true; +} static bool was_motion = false; static Time next_motion_time = CurrentTime; @@ -1418,156 +1307,135 @@ static Time next_motion_time = CurrentTime; // 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 ) +static Bool motion_predicate(Display*, XEvent* ev, XPointer) { - if( ev->type == MotionNotify ) - { - was_motion = true; + 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 ) + 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 + XSync(display(), False); // this helps to discard more MotionNotify events XEvent dummy; - XCheckIfEvent( display(), &dummy, motion_predicate, NULL ); + 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 ) - { - foreach( Kephal::Screen* screen, Kephal::Screens::self()->screens() ) - { - if( screen->geom().contains( QPoint( xroot, yroot ))) - { - if( options->electricBorderTiling() && - xroot <= screen->geom().x() + 20 && - yroot > screen->geom().y() + screen->geom().height()/4 && - yroot < screen->geom().y() + screen->geom().height() - screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricLeftMode ); - setElectricBorderMaximizing( true ); +void Client::checkQuickTilingMaximizationZones(int xroot, int yroot) +{ + foreach (Kephal::Screen * screen, Kephal::Screens::self()->screens()) { + if (screen->geom().contains(QPoint(xroot, yroot))) { + if (options->electricBorderTiling() && + xroot <= screen->geom().x() + 20 && + yroot > screen->geom().y() + screen->geom().height() / 4 && + yroot < screen->geom().y() + screen->geom().height() - screen->geom().height() / 4) { + setElectricBorderMode(ElectricLeftMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderTiling() && - xroot <= screen->geom().x() + 20 && - yroot <= screen->geom().y() + screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricTopLeftMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderTiling() && + xroot <= screen->geom().x() + 20 && + yroot <= screen->geom().y() + screen->geom().height() / 4) { + setElectricBorderMode(ElectricTopLeftMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderTiling() && - xroot <= screen->geom().x() + 20 && - yroot >= screen->geom().y() + screen->geom().height() - screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricBottomLeftMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderTiling() && + xroot <= screen->geom().x() + 20 && + yroot >= screen->geom().y() + screen->geom().height() - screen->geom().height() / 4) { + setElectricBorderMode(ElectricBottomLeftMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderTiling() && - xroot >= screen->geom().x() + screen->geom().width() - 20 && - yroot > screen->geom().y() + screen->geom().height()/4 && - yroot < screen->geom().y() + screen->geom().height() - screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricRightMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderTiling() && + xroot >= screen->geom().x() + screen->geom().width() - 20 && + yroot > screen->geom().y() + screen->geom().height() / 4 && + yroot < screen->geom().y() + screen->geom().height() - screen->geom().height() / 4) { + setElectricBorderMode(ElectricRightMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderTiling() && - xroot >= screen->geom().x() + screen->geom().width() - 20 && - yroot <= screen->geom().y() + screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricTopRightMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderTiling() && + xroot >= screen->geom().x() + screen->geom().width() - 20 && + yroot <= screen->geom().y() + screen->geom().height() / 4) { + setElectricBorderMode(ElectricTopRightMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderTiling() && - xroot >= screen->geom().x() + screen->geom().width() - 20 && - yroot >= screen->geom().y() + screen->geom().height() - screen->geom().height()/4 ) - { - setElectricBorderMode( ElectricBottomRightMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderTiling() && + xroot >= screen->geom().x() + screen->geom().width() - 20 && + yroot >= screen->geom().y() + screen->geom().height() - screen->geom().height() / 4) { + setElectricBorderMode(ElectricBottomRightMode); + setElectricBorderMaximizing(true); return; - } - else if( options->electricBorderMaximize() && - yroot <= screen->geom().y() + 5 && isMaximizable() ) - { - setElectricBorderMode( ElectricMaximizeMode ); - setElectricBorderMaximizing( true ); + } else if (options->electricBorderMaximize() && + yroot <= screen->geom().y() + 5 && isMaximizable()) { + setElectricBorderMode(ElectricMaximizeMode); + setElectricBorderMaximizing(true); return; - } } } - setElectricBorderMaximizing( false ); } + setElectricBorderMaximizing(false); +} // 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()) +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 ) - { + 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()) - { + } + 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()) + 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 ) + if (e->mode == NotifyUngrab) return; // we don't care - if ( e->detail == NotifyPointer ) + if (e->detail == NotifyPointer) return; // we don't care - if( !isShown( false ) || !isOnCurrentDesktop()) // we unmapped it, but it got focus meanwhile -> + 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 - { + 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 @@ -1585,69 +1453,65 @@ void Client::focusInEvent( XFocusInEvent* e ) // 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 ) +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 + 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 ) + 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 ) - { +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 ); + XCheckIfEvent(display(), &dummy, predicate_follows_focusin, (XPointer)c); return follows_focusin; - } +} -void Client::focusOutEvent( XFocusOutEvent* e ) - { - if( e->window != window()) +void Client::focusOutEvent(XFocusOutEvent* e) +{ + if (e->window != window()) return; // only window gets focus - if ( e->mode == NotifyGrab ) + if (e->mode == NotifyGrab) return; // we don't care - if ( isShade() ) + if (isShade()) return; // here neither - if ( e->detail != NotifyNonlinear - && e->detail != NotifyNonlinearVirtual ) + if (e->detail != NotifyNonlinear + && e->detail != NotifyNonlinearVirtual) // SELI check all this return; // hack for motif apps like netscape - if ( QApplication::activePopupWidget() ) + if (QApplication::activePopupWidget()) return; - if( !check_follows_focusin( this )) - setActive( false ); - } + 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 ); +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[] = - { + } else if (direction >= NET::TopLeft && direction <= NET::Left) { + static const Position convert[] = { PositionTopLeft, PositionTop, PositionTopRight, @@ -1656,211 +1520,199 @@ void Client::NETMoveResize( int x_root, int y_root, NET::Direction direction ) PositionBottom, PositionBottomLeft, PositionLeft - }; - if(!isResizable() || isShade()) + }; + if (!isResizable() || isShade()) return; - if( moveResizeMode ) - finishMoveResize( false ); + if (moveResizeMode) + finishMoveResize(false); buttonDown = true; - moveOffset = QPoint( x_root - x(), y_root - y()); // map from global + moveOffset = QPoint(x_root - x(), y_root - y()); // map from global invertedMoveOffset = rect().bottomRight() - moveOffset; unrestrictedMoveResize = false; mode = convert[ direction ]; - if( !startMoveResize()) + 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()); - } + } 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 ) - { +void Client::keyPressEvent(uint key_code) +{ updateUserTime(); - if ( !isMove() && !isResize() ) + 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; + int delta = is_control ? 1 : is_alt ? 32 : 8; QPoint pos = cursorPos(); - switch ( key_code ) - { + switch(key_code) { case Qt::Key_Left: - pos.rx() -= delta; - break; + pos.rx() -= delta; + break; case Qt::Key_Right: - pos.rx() += delta; - break; + pos.rx() += delta; + break; case Qt::Key_Up: - pos.ry() -= delta; - break; + pos.ry() -= delta; + break; case Qt::Key_Down: - pos.ry() += delta; - break; + pos.ry() += delta; + break; case Qt::Key_Space: case Qt::Key_Return: case Qt::Key_Enter: - finishMoveResize( false ); - buttonDown = false; - updateCursor(); - break; + finishMoveResize(false); + buttonDown = false; + updateCursor(); + break; case Qt::Key_Escape: - finishMoveResize( true ); - buttonDown = false; - updateCursor(); - break; - default: - return; - } - QCursor::setPos( pos ); + finishMoveResize(true); + buttonDown = false; + updateCursor(); + break; + default: + return; } + QCursor::setPos(pos); +} #ifdef HAVE_XSYNC -void Client::syncEvent( XSyncAlarmNotifyEvent* e ) - { - if( e->alarm == sync_alarm && XSyncValueEqual( e->counter_value, sync_counter_value )) - { +void Client::syncEvent(XSyncAlarmNotifyEvent* e) +{ + if (e->alarm == sync_alarm && XSyncValueEqual(e->counter_value, sync_counter_value)) { ready_for_painting = true; - if( isResize()) - { + if (isResize()) { delete sync_timeout; sync_timeout = NULL; - if( sync_resize_pending ) + if (sync_resize_pending) performMoveResize(); sync_resize_pending = false; - } } } +} #endif // **************************************** // Unmanaged // **************************************** -bool Unmanaged::windowEvent( XEvent* e ) - { +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()) - { + info->event(e, dirty, 2); // pass through the NET stuff + if (dirty[ NETWinInfo::PROTOCOLS2 ] & NET::WM2Opacity) { + if (compositing()) { addRepaintFull(); - scene->windowOpacityChanged( this ); - if( effects ) - static_cast(effects)->windowOpacityChanged( effectWindow(), old_opacity ); - } + scene->windowOpacityChanged(this); + if (effects) + static_cast(effects)->windowOpacityChanged(effectWindow(), 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 + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), geometry()); } - 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 - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), geometry()); - } #ifdef HAVE_XDAMAGE - if( e->type == Extensions::damageNotifyEvent()) - damageNotifyEvent( reinterpret_cast< XDamageNotifyEvent* >( e )); + if (e->type == Extensions::damageNotifyEvent()) + damageNotifyEvent(reinterpret_cast< XDamageNotifyEvent* >(e)); #endif - break; - } - } + break; + } + } return false; // don't eat events, even our own unmanaged widgets are tracked - } +} -void Unmanaged::mapNotifyEvent( XMapEvent* ) - { - } +void Unmanaged::mapNotifyEvent(XMapEvent*) +{ +} -void Unmanaged::unmapNotifyEvent( XUnmapEvent* ) - { +void Unmanaged::unmapNotifyEvent(XUnmapEvent*) +{ release(); - } +} -void Unmanaged::configureNotifyEvent( XConfigureEvent* e ) - { - if( effects ) +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( geometry()); // damage old area + QRect newgeom(e->x, e->y, e->width, e->height); + if (newgeom != geom) { + addWorkspaceRepaint(geometry()); // damage old area QRect old = geom; geom = newgeom; addRepaintFull(); - if( old.size() != geom.size()) + if (old.size() != geom.size()) discardWindowPixmap(); - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), old ); - } + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), old); } +} // **************************************** // Toplevel // **************************************** -void Toplevel::propertyNotifyEvent( XPropertyEvent* e ) - { - if( e->window != window()) +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(); - break; - } - if( effects ) - static_cast< EffectsHandlerImpl* >( effects )->propertyNotify( effectWindow(), e->atom ); + switch(e->atom) { + default: + if (e->atom == atoms->wm_client_leader) + getWmClientLeader(); + else if (e->atom == atoms->wm_window_role) + getWindowRole(); + break; } + if (effects) + static_cast< EffectsHandlerImpl* >(effects)->propertyNotify(effectWindow(), e->atom); +} // **************************************** // Group // **************************************** -bool Group::groupEvent( XEvent* e ) - { +bool Group::groupEvent(XEvent* e) +{ unsigned long dirty[ 2 ]; - leader_info->event( e, dirty, 2 ); // pass through the NET stuff - if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0 ) + leader_info->event(e, dirty, 2); // pass through the NET stuff + if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0) getIcons(); - if(( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId ) != 0 ) + if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId) != 0) startupIdChanged(); return false; - } +} } // namespace diff --git a/geometry.cpp b/geometry.cpp index 131951c23..99e190b16 100644 --- a/geometry.cpp +++ b/geometry.cpp @@ -59,19 +59,19 @@ namespace KWin Resizes the workspace after an XRANDR screen size change */ void Workspace::desktopResized() - { +{ QRect geom = Kephal::ScreenUtils::desktopGeometry(); NETSize desktop_geometry; desktop_geometry.width = geom.width(); desktop_geometry.height = geom.height(); - rootInfo->setDesktopGeometry( -1, desktop_geometry ); + rootInfo->setDesktopGeometry(-1, desktop_geometry); updateClientArea(); destroyElectricBorders(); updateElectricBorders(); - if( compositing() ) - compositeResetTimer.start( 0 ); - } + if (compositing()) + compositeResetTimer.start(0); +} /*! Updates the current client areas according to the current clients. @@ -85,37 +85,34 @@ void Workspace::desktopResized() \sa clientArea() */ -void Workspace::updateClientArea( bool force ) - { +void Workspace::updateClientArea(bool force) +{ int nscreens = Kephal::ScreenUtils::numScreens(); kDebug(1212) << "screens: " << nscreens << "desktops: " << numberOfDesktops(); - QVector< QRect > new_wareas( numberOfDesktops() + 1 ); - QVector< StrutRects > new_rmoveareas( numberOfDesktops() + 1 ); - QVector< QVector< QRect > > new_sareas( numberOfDesktops() + 1 ); - QVector< QRect > screens( nscreens ); + QVector< QRect > new_wareas(numberOfDesktops() + 1); + QVector< StrutRects > new_rmoveareas(numberOfDesktops() + 1); + QVector< QVector< QRect > > new_sareas(numberOfDesktops() + 1); + QVector< QRect > screens(nscreens); QRect desktopArea = Kephal::ScreenUtils::desktopGeometry(); - for( int iS = 0; + for (int iS = 0; iS < nscreens; - iS ++ ) - { - screens [iS] = Kephal::ScreenUtils::screenGeometry( iS ); - } - for( int i = 1; + iS ++) { + screens [iS] = Kephal::ScreenUtils::screenGeometry(iS); + } + for (int i = 1; i <= numberOfDesktops(); - ++i ) - { + ++i) { new_wareas[ i ] = desktopArea; - new_sareas[ i ].resize( nscreens ); - for( int iS = 0; - iS < nscreens; - iS ++ ) + new_sareas[ i ].resize(nscreens); + for (int iS = 0; + iS < nscreens; + iS ++) new_sareas[ i ][ iS ] = screens[ iS ]; - } - for ( ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) - { - if( !(*it)->hasStrut()) + } + for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) { + if (!(*it)->hasStrut()) continue; - QRect r = (*it)->adjustedClientArea( desktopArea, desktopArea ); + QRect r = (*it)->adjustedClientArea(desktopArea, desktopArea); StrutRects strutRegion = (*it)->strutRects(); // Ignore offscreen xinerama struts. These interfere with the larger monitors on the setup @@ -126,121 +123,109 @@ void Workspace::updateClientArea( bool force ) // or having some content appear offscreen (Relatively rare compared to other). bool hasOffscreenXineramaStrut = (*it)->hasOffscreenXineramaStrut(); - if( (*it)->isOnAllDesktops()) - { - for( int i = 1; - i <= numberOfDesktops(); - ++i ) - { - if( !hasOffscreenXineramaStrut ) - new_wareas[ i ] = new_wareas[ i ].intersected( r ); + if ((*it)->isOnAllDesktops()) { + for (int i = 1; + i <= numberOfDesktops(); + ++i) { + if (!hasOffscreenXineramaStrut) + new_wareas[ i ] = new_wareas[ i ].intersected(r); new_rmoveareas[ i ] += strutRegion; - for( int iS = 0; - iS < nscreens; - iS ++ ) - { + for (int iS = 0; + iS < nscreens; + iS ++) { new_sareas[ i ][ iS ] = new_sareas[ i ][ iS ].intersected( - (*it)->adjustedClientArea( desktopArea, screens[ iS ] )); - } + (*it)->adjustedClientArea(desktopArea, screens[ iS ])); } } - else - { - if( !hasOffscreenXineramaStrut ) - new_wareas[ (*it)->desktop() ] = new_wareas[ (*it)->desktop() ].intersected( r ); - new_rmoveareas[ (*it)->desktop() ] += strutRegion; - for( int iS = 0; - iS < nscreens; - iS ++ ) - { + } else { + if (!hasOffscreenXineramaStrut) + new_wareas[(*it)->desktop()] = new_wareas[(*it)->desktop()].intersected(r); + new_rmoveareas[(*it)->desktop()] += strutRegion; + for (int iS = 0; + iS < nscreens; + iS ++) { // kDebug (1212) << "adjusting new_sarea: " << screens[ iS ]; - new_sareas[ (*it)->desktop() ][ iS ] - = new_sareas[ (*it)->desktop() ][ iS ].intersected( - (*it)->adjustedClientArea( desktopArea, screens[ iS ] )); - } + new_sareas[(*it)->desktop()][ iS ] + = new_sareas[(*it)->desktop()][ iS ].intersected( + (*it)->adjustedClientArea(desktopArea, screens[ iS ])); } } + } #if 0 - for( int i = 1; + for (int i = 1; i <= numberOfDesktops(); - ++i ) - { - for( int iS = 0; - iS < nscreens; - iS ++ ) - kDebug (1212) << "new_sarea: " << new_sareas[ i ][ iS ]; - } + ++i) { + for (int iS = 0; + iS < nscreens; + iS ++) + kDebug(1212) << "new_sarea: " << new_sareas[ i ][ iS ]; + } #endif // TODO topmenu update for screenarea changes? - if( topmenu_space != NULL ) - { + if (topmenu_space != NULL) { QRect topmenu_area = desktopArea; - topmenu_area.setTop( topMenuHeight()); - for( int i = 1; - i <= numberOfDesktops(); - ++i ) - { - new_wareas[ i ] = new_wareas[ i ].intersected( topmenu_area ); - new_rmoveareas[ i ] += StrutRect( topmenu_area ); - } + topmenu_area.setTop(topMenuHeight()); + for (int i = 1; + i <= numberOfDesktops(); + ++i) { + new_wareas[ i ] = new_wareas[ i ].intersected(topmenu_area); + new_rmoveareas[ i ] += StrutRect(topmenu_area); } + } bool changed = force; - if(screenarea.isEmpty()) + if (screenarea.isEmpty()) changed = true; - for( int i = 1; - !changed && i <= numberOfDesktops(); - ++i ) - { - if( workarea[ i ] != new_wareas[ i ] ) + for (int i = 1; + !changed && i <= numberOfDesktops(); + ++i) { + if (workarea[ i ] != new_wareas[ i ]) changed = true; - if( restrictedmovearea[ i ] != new_rmoveareas[ i ] ) + if (restrictedmovearea[ i ] != new_rmoveareas[ i ]) changed = true; - if( screenarea[ i ].size() != new_sareas[ i ].size()) + if (screenarea[ i ].size() != new_sareas[ i ].size()) changed = true; - for( int iS = 0; - !changed && iS < nscreens; - iS ++ ) + for (int iS = 0; + !changed && iS < nscreens; + iS ++) if (new_sareas[ i ][ iS ] != screenarea [ i ][ iS ]) changed = true; - } + } - if ( changed ) - { + if (changed) { workarea = new_wareas; oldrestrictedmovearea = restrictedmovearea; restrictedmovearea = new_rmoveareas; screenarea = new_sareas; NETRect r; - for( int i = 1; i <= numberOfDesktops(); i++) - { + for (int i = 1; i <= numberOfDesktops(); i++) { r.pos.x = workarea[ i ].x(); r.pos.y = workarea[ i ].y(); r.size.width = workarea[ i ].width(); r.size.height = workarea[ i ].height(); - rootInfo->setWorkArea( i, r ); - } + rootInfo->setWorkArea(i, r); + } updateTopMenuGeometry(); - for( ClientList::ConstIterator it = clients.constBegin(); - it != clients.constEnd(); - ++it) + for (ClientList::ConstIterator it = clients.constBegin(); + it != clients.constEnd(); + ++it) (*it)->checkWorkspacePosition(); - for( ClientList::ConstIterator it = desktops.constBegin(); - it != desktops.constEnd(); - ++it) + for (ClientList::ConstIterator it = desktops.constBegin(); + it != desktops.constEnd(); + ++it) (*it)->checkWorkspacePosition(); - } - - kDebug(1212) << "Done."; } + kDebug(1212) << "Done."; +} + void Workspace::updateClientArea() - { - updateClientArea( false ); - } +{ + updateClientArea(false); +} /*! @@ -250,89 +235,88 @@ void Workspace::updateClientArea() \sa geometry() */ -QRect Workspace::clientArea( clientAreaOption opt, int screen, int desktop ) const - { - if( desktop == NETWinInfo::OnAllDesktops || desktop == 0 ) +QRect Workspace::clientArea(clientAreaOption opt, int screen, int desktop) const +{ + if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = currentDesktop(); - if( screen == -1 ) + if (screen == -1) screen = activeScreen(); - - QRect sarea = (!screenarea.isEmpty() - && screen < screenarea[ desktop ].size()) // screens may be missing during KWin initialization or screen config changes - ? screenarea[ desktop ][ screen ] - : Kephal::ScreenUtils::screenGeometry( screen ); + + QRect sarea = (!screenarea.isEmpty() + && screen < screenarea[ desktop ].size()) // screens may be missing during KWin initialization or screen config changes + ? screenarea[ desktop ][ screen ] + : Kephal::ScreenUtils::screenGeometry(screen); QRect warea = workarea[ desktop ].isNull() - ? Kephal::ScreenUtils::desktopGeometry() - : workarea[ desktop ]; - switch (opt) - { - case MaximizeArea: - if (options->xineramaMaximizeEnabled) - return sarea; - else - return warea; - case MaximizeFullArea: - if (options->xineramaMaximizeEnabled) - return Kephal::ScreenUtils::screenGeometry( screen ); - else - return Kephal::ScreenUtils::desktopGeometry(); - case FullScreenArea: - if (options->xineramaFullscreenEnabled) - return Kephal::ScreenUtils::screenGeometry( screen ); - else - return Kephal::ScreenUtils::desktopGeometry(); - case PlacementArea: - if (options->xineramaPlacementEnabled) - return sarea; - else - return warea; - case MovementArea: - if (options->xineramaMovementEnabled) - return Kephal::ScreenUtils::screenGeometry( screen ); - else - return Kephal::ScreenUtils::desktopGeometry(); - case WorkArea: + ? Kephal::ScreenUtils::desktopGeometry() + : workarea[ desktop ]; + switch(opt) { + case MaximizeArea: + if (options->xineramaMaximizeEnabled) + return sarea; + else return warea; - case FullArea: + case MaximizeFullArea: + if (options->xineramaMaximizeEnabled) + return Kephal::ScreenUtils::screenGeometry(screen); + else return Kephal::ScreenUtils::desktopGeometry(); - case ScreenArea: - return Kephal::ScreenUtils::screenGeometry( screen ); - } + case FullScreenArea: + if (options->xineramaFullscreenEnabled) + return Kephal::ScreenUtils::screenGeometry(screen); + else + return Kephal::ScreenUtils::desktopGeometry(); + case PlacementArea: + if (options->xineramaPlacementEnabled) + return sarea; + else + return warea; + case MovementArea: + if (options->xineramaMovementEnabled) + return Kephal::ScreenUtils::screenGeometry(screen); + else + return Kephal::ScreenUtils::desktopGeometry(); + case WorkArea: + return warea; + case FullArea: + return Kephal::ScreenUtils::desktopGeometry(); + case ScreenArea: + return Kephal::ScreenUtils::screenGeometry(screen); + } abort(); - } +} -QRect Workspace::clientArea( clientAreaOption opt, const QPoint& p, int desktop ) const - { - int screen = Kephal::ScreenUtils::screenId( p ); - return clientArea( opt, screen, desktop ); - } +QRect Workspace::clientArea(clientAreaOption opt, const QPoint& p, int desktop) const +{ + int screen = Kephal::ScreenUtils::screenId(p); + return clientArea(opt, screen, desktop); +} -QRect Workspace::clientArea( clientAreaOption opt, const Client* c ) const - { - return clientArea( opt, c->geometry().center(), c->desktop()); - } +QRect Workspace::clientArea(clientAreaOption opt, const Client* c) const +{ + return clientArea(opt, c->geometry().center(), c->desktop()); +} -QRegion Workspace::restrictedMoveArea( int desktop, StrutAreas areas ) const - { - if( desktop == NETWinInfo::OnAllDesktops || desktop == 0 ) +QRegion Workspace::restrictedMoveArea(int desktop, StrutAreas areas) const +{ + if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = currentDesktop(); QRegion region; - foreach( const StrutRect& rect, restrictedmovearea[desktop] ) - if( areas & rect.area() ) - region += rect; + foreach (const StrutRect & rect, restrictedmovearea[desktop]) + if (areas & rect.area()) + region += rect; return region; - } +} -QRegion Workspace::previousRestrictedMoveArea( int desktop, StrutAreas areas ) const - { - if( desktop == NETWinInfo::OnAllDesktops || desktop == 0 ) +QRegion Workspace::previousRestrictedMoveArea(int desktop, StrutAreas areas) const +{ + if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = currentDesktop(); QRegion region; - foreach( const StrutRect& rect, oldrestrictedmovearea.at(desktop) ) - if( areas & rect.area() ) - region += rect; + foreach (const StrutRect & rect, oldrestrictedmovearea.at(desktop)) + if (areas & rect.area()) + region += rect; return region; - } +} /*! Client \a c is moved around to position \a pos. This gives the @@ -343,26 +327,25 @@ QRegion Workspace::previousRestrictedMoveArea( int desktop, StrutAreas areas ) c effective snap zones. When 1.0, it means that the snap zones will be used without change. */ -QPoint Workspace::adjustClientPosition( Client* c, QPoint pos, bool unrestricted, double snapAdjust ) - { - //CT 16mar98, 27May98 - magics: BorderSnapZone, WindowSnapZone - //CT adapted for kwin on 25Nov1999 - //aleXXX 02Nov2000 added second snapping mode - if (options->windowSnapZone || options->borderSnapZone || options->centerSnapZone ) - { - const bool sOWO=options->snapOnlyWhenOverlapping; - const QRect maxRect = clientArea(MovementArea, pos+c->rect().center(), c->desktop()); +QPoint Workspace::adjustClientPosition(Client* c, QPoint pos, bool unrestricted, double snapAdjust) +{ + //CT 16mar98, 27May98 - magics: BorderSnapZone, WindowSnapZone + //CT adapted for kwin on 25Nov1999 + //aleXXX 02Nov2000 added second snapping mode + if (options->windowSnapZone || options->borderSnapZone || options->centerSnapZone) { + const bool sOWO = options->snapOnlyWhenOverlapping; + const QRect maxRect = clientArea(MovementArea, pos + c->rect().center(), c->desktop()); const int xmin = maxRect.left(); - const int xmax = maxRect.right()+1; //desk size + const int xmax = maxRect.right() + 1; //desk size const int ymin = maxRect.top(); - const int ymax = maxRect.bottom()+1; + const int ymax = maxRect.bottom() + 1; const int cx(pos.x()); const int cy(pos.y()); const int cw(c->width()); const int ch(c->height()); - const int rx(cx+cw); - const int ry(cy+ch); //these don't change + const int rx(cx + cw); + const int ry(cy + ch); //these don't change int nx(cx), ny(cy); //buffers int deltaX(xmax); @@ -370,157 +353,133 @@ QPoint Workspace::adjustClientPosition( Client* c, QPoint pos, bool unrestricted int lx, ly, lrx, lry; //coords and size for the comparison client, l - // border snap + // border snap int snap = options->borderSnapZone * snapAdjust; //snap trigger - if (snap) - { - if ((sOWO?(cxxmax):true) && (qAbs(rx-xmax) xmax) : true) && (qAbs(rx - xmax) < snap) && (qAbs(xmax - rx) < deltaX)) { + deltaX = rx - xmax; nx = xmax - cw; - } - - if ((sOWO?(cyymax):true) && (qAbs(ry-ymax) ymax) : true) && (qAbs(ry - ymax) < snap) && (qAbs(ymax - ry) < deltaY)) { + deltaY = ry - ymax; + ny = ymax - ch; + } + } + + // windows snap snap = options->windowSnapZone * snapAdjust; - if (snap) - { + if (snap) { QList::ConstIterator l; - for (l = clients.constBegin();l != clients.constEnd();++l ) - { + for (l = clients.constBegin(); l != clients.constEnd(); ++l) { if ((((*l)->isOnDesktop(c->desktop()) && !(*l)->isMinimized()) - || (c->isOnDesktop(NET::OnAllDesktops) && (*l)->isOnDesktop(Workspace::currentDesktop()) - && !(*l)->isMinimized())) - && (!(*l)->clientGroup() || (*l) == (*l)->clientGroup()->visible()) - && (*l) != c ) - { + || (c->isOnDesktop(NET::OnAllDesktops) && (*l)->isOnDesktop(Workspace::currentDesktop()) + && !(*l)->isMinimized())) + && (!(*l)->clientGroup() || (*l) == (*l)->clientGroup()->visible()) + && (*l) != c) { lx = (*l)->x(); ly = (*l)->y(); lrx = lx + (*l)->width(); lry = ly + (*l)->height(); - if ( (( cy <= lry ) && ( cy >= ly )) || - (( ry >= ly ) && ( ry <= lry )) || - (( cy <= ly ) && ( ry >= lry )) ) - { - if ((sOWO?(cx= ly)) || + ((ry >= ly) && (ry <= lry)) || + ((cy <= ly) && (ry >= lry))) { + if ((sOWO ? (cx < lrx) : true) && (qAbs(lrx - cx) < snap) && (qAbs(lrx - cx) < deltaX)) { + deltaX = qAbs(lrx - cx); nx = lrx; - } - if ((sOWO?(rx>lx):true) && (qAbs(rx-lx) lx) : true) && (qAbs(rx - lx) < snap) && (qAbs(rx - lx) < deltaX)) { deltaX = qAbs(rx - lx); nx = lx - cw; - } } + } - if ( (( cx <= lrx ) && ( cx >= lx )) || - (( rx >= lx ) && ( rx <= lrx )) || - (( cx <= lx ) && ( rx >= lrx )) ) - { - if ((sOWO?(cy= lx)) || + ((rx >= lx) && (rx <= lrx)) || + ((cx <= lx) && (rx >= lrx))) { + if ((sOWO ? (cy < lry) : true) && (qAbs(lry - cy) < snap) && (qAbs(lry - cy) < deltaY)) { + deltaY = qAbs(lry - cy); ny = lry; - } - //if ( (qAbs( ry-ly ) < snap) && (qAbs( ry - ly ) < deltaY )) - if ((sOWO?(ry>ly):true) && (qAbs(ry-ly) ly) : true) && (qAbs(ry - ly) < snap) && (qAbs(ry - ly) < deltaY)) { + deltaY = qAbs(ry - ly); + ny = ly - ch; + } + } // Corner snapping - if( nx == lrx || nx+cw == lx ) - { - if ((sOWO?(ry>lry):true) && (qAbs(lry-ry) lry) : true) && (qAbs(lry - ry) < snap) && (qAbs(lry - ry) < deltaY)) { + deltaY = qAbs(lry - ry); ny = lry - ch; - } - if ((sOWO?(cylrx):true) && (qAbs(lrx-rx) lrx) : true) && (qAbs(lrx - rx) < snap) && (qAbs(lrx - rx) < deltaX)) { + deltaX = qAbs(lrx - rx); nx = lrx - cw; - } - if ((sOWO?(cxcenterSnapZone * snapAdjust; //snap trigger - if (snap) - { - int diffX = qAbs( (xmin + xmax)/2 - (cx + cw/2) ); - int diffY = qAbs( (ymin + ymax)/2 - (cy + ch/2) ); - if (diffX < snap && diffY < snap && diffX < deltaX && diffY < deltaY) - { // Snap to center of screen + if (snap) { + int diffX = qAbs((xmin + xmax) / 2 - (cx + cw / 2)); + int diffY = qAbs((ymin + ymax) / 2 - (cy + ch / 2)); + if (diffX < snap && diffY < snap && diffX < deltaX && diffY < deltaY) { + // Snap to center of screen deltaX = diffX; deltaY = diffY; - nx = (xmin + xmax)/2 - cw/2; - ny = (ymin + ymax)/2 - ch/2; - } - else if ( options->borderSnapZone ) - { // Enhance border snap - if( ( nx == xmin || nx == xmax - cw ) && diffY < snap && diffY < deltaY) - { // Snap to vertical center on screen edge + nx = (xmin + xmax) / 2 - cw / 2; + ny = (ymin + ymax) / 2 - ch / 2; + } else if (options->borderSnapZone) { + // Enhance border snap + if ((nx == xmin || nx == xmax - cw) && diffY < snap && diffY < deltaY) { + // Snap to vertical center on screen edge deltaY = diffY; - ny = (ymin + ymax)/2 - ch/2; - } - else if ( (( unrestricted ? ny == ymin : ny <= ymin) || ny == ymax - ch ) && - diffX < snap && diffX < deltaX) - { // Snap to horizontal center on screen edge + ny = (ymin + ymax) / 2 - ch / 2; + } else if (((unrestricted ? ny == ymin : ny <= ymin) || ny == ymax - ch) && + diffX < snap && diffX < deltaX) { + // Snap to horizontal center on screen edge deltaX = diffX; - nx = (xmin + xmax)/2 - cw/2; - } + nx = (xmin + xmax) / 2 - cw / 2; } } + } pos = QPoint(nx, ny); - } - return pos; } + return pos; +} -QRect Workspace::adjustClientSize( Client* c, QRect moveResizeGeom, int mode ) - { - //adapted from adjustClientPosition on 29May2004 - //this function is called when resizing a window and will modify - //the new dimensions to snap to other windows/borders if appropriate - if ( options->windowSnapZone || options->borderSnapZone ) // || options->centerSnapZone ) - { - const bool sOWO=options->snapOnlyWhenOverlapping; +QRect Workspace::adjustClientSize(Client* c, QRect moveResizeGeom, int mode) +{ + //adapted from adjustClientPosition on 29May2004 + //this function is called when resizing a window and will modify + //the new dimensions to snap to other windows/borders if appropriate + if (options->windowSnapZone || options->borderSnapZone) { // || options->centerSnapZone ) + const bool sOWO = options->snapOnlyWhenOverlapping; const QRect maxRect = clientArea(MovementArea, c->rect().center(), c->desktop()); const int xmin = maxRect.left(); @@ -540,212 +499,206 @@ QRect Workspace::adjustClientSize( Client* c, QRect moveResizeGeom, int mode ) int lx, ly, lrx, lry; //coords and size for the comparison client, l - // border snap + // border snap int snap = options->borderSnapZone; //snap trigger - if (snap) - { + if (snap) { deltaX = int(snap); deltaY = int(snap); #define SNAP_BORDER_TOP \ - if ((sOWO?(newcyymax):true) && (qAbs(ymax-newry)ymax):true) && (qAbs(ymax-newry)xmax):true) && (qAbs(xmax-newrx)xmax):true) && (qAbs(xmax-newrx)windowSnapZone; - if (snap) - { + if (snap) { deltaX = int(snap); deltaY = int(snap); QList::ConstIterator l; - for (l = clients.constBegin();l != clients.constEnd();++l ) - { + for (l = clients.constBegin(); l != clients.constEnd(); ++l) { if ((*l)->isOnDesktop(currentDesktop()) && - !(*l)->isMinimized() - && (*l) != c ) - { - lx = (*l)->x()-1; - ly = (*l)->y()-1; - lrx =(*l)->x() + (*l)->width(); - lry =(*l)->y() + (*l)->height(); + !(*l)->isMinimized() + && (*l) != c) { + lx = (*l)->x() - 1; + ly = (*l)->y() - 1; + lrx = (*l)->x() + (*l)->width(); + lry = (*l)->y() + (*l)->height(); #define WITHIN_HEIGHT ((( newcy <= lry ) && ( newcy >= ly )) || \ - (( newry >= ly ) && ( newry <= lry )) || \ - (( newcy <= ly ) && ( newry >= lry )) ) + (( newry >= ly ) && ( newry <= lry )) || \ + (( newcy <= ly ) && ( newry >= lry )) ) #define WITHIN_WIDTH ( (( cx <= lrx ) && ( cx >= lx )) || \ - (( rx >= lx ) && ( rx <= lrx )) || \ - (( cx <= lx ) && ( rx >= lrx )) ) + (( rx >= lx ) && ( rx <= lrx )) || \ + (( cx <= lx ) && ( rx >= lrx )) ) #define SNAP_WINDOW_TOP if ( (sOWO?(newcyly):true) \ - && WITHIN_WIDTH \ - && (qAbs( ly - newry ) < deltaY) ) { \ - deltaY = qAbs( ly - newry ); \ - newry=ly; \ - } + && WITHIN_WIDTH \ + && (qAbs( ly - newry ) < deltaY) ) { \ + deltaY = qAbs( ly - newry ); \ + newry=ly; \ +} #define SNAP_WINDOW_LEFT if ( (sOWO?(newcxlx):true) \ - && WITHIN_HEIGHT \ - && (qAbs( lx - newrx ) < deltaX)) \ - { \ - deltaX = qAbs( lx - newrx ); \ - newrx=lx; \ - } + && WITHIN_HEIGHT \ + && (qAbs( lx - newrx ) < deltaX)) \ +{ \ + deltaX = qAbs( lx - newrx ); \ + newrx=lx; \ +} #define SNAP_WINDOW_C_TOP if ( (sOWO?(newcylry):true) \ - && (newcx == lrx || newrx == lx) \ - && qAbs(lry-newry) < deltaY ) { \ - deltaY = qAbs( lry - newry - 1 ); \ - newry = lry - 1; \ - } + && (newcx == lrx || newrx == lx) \ + && qAbs(lry-newry) < deltaY ) { \ + deltaY = qAbs( lry - newry - 1 ); \ + newry = lry - 1; \ +} #define SNAP_WINDOW_C_LEFT if ( (sOWO?(newcxlrx):true) \ - && (newcy == lry || newry == ly) \ - && qAbs(lrx-newrx) < deltaX ) { \ - deltaX = qAbs( lrx - newrx - 1 ); \ - newrx = lrx - 1; \ - } + && (newcy == lry || newry == ly) \ + && qAbs(lrx-newrx) < deltaX ) { \ + deltaX = qAbs( lrx - newrx - 1 ); \ + newrx = lrx - 1; \ +} - switch ( mode ) - { - case PositionBottomRight: + switch(mode) { + case PositionBottomRight: SNAP_WINDOW_BOTTOM SNAP_WINDOW_RIGHT SNAP_WINDOW_C_BOTTOM SNAP_WINDOW_C_RIGHT break; - case PositionRight: + case PositionRight: SNAP_WINDOW_RIGHT SNAP_WINDOW_C_RIGHT break; - case PositionBottom: + case PositionBottom: SNAP_WINDOW_BOTTOM SNAP_WINDOW_C_BOTTOM break; - case PositionTopLeft: + case PositionTopLeft: SNAP_WINDOW_TOP SNAP_WINDOW_LEFT SNAP_WINDOW_C_TOP SNAP_WINDOW_C_LEFT break; - case PositionLeft: + case PositionLeft: SNAP_WINDOW_LEFT SNAP_WINDOW_C_LEFT break; - case PositionTop: + case PositionTop: SNAP_WINDOW_TOP SNAP_WINDOW_C_TOP break; - case PositionTopRight: + case PositionTopRight: SNAP_WINDOW_TOP SNAP_WINDOW_RIGHT SNAP_WINDOW_C_TOP SNAP_WINDOW_C_RIGHT break; - case PositionBottomLeft: + case PositionBottomLeft: SNAP_WINDOW_BOTTOM SNAP_WINDOW_LEFT SNAP_WINDOW_C_BOTTOM SNAP_WINDOW_C_LEFT break; - default: + default: abort(); break; - } } } } + } - // center snap + // center snap //snap = options->centerSnapZone; //if (snap) // { @@ -755,16 +708,16 @@ QRect Workspace::adjustClientSize( Client* c, QRect moveResizeGeom, int mode ) // // 2) Snap to the horizontal and vertical center lines of the screen // } - moveResizeGeom = QRect(QPoint(newcx, newcy), QPoint(newrx, newry)); - } - return moveResizeGeom; + moveResizeGeom = QRect(QPoint(newcx, newcy), QPoint(newrx, newry)); } + return moveResizeGeom; +} /*! Marks the client as being moved around by the user. */ -void Workspace::setClientIsMoving( Client *c ) - { +void Workspace::setClientIsMoving(Client *c) +{ Q_ASSERT(!c || !movingClient); // Catch attempts to move a second // window while still moving the first one. movingClient = c; @@ -772,57 +725,54 @@ void Workspace::setClientIsMoving( Client *c ) ++block_focus; else --block_focus; - } +} /*! Cascades all clients on the current desktop */ void Workspace::cascadeDesktop() - { +{ // TODO XINERAMA this probably is not right for xinerama - Q_ASSERT( block_stacking_updates == 0 ); - initPositioning->reinitCascading( currentDesktop()); - QRect area = clientArea( PlacementArea, QPoint( 0, 0 ), currentDesktop()); - foreach( Client* client, stackingOrder() ) - { - if((!client->isOnDesktop(currentDesktop())) || - (client->isMinimized()) || - (client->isOnAllDesktops()) || - (!client->isMovable()) ) + Q_ASSERT(block_stacking_updates == 0); + initPositioning->reinitCascading(currentDesktop()); + QRect area = clientArea(PlacementArea, QPoint(0, 0), currentDesktop()); + foreach (Client * client, stackingOrder()) { + if ((!client->isOnDesktop(currentDesktop())) || + (client->isMinimized()) || + (client->isOnAllDesktops()) || + (!client->isMovable())) continue; initPositioning->placeCascaded(client, area); - } } +} /*! Unclutters the current desktop by smart-placing all clients again. */ void Workspace::unclutterDesktop() - { - for ( int i = clients.size() - 1; i>=0; i-- ) - { - if( ( !clients.at( i )->isOnDesktop( currentDesktop() ) ) || - (clients.at( i )->isMinimized()) || - (clients.at( i )->isOnAllDesktops()) || - (!clients.at( i )->isMovable()) ) +{ + for (int i = clients.size() - 1; i >= 0; i--) { + if ((!clients.at(i)->isOnDesktop(currentDesktop())) || + (clients.at(i)->isMinimized()) || + (clients.at(i)->isOnAllDesktops()) || + (!clients.at(i)->isMovable())) continue; - initPositioning->placeSmart(clients.at( i ), QRect()); - } + initPositioning->placeSmart(clients.at(i), QRect()); } +} -void Workspace::updateTopMenuGeometry( Client* c ) - { - if( !managingTopMenus()) +void Workspace::updateTopMenuGeometry(Client* c) +{ + if (!managingTopMenus()) return; - if( c != NULL ) - { + if (c != NULL) { XEvent ev; ev.xclient.display = display(); ev.xclient.type = ClientMessage; ev.xclient.window = c->window(); - static Atom msg_type_atom = XInternAtom( display(), "_KDE_TOPMENU_MINSIZE", False ); + static Atom msg_type_atom = XInternAtom(display(), "_KDE_TOPMENU_MINSIZE", False); ev.xclient.message_type = msg_type_atom; ev.xclient.format = 32; ev.xclient.data.l[0] = xTime(); @@ -830,68 +780,66 @@ void Workspace::updateTopMenuGeometry( Client* c ) ev.xclient.data.l[2] = topmenu_space->height(); ev.xclient.data.l[3] = 0; ev.xclient.data.l[4] = 0; - XSendEvent( display(), c->window(), False, NoEventMask, &ev ); - KWindowSystem::setStrut( c->window(), 0, 0, topmenu_height, 0 ); // so that kicker etc. know + XSendEvent(display(), c->window(), False, NoEventMask, &ev); + KWindowSystem::setStrut(c->window(), 0, 0, topmenu_height, 0); // so that kicker etc. know c->checkWorkspacePosition(); return; - } + } // c == NULL - update all, including topmenu_space QRect area; - area = clientArea( MaximizeFullArea, QPoint( 0, 0 ), 1 ); // HACK desktop ? - area.setHeight( topMenuHeight()); - topmenu_space->setGeometry( area ); - for( ClientList::ConstIterator it = topmenus.constBegin(); - it != topmenus.constEnd(); - ++it ) - updateTopMenuGeometry( *it ); - } + area = clientArea(MaximizeFullArea, QPoint(0, 0), 1); // HACK desktop ? + area.setHeight(topMenuHeight()); + topmenu_space->setGeometry(area); + for (ClientList::ConstIterator it = topmenus.constBegin(); + it != topmenus.constEnd(); + ++it) + updateTopMenuGeometry(*it); +} // When kwin crashes, windows will not be gravitated back to their original position // and will remain offset by the size of the decoration. So when restarting, fix this // (the property with the size of the frame remains on the window after the crash). -void Workspace::fixPositionAfterCrash( Window w, const XWindowAttributes& attr ) - { - NETWinInfo i( display(), w, rootWindow(), NET::WMFrameExtents ); +void Workspace::fixPositionAfterCrash(Window w, const XWindowAttributes& attr) +{ + NETWinInfo i(display(), w, rootWindow(), NET::WMFrameExtents); NETStrut frame = i.frameExtents(); - if( frame.left != 0 || frame.top != 0 ) - XMoveWindow( display(), w, attr.x - frame.left, attr.y - frame.top ); - } + if (frame.left != 0 || frame.top != 0) + XMoveWindow(display(), w, attr.x - frame.left, attr.y - frame.top); +} //******************************************** // Client //******************************************** -void Client::keepInArea( QRect area, bool partial ) - { - if( partial ) - { +void Client::keepInArea(QRect area, bool partial) +{ + if (partial) { // increase the area so that can have only 100 pixels in the area - area.setLeft( qMin( area.left() - width() + 100, area.left())); - area.setTop( qMin( area.top() - height() + 100, area.top())); - area.setRight( qMax( area.right() + width() - 100, area.right())); - area.setBottom( qMax( area.bottom() + height() - 100, area.bottom())); - } - if( !partial ) - { // resize to fit into area - if( area.width() < width() || area.height() < height()) - resizeWithChecks( qMin( area.width(), width()), qMin( area.height(), height())); - } - if ( geometry().right() > area.right() && width() < area.width() ) - move( area.right() - width() + 1, y() ); - if ( geometry().bottom() > area.bottom() && height() < area.height() ) - move( x(), area.bottom() - height() + 1 ); - if( !area.contains( geometry().topLeft() )) - { + area.setLeft(qMin(area.left() - width() + 100, area.left())); + area.setTop(qMin(area.top() - height() + 100, area.top())); + area.setRight(qMax(area.right() + width() - 100, area.right())); + area.setBottom(qMax(area.bottom() + height() - 100, area.bottom())); + } + if (!partial) { + // resize to fit into area + if (area.width() < width() || area.height() < height()) + resizeWithChecks(qMin(area.width(), width()), qMin(area.height(), height())); + } + if (geometry().right() > area.right() && width() < area.width()) + move(area.right() - width() + 1, y()); + if (geometry().bottom() > area.bottom() && height() < area.height()) + move(x(), area.bottom() - height() + 1); + if (!area.contains(geometry().topLeft())) { int tx = x(); int ty = y(); - if ( tx < area.x() ) + if (tx < area.x()) tx = area.x(); - if ( ty < area.y() ) + if (ty < area.y()) ty = area.y(); - move( tx, ty ); - } + move(tx, ty); } +} /*! Returns \a area with the client's strut taken into account. @@ -900,353 +848,334 @@ void Client::keepInArea( QRect area, bool partial ) */ // TODO move to Workspace? -QRect Client::adjustedClientArea( const QRect &desktopArea, const QRect& area ) const - { +QRect Client::adjustedClientArea(const QRect &desktopArea, const QRect& area) const +{ QRect r = area; // topmenu area is reserved in updateClientArea() - if( isTopMenu()) + if (isTopMenu()) return r; NETExtendedStrut str = strut(); QRect stareaL = QRect( - 0, - str . left_start, - str . left_width, - str . left_end - str . left_start + 1 ); - QRect stareaR = QRect ( - desktopArea . right () - str . right_width + 1, - str . right_start, - str . right_width, - str . right_end - str . right_start + 1 ); - QRect stareaT = QRect ( - str . top_start, - 0, - str . top_end - str . top_start + 1, - str . top_width); - QRect stareaB = QRect ( - str . bottom_start, - desktopArea . bottom () - str . bottom_width + 1, - str . bottom_end - str . bottom_start + 1, - str . bottom_width); + 0, + str . left_start, + str . left_width, + str . left_end - str . left_start + 1); + QRect stareaR = QRect( + desktopArea . right() - str . right_width + 1, + str . right_start, + str . right_width, + str . right_end - str . right_start + 1); + QRect stareaT = QRect( + str . top_start, + 0, + str . top_end - str . top_start + 1, + str . top_width); + QRect stareaB = QRect( + str . bottom_start, + desktopArea . bottom() - str . bottom_width + 1, + str . bottom_end - str . bottom_start + 1, + str . bottom_width); - QRect screenarea = workspace()->clientArea( ScreenArea, this ); + QRect screenarea = workspace()->clientArea(ScreenArea, this); // HACK: workarea handling is not xinerama aware, so if this strut // reserves place at a xinerama edge that's inside the virtual screen, // ignore the strut for workspace setting. - if( area == Kephal::ScreenUtils::desktopGeometry()) - { - if( stareaL.left() < screenarea.left()) + if (area == Kephal::ScreenUtils::desktopGeometry()) { + if (stareaL.left() < screenarea.left()) stareaL = QRect(); - if( stareaR.right() > screenarea.right()) + if (stareaR.right() > screenarea.right()) stareaR = QRect(); - if( stareaT.top() < screenarea.top()) + if (stareaT.top() < screenarea.top()) stareaT = QRect(); - if( stareaB.bottom() < screenarea.bottom()) + if (stareaB.bottom() < screenarea.bottom()) stareaB = QRect(); - } + } // Handle struts at xinerama edges that are inside the virtual screen. // They're given in virtual screen coordinates, make them affect only // their xinerama screen. - stareaL.setLeft( qMax( stareaL.left(), screenarea.left())); - stareaR.setRight( qMin( stareaR.right(), screenarea.right())); - stareaT.setTop( qMax( stareaT.top(), screenarea.top())); - stareaB.setBottom( qMin( stareaB.bottom(), screenarea.bottom())); + stareaL.setLeft(qMax(stareaL.left(), screenarea.left())); + stareaR.setRight(qMin(stareaR.right(), screenarea.right())); + stareaT.setTop(qMax(stareaT.top(), screenarea.top())); + stareaB.setBottom(qMin(stareaB.bottom(), screenarea.bottom())); - if (stareaL . intersects (area)) { + if (stareaL . intersects(area)) { // kDebug (1212) << "Moving left of: " << r << " to " << stareaL.right() + 1; - r . setLeft( stareaL . right() + 1 ); + r . setLeft(stareaL . right() + 1); } - if (stareaR . intersects (area)) { + if (stareaR . intersects(area)) { // kDebug (1212) << "Moving right of: " << r << " to " << stareaR.left() - 1; - r . setRight( stareaR . left() - 1 ); + r . setRight(stareaR . left() - 1); } - if (stareaT . intersects (area)) { + if (stareaT . intersects(area)) { // kDebug (1212) << "Moving top of: " << r << " to " << stareaT.bottom() + 1; - r . setTop( stareaT . bottom() + 1 ); + r . setTop(stareaT . bottom() + 1); } - if (stareaB . intersects (area)) { + if (stareaB . intersects(area)) { // kDebug (1212) << "Moving bottom of: " << r << " to " << stareaB.top() - 1; - r . setBottom( stareaB . top() - 1 ); + r . setBottom(stareaB . top() - 1); } return r; - } +} NETExtendedStrut Client::strut() const - { +{ NETExtendedStrut ext = info->extendedStrut(); NETStrut str = info->strut(); - if( ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0 - && ( str.left != 0 || str.right != 0 || str.top != 0 || str.bottom != 0 )) - { + if (ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0 + && (str.left != 0 || str.right != 0 || str.top != 0 || str.bottom != 0)) { // build extended from simple - if( str.left != 0 ) - { + if (str.left != 0) { ext.left_width = str.left; ext.left_start = 0; ext.left_end = displayHeight(); - } - if( str.right != 0 ) - { + } + if (str.right != 0) { ext.right_width = str.right; ext.right_start = 0; ext.right_end = displayHeight(); - } - if( str.top != 0 ) - { + } + if (str.top != 0) { ext.top_width = str.top; ext.top_start = 0; ext.top_end = displayWidth(); - } - if( str.bottom != 0 ) - { + } + if (str.bottom != 0) { ext.bottom_width = str.bottom; ext.bottom_start = 0; ext.bottom_end = displayWidth(); - } } + } return ext; - } +} -StrutRect Client::strutRect( StrutArea area ) const - { - assert( area != StrutAreaAll ); // Not valid +StrutRect Client::strutRect(StrutArea area) const +{ + assert(area != StrutAreaAll); // Not valid NETExtendedStrut strutArea = strut(); - switch( area ) - { - case StrutAreaTop: - if( strutArea.top_width != 0 ) - return StrutRect( QRect( - strutArea.top_start, 0, - strutArea.top_end - strutArea.top_start, strutArea.top_width - ), StrutAreaTop ); - break; - case StrutAreaRight: - if( strutArea.right_width != 0 ) - return StrutRect( QRect( - displayWidth() - strutArea.right_width, strutArea.right_start, - strutArea.right_width, strutArea.right_end - strutArea.right_start - ), StrutAreaRight ); - break; - case StrutAreaBottom: - if( strutArea.bottom_width != 0 ) - return StrutRect( QRect( - strutArea.bottom_start, displayHeight() - strutArea.bottom_width, - strutArea.bottom_end - strutArea.bottom_start, strutArea.bottom_width - ), StrutAreaBottom ); - break; - case StrutAreaLeft: - if( strutArea.left_width != 0 ) - return StrutRect( QRect( - 0, strutArea.left_start, - strutArea.left_width, strutArea.left_end - strutArea.left_start - ), StrutAreaLeft ); - break; - default: - abort(); // Not valid - } - return StrutRect(); // Null rect + switch(area) { + case StrutAreaTop: + if (strutArea.top_width != 0) + return StrutRect(QRect( + strutArea.top_start, 0, + strutArea.top_end - strutArea.top_start, strutArea.top_width + ), StrutAreaTop); + break; + case StrutAreaRight: + if (strutArea.right_width != 0) + return StrutRect(QRect( + displayWidth() - strutArea.right_width, strutArea.right_start, + strutArea.right_width, strutArea.right_end - strutArea.right_start + ), StrutAreaRight); + break; + case StrutAreaBottom: + if (strutArea.bottom_width != 0) + return StrutRect(QRect( + strutArea.bottom_start, displayHeight() - strutArea.bottom_width, + strutArea.bottom_end - strutArea.bottom_start, strutArea.bottom_width + ), StrutAreaBottom); + break; + case StrutAreaLeft: + if (strutArea.left_width != 0) + return StrutRect(QRect( + 0, strutArea.left_start, + strutArea.left_width, strutArea.left_end - strutArea.left_start + ), StrutAreaLeft); + break; + default: + abort(); // Not valid } + return StrutRect(); // Null rect +} StrutRects Client::strutRects() const - { +{ StrutRects region; - region += strutRect( StrutAreaTop ); - region += strutRect( StrutAreaRight ); - region += strutRect( StrutAreaBottom ); - region += strutRect( StrutAreaLeft ); + region += strutRect(StrutAreaTop); + region += strutRect(StrutAreaRight); + region += strutRect(StrutAreaBottom); + region += strutRect(StrutAreaLeft); return region; - } +} bool Client::hasStrut() const - { +{ NETExtendedStrut ext = strut(); - if( ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0 ) + if (ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0) return false; return true; - } +} bool Client::hasOffscreenXineramaStrut() const - { +{ // Get strut as a QRegion QRegion region; - region += strutRect( StrutAreaTop ); - region += strutRect( StrutAreaRight ); - region += strutRect( StrutAreaBottom ); - region += strutRect( StrutAreaLeft ); + region += strutRect(StrutAreaTop); + region += strutRect(StrutAreaRight); + region += strutRect(StrutAreaBottom); + region += strutRect(StrutAreaLeft); // Remove all visible areas so that only the invisible remain int numScreens = Kephal::ScreenUtils::numScreens(); - for( int i = 0; i < numScreens; i ++ ) - region -= Kephal::ScreenUtils::screenGeometry( i ); + for (int i = 0; i < numScreens; i ++) + region -= Kephal::ScreenUtils::screenGeometry(i); // If there's anything left then we have an offscreen strut return !region.isEmpty(); - } +} void Client::checkWorkspacePosition() - { - if( isDesktop()) +{ + if (isDesktop()) return; - if( isFullScreen()) - { - QRect area = workspace()->clientArea( FullScreenArea, this ); - if( geometry() != area ) - setGeometry( area ); + if (isFullScreen()) { + QRect area = workspace()->clientArea(FullScreenArea, this); + if (geometry() != area) + setGeometry(area); return; - } - if( isDock()) + } + if (isDock()) return; - if( isTopMenu()) - { - if( workspace()->managingTopMenus()) - { + if (isTopMenu()) { + if (workspace()->managingTopMenus()) { QRect area; ClientList mainclients = mainClients(); - if( mainclients.count() == 1 ) - area = workspace()->clientArea( MaximizeFullArea, mainclients.first()); + if (mainclients.count() == 1) + area = workspace()->clientArea(MaximizeFullArea, mainclients.first()); else - area = workspace()->clientArea( MaximizeFullArea, QPoint( 0, 0 ), desktop()); - area.setHeight( workspace()->topMenuHeight()); + area = workspace()->clientArea(MaximizeFullArea, QPoint(0, 0), desktop()); + area.setHeight(workspace()->topMenuHeight()); // kDebug(1212) << "TOPMENU size adjust: " << area << ":" << this; - setGeometry( area ); - } - return; + setGeometry(area); } + return; + } - if( maximizeMode() != MaximizeRestore ) - // TODO update geom_restore? - changeMaximize( false, false, true ); // adjust size + if (maximizeMode() != MaximizeRestore) + // TODO update geom_restore? + changeMaximize(false, false, true); // adjust size - if( !isShade()) // TODO - { + if (!isShade()) { // TODO // this can be true only if this window was mapped before KWin // was started - in such case, don't adjust position to workarea, // because the window already had its position, and if a window // with a strut altering the workarea would be managed in initialization // after this one, this window would be moved - if( workspace()->initializing()) + if (workspace()->initializing()) return; // If the window was touching an edge before but not now move it so it is again. // Old and new maximums have different starting values so windows on the screen // edge will move when a new strut is placed on the edge. - const QRect& screenArea = workspace()->clientArea( ScreenArea, this ); + const QRect& screenArea = workspace()->clientArea(ScreenArea, this); int oldTopMax = screenArea.y(); int oldRightMax = screenArea.x() + screenArea.width(); int oldBottomMax = screenArea.y() + screenArea.height(); int oldLeftMax = screenArea.x(); int topMax = INT_MIN, rightMax = INT_MAX, bottomMax = INT_MAX, leftMax = INT_MIN; QRect newGeom = geometry(); - const QRect& newGeomTall = QRect( newGeom.x(), 0, newGeom.width(), displayHeight() ); // Full screen height - const QRect& newGeomWide = QRect( 0, newGeom.y(), displayWidth(), newGeom.height() ); // Full screen width + const QRect& newGeomTall = QRect(newGeom.x(), 0, newGeom.width(), displayHeight()); // Full screen height + const QRect& newGeomWide = QRect(0, newGeom.y(), displayWidth(), newGeom.height()); // Full screen width // Get the max strut point for each side where the window is (E.g. Highest point for // the bottom struts bounded by the window's left and right sides). - foreach( const QRect& r, workspace()->previousRestrictedMoveArea( desktop(), StrutAreaTop ).rects() ) - { + foreach (const QRect & r, workspace()->previousRestrictedMoveArea(desktop(), StrutAreaTop).rects()) { QRect rect = r & newGeomTall; - if( !rect.isEmpty() ) - oldTopMax = qMax( oldTopMax, rect.y() + rect.height() ); - } - foreach( const QRect& r, workspace()->previousRestrictedMoveArea( desktop(), StrutAreaRight ).rects() ) - { + if (!rect.isEmpty()) + oldTopMax = qMax(oldTopMax, rect.y() + rect.height()); + } + foreach (const QRect & r, workspace()->previousRestrictedMoveArea(desktop(), StrutAreaRight).rects()) { QRect rect = r & newGeomWide; - if( !rect.isEmpty() ) - oldRightMax = qMin( oldRightMax, rect.x() ); - } - foreach( const QRect& r, workspace()->previousRestrictedMoveArea( desktop(), StrutAreaBottom ).rects() ) - { + if (!rect.isEmpty()) + oldRightMax = qMin(oldRightMax, rect.x()); + } + foreach (const QRect & r, workspace()->previousRestrictedMoveArea(desktop(), StrutAreaBottom).rects()) { QRect rect = r & newGeomTall; - if( !rect.isEmpty() ) - oldBottomMax = qMin( oldBottomMax, rect.y() ); - } - foreach( const QRect& r, workspace()->previousRestrictedMoveArea( desktop(), StrutAreaLeft ).rects() ) - { + if (!rect.isEmpty()) + oldBottomMax = qMin(oldBottomMax, rect.y()); + } + foreach (const QRect & r, workspace()->previousRestrictedMoveArea(desktop(), StrutAreaLeft).rects()) { QRect rect = r & newGeomWide; - if( !rect.isEmpty() ) - oldLeftMax = qMax( oldLeftMax, rect.x() + rect.width() ); - } - foreach( const QRect& r, workspace()->restrictedMoveArea( desktop(), StrutAreaTop ).rects() ) - { + if (!rect.isEmpty()) + oldLeftMax = qMax(oldLeftMax, rect.x() + rect.width()); + } + foreach (const QRect & r, workspace()->restrictedMoveArea(desktop(), StrutAreaTop).rects()) { QRect rect = r & newGeomTall; - if( !rect.isEmpty() ) - topMax = qMax( topMax, rect.y() + rect.height() ); - } - foreach( const QRect& r, workspace()->restrictedMoveArea( desktop(), StrutAreaRight ).rects() ) - { + if (!rect.isEmpty()) + topMax = qMax(topMax, rect.y() + rect.height()); + } + foreach (const QRect & r, workspace()->restrictedMoveArea(desktop(), StrutAreaRight).rects()) { QRect rect = r & newGeomWide; - if( !rect.isEmpty() ) - rightMax = qMin( rightMax, rect.x() ); - } - foreach( const QRect& r, workspace()->restrictedMoveArea( desktop(), StrutAreaBottom ).rects() ) - { + if (!rect.isEmpty()) + rightMax = qMin(rightMax, rect.x()); + } + foreach (const QRect & r, workspace()->restrictedMoveArea(desktop(), StrutAreaBottom).rects()) { QRect rect = r & newGeomTall; - if( !rect.isEmpty() ) - bottomMax = qMin( bottomMax, rect.y() ); - } - foreach( const QRect& r, workspace()->restrictedMoveArea( desktop(), StrutAreaLeft ).rects() ) - { + if (!rect.isEmpty()) + bottomMax = qMin(bottomMax, rect.y()); + } + foreach (const QRect & r, workspace()->restrictedMoveArea(desktop(), StrutAreaLeft).rects()) { QRect rect = r & newGeomWide; - if( !rect.isEmpty() ) - leftMax = qMax( leftMax, rect.x() + rect.width() ); - } + if (!rect.isEmpty()) + leftMax = qMax(leftMax, rect.x() + rect.width()); + } // Check if the sides were touching before but are no longer - if( newGeom.y() == oldTopMax && - newGeom.y() != topMax ) - { // Top was touching before but isn't anymore + if (newGeom.y() == oldTopMax && + newGeom.y() != topMax) { + // Top was touching before but isn't anymore // If the other side was touching make sure it still is afterwards - if( newGeom.y() + newGeom.height() == oldBottomMax ) - newGeom.setTop( qMax( topMax, screenArea.y() )); + if (newGeom.y() + newGeom.height() == oldBottomMax) + newGeom.setTop(qMax(topMax, screenArea.y())); else - newGeom.moveTop( qMax( topMax, screenArea.y() )); + newGeom.moveTop(qMax(topMax, screenArea.y())); // Make sure it doesn't go off the other side of the screen/under an opposite strut - newGeom.setBottom( qMin( qMin( bottomMax - 1, screenArea.bottom() ), - newGeom.y() + newGeom.height() - 1 )); - } - if( newGeom.x() + newGeom.width() == oldRightMax && - newGeom.x() + newGeom.width() != rightMax ) - { // Right was touching before but isn't anymore + newGeom.setBottom(qMin(qMin(bottomMax - 1, screenArea.bottom()), + newGeom.y() + newGeom.height() - 1)); + } + if (newGeom.x() + newGeom.width() == oldRightMax && + newGeom.x() + newGeom.width() != rightMax) { + // Right was touching before but isn't anymore // If the other side was touching make sure it still is afterwards - if( newGeom.x() == oldLeftMax ) - newGeom.setRight( qMin( rightMax - 1, screenArea.right() )); + if (newGeom.x() == oldLeftMax) + newGeom.setRight(qMin(rightMax - 1, screenArea.right())); else - newGeom.moveRight( qMin( rightMax - 1, screenArea.right() )); + newGeom.moveRight(qMin(rightMax - 1, screenArea.right())); // Make sure it doesn't go off the other side of the screen/under an opposite strut - newGeom.setLeft( qMax( qMax( leftMax, screenArea.x() ), - newGeom.x() )); - } - if( newGeom.y() + newGeom.height() == oldBottomMax && - newGeom.y() + newGeom.height() != bottomMax ) - { // Bottom was touching before but isn't anymore + newGeom.setLeft(qMax(qMax(leftMax, screenArea.x()), + newGeom.x())); + } + if (newGeom.y() + newGeom.height() == oldBottomMax && + newGeom.y() + newGeom.height() != bottomMax) { + // Bottom was touching before but isn't anymore // If the other side was touching make sure it still is afterwards - if( newGeom.y() == oldTopMax ) - newGeom.setBottom( qMin( bottomMax - 1, screenArea.bottom() )); + if (newGeom.y() == oldTopMax) + newGeom.setBottom(qMin(bottomMax - 1, screenArea.bottom())); else - newGeom.moveBottom( qMin( bottomMax - 1, screenArea.bottom() )); + newGeom.moveBottom(qMin(bottomMax - 1, screenArea.bottom())); // Make sure it doesn't go off the other side of the screen/under an opposite strut - newGeom.setTop( qMax( qMax( topMax, screenArea.y() ), - newGeom.y() )); - } - if( newGeom.x() == oldLeftMax && - newGeom.x() != leftMax ) - { // Left was touching before but isn't anymore + newGeom.setTop(qMax(qMax(topMax, screenArea.y()), + newGeom.y())); + } + if (newGeom.x() == oldLeftMax && + newGeom.x() != leftMax) { + // Left was touching before but isn't anymore // If the other side was touching make sure it still is afterwards - if( newGeom.x() + newGeom.width() == oldRightMax ) - newGeom.setLeft( qMax( leftMax, screenArea.x() )); + if (newGeom.x() + newGeom.width() == oldRightMax) + newGeom.setLeft(qMax(leftMax, screenArea.x())); else - newGeom.moveLeft( qMax( leftMax, screenArea.x() )); + newGeom.moveLeft(qMax(leftMax, screenArea.x())); // Make sure it doesn't go off the other side of the screen/under an opposite strut - newGeom.setRight( qMin( qMin( rightMax - 1, screenArea.right() ), - newGeom.x() + newGeom.width() - 1 )); - } + newGeom.setRight(qMin(qMin(rightMax - 1, screenArea.right()), + newGeom.x() + newGeom.width() - 1)); + } // Obey size hints. TODO: We really should make sure it stays in the right place - newGeom.setSize( adjustedSize( newGeom.size() )); + newGeom.setSize(adjustedSize(newGeom.size())); - if( newGeom != geometry() ) - setGeometry( newGeom ); - } + if (newGeom != geometry()) + setGeometry(newGeom); } +} // Try to be smart about keeping the clients visible. // If the client was fully inside the workspace before, try to keep @@ -1258,76 +1187,68 @@ void Client::checkWorkspacePosition() // again (not fully, as that could(?) be potentionally annoying) by // moving it slightly inside the workarea (those '+ 5'). // Again, this is done for the x direction, y direction will be done by x<->y swapping -void Client::checkDirection( int new_diff, int old_diff, QRect& rect, const QRect& area ) - { - if( old_diff != INT_MIN ) // was inside workarea - { - if( old_diff == INT_MAX ) // was in workarea, but far from edge - { - if( new_diff == INT_MIN ) // is not anymore fully in workarea - { - rect.setLeft( area.left()); - rect.setRight( area.right()); - } +void Client::checkDirection(int new_diff, int old_diff, QRect& rect, const QRect& area) +{ + if (old_diff != INT_MIN) { // was inside workarea + if (old_diff == INT_MAX) { // was in workarea, but far from edge + if (new_diff == INT_MIN) { // is not anymore fully in workarea + rect.setLeft(area.left()); + rect.setRight(area.right()); + } return; - } - if( isMovable()) - { - if( old_diff < 0 ) // was in left third, keep distance from left edge - rect.moveLeft( area.left() + ( -old_diff - 1 )); - else // old_diff > 0 // was in right third, keep distance from right edge - rect.moveRight( area.right() - ( old_diff - 1 )); - } - else if( isResizable()) - { - if( old_diff < 0 ) - rect.setLeft( area.left() + ( -old_diff - 1 ) ); - else // old_diff > 0 - rect.setRight( area.right() - ( old_diff - 1 )); - } - if( rect.width() > area.width() && isResizable()) - rect.setWidth( area.width()); - if( isMovable()) - { - if( rect.left() < area.left()) - rect.moveLeft( area.left()); - else if( rect.right() > area.right()) - rect.moveRight( area.right()); - } } - if( rect.right() < area.left() + 5 || rect.left() > area.right() - 5 ) - { // not visible (almost) at all - try to make it at least partially visible - if( isMovable()) - { - if( rect.left() < area.left() + 5 ) - rect.moveRight( area.left() + 5 ); - if( rect.right() > area.right() - 5 ) - rect.moveLeft( area.right() - 5 ); - } + if (isMovable()) { + if (old_diff < 0) // was in left third, keep distance from left edge + rect.moveLeft(area.left() + (-old_diff - 1)); + else // old_diff > 0 // was in right third, keep distance from right edge + rect.moveRight(area.right() - (old_diff - 1)); + } else if (isResizable()) { + if (old_diff < 0) + rect.setLeft(area.left() + (-old_diff - 1)); + else // old_diff > 0 + rect.setRight(area.right() - (old_diff - 1)); + } + if (rect.width() > area.width() && isResizable()) + rect.setWidth(area.width()); + if (isMovable()) { + if (rect.left() < area.left()) + rect.moveLeft(area.left()); + else if (rect.right() > area.right()) + rect.moveRight(area.right()); } } + if (rect.right() < area.left() + 5 || rect.left() > area.right() - 5) { + // not visible (almost) at all - try to make it at least partially visible + if (isMovable()) { + if (rect.left() < area.left() + 5) + rect.moveRight(area.left() + 5); + if (rect.right() > area.right() - 5) + rect.moveLeft(area.right() - 5); + } + } +} /*! Adjust the frame size \a frame according to he window's size hints. */ -QSize Client::adjustedSize( const QSize& frame, Sizemode mode ) const - { +QSize Client::adjustedSize(const QSize& frame, Sizemode mode) const +{ // first, get the window size for the given frame size s - QSize wsize( frame.width() - ( border_left + border_right ), - frame.height() - ( border_top + border_bottom )); - if( wsize.isEmpty()) - wsize = QSize( 1, 1 ); + QSize wsize(frame.width() - (border_left + border_right), + frame.height() - (border_top + border_bottom)); + if (wsize.isEmpty()) + wsize = QSize(1, 1); - return sizeForClientSize( wsize, mode, false ); - } + return sizeForClientSize(wsize, mode, false); +} // this helper returns proper size even if the window is shaded // see also the comment in Client::setGeometry() QSize Client::adjustedSize() const - { - return sizeForClientSize( clientSize()); - } +{ + return sizeForClientSize(clientSize()); +} /*! Calculate the appropriate frame size for the given client size \a @@ -1337,39 +1258,37 @@ QSize Client::adjustedSize() const maximum and incremental size changes). */ -QSize Client::sizeForClientSize( const QSize& wsize, Sizemode mode, bool noframe ) const - { +QSize Client::sizeForClientSize(const QSize& wsize, Sizemode mode, bool noframe) const +{ int w = wsize.width(); int h = wsize.height(); - if( w < 1 || h < 1 ) - { + if (w < 1 || h < 1) { kWarning(1212) << "sizeForClientSize() with empty size!" ; kWarning(1212) << kBacktrace() ; - } - if (w<1) w = 1; - if (h<1) h = 1; + } + if (w < 1) w = 1; + if (h < 1) h = 1; // basesize, minsize, maxsize, paspect and resizeinc have all values defined, // even if they're not set in flags - see getWmNormalHints() QSize min_size = clientGroup() ? clientGroup()->minSize() : minSize(); QSize max_size = clientGroup() ? clientGroup()->maxSize() : maxSize(); - if( decoration != NULL ) - { + if (decoration != NULL) { QSize decominsize = decoration->minimumSize(); - QSize border_size( border_left + border_right, border_top + border_bottom ); - if( border_size.width() > decominsize.width()) // just in case - decominsize.setWidth( border_size.width()); - if( border_size.height() > decominsize.height()) - decominsize.setHeight( border_size.height()); - if( decominsize.width() > min_size.width()) - min_size.setWidth( decominsize.width()); - if( decominsize.height() > min_size.height()) - min_size.setHeight( decominsize.height()); - } - w = qMin( max_size.width(), w ); - h = qMin( max_size.height(), h ); - w = qMax( min_size.width(), w ); - h = qMax( min_size.height(), h ); + QSize border_size(border_left + border_right, border_top + border_bottom); + if (border_size.width() > decominsize.width()) // just in case + decominsize.setWidth(border_size.width()); + if (border_size.height() > decominsize.height()) + decominsize.setHeight(border_size.height()); + if (decominsize.width() > min_size.width()) + min_size.setWidth(decominsize.width()); + if (decominsize.height() > min_size.height()) + min_size.setHeight(decominsize.height()); + } + w = qMin(max_size.width(), w); + h = qMin(max_size.height(), h); + w = qMax(min_size.width(), w); + h = qMax(min_size.height(), h); int w1 = w; int h1 = h; @@ -1377,8 +1296,8 @@ QSize Client::sizeForClientSize( const QSize& wsize, Sizemode mode, bool noframe int height_inc = xSizeHint.height_inc; int basew_inc = xSizeHint.min_width; // see getWmNormalHints() int baseh_inc = xSizeHint.min_height; - w = int(( w - basew_inc ) / width_inc ) * width_inc + basew_inc; - h = int(( h - baseh_inc ) / height_inc ) * height_inc + baseh_inc; + w = int((w - basew_inc) / width_inc) * width_inc + basew_inc; + h = int((h - baseh_inc) / height_inc) * height_inc + baseh_inc; // code for aspect ratios based on code from FVWM /* * The math looks like this: @@ -1394,8 +1313,7 @@ QSize Client::sizeForClientSize( const QSize& wsize, Sizemode mode, bool noframe * maxAspectX * dheight < maxAspectY * dwidth * */ - if( xSizeHint.flags & PAspect ) - { + if (xSizeHint.flags & PAspect) { double min_aspect_w = xSizeHint.min_aspect.x; // use doubles, because the values can be MAX_INT double min_aspect_h = xSizeHint.min_aspect.y; // and multiplying would go wrong otherwise double max_aspect_w = xSizeHint.max_aspect.x; @@ -1410,199 +1328,183 @@ QSize Client::sizeForClientSize( const QSize& wsize, Sizemode mode, bool noframe int max_height = max_size.height() - xSizeHint.base_height; int min_height = min_size.height() - xSizeHint.base_height; #define ASPECT_CHECK_GROW_W \ - if( min_aspect_w * h > min_aspect_h * w ) \ - { \ - int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ - if( w + delta <= max_width ) \ - w += delta; \ - } + if ( min_aspect_w * h > min_aspect_h * w ) \ + { \ + int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ + if ( w + delta <= max_width ) \ + w += delta; \ + } #define ASPECT_CHECK_SHRINK_H_GROW_W \ - if( min_aspect_w * h > min_aspect_h * w ) \ - { \ - int delta = int( h - w * min_aspect_h / min_aspect_w ) / height_inc * height_inc; \ - if( h - delta >= min_height ) \ - h -= delta; \ - else \ - { \ - int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ - if( w + delta <= max_width ) \ - w += delta; \ - } \ - } + if ( min_aspect_w * h > min_aspect_h * w ) \ + { \ + int delta = int( h - w * min_aspect_h / min_aspect_w ) / height_inc * height_inc; \ + if ( h - delta >= min_height ) \ + h -= delta; \ + else \ + { \ + int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ + if ( w + delta <= max_width ) \ + w += delta; \ + } \ + } #define ASPECT_CHECK_GROW_H \ - if( max_aspect_w * h < max_aspect_h * w ) \ - { \ - int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ - if( h + delta <= max_height ) \ - h += delta; \ - } + if ( max_aspect_w * h < max_aspect_h * w ) \ + { \ + int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ + if ( h + delta <= max_height ) \ + h += delta; \ + } #define ASPECT_CHECK_SHRINK_W_GROW_H \ - if( max_aspect_w * h < max_aspect_h * w ) \ - { \ - int delta = int( w - max_aspect_w * h / max_aspect_h ) / width_inc * width_inc; \ - if( w - delta >= min_width ) \ - w -= delta; \ - else \ - { \ - int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ - if( h + delta <= max_height ) \ - h += delta; \ - } \ - } - switch( mode ) - { - case SizemodeAny: + if ( max_aspect_w * h < max_aspect_h * w ) \ + { \ + int delta = int( w - max_aspect_w * h / max_aspect_h ) / width_inc * width_inc; \ + if ( w - delta >= min_width ) \ + w -= delta; \ + else \ + { \ + int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ + if ( h + delta <= max_height ) \ + h += delta; \ + } \ + } + switch(mode) { + case SizemodeAny: #if 0 // make SizemodeAny equal to SizemodeFixedW - prefer keeping fixed width, - // so that changing aspect ratio to a different value and back keeps the same size (#87298) - { + // so that changing aspect ratio to a different value and back keeps the same size (#87298) + { ASPECT_CHECK_SHRINK_H_GROW_W ASPECT_CHECK_SHRINK_W_GROW_H ASPECT_CHECK_GROW_H ASPECT_CHECK_GROW_W break; - } -#endif - case SizemodeFixedW: - { - // the checks are order so that attempts to modify height are first - ASPECT_CHECK_GROW_H - ASPECT_CHECK_SHRINK_H_GROW_W - ASPECT_CHECK_SHRINK_W_GROW_H - ASPECT_CHECK_GROW_W - break; - } - case SizemodeFixedH: - { - ASPECT_CHECK_GROW_W - ASPECT_CHECK_SHRINK_W_GROW_H - ASPECT_CHECK_SHRINK_H_GROW_W - ASPECT_CHECK_GROW_H - break; - } - case SizemodeMax: - { - // first checks that try to shrink - ASPECT_CHECK_SHRINK_H_GROW_W - ASPECT_CHECK_SHRINK_W_GROW_H - ASPECT_CHECK_GROW_W - ASPECT_CHECK_GROW_H - break; - } } +#endif + case SizemodeFixedW: { + // the checks are order so that attempts to modify height are first + ASPECT_CHECK_GROW_H + ASPECT_CHECK_SHRINK_H_GROW_W + ASPECT_CHECK_SHRINK_W_GROW_H + ASPECT_CHECK_GROW_W + break; + } + case SizemodeFixedH: { + ASPECT_CHECK_GROW_W + ASPECT_CHECK_SHRINK_W_GROW_H + ASPECT_CHECK_SHRINK_H_GROW_W + ASPECT_CHECK_GROW_H + break; + } + case SizemodeMax: { + // first checks that try to shrink + ASPECT_CHECK_SHRINK_H_GROW_W + ASPECT_CHECK_SHRINK_W_GROW_H + ASPECT_CHECK_GROW_W + ASPECT_CHECK_GROW_H + break; + } + } #undef ASPECT_CHECK_SHRINK_H_GROW_W #undef ASPECT_CHECK_SHRINK_W_GROW_H #undef ASPECT_CHECK_GROW_W #undef ASPECT_CHECK_GROW_H w += xSizeHint.base_width; h += xSizeHint.base_height; - } - if( !rules()->checkStrictGeometry( true )) - { // disobey increments and aspect by explicit rule - w = w1; - h = h1; - } + } + if (!rules()->checkStrictGeometry(true)) { + // disobey increments and aspect by explicit rule + w = w1; + h = h1; + } - if( !noframe ) - { + if (!noframe) { w += border_left + border_right; h += border_top + border_bottom; - } - return rules()->checkSize( QSize( w, h )); } + return rules()->checkSize(QSize(w, h)); +} /*! Gets the client's normal WM hints and reconfigures itself respectively. */ void Client::getWmNormalHints() - { +{ long msize; - if (XGetWMNormalHints(display(), window(), &xSizeHint, &msize) == 0 ) + if (XGetWMNormalHints(display(), window(), &xSizeHint, &msize) == 0) xSizeHint.flags = 0; // set defined values for the fields, even if they're not in flags - if( ! ( xSizeHint.flags & PMinSize )) + if (!(xSizeHint.flags & PMinSize)) xSizeHint.min_width = xSizeHint.min_height = 0; - if( xSizeHint.flags & PBaseSize ) - { + if (xSizeHint.flags & PBaseSize) { // PBaseSize is a fallback for PMinSize according to ICCCM 4.1.2.3 // The other way around PMinSize is not a complete fallback for PBaseSize, // so that's not handled here. - if( ! ( xSizeHint.flags & PMinSize )) - { + if (!(xSizeHint.flags & PMinSize)) { xSizeHint.min_width = xSizeHint.base_width; xSizeHint.min_height = xSizeHint.base_height; - } } - else + } else xSizeHint.base_width = xSizeHint.base_height = 0; - if( ! ( xSizeHint.flags & PMaxSize )) + if (!(xSizeHint.flags & PMaxSize)) xSizeHint.max_width = xSizeHint.max_height = INT_MAX; - else - { - xSizeHint.max_width = qMax( xSizeHint.max_width, 1 ); - xSizeHint.max_height = qMax( xSizeHint.max_height, 1 ); - } - if( xSizeHint.flags & PResizeInc ) - { - xSizeHint.width_inc = qMax( xSizeHint.width_inc, 1 ); - xSizeHint.height_inc = qMax( xSizeHint.height_inc, 1 ); - } - else - { + else { + xSizeHint.max_width = qMax(xSizeHint.max_width, 1); + xSizeHint.max_height = qMax(xSizeHint.max_height, 1); + } + if (xSizeHint.flags & PResizeInc) { + xSizeHint.width_inc = qMax(xSizeHint.width_inc, 1); + xSizeHint.height_inc = qMax(xSizeHint.height_inc, 1); + } else { xSizeHint.width_inc = 1; xSizeHint.height_inc = 1; - } - if( xSizeHint.flags & PAspect ) - { // no dividing by zero - xSizeHint.min_aspect.y = qMax( xSizeHint.min_aspect.y, 1 ); - xSizeHint.max_aspect.y = qMax( xSizeHint.max_aspect.y, 1 ); - } - else - { + } + if (xSizeHint.flags & PAspect) { + // no dividing by zero + xSizeHint.min_aspect.y = qMax(xSizeHint.min_aspect.y, 1); + xSizeHint.max_aspect.y = qMax(xSizeHint.max_aspect.y, 1); + } else { xSizeHint.min_aspect.x = 1; xSizeHint.min_aspect.y = INT_MAX; xSizeHint.max_aspect.x = INT_MAX; xSizeHint.max_aspect.y = 1; - } - if( ! ( xSizeHint.flags & PWinGravity )) + } + if (!(xSizeHint.flags & PWinGravity)) xSizeHint.win_gravity = NorthWestGravity; // Update min/max size of this group - if( clientGroup() ) + if (clientGroup()) clientGroup()->updateMinMaxSize(); - if( isManaged()) - { // update to match restrictions + if (isManaged()) { + // update to match restrictions QSize new_size = adjustedSize(); - if( new_size != size() && !isFullScreen()) - { + if (new_size != size() && !isFullScreen()) { QRect orig_geometry = geometry(); - resizeWithChecks( new_size ); - if( ( !isSpecialWindow() || isToolbar()) && !isFullScreen()) - { + resizeWithChecks(new_size); + if ((!isSpecialWindow() || isToolbar()) && !isFullScreen()) { // try to keep the window in its xinerama screen if possible, // if that fails at least keep it visible somewhere - QRect area = workspace()->clientArea( MovementArea, this ); - if( area.contains( orig_geometry )) - keepInArea( area ); - area = workspace()->clientArea( WorkArea, this ); - if( area.contains( orig_geometry )) - keepInArea( area ); - } + QRect area = workspace()->clientArea(MovementArea, this); + if (area.contains(orig_geometry)) + keepInArea(area); + area = workspace()->clientArea(WorkArea, this); + if (area.contains(orig_geometry)) + keepInArea(area); } } - updateAllowedActions(); // affects isResizeable() } + updateAllowedActions(); // affects isResizeable() +} QSize Client::minSize() const - { - return rules()->checkMinSize( QSize( xSizeHint.min_width, xSizeHint.min_height )); - } +{ + return rules()->checkMinSize(QSize(xSizeHint.min_width, xSizeHint.min_height)); +} QSize Client::maxSize() const - { - return rules()->checkMaxSize( QSize( xSizeHint.max_width, xSizeHint.max_height )); - } +{ + return rules()->checkMaxSize(QSize(xSizeHint.max_width, xSizeHint.max_height)); +} /*! Auxiliary function to inform the client about the current window @@ -1610,7 +1512,7 @@ QSize Client::maxSize() const */ void Client::sendSyntheticConfigureNotify() - { +{ XConfigureEvent c; c.type = ConfigureNotify; c.send_event = True; @@ -1623,329 +1525,320 @@ void Client::sendSyntheticConfigureNotify() c.border_width = 0; c.above = None; c.override_redirect = 0; - XSendEvent( display(), c.event, true, StructureNotifyMask, (XEvent*)&c ); - } + XSendEvent(display(), c.event, true, StructureNotifyMask, (XEvent*)&c); +} -const QPoint Client::calculateGravitation( bool invert, int gravity ) const - { +const QPoint Client::calculateGravitation(bool invert, int gravity) const +{ int dx, dy; dx = dy = 0; - if( gravity == 0 ) // default (nonsense) value for the argument + if (gravity == 0) // default (nonsense) value for the argument gravity = xSizeHint.win_gravity; // dx, dy specify how the client window moves to make space for the frame - switch (gravity) - { - case NorthWestGravity: // move down right - default: - dx = border_left; - dy = border_top; - break; - case NorthGravity: // move right - dx = 0; - dy = border_top; - break; - case NorthEastGravity: // move down left - dx = -border_right; - dy = border_top; - break; - case WestGravity: // move right - dx = border_left; - dy = 0; - break; - case CenterGravity: - break; // will be handled specially - case StaticGravity: // don't move - dx = 0; - dy = 0; - break; - case EastGravity: // move left - dx = -border_right; - dy = 0; - break; - case SouthWestGravity: // move up right - dx = border_left ; - dy = -border_bottom; - break; - case SouthGravity: // move up - dx = 0; - dy = -border_bottom; - break; - case SouthEastGravity: // move up left - dx = -border_right; - dy = -border_bottom; - break; - } - if( gravity != CenterGravity ) - { // translate from client movement to frame movement + switch(gravity) { + case NorthWestGravity: // move down right + default: + dx = border_left; + dy = border_top; + break; + case NorthGravity: // move right + dx = 0; + dy = border_top; + break; + case NorthEastGravity: // move down left + dx = -border_right; + dy = border_top; + break; + case WestGravity: // move right + dx = border_left; + dy = 0; + break; + case CenterGravity: + break; // will be handled specially + case StaticGravity: // don't move + dx = 0; + dy = 0; + break; + case EastGravity: // move left + dx = -border_right; + dy = 0; + break; + case SouthWestGravity: // move up right + dx = border_left ; + dy = -border_bottom; + break; + case SouthGravity: // move up + dx = 0; + dy = -border_bottom; + break; + case SouthEastGravity: // move up left + dx = -border_right; + dy = -border_bottom; + break; + } + if (gravity != CenterGravity) { + // translate from client movement to frame movement dx -= border_left; dy -= border_top; - } - else - { // center of the frame will be at the same position client center without frame would be - dx = - ( border_left + border_right ) / 2; - dy = - ( border_top + border_bottom ) / 2; - } - if( !invert ) - return QPoint( x() + dx, y() + dy ); - else - return QPoint( x() - dx, y() - dy ); + } else { + // center of the frame will be at the same position client center without frame would be + dx = - (border_left + border_right) / 2; + dy = - (border_top + border_bottom) / 2; } + if (!invert) + return QPoint(x() + dx, y() + dy); + else + return QPoint(x() - dx, y() - dy); +} -void Client::configureRequest( int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool ) - { - if ( maximizeMode() == MaximizeFull) // bugs #158974, #252314 +void Client::configureRequest(int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool) +{ + if (maximizeMode() == MaximizeFull) // bugs #158974, #252314 return; // "maximized" is a user setting -> we do not allow the client to resize itself away from this & against the user wish - if( gravity == 0 ) // default (nonsense) value for the argument + if (gravity == 0) // default (nonsense) value for the argument gravity = xSizeHint.win_gravity; - if( value_mask & ( CWX | CWY )) - { - QPoint new_pos = calculateGravitation( true, gravity ); // undo gravitation - if ( value_mask & CWX ) - new_pos.setX( rx ); - if ( value_mask & CWY ) - new_pos.setY( ry ); + if (value_mask & (CWX | CWY)) { + QPoint new_pos = calculateGravitation(true, gravity); // undo gravitation + if (value_mask & CWX) + new_pos.setX(rx); + if (value_mask & CWY) + new_pos.setY(ry); // clever(?) workaround for applications like xv that want to set // the location to the current location but miscalculate the // frame size due to kwin being a double-reparenting window // manager - if ( new_pos.x() == x() + clientPos().x() && new_pos.y() == y() + clientPos().y() - && gravity == NorthWestGravity && !from_tool ) - { - new_pos.setX( x()); - new_pos.setY( y()); - } + if (new_pos.x() == x() + clientPos().x() && new_pos.y() == y() + clientPos().y() + && gravity == NorthWestGravity && !from_tool) { + new_pos.setX(x()); + new_pos.setY(y()); + } int nw = clientSize().width(); int nh = clientSize().height(); - if ( value_mask & CWWidth ) + if (value_mask & CWWidth) nw = rw; - if ( value_mask & CWHeight ) + if (value_mask & CWHeight) nh = rh; - QSize ns = sizeForClientSize( QSize( nw, nh ) ); // enforces size if needed - new_pos = rules()->checkPosition( new_pos ); + QSize ns = sizeForClientSize(QSize(nw, nh)); // enforces size if needed + new_pos = rules()->checkPosition(new_pos); QRect orig_geometry = geometry(); - GeometryUpdatesBlocker blocker( this ); - move( new_pos ); - plainResize( ns ); - setGeometry( QRect( calculateGravitation( false, gravity ), size())); - updateFullScreenHack( QRect( new_pos, QSize( nw, nh ))); - QRect area = workspace()->clientArea( WorkArea, this ); - if( !from_tool && ( !isSpecialWindow() || isToolbar()) && !isFullScreen() - && area.contains( orig_geometry )) - keepInArea( area ); + GeometryUpdatesBlocker blocker(this); + move(new_pos); + plainResize(ns); + setGeometry(QRect(calculateGravitation(false, gravity), size())); + updateFullScreenHack(QRect(new_pos, QSize(nw, nh))); + QRect area = workspace()->clientArea(WorkArea, this); + if (!from_tool && (!isSpecialWindow() || isToolbar()) && !isFullScreen() + && area.contains(orig_geometry)) + keepInArea(area); // this is part of the kicker-xinerama-hack... it should be // safe to remove when kicker gets proper ExtendedStrut support; // see Workspace::updateClientArea() and // Client::adjustedClientArea() - if (hasStrut ()) - workspace() -> updateClientArea (); - } + if (hasStrut()) + workspace() -> updateClientArea(); + } - if ( value_mask & (CWWidth | CWHeight ) - && ! ( value_mask & ( CWX | CWY )) ) // pure resize - { + if (value_mask & (CWWidth | CWHeight) + && !(value_mask & (CWX | CWY))) { // pure resize int nw = clientSize().width(); int nh = clientSize().height(); - if ( value_mask & CWWidth ) + if (value_mask & CWWidth) nw = rw; - if ( value_mask & CWHeight ) + if (value_mask & CWHeight) nh = rh; - QSize ns = sizeForClientSize( QSize( nw, nh ) ); + QSize ns = sizeForClientSize(QSize(nw, nh)); - if( ns != size()) // don't restore if some app sets its own size again - { + if (ns != size()) { // don't restore if some app sets its own size again QRect orig_geometry = geometry(); - GeometryUpdatesBlocker blocker( this ); + GeometryUpdatesBlocker blocker(this); int save_gravity = xSizeHint.win_gravity; xSizeHint.win_gravity = gravity; - resizeWithChecks( ns ); + resizeWithChecks(ns); xSizeHint.win_gravity = save_gravity; - updateFullScreenHack( QRect( calculateGravitation( true, xSizeHint.win_gravity ), QSize( nw, nh ))); - if( !from_tool && ( !isSpecialWindow() || isToolbar()) && !isFullScreen()) - { + updateFullScreenHack(QRect(calculateGravitation(true, xSizeHint.win_gravity), QSize(nw, nh))); + if (!from_tool && (!isSpecialWindow() || isToolbar()) && !isFullScreen()) { // try to keep the window in its xinerama screen if possible, // if that fails at least keep it visible somewhere - QRect area = workspace()->clientArea( MovementArea, this ); - if( area.contains( orig_geometry )) - keepInArea( area ); - area = workspace()->clientArea( WorkArea, this ); - if( area.contains( orig_geometry )) - keepInArea( area ); - } + QRect area = workspace()->clientArea(MovementArea, this); + if (area.contains(orig_geometry)) + keepInArea(area); + area = workspace()->clientArea(WorkArea, this); + if (area.contains(orig_geometry)) + keepInArea(area); } } + } // No need to send synthetic configure notify event here, either it's sent together // with geometry change, or there's no need to send it. // Handling of the real ConfigureRequest event forces sending it, as there it's necessary. - } +} -void Client::resizeWithChecks( int w, int h, ForceGeometry_t force ) - { - assert( !shade_geometry_change ); - if( isShade()) - { - if( h == border_top + border_bottom ) - { +void Client::resizeWithChecks(int w, int h, ForceGeometry_t force) +{ + assert(!shade_geometry_change); + if (isShade()) { + if (h == border_top + border_bottom) { kWarning(1212) << "Shaded geometry passed for size:" ; kWarning(1212) << kBacktrace() ; - } } + } int newx = x(); int newy = y(); - QRect area = workspace()->clientArea( WorkArea, this ); + QRect area = workspace()->clientArea(WorkArea, this); // don't allow growing larger than workarea - if( w > area.width()) + if (w > area.width()) w = area.width(); - if( h > area.height()) + if (h > area.height()) h = area.height(); - QSize tmp = adjustedSize( QSize( w, h )); // checks size constraints, including min/max size + QSize tmp = adjustedSize(QSize(w, h)); // checks size constraints, including min/max size w = tmp.width(); h = tmp.height(); - switch( xSizeHint.win_gravity ) - { - case NorthWestGravity: // top left corner doesn't move - default: - break; - case NorthGravity: // middle of top border doesn't move - newx = ( newx + width() / 2 ) - ( w / 2 ); - break; - case NorthEastGravity: // top right corner doesn't move - newx = newx + width() - w; - break; - case WestGravity: // middle of left border doesn't move - newy = ( newy + height() / 2 ) - ( h / 2 ); - break; - case CenterGravity: // middle point doesn't move - newx = ( newx + width() / 2 ) - ( w / 2 ); - newy = ( newy + height() / 2 ) - ( h / 2 ); - break; - case StaticGravity: // top left corner of _client_ window doesn't move - // since decoration doesn't change, equal to NorthWestGravity - break; - case EastGravity: // // middle of right border doesn't move - newx = newx + width() - w; - newy = ( newy + height() / 2 ) - ( h / 2 ); - break; - case SouthWestGravity: // bottom left corner doesn't move - newy = newy + height() - h; - break; - case SouthGravity: // middle of bottom border doesn't move - newx = ( newx + width() / 2 ) - ( w / 2 ); - newy = newy + height() - h; - break; - case SouthEastGravity: // bottom right corner doesn't move - newx = newx + width() - w; - newy = newy + height() - h; - break; - } - setGeometry( newx, newy, w, h, force ); + switch(xSizeHint.win_gravity) { + case NorthWestGravity: // top left corner doesn't move + default: + break; + case NorthGravity: // middle of top border doesn't move + newx = (newx + width() / 2) - (w / 2); + break; + case NorthEastGravity: // top right corner doesn't move + newx = newx + width() - w; + break; + case WestGravity: // middle of left border doesn't move + newy = (newy + height() / 2) - (h / 2); + break; + case CenterGravity: // middle point doesn't move + newx = (newx + width() / 2) - (w / 2); + newy = (newy + height() / 2) - (h / 2); + break; + case StaticGravity: // top left corner of _client_ window doesn't move + // since decoration doesn't change, equal to NorthWestGravity + break; + case EastGravity: // // middle of right border doesn't move + newx = newx + width() - w; + newy = (newy + height() / 2) - (h / 2); + break; + case SouthWestGravity: // bottom left corner doesn't move + newy = newy + height() - h; + break; + case SouthGravity: // middle of bottom border doesn't move + newx = (newx + width() / 2) - (w / 2); + newy = newy + height() - h; + break; + case SouthEastGravity: // bottom right corner doesn't move + newx = newx + width() - w; + newy = newy + height() - h; + break; } + setGeometry(newx, newy, w, h, force); +} // _NET_MOVERESIZE_WINDOW -void Client::NETMoveResizeWindow( int flags, int x, int y, int width, int height ) - { +void Client::NETMoveResizeWindow(int flags, int x, int y, int width, int height) +{ int gravity = flags & 0xff; int value_mask = 0; - if( flags & ( 1 << 8 )) + if (flags & (1 << 8)) value_mask |= CWX; - if( flags & ( 1 << 9 )) + if (flags & (1 << 9)) value_mask |= CWY; - if( flags & ( 1 << 10 )) + if (flags & (1 << 10)) value_mask |= CWWidth; - if( flags & ( 1 << 11 )) + if (flags & (1 << 11)) value_mask |= CWHeight; - configureRequest( value_mask, x, y, width, height, gravity, true ); - } + configureRequest(value_mask, x, y, width, height, gravity, true); +} /*! Returns whether the window is moveable or has a fixed position. */ bool Client::isMovable() const - { - if( !motif_may_move || isFullScreen()) +{ + if (!motif_may_move || isFullScreen()) return false; - if( isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) + if (isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) return false; - if( maximizeMode() == MaximizeFull && !options->moveResizeMaximizedWindows() ) + if (maximizeMode() == MaximizeFull && !options->moveResizeMaximizedWindows()) return false; - if( rules()->checkPosition( invalidPoint ) != invalidPoint ) // forced position + if (rules()->checkPosition(invalidPoint) != invalidPoint) // forced position return false; return true; - } +} /*! Returns whether the window is moveable across Xinerama screens */ bool Client::isMovableAcrossScreens() const - { - if( !motif_may_move ) +{ + if (!motif_may_move) return false; - if( isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) + if (isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) return false; - if( rules()->checkPosition( invalidPoint ) != invalidPoint ) // forced position + if (rules()->checkPosition(invalidPoint) != invalidPoint) // forced position return false; return true; - } +} /*! Returns whether the window is resizable or has a fixed size. */ bool Client::isResizable() const - { - if( !motif_may_resize || isFullScreen()) +{ + if (!motif_may_resize || isFullScreen()) return false; - if( isSpecialWindow() || isSplash() || isToolbar()) + if (isSpecialWindow() || isSplash() || isToolbar()) return false; - if( maximizeMode() == MaximizeFull && !options->moveResizeMaximizedWindows() ) + if (maximizeMode() == MaximizeFull && !options->moveResizeMaximizedWindows()) return false; - if( rules()->checkSize( QSize()).isValid()) // forced size + if (rules()->checkSize(QSize()).isValid()) // forced size return false; QSize min = clientGroup() ? clientGroup()->minSize() : minSize(); QSize max = clientGroup() ? clientGroup()->maxSize() : maxSize(); return min.width() < max.width() || min.height() < max.height(); - } +} /* Returns whether the window is maximizable or not */ bool Client::isMaximizable() const +{ { - { // isMovable() and isResizable() may be false for maximized windows - // with moving/resizing maximized windows disabled - TemporaryAssign< MaximizeMode > tmp( max_mode, MaximizeRestore ); - if( !isMovable() || !isResizable() || isToolbar()) // SELI isToolbar() ? + // isMovable() and isResizable() may be false for maximized windows + // with moving/resizing maximized windows disabled + TemporaryAssign< MaximizeMode > tmp(max_mode, MaximizeRestore); + if (!isMovable() || !isResizable() || isToolbar()) // SELI isToolbar() ? return false; - } - if ( maximizeMode() != MaximizeRestore ) + } + if (maximizeMode() != MaximizeRestore) return true; QSize max = maxSize(); #if 0 - if( max.width() < 32767 || max.height() < 32767 ) // sizes are 16bit with X + if (max.width() < 32767 || max.height() < 32767) // sizes are 16bit with X return false; #else // apparently there are enough apps which specify some arbitrary value // for their maximum size just for the fun of it - QSize areasize = workspace()->clientArea( MaximizeArea, this ).size(); - if( max.width() < areasize.width() || max.height() < areasize.height()) + QSize areasize = workspace()->clientArea(MaximizeArea, this).size(); + if (max.width() < areasize.width() || max.height() < areasize.height()) return false; #endif return true; - } +} /*! Reimplemented to inform the client about the new window position. */ -void Client::setGeometry( int x, int y, int w, int h, ForceGeometry_t force, bool emitJs ) - { +void Client::setGeometry(int x, int y, int w, int h, ForceGeometry_t force, bool emitJs) +{ // this code is also duplicated in Client::plainResize() // Ok, the shading geometry stuff. Generally, code doesn't care about shaded geometry, // simply because there are too many places dealing with geometry. Those places @@ -1957,869 +1850,789 @@ void Client::setGeometry( int x, int y, int w, int h, ForceGeometry_t force, boo // setGeometry( geometry()) - geometry() will return the shaded frame geometry. // Such code is wrong and should be changed to handle the case when the window is shaded, // for example using Client::clientSize() - - if( shade_geometry_change ) + + if (shade_geometry_change) ; // nothing - else if( isShade()) - { - if( h == border_top + border_bottom ) - { + else if (isShade()) { + if (h == border_top + border_bottom) { kDebug(1212) << "Shaded geometry passed for size:"; kDebug(1212) << kBacktrace(); - } - else - { - client_size = QSize( w - border_left - border_right, h - border_top - border_bottom ); + } else { + client_size = QSize(w - border_left - border_right, h - border_top - border_bottom); h = border_top + border_bottom; - } } - else - { - client_size = QSize( w - border_left - border_right, h - border_top - border_bottom ); - } - QRect g( x, y, w, h ); - if( block_geometry_updates == 0 && g != rules()->checkGeometry( g )) - { - kDebug(1212) << "forced geometry fail:" << g << ":" << rules()->checkGeometry( g ); + } else { + client_size = QSize(w - border_left - border_right, h - border_top - border_bottom); + } + QRect g(x, y, w, h); + if (block_geometry_updates == 0 && g != rules()->checkGeometry(g)) { + kDebug(1212) << "forced geometry fail:" << g << ":" << rules()->checkGeometry(g); kDebug(1212) << kBacktrace(); - } - if( force == NormalGeometrySet && geom == g && pending_geometry_update == PendingGeometryNone ) + } + if (force == NormalGeometrySet && geom == g && pending_geometry_update == PendingGeometryNone) return; geom = g; - if( block_geometry_updates != 0 ) - { - if( pending_geometry_update == PendingGeometryForced ) + if (block_geometry_updates != 0) { + if (pending_geometry_update == PendingGeometryForced) {} // maximum, nothing needed - else if( force == ForceGeometrySet ) + else if (force == ForceGeometrySet) pending_geometry_update = PendingGeometryForced; else pending_geometry_update = PendingGeometryNormal; return; - } - bool resized = ( geom_before_block.size() != geom.size() || pending_geometry_update == PendingGeometryForced ); - if( resized ) - { - resizeDecoration( QSize( w, h )); - XMoveResizeWindow( display(), frameId(), x, y, w, h ); - if( !isShade()) - { + } + bool resized = (geom_before_block.size() != geom.size() || pending_geometry_update == PendingGeometryForced); + if (resized) { + resizeDecoration(QSize(w, h)); + XMoveResizeWindow(display(), frameId(), x, y, w, h); + if (!isShade()) { QSize cs = clientSize(); - XMoveResizeWindow( display(), wrapperId(), clientPos().x(), clientPos().y(), - cs.width(), cs.height()); - XMoveResizeWindow( display(), window(), 0, 0, cs.width(), cs.height()); - } - updateShape(); + XMoveResizeWindow(display(), wrapperId(), clientPos().x(), clientPos().y(), + cs.width(), cs.height()); + XMoveResizeWindow(display(), window(), 0, 0, cs.width(), cs.height()); } - else - XMoveWindow( display(), frameId(), x, y ); + updateShape(); + } else + XMoveWindow(display(), frameId(), x, y); // SELI TODO won't this be too expensive? sendSyntheticConfigureNotify(); updateWindowRules(); - - // keep track of old maximize mode + + // keep track of old maximize mode // to detect changes checkMaximizeGeometry(); - workspace()->checkActiveScreen( this ); + workspace()->checkActiveScreen(this); workspace()->updateStackingOrder(); workspace()->checkUnredirect(); - + // need to regenerate decoration pixmaps when either // - size is changed // - maximize mode is changed to MaximizeRestore, when size unchanged // which can happen when untabbing maximized windows - if( resized ) - { + if (resized) { discardWindowPixmap(); - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), geom_before_block ); - } - const QRect deco_rect = decorationRect().translated( geom.x(), geom.y() ); - addWorkspaceRepaint( deco_rect_before_block ); - addWorkspaceRepaint( deco_rect ); + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), geom_before_block); + } + const QRect deco_rect = decorationRect().translated(geom.x(), geom.y()); + addWorkspaceRepaint(deco_rect_before_block); + addWorkspaceRepaint(deco_rect); geom_before_block = geom; deco_rect_before_block = deco_rect; // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - - if(emitJs == true) - { + if (clientGroup()) + clientGroup()->updateStates(this); + + if (emitJs == true) { emit s_clientMoved(); - } - } -void Client::plainResize( int w, int h, ForceGeometry_t force, bool emitJs ) - { +} + +void Client::plainResize(int w, int h, ForceGeometry_t force, bool emitJs) +{ // this code is also duplicated in Client::setGeometry(), and it's also commented there - if( shade_geometry_change ) + if (shade_geometry_change) ; // nothing - else if( isShade()) - { - if( h == border_top + border_bottom ) - { + else if (isShade()) { + if (h == border_top + border_bottom) { kDebug(1212) << "Shaded geometry passed for size:"; kDebug(1212) << kBacktrace(); - } - else - { - client_size = QSize( w - border_left - border_right, h - border_top - border_bottom ); + } else { + client_size = QSize(w - border_left - border_right, h - border_top - border_bottom); h = border_top + border_bottom; - } } - else - { - client_size = QSize( w - border_left - border_right, h - border_top - border_bottom ); - } - QSize s( w, h ); - if( block_geometry_updates == 0 && s != rules()->checkSize( s )) - { - kDebug(1212) << "forced size fail:" << s << ":" << rules()->checkSize( s ); + } else { + client_size = QSize(w - border_left - border_right, h - border_top - border_bottom); + } + QSize s(w, h); + if (block_geometry_updates == 0 && s != rules()->checkSize(s)) { + kDebug(1212) << "forced size fail:" << s << ":" << rules()->checkSize(s); kDebug(1212) << kBacktrace(); - } + } // resuming geometry updates is handled only in setGeometry() - assert( pending_geometry_update == PendingGeometryNone || block_geometry_updates > 0 ); - if( force == NormalGeometrySet && geom.size() == s ) + assert(pending_geometry_update == PendingGeometryNone || block_geometry_updates > 0); + if (force == NormalGeometrySet && geom.size() == s) return; - geom.setSize( s ); - if( block_geometry_updates != 0 ) - { - if( pending_geometry_update == PendingGeometryForced ) + geom.setSize(s); + if (block_geometry_updates != 0) { + if (pending_geometry_update == PendingGeometryForced) {} // maximum, nothing needed - else if( force == ForceGeometrySet ) + else if (force == ForceGeometrySet) pending_geometry_update = PendingGeometryForced; else pending_geometry_update = PendingGeometryNormal; return; - } - resizeDecoration( s ); - XResizeWindow( display(), frameId(), w, h ); + } + resizeDecoration(s); + XResizeWindow(display(), frameId(), w, h); // resizeDecoration( s ); - if( !isShade()) - { + if (!isShade()) { QSize cs = clientSize(); - XMoveResizeWindow( display(), wrapperId(), clientPos().x(), clientPos().y(), - cs.width(), cs.height()); - XMoveResizeWindow( display(), window(), 0, 0, cs.width(), cs.height()); - } + XMoveResizeWindow(display(), wrapperId(), clientPos().x(), clientPos().y(), + cs.width(), cs.height()); + XMoveResizeWindow(display(), window(), 0, 0, cs.width(), cs.height()); + } updateShape(); - - if(emitJs == true) { + + if (emitJs == true) { emit s_clientMoved(); } - + sendSyntheticConfigureNotify(); updateWindowRules(); checkMaximizeGeometry(); - workspace()->checkActiveScreen( this ); + workspace()->checkActiveScreen(this); workspace()->updateStackingOrder(); workspace()->checkUnredirect(); discardWindowPixmap(); - if( scene != NULL ) - scene->windowGeometryShapeChanged( this ); - if( effects != NULL ) - static_cast(effects)->windowGeometryShapeChanged( effectWindow(), geom_before_block ); - const QRect deco_rect = decorationRect().translated( geom.x(), geom.y() ); - addWorkspaceRepaint( deco_rect_before_block ); - addWorkspaceRepaint( deco_rect ); + if (scene != NULL) + scene->windowGeometryShapeChanged(this); + if (effects != NULL) + static_cast(effects)->windowGeometryShapeChanged(effectWindow(), geom_before_block); + const QRect deco_rect = decorationRect().translated(geom.x(), geom.y()); + addWorkspaceRepaint(deco_rect_before_block); + addWorkspaceRepaint(deco_rect); geom_before_block = geom; deco_rect_before_block = deco_rect; // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} /*! Reimplemented to inform the client about the new window position. */ -void Client::move( int x, int y, ForceGeometry_t force ) - { +void Client::move(int x, int y, ForceGeometry_t force) +{ // resuming geometry updates is handled only in setGeometry() - assert( pending_geometry_update == PendingGeometryNone || block_geometry_updates > 0 ); - QPoint p( x, y ); - if( block_geometry_updates == 0 && p != rules()->checkPosition( p )) - { - kDebug(1212) << "forced position fail:" << p << ":" << rules()->checkPosition( p ); + assert(pending_geometry_update == PendingGeometryNone || block_geometry_updates > 0); + QPoint p(x, y); + if (block_geometry_updates == 0 && p != rules()->checkPosition(p)) { + kDebug(1212) << "forced position fail:" << p << ":" << rules()->checkPosition(p); kDebug(1212) << kBacktrace(); - } - if( force == NormalGeometrySet && geom.topLeft() == p ) + } + if (force == NormalGeometrySet && geom.topLeft() == p) return; - geom.moveTopLeft( p ); - if( block_geometry_updates != 0 ) - { - if( pending_geometry_update == PendingGeometryForced ) + geom.moveTopLeft(p); + if (block_geometry_updates != 0) { + if (pending_geometry_update == PendingGeometryForced) {} // maximum, nothing needed - else if( force == ForceGeometrySet ) + else if (force == ForceGeometrySet) pending_geometry_update = PendingGeometryForced; else pending_geometry_update = PendingGeometryNormal; return; - } - XMoveWindow( display(), frameId(), x, y ); + } + XMoveWindow(display(), frameId(), x, y); sendSyntheticConfigureNotify(); updateWindowRules(); checkMaximizeGeometry(); - workspace()->checkActiveScreen( this ); + workspace()->checkActiveScreen(this); workspace()->updateStackingOrder(); workspace()->checkUnredirect(); - workspace()->notifyTilingWindowMove( this, moveResizeGeom, initialMoveResizeGeom ); + workspace()->notifyTilingWindowMove(this, moveResizeGeom, initialMoveResizeGeom); // client itself is not damaged - const QRect deco_rect = decorationRect().translated( geom.x(), geom.y() ); - addWorkspaceRepaint( deco_rect_before_block ); - addWorkspaceRepaint( deco_rect ); // trigger repaint of window's new location + const QRect deco_rect = decorationRect().translated(geom.x(), geom.y()); + addWorkspaceRepaint(deco_rect_before_block); + addWorkspaceRepaint(deco_rect); // trigger repaint of window's new location geom_before_block = geom; deco_rect_before_block = deco_rect; // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} -void Client::blockGeometryUpdates( bool block ) - { - if( block ) - { - if( block_geometry_updates == 0 ) +void Client::blockGeometryUpdates(bool block) +{ + if (block) { + if (block_geometry_updates == 0) pending_geometry_update = PendingGeometryNone; ++block_geometry_updates; - } - else - { - if( --block_geometry_updates == 0 ) - { - if( pending_geometry_update != PendingGeometryNone ) - { - if( isShade()) - setGeometry( QRect( pos(), adjustedSize()), NormalGeometrySet ); + } else { + if (--block_geometry_updates == 0) { + if (pending_geometry_update != PendingGeometryNone) { + if (isShade()) + setGeometry(QRect(pos(), adjustedSize()), NormalGeometrySet); else - setGeometry( geometry(), NormalGeometrySet ); + setGeometry(geometry(), NormalGeometrySet); pending_geometry_update = PendingGeometryNone; - } } } } +} -void Client::maximize( MaximizeMode m ) - { - setMaximize( m & MaximizeVertical, m & MaximizeHorizontal ); - } +void Client::maximize(MaximizeMode m) +{ + setMaximize(m & MaximizeVertical, m & MaximizeHorizontal); +} /*! Sets the maximization according to \a vertically and \a horizontally */ -void Client::setMaximize( bool vertically, bool horizontally ) - { +void Client::setMaximize(bool vertically, bool horizontally) +{ //Scripting call. Does not use a signal/slot mechanism //as ensuring connections was a bit difficult between //so many clients and the workspace SWrapper::WorkspaceProxy* ws_wrap = SWrapper::WorkspaceProxy::instance(); - if(ws_wrap != 0) { + if (ws_wrap != 0) { ws_wrap->sl_clientMaximizeSet(this, QPair(vertically, horizontally)); } - + emit maximizeSet(QPair(vertically, horizontally)); - + // changeMaximize() flips the state, so change from set->flip changeMaximize( max_mode & MaximizeVertical ? !vertically : vertically, max_mode & MaximizeHorizontal ? !horizontally : horizontally, - false ); - if( effects ) - static_cast(effects)->windowUserMovedResized( effectWindow(), true, true ); + false); + if (effects) + static_cast(effects)->windowUserMovedResized(effectWindow(), true, true); // Update states of all other windows in this group - if( clientGroup() ) - clientGroup()->updateStates( this ); - } + if (clientGroup()) + clientGroup()->updateStates(this); +} -void Client::changeMaximize( bool vertical, bool horizontal, bool adjust ) - { - if( !isMaximizable()) +void Client::changeMaximize(bool vertical, bool horizontal, bool adjust) +{ + if (!isMaximizable()) return; MaximizeMode old_mode = max_mode; // 'adjust == true' means to update the size only, e.g. after changing workspace size - if( !adjust ) - { - if( vertical ) - max_mode = MaximizeMode( max_mode ^ MaximizeVertical ); - if( horizontal ) - max_mode = MaximizeMode( max_mode ^ MaximizeHorizontal ); - } + if (!adjust) { + if (vertical) + max_mode = MaximizeMode(max_mode ^ MaximizeVertical); + if (horizontal) + max_mode = MaximizeMode(max_mode ^ MaximizeHorizontal); + } - max_mode = rules()->checkMaximize( max_mode ); - if( !adjust && max_mode == old_mode ) + max_mode = rules()->checkMaximize(max_mode); + if (!adjust && max_mode == old_mode) return; - GeometryUpdatesBlocker blocker( this ); + GeometryUpdatesBlocker blocker(this); // maximing one way and unmaximizing the other way shouldn't happen, // so restore first and then maximize the other way - if( ( old_mode == MaximizeVertical && max_mode == MaximizeHorizontal ) - || ( old_mode == MaximizeHorizontal && max_mode == MaximizeVertical )) - { - changeMaximize( false, false, false ); // restore - } + if ((old_mode == MaximizeVertical && max_mode == MaximizeHorizontal) + || (old_mode == MaximizeHorizontal && max_mode == MaximizeVertical)) { + changeMaximize(false, false, false); // restore + } QRect clientArea; - if( isElectricBorderMaximizing() ) - clientArea = workspace()->clientArea( MaximizeArea, cursorPos(), desktop() ); + if (isElectricBorderMaximizing()) + clientArea = workspace()->clientArea(MaximizeArea, cursorPos(), desktop()); else - clientArea = workspace()->clientArea( MaximizeArea, this ); + clientArea = workspace()->clientArea(MaximizeArea, this); - if( options->borderlessMaximizedWindows() ) + if (options->borderlessMaximizedWindows()) setNoBorder(app_noborder || max_mode == MaximizeFull); // save sizes for restoring, if maximalizing - if( !adjust && !( y() == clientArea.top() && height() == clientArea.height())) - { - geom_restore.setTop( y()); - geom_restore.setHeight( height()); - } - if( !adjust && !( x() == clientArea.left() && width() == clientArea.width())) - { - geom_restore.setLeft( x()); - geom_restore.setWidth( width()); - } + if (!adjust && !(y() == clientArea.top() && height() == clientArea.height())) { + geom_restore.setTop(y()); + geom_restore.setHeight(height()); + } + if (!adjust && !(x() == clientArea.left() && width() == clientArea.width())) { + geom_restore.setLeft(x()); + geom_restore.setWidth(width()); + } - if( !adjust ) - { - if(( vertical && !(old_mode & MaximizeVertical )) - || ( horizontal && !( old_mode & MaximizeHorizontal ))) - Notify::raise( Notify::Maximize ); + if (!adjust) { + if ((vertical && !(old_mode & MaximizeVertical)) + || (horizontal && !(old_mode & MaximizeHorizontal))) + Notify::raise(Notify::Maximize); else - Notify::raise( Notify::UnMaximize ); - } + Notify::raise(Notify::UnMaximize); + } ForceGeometry_t geom_mode = NormalGeometrySet; - if( decoration != NULL ) // decorations may turn off some borders when maximized - { - if( checkBorderSizes( false )) // only query, don't resize + if (decoration != NULL) { // decorations may turn off some borders when maximized + if (checkBorderSizes(false)) // only query, don't resize geom_mode = ForceGeometrySet; - } + } // Conditional quick tiling exit points - if( quick_tile_mode != QuickTileNone ) - { - if( old_mode == MaximizeFull && - !clientArea.contains( geom_restore.center() )) - { // Not restoring on the same screen + if (quick_tile_mode != QuickTileNone) { + if (old_mode == MaximizeFull && + !clientArea.contains(geom_restore.center())) { + // Not restoring on the same screen // TODO: The following doesn't work for some reason //geom_restore = geom_pretile; // Restore to the pretiled geometry //quick_tile_mode = QuickTileNone; // And exit quick tile mode manually - } - else if(( old_mode == MaximizeVertical && max_mode == MaximizeRestore ) || - ( old_mode == MaximizeFull && max_mode == MaximizeHorizontal )) - { // Modifying geometry of a tiled window + } else if ((old_mode == MaximizeVertical && max_mode == MaximizeRestore) || + (old_mode == MaximizeFull && max_mode == MaximizeHorizontal)) { + // Modifying geometry of a tiled window quick_tile_mode = QuickTileNone; // Exit quick tile mode without restoring geometry - } } + } // restore partial maximizations - if ( old_mode==MaximizeFull && max_mode==MaximizeRestore ) - { - if ( maximizeModeRestore()==MaximizeVertical ) - { - max_mode = MaximizeVertical; - maxmode_restore = MaximizeRestore; - } - if ( maximizeModeRestore()==MaximizeHorizontal ) - { - max_mode = MaximizeHorizontal; - maxmode_restore = MaximizeRestore; - } - } - - switch (max_mode) - { - - case MaximizeVertical: - { - if( old_mode & MaximizeHorizontal ) // actually restoring from MaximizeFull - { - if( geom_restore.width() == 0 || !clientArea.contains( geom_restore.center() )) - { // needs placement - plainResize( adjustedSize( QSize( width() * 2 / 3, clientArea.height()), SizemodeFixedH ), geom_mode ); - workspace()->placeSmart( this, clientArea ); - } - else - { - setGeometry( QRect(QPoint( geom_restore.x(), clientArea.top()), - adjustedSize(QSize( geom_restore.width(), clientArea.height()), SizemodeFixedH )), geom_mode ); - } - } - else - { - setGeometry( QRect(QPoint(x(), clientArea.top()), - adjustedSize(QSize(width(), clientArea.height()), SizemodeFixedH )), geom_mode ); - } - info->setState( NET::MaxVert, NET::Max ); - break; - } - - case MaximizeHorizontal: - { - if( old_mode & MaximizeVertical ) // actually restoring from MaximizeFull - { - if( geom_restore.height() == 0 || !clientArea.contains( geom_restore.center() ) ) - { // needs placement - plainResize( adjustedSize( QSize( clientArea.width(), height() * 2 / 3 ), SizemodeFixedW ), geom_mode ); - workspace()->placeSmart( this, clientArea ); - } - else - { - setGeometry( QRect( QPoint(clientArea.left(), geom_restore.y()), - adjustedSize(QSize(clientArea.width(), geom_restore.height()), SizemodeFixedW )), geom_mode ); - } - } - else - { - setGeometry( QRect( QPoint(clientArea.left(), y()), - adjustedSize(QSize(clientArea.width(), height()), SizemodeFixedW )), geom_mode ); - } - info->setState( NET::MaxHoriz, NET::Max ); - break; - } - - case MaximizeRestore: - { - QRect restore = geometry(); - // when only partially maximized, geom_restore may not have the other dimension remembered - if( old_mode & MaximizeVertical ) - { - restore.setTop( geom_restore.top()); - restore.setBottom( geom_restore.bottom()); - } - if( old_mode & MaximizeHorizontal ) - { - restore.setLeft( geom_restore.left()); - restore.setRight( geom_restore.right()); - } - if( !restore.isValid()) - { - QSize s = QSize( clientArea.width()*2/3, clientArea.height()*2/3 ); - if( geom_restore.width() > 0 ) - s.setWidth( geom_restore.width()); - if( geom_restore.height() > 0 ) - s.setHeight( geom_restore.height()); - plainResize( adjustedSize( s )); - workspace()->placeSmart( this, clientArea ); - restore = geometry(); - if( geom_restore.width() > 0 ) - restore.moveLeft( geom_restore.x()); - if( geom_restore.height() > 0 ) - restore.moveTop( geom_restore.y()); - } - setGeometry( restore, geom_mode ); - if( !clientArea.contains( geom_restore.center() )) // Not restoring to the same screen - workspace()->place( this, clientArea ); - info->setState( 0, NET::Max ); - break; - } - - case MaximizeFull: - { - if( !adjust ) - { - if( old_mode & MaximizeVertical ) - maxmode_restore = MaximizeVertical; - if( old_mode & MaximizeHorizontal ) - maxmode_restore = MaximizeHorizontal; - } - QSize adjSize = adjustedSize(clientArea.size(), SizemodeMax ); - QRect r = QRect(clientArea.topLeft(), adjSize); - setGeometry( r, geom_mode ); - info->setState( NET::Max, NET::Max ); - break; - } - default: - break; + if (old_mode == MaximizeFull && max_mode == MaximizeRestore) { + if (maximizeModeRestore() == MaximizeVertical) { + max_mode = MaximizeVertical; + maxmode_restore = MaximizeRestore; } + if (maximizeModeRestore() == MaximizeHorizontal) { + max_mode = MaximizeHorizontal; + maxmode_restore = MaximizeRestore; + } + } + + switch(max_mode) { + + case MaximizeVertical: { + if (old_mode & MaximizeHorizontal) { // actually restoring from MaximizeFull + if (geom_restore.width() == 0 || !clientArea.contains(geom_restore.center())) { + // needs placement + plainResize(adjustedSize(QSize(width() * 2 / 3, clientArea.height()), SizemodeFixedH), geom_mode); + workspace()->placeSmart(this, clientArea); + } else { + setGeometry(QRect(QPoint(geom_restore.x(), clientArea.top()), + adjustedSize(QSize(geom_restore.width(), clientArea.height()), SizemodeFixedH)), geom_mode); + } + } else { + setGeometry(QRect(QPoint(x(), clientArea.top()), + adjustedSize(QSize(width(), clientArea.height()), SizemodeFixedH)), geom_mode); + } + info->setState(NET::MaxVert, NET::Max); + break; + } + + case MaximizeHorizontal: { + if (old_mode & MaximizeVertical) { // actually restoring from MaximizeFull + if (geom_restore.height() == 0 || !clientArea.contains(geom_restore.center())) { + // needs placement + plainResize(adjustedSize(QSize(clientArea.width(), height() * 2 / 3), SizemodeFixedW), geom_mode); + workspace()->placeSmart(this, clientArea); + } else { + setGeometry(QRect(QPoint(clientArea.left(), geom_restore.y()), + adjustedSize(QSize(clientArea.width(), geom_restore.height()), SizemodeFixedW)), geom_mode); + } + } else { + setGeometry(QRect(QPoint(clientArea.left(), y()), + adjustedSize(QSize(clientArea.width(), height()), SizemodeFixedW)), geom_mode); + } + info->setState(NET::MaxHoriz, NET::Max); + break; + } + + case MaximizeRestore: { + QRect restore = geometry(); + // when only partially maximized, geom_restore may not have the other dimension remembered + if (old_mode & MaximizeVertical) { + restore.setTop(geom_restore.top()); + restore.setBottom(geom_restore.bottom()); + } + if (old_mode & MaximizeHorizontal) { + restore.setLeft(geom_restore.left()); + restore.setRight(geom_restore.right()); + } + if (!restore.isValid()) { + QSize s = QSize(clientArea.width() * 2 / 3, clientArea.height() * 2 / 3); + if (geom_restore.width() > 0) + s.setWidth(geom_restore.width()); + if (geom_restore.height() > 0) + s.setHeight(geom_restore.height()); + plainResize(adjustedSize(s)); + workspace()->placeSmart(this, clientArea); + restore = geometry(); + if (geom_restore.width() > 0) + restore.moveLeft(geom_restore.x()); + if (geom_restore.height() > 0) + restore.moveTop(geom_restore.y()); + } + setGeometry(restore, geom_mode); + if (!clientArea.contains(geom_restore.center())) // Not restoring to the same screen + workspace()->place(this, clientArea); + info->setState(0, NET::Max); + break; + } + + case MaximizeFull: { + if (!adjust) { + if (old_mode & MaximizeVertical) + maxmode_restore = MaximizeVertical; + if (old_mode & MaximizeHorizontal) + maxmode_restore = MaximizeHorizontal; + } + QSize adjSize = adjustedSize(clientArea.size(), SizemodeMax); + QRect r = QRect(clientArea.topLeft(), adjSize); + setGeometry(r, geom_mode); + info->setState(NET::Max, NET::Max); + break; + } + default: + break; + } updateAllowedActions(); - if( decoration != NULL ) + if (decoration != NULL) decoration->maximizeChange(); updateWindowRules(); - } +} void Client::resetMaximize() - { - if( max_mode == MaximizeRestore ) +{ + if (max_mode == MaximizeRestore) return; max_mode = MaximizeRestore; - Notify::raise( Notify::UnMaximize ); - info->setState( 0, NET::Max ); + Notify::raise(Notify::UnMaximize); + info->setState(0, NET::Max); updateAllowedActions(); - if( decoration != NULL ) - decoration->borders( border_left, border_right, border_top, border_bottom ); - if( isShade()) - setGeometry( QRect( pos(), sizeForClientSize( clientSize())), ForceGeometrySet ); + if (decoration != NULL) + decoration->borders(border_left, border_right, border_top, border_bottom); + if (isShade()) + setGeometry(QRect(pos(), sizeForClientSize(clientSize())), ForceGeometrySet); else - setGeometry( geometry(), ForceGeometrySet ); - if( decoration != NULL ) + setGeometry(geometry(), ForceGeometrySet); + if (decoration != NULL) decoration->maximizeChange(); - } +} void Client::checkMaximizeGeometry() - { +{ // when adding new bail-out conditions here, checkMaximizeGeometry() needs to be called // when after the condition is no longer true - if( isShade()) + if (isShade()) return; - if( isMove() || isResize()) // this is because of the option to disallow moving/resizing of max-ed windows + if (isMove() || isResize()) // this is because of the option to disallow moving/resizing of max-ed windows return; // Just in case. static int recursion_protection = 0; - if( recursion_protection > 3 ) - { - kWarning( 1212 ) << "Check maximize overflow - you loose!" ; - kWarning( 1212 ) << kBacktrace() ; + if (recursion_protection > 3) { + kWarning(1212) << "Check maximize overflow - you loose!" ; + kWarning(1212) << kBacktrace() ; return; - } + } ++recursion_protection; - QRect max_area = workspace()->clientArea( MaximizeArea, this ); - if( geometry() == max_area ) - { - if( max_mode != MaximizeFull ) - maximize( MaximizeFull ); - } - else if( x() == max_area.left() && width() == max_area.width()) - { - if( max_mode != MaximizeHorizontal ) - maximize( MaximizeHorizontal ); - } - else if( y() == max_area.top() && height() == max_area.height()) - { - if( max_mode != MaximizeVertical ) - maximize( MaximizeVertical ); - } - else if( max_mode != MaximizeRestore ) - { + QRect max_area = workspace()->clientArea(MaximizeArea, this); + if (geometry() == max_area) { + if (max_mode != MaximizeFull) + maximize(MaximizeFull); + } else if (x() == max_area.left() && width() == max_area.width()) { + if (max_mode != MaximizeHorizontal) + maximize(MaximizeHorizontal); + } else if (y() == max_area.top() && height() == max_area.height()) { + if (max_mode != MaximizeVertical) + maximize(MaximizeVertical); + } else if (max_mode != MaximizeRestore) { resetMaximize(); // not maximize( MaximizeRestore ), that'd change geometry - this is called from setGeometry() - } + } --recursion_protection; - } +} -bool Client::isFullScreenable( bool fullscreen_hack ) const - { - if( !rules()->checkFullScreen( true )) +bool Client::isFullScreenable(bool fullscreen_hack) const +{ + if (!rules()->checkFullScreen(true)) return false; - if( fullscreen_hack ) + if (fullscreen_hack) return isNormalWindow(); - if( rules()->checkStrictGeometry( false )) - { + if (rules()->checkStrictGeometry(false)) { // the app wouldn't fit exactly fullscreen geometry due to its strict geometry requirements - QRect fsarea = workspace()->clientArea( FullScreenArea, this ); - if( sizeForClientSize( fsarea.size(), SizemodeAny, true ) != fsarea.size()) + QRect fsarea = workspace()->clientArea(FullScreenArea, this); + if (sizeForClientSize(fsarea.size(), SizemodeAny, true) != fsarea.size()) return false; - } - // don't check size constrains - some apps request fullscreen despite requesting fixed size - return !isSpecialWindow(); // also better disallow only weird types to go fullscreen } + // don't check size constrains - some apps request fullscreen despite requesting fixed size + return !isSpecialWindow(); // also better disallow only weird types to go fullscreen +} bool Client::userCanSetFullScreen() const - { - if( fullscreen_mode == FullScreenHack ) +{ + if (fullscreen_mode == FullScreenHack) return false; - if( !isFullScreenable( false )) + if (!isFullScreenable(false)) return false; // isMaximizable() returns false if fullscreen - TemporaryAssign< FullScreenMode > tmp( fullscreen_mode, FullScreenNone ); + TemporaryAssign< FullScreenMode > tmp(fullscreen_mode, FullScreenNone); return isNormalWindow() && isMaximizable(); - } +} -void Client::setFullScreen( bool set, bool user ) - { - if( !isFullScreen() && !set ) +void Client::setFullScreen(bool set, bool user) +{ + if (!isFullScreen() && !set) return; - if( fullscreen_mode == FullScreenHack ) + if (fullscreen_mode == FullScreenHack) return; - if( user && !userCanSetFullScreen()) + if (user && !userCanSetFullScreen()) return; - set = rules()->checkFullScreen( set ); - setShade( ShadeNone ); + set = rules()->checkFullScreen(set); + setShade(ShadeNone); bool was_fs = isFullScreen(); - if( !was_fs ) + if (!was_fs) geom_fs_restore = geometry(); fullscreen_mode = set ? FullScreenNormal : FullScreenNone; - if( was_fs == isFullScreen()) + if (was_fs == isFullScreen()) return; - if ( set ) - workspace()->raiseClient( this ); - StackingUpdatesBlocker blocker1( workspace()); - GeometryUpdatesBlocker blocker2( this ); - workspace()->updateClientLayer( this ); // active fullscreens get different layer - info->setState( isFullScreen() ? NET::FullScreen : 0, NET::FullScreen ); - updateDecoration( false, false ); - if( isFullScreen()) - if( info->fullscreenMonitors().isSet()) - setGeometry( fullscreenMonitorsArea( info->fullscreenMonitors())); + if (set) + workspace()->raiseClient(this); + StackingUpdatesBlocker blocker1(workspace()); + GeometryUpdatesBlocker blocker2(this); + workspace()->updateClientLayer(this); // active fullscreens get different layer + info->setState(isFullScreen() ? NET::FullScreen : 0, NET::FullScreen); + updateDecoration(false, false); + if (isFullScreen()) + if (info->fullscreenMonitors().isSet()) + setGeometry(fullscreenMonitorsArea(info->fullscreenMonitors())); else - setGeometry( workspace()->clientArea( FullScreenArea, this )); - else - { - if( !geom_fs_restore.isNull()) - setGeometry( QRect( geom_fs_restore.topLeft(), adjustedSize( geom_fs_restore.size()))); + setGeometry(workspace()->clientArea(FullScreenArea, this)); + else { + if (!geom_fs_restore.isNull()) + setGeometry(QRect(geom_fs_restore.topLeft(), adjustedSize(geom_fs_restore.size()))); // TODO isShaded() ? - else - { // does this ever happen? - setGeometry( workspace()->clientArea( MaximizeArea, this )); - } + else { + // does this ever happen? + setGeometry(workspace()->clientArea(MaximizeArea, this)); } + } updateWindowRules(); workspace()->checkUnredirect(); - + SWrapper::WorkspaceProxy* ws_object = SWrapper::WorkspaceProxy::instance(); - if(ws_object != 0) { - ws_object->sl_clientFullScreenSet(this, set, user); + if (ws_object != 0) { + ws_object->sl_clientFullScreenSet(this, set, user); } - + emit s_fullScreenSet(set, user); - } +} -void Client::updateFullscreenMonitors( NETFullscreenMonitors topology ) - { +void Client::updateFullscreenMonitors(NETFullscreenMonitors topology) +{ int nscreens = Kephal::ScreenUtils::numScreens(); // kDebug( 1212 ) << "incoming request with top: " << topology.top << " bottom: " << topology.bottom // << " left: " << topology.left << " right: " << topology.right // << ", we have: " << nscreens << " screens."; - if( topology.top >= nscreens || - topology.bottom >= nscreens || - topology.left >= nscreens || - topology.right >= nscreens ) - { - kWarning( 1212 ) << "fullscreenMonitors update failed. request higher than number of screens."; - return; - } - - info->setFullscreenMonitors( topology ); - if( isFullScreen()) - setGeometry( fullscreenMonitorsArea( topology )); + if (topology.top >= nscreens || + topology.bottom >= nscreens || + topology.left >= nscreens || + topology.right >= nscreens) { + kWarning(1212) << "fullscreenMonitors update failed. request higher than number of screens."; + return; } + info->setFullscreenMonitors(topology); + if (isFullScreen()) + setGeometry(fullscreenMonitorsArea(topology)); +} + /*! Calculates the bounding rectangle defined by the 4 monitor indices indicating the top, bottom, left, and right edges of the window when the fullscreen state is enabled. */ QRect Client::fullscreenMonitorsArea(NETFullscreenMonitors requestedTopology) const - { +{ QRect top, bottom, left, right, total; - top = Kephal::ScreenUtils::screenGeometry( requestedTopology.top ); - bottom = Kephal::ScreenUtils::screenGeometry(requestedTopology.bottom ); - left = Kephal::ScreenUtils::screenGeometry(requestedTopology.left ); - right = Kephal::ScreenUtils::screenGeometry(requestedTopology.right ); - total = top.united( bottom.united( left.united( right ) ) ); + top = Kephal::ScreenUtils::screenGeometry(requestedTopology.top); + bottom = Kephal::ScreenUtils::screenGeometry(requestedTopology.bottom); + left = Kephal::ScreenUtils::screenGeometry(requestedTopology.left); + right = Kephal::ScreenUtils::screenGeometry(requestedTopology.right); + total = top.united(bottom.united(left.united(right))); // kDebug( 1212 ) << "top: " << top << " bottom: " << bottom // << " left: " << left << " right: " << right; // kDebug( 1212 ) << "returning rect: " << total; return total; - } +} -int Client::checkFullScreenHack( const QRect& geom ) const - { - if( !options->legacyFullscreenSupport ) +int Client::checkFullScreenHack(const QRect& geom) const +{ + if (!options->legacyFullscreenSupport) return 0; // if it's noborder window, and has size of one screen or the whole desktop geometry, it's fullscreen hack - if( noBorder() && app_noborder && isFullScreenable( true )) - { - if( geom.size() == workspace()->clientArea( FullArea, geom.center(), desktop()).size()) + if (noBorder() && app_noborder && isFullScreenable(true)) { + if (geom.size() == workspace()->clientArea(FullArea, geom.center(), desktop()).size()) return 2; // full area fullscreen hack - if( geom.size() == workspace()->clientArea( ScreenArea, geom.center(), desktop()).size()) + if (geom.size() == workspace()->clientArea(ScreenArea, geom.center(), desktop()).size()) return 1; // xinerama-aware fullscreen hack - } + } return 0; - } +} -void Client::updateFullScreenHack( const QRect& geom ) - { - int type = checkFullScreenHack( geom ); - if( fullscreen_mode == FullScreenNone && type != 0 ) - { +void Client::updateFullScreenHack(const QRect& geom) +{ + int type = checkFullScreenHack(geom); + if (fullscreen_mode == FullScreenNone && type != 0) { fullscreen_mode = FullScreenHack; - updateDecoration( false, false ); + updateDecoration(false, false); QRect geom; - if( rules()->checkStrictGeometry( false )) - { + if (rules()->checkStrictGeometry(false)) { geom = type == 2 // 1 - it's xinerama-aware fullscreen hack, 2 - it's full area - ? workspace()->clientArea( FullArea, geom.center(), desktop()) - : workspace()->clientArea( ScreenArea, geom.center(), desktop()); - } - else - geom = workspace()->clientArea( FullScreenArea, geom.center(), desktop()); - setGeometry( geom ); - } - else if( fullscreen_mode == FullScreenHack && type == 0 ) - { + ? workspace()->clientArea(FullArea, geom.center(), desktop()) + : workspace()->clientArea(ScreenArea, geom.center(), desktop()); + } else + geom = workspace()->clientArea(FullScreenArea, geom.center(), desktop()); + setGeometry(geom); + } else if (fullscreen_mode == FullScreenHack && type == 0) { fullscreen_mode = FullScreenNone; - updateDecoration( false, false ); + updateDecoration(false, false); // whoever called this must setup correct geometry - } - StackingUpdatesBlocker blocker( workspace()); - workspace()->updateClientLayer( this ); // active fullscreens get different layer } + StackingUpdatesBlocker blocker(workspace()); + workspace()->updateClientLayer(this); // active fullscreens get different layer +} static QRect* visible_bound = 0; static GeometryTip* geometryTip = 0; -void Client::drawbound( const QRect& geom ) - { - assert( visible_bound == NULL ); - visible_bound = new QRect( geom ); - doDrawbound( *visible_bound, false ); - } +void Client::drawbound(const QRect& geom) +{ + assert(visible_bound == NULL); + visible_bound = new QRect(geom); + doDrawbound(*visible_bound, false); +} void Client::clearbound() - { - if( visible_bound == NULL ) +{ + if (visible_bound == NULL) return; - doDrawbound( *visible_bound, true ); + doDrawbound(*visible_bound, true); delete visible_bound; visible_bound = 0; - } +} -void Client::doDrawbound( const QRect& geom, bool clear ) - { - if( effects && static_cast(effects)->provides( Effect::Resize ) ) +void Client::doDrawbound(const QRect& geom, bool clear) +{ + if (effects && static_cast(effects)->provides(Effect::Resize)) return; // done by effect - if( decoration != NULL && decoration->drawbound( geom, clear ) ) + if (decoration != NULL && decoration->drawbound(geom, clear)) return; // done by decoration XGCValues xgc; xgc.function = GXxor; - xgc.foreground = WhitePixel( display(), DefaultScreen( display())); + xgc.foreground = WhitePixel(display(), DefaultScreen(display())); xgc.line_width = 5; xgc.subwindow_mode = IncludeInferiors; - GC gc = XCreateGC( display(), DefaultRootWindow( display()), - GCFunction | GCForeground | GCLineWidth | GCSubwindowMode, &xgc ); + GC gc = XCreateGC(display(), DefaultRootWindow(display()), + GCFunction | GCForeground | GCLineWidth | GCSubwindowMode, &xgc); // the line is 5 pixel thick, so compensate for the extra two pixels // on outside (#88657) QRect g = geom; - if( g.width() > 5 ) - { - g.setLeft( g.left() + 2 ); - g.setRight( g.right() - 2 ); - } - if( g.height() > 5 ) - { - g.setTop( g.top() + 2 ); - g.setBottom( g.bottom() - 2 ); - } - XDrawRectangle( display(), DefaultRootWindow( display()), gc, g.x(), g.y(), g.width(), g.height()); - XFreeGC( display(), gc ); + if (g.width() > 5) { + g.setLeft(g.left() + 2); + g.setRight(g.right() - 2); } + if (g.height() > 5) { + g.setTop(g.top() + 2); + g.setBottom(g.bottom() - 2); + } + XDrawRectangle(display(), DefaultRootWindow(display()), gc, g.x(), g.y(), g.width(), g.height()); + XFreeGC(display(), gc); +} void Client::positionGeometryTip() - { - assert( isMove() || isResize()); +{ + assert(isMove() || isResize()); // Position and Size display - if ( effects && static_cast(effects)->provides( Effect::GeometryTip ) ) + if (effects && static_cast(effects)->provides(Effect::GeometryTip)) return; // some effect paints this for us - if ( options->showGeometryTip() ) - { - if( !geometryTip ) - { // save under is not necessary with opaque, and seem to make things slower - bool save_under = ( isMove() && rules()->checkMoveResizeMode( options->moveMode ) != Options::Opaque ) - || ( isResize() && rules()->checkMoveResizeMode( options->resizeMode ) != Options::Opaque ); - geometryTip = new GeometryTip( &xSizeHint, save_under ); - } - QRect wgeom( moveResizeGeom ); // position of the frame, size of the window itself - wgeom.setWidth( wgeom.width() - ( width() - clientSize().width())); - wgeom.setHeight( wgeom.height() - ( height() - clientSize().height())); - if( isShade()) - wgeom.setHeight( 0 ); - geometryTip->setGeometry( wgeom ); - if( !geometryTip->isVisible()) + if (options->showGeometryTip()) { + if (!geometryTip) { + // save under is not necessary with opaque, and seem to make things slower + bool save_under = (isMove() && rules()->checkMoveResizeMode(options->moveMode) != Options::Opaque) + || (isResize() && rules()->checkMoveResizeMode(options->resizeMode) != Options::Opaque); + geometryTip = new GeometryTip(&xSizeHint, save_under); + } + QRect wgeom(moveResizeGeom); // position of the frame, size of the window itself + wgeom.setWidth(wgeom.width() - (width() - clientSize().width())); + wgeom.setHeight(wgeom.height() - (height() - clientSize().height())); + if (isShade()) + wgeom.setHeight(0); + geometryTip->setGeometry(wgeom); + if (!geometryTip->isVisible()) geometryTip->show(); geometryTip->raise(); - } } +} class EatAllPaintEvents : public QObject - { - protected: - virtual bool eventFilter( QObject* o, QEvent* e ) - { return e->type() == QEvent::Paint && o != geometryTip; } - }; +{ +protected: + virtual bool eventFilter(QObject* o, QEvent* e) { + return e->type() == QEvent::Paint && o != geometryTip; + } +}; static EatAllPaintEvents* eater = 0; bool Client::startMoveResize() - { - assert( !moveResizeMode ); - assert( QWidget::keyboardGrabber() == NULL ); - assert( QWidget::mouseGrabber() == NULL ); +{ + assert(!moveResizeMode); + assert(QWidget::keyboardGrabber() == NULL); + assert(QWidget::mouseGrabber() == NULL); stopDelayedMoveResize(); - if( QApplication::activePopupWidget() != NULL ) + if (QApplication::activePopupWidget() != NULL) return false; // popups have grab bool has_grab = false; // This reportedly improves smoothness of the moveresize operation, // something with Enter/LeaveNotify events, looks like XFree performance problem or something *shrug* // (http://lists.kde.org/?t=107302193400001&r=1&w=2) XSetWindowAttributes attrs; - QRect r = workspace()->clientArea( FullArea, this ); - move_resize_grab_window = XCreateWindow( display(), rootWindow(), r.x(), r.y(), - r.width(), r.height(), 0, CopyFromParent, InputOnly, CopyFromParent, 0, &attrs ); - XMapRaised( display(), move_resize_grab_window ); - if( XGrabPointer( display(), move_resize_grab_window, False, - ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask, - GrabModeAsync, GrabModeAsync, move_resize_grab_window, cursor.handle(), xTime() ) == Success ) + QRect r = workspace()->clientArea(FullArea, this); + move_resize_grab_window = XCreateWindow(display(), rootWindow(), r.x(), r.y(), + r.width(), r.height(), 0, CopyFromParent, InputOnly, CopyFromParent, 0, &attrs); + XMapRaised(display(), move_resize_grab_window); + if (XGrabPointer(display(), move_resize_grab_window, False, + ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask, + GrabModeAsync, GrabModeAsync, move_resize_grab_window, cursor.handle(), xTime()) == Success) has_grab = true; - if( grabXKeyboard( frameId())) + if (grabXKeyboard(frameId())) has_grab = move_resize_has_keyboard_grab = true; - if( !has_grab ) // at least one grab is necessary in order to be able to finish move/resize - { - XDestroyWindow( display(), move_resize_grab_window ); + if (!has_grab) { // at least one grab is necessary in order to be able to finish move/resize + XDestroyWindow(display(), move_resize_grab_window); move_resize_grab_window = None; return false; - } - if( maximizeMode() == MaximizeFull && options->electricBorderMaximize() && - !options->moveResizeMaximizedWindows() ) - { // If we have quick maximization enabled then it's safe to automatically restore windows - // when starting a move as the user can undo their action by moving the window back to - // the top of the screen. When the setting is disabled then doing so is confusing. + } + if (maximizeMode() == MaximizeFull && options->electricBorderMaximize() && + !options->moveResizeMaximizedWindows()) { + // If we have quick maximization enabled then it's safe to automatically restore windows + // when starting a move as the user can undo their action by moving the window back to + // the top of the screen. When the setting is disabled then doing so is confusing. const QRect before = geometry(); - setMaximize( false, false ); + setMaximize(false, false); // Move the window so it's under the cursor moveOffset = QPoint( - double( moveOffset.x() ) / double( before.width() ) * double( geom_restore.width() ), - double( moveOffset.y() ) / double( before.height() ) * double( geom_restore.height() ) - ); - } - if( maximizeMode() != MaximizeRestore ) + double(moveOffset.x()) / double(before.width()) * double(geom_restore.width()), + double(moveOffset.y()) / double(before.height()) * double(geom_restore.height()) + ); + } + if (maximizeMode() != MaximizeRestore) resetMaximize(); // TODO: I have no idea what this does... Is it needed? - if( quick_tile_mode != QuickTileNone && isMovable() && mode == PositionCenter ) // Cannot use isMove() yet - { // Exit quick tile mode when the user attempts to move a tiled window + if (quick_tile_mode != QuickTileNone && isMovable() && mode == PositionCenter) { // Cannot use isMove() yet + // Exit quick tile mode when the user attempts to move a tiled window const QRect before = geometry(); - setQuickTileMode( QuickTileNone ); + setQuickTileMode(QuickTileNone); // Move the window so it's under the cursor moveOffset = QPoint( - double( moveOffset.x() ) / double( before.width() ) * double( geom_pretile.width() ), - double( moveOffset.y() ) / double( before.height() ) * double( geom_pretile.height() ) - ); - } - if( quick_tile_mode != QuickTileNone && mode != PositionCenter ) // Cannot use isResize() yet - { // Exit quick tile mode when the user attempts to resize a tiled window + double(moveOffset.x()) / double(before.width()) * double(geom_pretile.width()), + double(moveOffset.y()) / double(before.height()) * double(geom_pretile.height()) + ); + } + if (quick_tile_mode != QuickTileNone && mode != PositionCenter) { // Cannot use isResize() yet + // Exit quick tile mode when the user attempts to resize a tiled window quick_tile_mode = QuickTileNone; // Do so without restoring original geometry - } + } moveResizeMode = true; workspace()->setClientIsMoving(this); initialMoveResizeGeom = moveResizeGeom = geometry(); checkUnrestrictedMoveResize(); - if ( ( isMove() && rules()->checkMoveResizeMode( options->moveMode ) != Options::Opaque ) - || ( isResize() && rules()->checkMoveResizeMode( options->resizeMode ) != Options::Opaque ) ) - { + if ((isMove() && rules()->checkMoveResizeMode(options->moveMode) != Options::Opaque) + || (isResize() && rules()->checkMoveResizeMode(options->resizeMode) != Options::Opaque)) { grabXServer(); kapp->sendPostedEvents(); // we have server grab -> nothing should cause paint events @@ -2829,265 +2642,250 @@ bool Client::startMoveResize() // paint events for the geometrytip need to be allowed, though eater = new EatAllPaintEvents; // not needed anymore? kapp->installEventFilter( eater ); - } - Notify::raise( isResize() ? Notify::ResizeStart : Notify::MoveStart ); - if( effects ) - static_cast(effects)->windowUserMovedResized( effectWindow(), true, false ); - if( options->electricBorders() == Options::ElectricMoveOnly || - options->electricBorderMaximize() || - options->electricBorderTiling() ) - workspace()->reserveElectricBorderSwitching( true ); - return true; } + Notify::raise(isResize() ? Notify::ResizeStart : Notify::MoveStart); + if (effects) + static_cast(effects)->windowUserMovedResized(effectWindow(), true, false); + if (options->electricBorders() == Options::ElectricMoveOnly || + options->electricBorderMaximize() || + options->electricBorderTiling()) + workspace()->reserveElectricBorderSwitching(true); + return true; +} -void Client::finishMoveResize( bool cancel ) - { +void Client::finishMoveResize(bool cancel) +{ // store for notification bool wasResize = isResize(); bool wasMove = isMove(); leaveMoveResize(); - if( workspace()->tilingEnabled() ) - { - if( wasResize ) - workspace()->notifyTilingWindowResizeDone( this, moveResizeGeom, initialMoveResizeGeom, cancel ); - else if( wasMove ) - workspace()->notifyTilingWindowMoveDone( this, moveResizeGeom, initialMoveResizeGeom, cancel ); - } - else - { - if( cancel ) - setGeometry( initialMoveResizeGeom ); - else - setGeometry( moveResizeGeom ); - } - if( cancel ) - setGeometry( initialMoveResizeGeom ); + if (workspace()->tilingEnabled()) { + if (wasResize) + workspace()->notifyTilingWindowResizeDone(this, moveResizeGeom, initialMoveResizeGeom, cancel); + else if (wasMove) + workspace()->notifyTilingWindowMoveDone(this, moveResizeGeom, initialMoveResizeGeom, cancel); + } else { + if (cancel) + setGeometry(initialMoveResizeGeom); + else + setGeometry(moveResizeGeom); + } + if (cancel) + setGeometry(initialMoveResizeGeom); - if( isElectricBorderMaximizing() ) - { + if (isElectricBorderMaximizing()) { cancel = true; + } + if (isElectricBorderMaximizing()) { + switch(electricMode) { + case ElectricMaximizeMode: + if (maximizeMode() == MaximizeFull) + setMaximize(false, false); + else + setMaximize(true, true); + workspace()->restoreElectricBorderSize(ElectricTop); + break; + case ElectricLeftMode: + setQuickTileMode(QuickTileLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricRightMode: + setQuickTileMode(QuickTileRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; + case ElectricTopLeftMode: + setQuickTileMode(QuickTileTopLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricTopRightMode: + setQuickTileMode(QuickTileTopRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; + case ElectricBottomLeftMode: + setQuickTileMode(QuickTileBottomLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricBottomRightMode: + setQuickTileMode(QuickTileBottomRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; } - if( isElectricBorderMaximizing() ) - { - switch( electricMode ) - { - case ElectricMaximizeMode: - if( maximizeMode() == MaximizeFull ) - setMaximize( false, false ); - else - setMaximize( true, true ); - workspace()->restoreElectricBorderSize( ElectricTop ); - break; - case ElectricLeftMode: - setQuickTileMode( QuickTileLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricRightMode: - setQuickTileMode( QuickTileRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - case ElectricTopLeftMode: - setQuickTileMode( QuickTileTopLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricTopRightMode: - setQuickTileMode( QuickTileTopRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - case ElectricBottomLeftMode: - setQuickTileMode( QuickTileBottomLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricBottomRightMode: - setQuickTileMode( QuickTileBottomRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - } electricMaximizing = false; workspace()->hideElectricBorderWindowOutline(); + } + if (isElectricBorderMaximizing()) { + switch(electricMode) { + case ElectricMaximizeMode: + if (maximizeMode() == MaximizeFull) + setMaximize(false, false); + else + setMaximize(true, true); + workspace()->restoreElectricBorderSize(ElectricTop); + break; + case ElectricLeftMode: + setQuickTileMode(QuickTileLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricRightMode: + setQuickTileMode(QuickTileRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; + case ElectricTopLeftMode: + setQuickTileMode(QuickTileTopLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricTopRightMode: + setQuickTileMode(QuickTileTopRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; + case ElectricBottomLeftMode: + setQuickTileMode(QuickTileBottomLeft); + workspace()->restoreElectricBorderSize(ElectricLeft); + break; + case ElectricBottomRightMode: + setQuickTileMode(QuickTileBottomRight); + workspace()->restoreElectricBorderSize(ElectricRight); + break; } - if( isElectricBorderMaximizing() ) - { - switch( electricMode ) - { - case ElectricMaximizeMode: - if( maximizeMode() == MaximizeFull ) - setMaximize( false, false ); - else - setMaximize( true, true ); - workspace()->restoreElectricBorderSize( ElectricTop ); - break; - case ElectricLeftMode: - setQuickTileMode( QuickTileLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricRightMode: - setQuickTileMode( QuickTileRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - case ElectricTopLeftMode: - setQuickTileMode( QuickTileTopLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricTopRightMode: - setQuickTileMode( QuickTileTopRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - case ElectricBottomLeftMode: - setQuickTileMode( QuickTileBottomLeft ); - workspace()->restoreElectricBorderSize( ElectricLeft ); - break; - case ElectricBottomRightMode: - setQuickTileMode( QuickTileBottomRight ); - workspace()->restoreElectricBorderSize( ElectricRight ); - break; - } electricMaximizing = false; workspace()->hideElectricBorderWindowOutline(); - } + } checkMaximizeGeometry(); // FRAME update(); - Notify::raise( isResize() ? Notify::ResizeEnd : Notify::MoveEnd ); - if( effects ) - static_cast(effects)->windowUserMovedResized( effectWindow(), false, true ); - } + Notify::raise(isResize() ? Notify::ResizeEnd : Notify::MoveEnd); + if (effects) + static_cast(effects)->windowUserMovedResized(effectWindow(), false, true); +} void Client::leaveMoveResize() - { +{ clearbound(); - if (geometryTip) - { + if (geometryTip) { geometryTip->hide(); delete geometryTip; geometryTip = NULL; - } - if ( ( isMove() && rules()->checkMoveResizeMode( options->moveMode ) != Options::Opaque ) - || ( isResize() && rules()->checkMoveResizeMode( options->resizeMode ) != Options::Opaque ) ) + } + if ((isMove() && rules()->checkMoveResizeMode(options->moveMode) != Options::Opaque) + || (isResize() && rules()->checkMoveResizeMode(options->resizeMode) != Options::Opaque)) ungrabXServer(); - if( move_resize_has_keyboard_grab ) + if (move_resize_has_keyboard_grab) ungrabXKeyboard(); move_resize_has_keyboard_grab = false; - XUngrabPointer( display(), xTime() ); - XDestroyWindow( display(), move_resize_grab_window ); + XUngrabPointer(display(), xTime()); + XDestroyWindow(display(), move_resize_grab_window); move_resize_grab_window = None; workspace()->setClientIsMoving(0); - if( move_faked_activity ) - workspace()->unfakeActivity( this ); + if (move_faked_activity) + workspace()->unfakeActivity(this); move_faked_activity = false; moveResizeMode = false; delete eater; eater = 0; delete sync_timeout; sync_timeout = NULL; - if( options->electricBorders() == Options::ElectricMoveOnly || - options->electricBorderMaximize() || - options->electricBorderTiling() ) - workspace()->reserveElectricBorderSwitching( false ); - } + if (options->electricBorders() == Options::ElectricMoveOnly || + options->electricBorderMaximize() || + options->electricBorderTiling()) + workspace()->reserveElectricBorderSwitching(false); +} // This function checks if it actually makes sense to perform a restricted move/resize. // If e.g. the titlebar is already outside of the workarea, there's no point in performing // a restricted move resize, because then e.g. resize would also move the window (#74555). // NOTE: Most of it is duplicated from handleMoveResize(). void Client::checkUnrestrictedMoveResize() - { - if( unrestrictedMoveResize ) +{ + if (unrestrictedMoveResize) return; - QRect desktopArea = workspace()->clientArea( WorkArea, moveResizeGeom.center(), desktop()); + QRect desktopArea = workspace()->clientArea(WorkArea, moveResizeGeom.center(), desktop()); int left_marge, right_marge, top_marge, bottom_marge, titlebar_marge; // restricted move/resize - keep at least part of the titlebar always visible // how much must remain visible when moved away in that direction - left_marge = qMin( 100 + border_right, moveResizeGeom.width()); - right_marge = qMin( 100 + border_left, moveResizeGeom.width()); + left_marge = qMin(100 + border_right, moveResizeGeom.width()); + right_marge = qMin(100 + border_left, moveResizeGeom.width()); // width/height change with opaque resizing, use the initial ones titlebar_marge = initialMoveResizeGeom.height(); top_marge = border_bottom; bottom_marge = border_top; - if( isResize()) - { - if( moveResizeGeom.bottom() < desktopArea.top() + top_marge ) + if (isResize()) { + if (moveResizeGeom.bottom() < desktopArea.top() + top_marge) unrestrictedMoveResize = true; - if( moveResizeGeom.top() > desktopArea.bottom() - bottom_marge ) + if (moveResizeGeom.top() > desktopArea.bottom() - bottom_marge) unrestrictedMoveResize = true; - if( moveResizeGeom.right() < desktopArea.left() + left_marge ) + if (moveResizeGeom.right() < desktopArea.left() + left_marge) unrestrictedMoveResize = true; - if( moveResizeGeom.left() > desktopArea.right() - right_marge ) + if (moveResizeGeom.left() > desktopArea.right() - right_marge) unrestrictedMoveResize = true; - if( !unrestrictedMoveResize && moveResizeGeom.top() < desktopArea.top() ) // titlebar mustn't go out + if (!unrestrictedMoveResize && moveResizeGeom.top() < desktopArea.top()) // titlebar mustn't go out unrestrictedMoveResize = true; - } - if( isMove()) - { - if( moveResizeGeom.bottom() < desktopArea.top() + titlebar_marge - 1 ) // titlebar mustn't go out + } + if (isMove()) { + if (moveResizeGeom.bottom() < desktopArea.top() + titlebar_marge - 1) // titlebar mustn't go out unrestrictedMoveResize = true; // no need to check top_marge, titlebar_marge already handles it - if( moveResizeGeom.top() > desktopArea.bottom() - bottom_marge ) + if (moveResizeGeom.top() > desktopArea.bottom() - bottom_marge) unrestrictedMoveResize = true; - if( moveResizeGeom.right() < desktopArea.left() + left_marge ) + if (moveResizeGeom.right() < desktopArea.left() + left_marge) unrestrictedMoveResize = true; - if( moveResizeGeom.left() > desktopArea.right() - right_marge ) + if (moveResizeGeom.left() > desktopArea.right() - right_marge) unrestrictedMoveResize = true; - } } +} // When the user pressed mouse on the titlebar, don't activate move immediatelly, // since it may be just a click. Activate instead after a delay. Move used to be // activated only after moving by several pixels, but that looks bad. void Client::startDelayedMoveResize() - { +{ delete delayedMoveResizeTimer; - delayedMoveResizeTimer = new QTimer( this ); - connect( delayedMoveResizeTimer, SIGNAL( timeout()), this, SLOT( delayedMoveResize())); - delayedMoveResizeTimer->setSingleShot( true ); - delayedMoveResizeTimer->start( QApplication::startDragTime() ); - } + delayedMoveResizeTimer = new QTimer(this); + connect(delayedMoveResizeTimer, SIGNAL(timeout()), this, SLOT(delayedMoveResize())); + delayedMoveResizeTimer->setSingleShot(true); + delayedMoveResizeTimer->start(QApplication::startDragTime()); +} void Client::stopDelayedMoveResize() - { +{ delete delayedMoveResizeTimer; delayedMoveResizeTimer = NULL; - } +} void Client::delayedMoveResize() - { - assert( buttonDown ); - if( !startMoveResize()) +{ + assert(buttonDown); + if (!startMoveResize()) buttonDown = false; updateCursor(); stopDelayedMoveResize(); - } +} -void Client::handleMoveResize( int x, int y, int x_root, int y_root ) - { - if(( mode == PositionCenter && !isMovableAcrossScreens() ) - || ( mode != PositionCenter && ( isShade() || !isResizable()))) +void Client::handleMoveResize(int x, int y, int x_root, int y_root) +{ + if ((mode == PositionCenter && !isMovableAcrossScreens()) + || (mode != PositionCenter && (isShade() || !isResizable()))) return; - if ( !moveResizeMode ) - { - QPoint p( QPoint( x - padding_left, y - padding_top ) - moveOffset ); - if (p.manhattanLength() >= KGlobalSettings::dndEventDelay()) - { - if( !startMoveResize()) - { + if (!moveResizeMode) { + QPoint p(QPoint(x - padding_left, y - padding_top) - moveOffset); + if (p.manhattanLength() >= KGlobalSettings::dndEventDelay()) { + if (!startMoveResize()) { buttonDown = false; updateCursor(); return; - } - updateCursor(); } - else + updateCursor(); + } else return; - } + } // ShadeHover or ShadeActive, ShadeNormal was already avoided above - if ( mode != PositionCenter && shade_mode != ShadeNone ) - setShade( ShadeNone ); + if (mode != PositionCenter && shade_mode != ShadeNone) + setShade(ShadeNone); - QPoint globalPos( x_root, y_root ); + QPoint globalPos(x_root, y_root); // these two points limit the geometry rectangle, i.e. if bottomleft resizing is done, // the bottomleft corner should be at is at (topleft.x(), bottomright().y()) QPoint topleft = globalPos - moveOffset; @@ -3099,383 +2897,346 @@ void Client::handleMoveResize( int x, int y, int x_root, int y_root ) // When doing a restricted move we must always keep 100px of the titlebar // visible to allow the user to be able to move it again. int frameLeft, frameRight, frameTop, frameBottom; - if( decoration ) - decoration->borders( frameLeft, frameRight, frameTop, frameBottom ); + if (decoration) + decoration->borders(frameLeft, frameRight, frameTop, frameBottom); else frameTop = 10; - int titlebarArea = qMin( frameTop * 100, moveResizeGeom.width() * moveResizeGeom.height() ); + int titlebarArea = qMin(frameTop * 100, moveResizeGeom.width() * moveResizeGeom.height()); bool update = false; - if( isResize()) - { + if (isResize()) { // query layout for supported resize mode - if( workspace()->tilingEnabled() ) - { - mode = workspace()->supportedTilingResizeMode( this, mode ); - } + if (workspace()->tilingEnabled()) { + mode = workspace()->supportedTilingResizeMode(this, mode); + } // first resize (without checking constrains), then snap, then check bounds, then check constrains QRect orig = initialMoveResizeGeom; Sizemode sizemode = SizemodeAny; - switch ( mode ) - { - case PositionTopLeft: - moveResizeGeom = QRect( topleft, orig.bottomRight() ) ; - break; - case PositionBottomRight: - moveResizeGeom = QRect( orig.topLeft(), bottomright ) ; - break; - case PositionBottomLeft: - moveResizeGeom = QRect( QPoint( topleft.x(), orig.y() ), QPoint( orig.right(), bottomright.y()) ) ; - break; - case PositionTopRight: - moveResizeGeom = QRect( QPoint( orig.x(), topleft.y() ), QPoint( bottomright.x(), orig.bottom()) ) ; - break; - case PositionTop: - moveResizeGeom = QRect( QPoint( orig.left(), topleft.y() ), orig.bottomRight() ) ; - sizemode = SizemodeFixedH; // try not to affect height - break; - case PositionBottom: - moveResizeGeom = QRect( orig.topLeft(), QPoint( orig.right(), bottomright.y() ) ) ; - sizemode = SizemodeFixedH; - break; - case PositionLeft: - moveResizeGeom = QRect( QPoint( topleft.x(), orig.top() ), orig.bottomRight() ) ; - sizemode = SizemodeFixedW; - break; - case PositionRight: - moveResizeGeom = QRect( orig.topLeft(), QPoint( bottomright.x(), orig.bottom() ) ) ; - sizemode = SizemodeFixedW; - break; - case PositionCenter: - // exception for tiling - // Center means no resizing allowed - if( workspace()->tilingEnabled() ) - { - finishMoveResize( false ); - buttonDown = false; - return; - } - default: - abort(); - break; + switch(mode) { + case PositionTopLeft: + moveResizeGeom = QRect(topleft, orig.bottomRight()) ; + break; + case PositionBottomRight: + moveResizeGeom = QRect(orig.topLeft(), bottomright) ; + break; + case PositionBottomLeft: + moveResizeGeom = QRect(QPoint(topleft.x(), orig.y()), QPoint(orig.right(), bottomright.y())) ; + break; + case PositionTopRight: + moveResizeGeom = QRect(QPoint(orig.x(), topleft.y()), QPoint(bottomright.x(), orig.bottom())) ; + break; + case PositionTop: + moveResizeGeom = QRect(QPoint(orig.left(), topleft.y()), orig.bottomRight()) ; + sizemode = SizemodeFixedH; // try not to affect height + break; + case PositionBottom: + moveResizeGeom = QRect(orig.topLeft(), QPoint(orig.right(), bottomright.y())) ; + sizemode = SizemodeFixedH; + break; + case PositionLeft: + moveResizeGeom = QRect(QPoint(topleft.x(), orig.top()), orig.bottomRight()) ; + sizemode = SizemodeFixedW; + break; + case PositionRight: + moveResizeGeom = QRect(orig.topLeft(), QPoint(bottomright.x(), orig.bottom())) ; + sizemode = SizemodeFixedW; + break; + case PositionCenter: + // exception for tiling + // Center means no resizing allowed + if (workspace()->tilingEnabled()) { + finishMoveResize(false); + buttonDown = false; + return; } - workspace()->notifyTilingWindowResize( this, moveResizeGeom, initialMoveResizeGeom ); + default: + abort(); + break; + } + workspace()->notifyTilingWindowResize(this, moveResizeGeom, initialMoveResizeGeom); // adjust new size to snap to other windows/borders - moveResizeGeom = workspace()->adjustClientSize( this, moveResizeGeom, mode ); + moveResizeGeom = workspace()->adjustClientSize(this, moveResizeGeom, mode); - if(!unrestrictedMoveResize) - { + if (!unrestrictedMoveResize) { // Make sure the titlebar isn't behind a restricted area. We don't need to restrict // the other directions. If not visible enough, move the window to the closest valid // point. We bruteforce this by slowly moving the window back to its previous position. - for(;;) - { - QRegion titlebarRegion( moveResizeGeom.left(), moveResizeGeom.top(), - moveResizeGeom.width(), frameTop ); - titlebarRegion &= workspace()->clientArea( FullArea, -1, 0 ); // On the screen - titlebarRegion -= workspace()->restrictedMoveArea( desktop() ); // Strut areas + for (;;) { + QRegion titlebarRegion(moveResizeGeom.left(), moveResizeGeom.top(), + moveResizeGeom.width(), frameTop); + titlebarRegion &= workspace()->clientArea(FullArea, -1, 0); // On the screen + titlebarRegion -= workspace()->restrictedMoveArea(desktop()); // Strut areas // Now we have a region of all the visible areas of the titlebar // Count the visible pixels and check to see if it's enough int visiblePixels = 0; - foreach( const QRect& rect, titlebarRegion.rects() ) - if( rect.height() >= frameTop ) // Only the full height regions, prevents long slim areas - visiblePixels += rect.width() * rect.height(); - if( visiblePixels >= titlebarArea ) + foreach (const QRect & rect, titlebarRegion.rects()) + if (rect.height() >= frameTop) // Only the full height regions, prevents long slim areas + visiblePixels += rect.width() * rect.height(); + if (visiblePixels >= titlebarArea) break; // We have reached a valid position // Not visible enough, move the window to the closest valid point. We bruteforce // this by slowly moving the window back to its previous position. - if( previousMoveResizeGeom.y() != moveResizeGeom.y() ) - { - if( previousMoveResizeGeom.y() > moveResizeGeom.y() ) - moveResizeGeom.setTop( moveResizeGeom.y() + 1 ); + if (previousMoveResizeGeom.y() != moveResizeGeom.y()) { + if (previousMoveResizeGeom.y() > moveResizeGeom.y()) + moveResizeGeom.setTop(moveResizeGeom.y() + 1); else - moveResizeGeom.setTop( moveResizeGeom.y() - 1 ); - } - else // Our heights match but we still don't have a valid area, maybe - { // we are trying to resize in from the side? + moveResizeGeom.setTop(moveResizeGeom.y() - 1); + } else { // Our heights match but we still don't have a valid area, maybe + // we are trying to resize in from the side? bool breakLoop = false; - switch( mode ) - { - case PositionTopLeft: - case PositionLeft: - if( previousMoveResizeGeom.x() >= moveResizeGeom.x() ) - { - breakLoop = true; - break; - } - moveResizeGeom.setLeft( moveResizeGeom.x() - 1 ); - break; - case PositionTopRight: - case PositionRight: - if( previousMoveResizeGeom.right() <= moveResizeGeom.right() ) - { - breakLoop = true; - break; - } - moveResizeGeom.setRight( moveResizeGeom.x() + moveResizeGeom.width() ); - break; - default: + switch(mode) { + case PositionTopLeft: + case PositionLeft: + if (previousMoveResizeGeom.x() >= moveResizeGeom.x()) { breakLoop = true; + break; } - if( breakLoop ) + moveResizeGeom.setLeft(moveResizeGeom.x() - 1); break; + case PositionTopRight: + case PositionRight: + if (previousMoveResizeGeom.right() <= moveResizeGeom.right()) { + breakLoop = true; + break; + } + moveResizeGeom.setRight(moveResizeGeom.x() + moveResizeGeom.width()); + break; + default: + breakLoop = true; } + if (breakLoop) + break; } } + } // Always obey size hints, even when in "unrestricted" mode - QSize size = adjustedSize( moveResizeGeom.size(), sizemode ); + QSize size = adjustedSize(moveResizeGeom.size(), sizemode); // the new topleft and bottomright corners (after checking size constrains), if they'll be needed - topleft = QPoint( moveResizeGeom.right() - size.width() + 1, moveResizeGeom.bottom() - size.height() + 1 ); - bottomright = QPoint( moveResizeGeom.left() + size.width() - 1, moveResizeGeom.top() + size.height() - 1 ); + topleft = QPoint(moveResizeGeom.right() - size.width() + 1, moveResizeGeom.bottom() - size.height() + 1); + bottomright = QPoint(moveResizeGeom.left() + size.width() - 1, moveResizeGeom.top() + size.height() - 1); orig = moveResizeGeom; - switch ( mode ) - { // these 4 corners ones are copied from above - case PositionTopLeft: - moveResizeGeom = QRect( topleft, orig.bottomRight() ) ; - break; - case PositionBottomRight: - moveResizeGeom = QRect( orig.topLeft(), bottomright ) ; - break; - case PositionBottomLeft: - moveResizeGeom = QRect( QPoint( topleft.x(), orig.y() ), QPoint( orig.right(), bottomright.y()) ) ; - break; - case PositionTopRight: - moveResizeGeom = QRect( QPoint( orig.x(), topleft.y() ), QPoint( bottomright.x(), orig.bottom()) ) ; - break; + switch(mode) { + // these 4 corners ones are copied from above + case PositionTopLeft: + moveResizeGeom = QRect(topleft, orig.bottomRight()) ; + break; + case PositionBottomRight: + moveResizeGeom = QRect(orig.topLeft(), bottomright) ; + break; + case PositionBottomLeft: + moveResizeGeom = QRect(QPoint(topleft.x(), orig.y()), QPoint(orig.right(), bottomright.y())) ; + break; + case PositionTopRight: + moveResizeGeom = QRect(QPoint(orig.x(), topleft.y()), QPoint(bottomright.x(), orig.bottom())) ; + break; // The side ones can't be copied exactly - if aspect ratios are specified, both dimensions may change. // Therefore grow to the right/bottom if needed. // TODO it should probably obey gravity rather than always using right/bottom ? - case PositionTop: - moveResizeGeom = QRect( QPoint( orig.left(), topleft.y() ), QPoint( bottomright.x(), orig.bottom()) ) ; - break; - case PositionBottom: - moveResizeGeom = QRect( orig.topLeft(), QPoint( bottomright.x(), bottomright.y() ) ) ; - break; - case PositionLeft: - moveResizeGeom = QRect( QPoint( topleft.x(), orig.top() ), QPoint( orig.right(), bottomright.y())); - break; - case PositionRight: - moveResizeGeom = QRect( orig.topLeft(), QPoint( bottomright.x(), bottomright.y() ) ) ; - break; - case PositionCenter: - default: - abort(); - break; - } - - if( moveResizeGeom.size() != previousMoveResizeGeom.size()) - update = true; + case PositionTop: + moveResizeGeom = QRect(QPoint(orig.left(), topleft.y()), QPoint(bottomright.x(), orig.bottom())) ; + break; + case PositionBottom: + moveResizeGeom = QRect(orig.topLeft(), QPoint(bottomright.x(), bottomright.y())) ; + break; + case PositionLeft: + moveResizeGeom = QRect(QPoint(topleft.x(), orig.top()), QPoint(orig.right(), bottomright.y())); + break; + case PositionRight: + moveResizeGeom = QRect(orig.topLeft(), QPoint(bottomright.x(), bottomright.y())) ; + break; + case PositionCenter: + default: + abort(); + break; } - else if( isMove()) - { - assert( mode == PositionCenter ); - if( !isMovable() ) // isMovableAcrossScreens() must have been true to get here - { // Special moving of maximized windows on Xinerama screens - int screen = workspace()->screenNumber( globalPos ); - moveResizeGeom = workspace()->clientArea( - isFullScreen() ? FullScreenArea : MaximizeArea, screen, 0 ); - } - else - { - // first move, then snap, then check bounds - moveResizeGeom.moveTopLeft( topleft ); - moveResizeGeom.moveTopLeft( workspace()->adjustClientPosition( this, moveResizeGeom.topLeft(), - unrestrictedMoveResize )); - if(!unrestrictedMoveResize) - { + if (moveResizeGeom.size() != previousMoveResizeGeom.size()) + update = true; + } else if (isMove()) { + assert(mode == PositionCenter); + if (!isMovable()) { // isMovableAcrossScreens() must have been true to get here + // Special moving of maximized windows on Xinerama screens + int screen = workspace()->screenNumber(globalPos); + moveResizeGeom = workspace()->clientArea( + isFullScreen() ? FullScreenArea : MaximizeArea, screen, 0); + } else { + // first move, then snap, then check bounds + moveResizeGeom.moveTopLeft(topleft); + moveResizeGeom.moveTopLeft(workspace()->adjustClientPosition(this, moveResizeGeom.topLeft(), + unrestrictedMoveResize)); + + if (!unrestrictedMoveResize) { // Make sure the titlebar isn't behind a restricted area. - for(;;) - { - QRegion titlebarRegion( moveResizeGeom.left(), moveResizeGeom.top(), - moveResizeGeom.width(), frameTop ); - titlebarRegion &= workspace()->clientArea( FullArea, -1, 0 ); // On the screen - titlebarRegion -= workspace()->restrictedMoveArea( desktop() ); // Strut areas + for (;;) { + QRegion titlebarRegion(moveResizeGeom.left(), moveResizeGeom.top(), + moveResizeGeom.width(), frameTop); + titlebarRegion &= workspace()->clientArea(FullArea, -1, 0); // On the screen + titlebarRegion -= workspace()->restrictedMoveArea(desktop()); // Strut areas // Now we have a region of all the visible areas of the titlebar // Count the visible pixels and check to see if it's enough int visiblePixels = 0; - foreach( const QRect& rect, titlebarRegion.rects() ) - if( rect.height() >= frameTop ) // Only the full height regions, prevents long slim areas - visiblePixels += rect.width() * rect.height(); - if( visiblePixels >= titlebarArea ) + foreach (const QRect & rect, titlebarRegion.rects()) + if (rect.height() >= frameTop) // Only the full height regions, prevents long slim areas + visiblePixels += rect.width() * rect.height(); + if (visiblePixels >= titlebarArea) break; // We have reached a valid position // Move it (Favour vertically) - if( previousMoveResizeGeom.y() != moveResizeGeom.y() ) - moveResizeGeom.translate( 0, - previousMoveResizeGeom.y() > moveResizeGeom.y() ? 1 : -1 ); + if (previousMoveResizeGeom.y() != moveResizeGeom.y()) + moveResizeGeom.translate(0, + previousMoveResizeGeom.y() > moveResizeGeom.y() ? 1 : -1); else - moveResizeGeom.translate( previousMoveResizeGeom.x() > moveResizeGeom.x() ? 1 : -1, - 0 ); - if( moveResizeGeom == previousMoveResizeGeom ) + moveResizeGeom.translate(previousMoveResizeGeom.x() > moveResizeGeom.x() ? 1 : -1, + 0); + if (moveResizeGeom == previousMoveResizeGeom) break; // Prevent lockup - } } } - if( moveResizeGeom.topLeft() != previousMoveResizeGeom.topLeft()) - update = true; } - else + if (moveResizeGeom.topLeft() != previousMoveResizeGeom.topLeft()) + update = true; + } else abort(); - if( isResize()) - { - if( sync_timeout != NULL ) - { + if (isResize()) { + if (sync_timeout != NULL) { sync_resize_pending = true; return; - } } + } - if( update ) + if (update) performMoveResize(); - if ( isMove() ) - { - workspace()->notifyTilingWindowMove( this, moveResizeGeom, initialMoveResizeGeom ); + if (isMove()) { + workspace()->notifyTilingWindowMove(this, moveResizeGeom, initialMoveResizeGeom); workspace()->checkElectricBorder(globalPos, xTime()); } - } +} void Client::performMoveResize() - { +{ bool haveResizeEffect = false; bool transparent = false; - if( isResize() ) - { - haveResizeEffect = effects && static_cast(effects)->provides( Effect::Resize ); - transparent = haveResizeEffect || rules()->checkMoveResizeMode( options->resizeMode) != Options::Opaque; - } - else if ( isMove()) - transparent = rules()->checkMoveResizeMode( options->moveMode) != Options::Opaque; - + if (isResize()) { + haveResizeEffect = effects && static_cast(effects)->provides(Effect::Resize); + transparent = haveResizeEffect || rules()->checkMoveResizeMode(options->resizeMode) != Options::Opaque; + } else if (isMove()) + transparent = rules()->checkMoveResizeMode(options->moveMode) != Options::Opaque; + #ifdef HAVE_XSYNC - if( isResize() && !transparent && sync_counter != None && !sync_resize_pending ) - { - sync_timeout = new QTimer( this ); - connect( sync_timeout, SIGNAL( timeout()), SLOT( syncTimeout())); - sync_timeout->setSingleShot( true ); - sync_timeout->start( 500 ); + if (isResize() && !transparent && sync_counter != None && !sync_resize_pending) { + sync_timeout = new QTimer(this); + connect(sync_timeout, SIGNAL(timeout()), SLOT(syncTimeout())); + sync_timeout->setSingleShot(true); + sync_timeout->start(500); sendSyncRequest(); - } + } #endif - if( transparent ) - { - if( !haveResizeEffect ) + if (transparent) { + if (!haveResizeEffect) clearbound(); // it's necessary to move the geometry tip when there's no outline positionGeometryTip(); // shown, otherwise it would cause repaint problems in case - if( !haveResizeEffect ) - drawbound( moveResizeGeom ); // they overlap; the paint event will come after this, - } - else - { - if( !workspace()->tilingEnabled() ) - setGeometry( moveResizeGeom ); + if (!haveResizeEffect) + drawbound(moveResizeGeom); // they overlap; the paint event will come after this, + } else { + if (!workspace()->tilingEnabled()) + setGeometry(moveResizeGeom); positionGeometryTip(); - } - if( effects ) - { - static_cast(effects)->windowMoveResizeGeometryUpdate( effectWindow(), moveResizeGeom ); - static_cast(effects)->windowUserMovedResized( effectWindow(), false, false ); - } } + if (effects) { + static_cast(effects)->windowMoveResizeGeometryUpdate(effectWindow(), moveResizeGeom); + static_cast(effects)->windowUserMovedResized(effectWindow(), false, false); + } +} void Client::syncTimeout() - { +{ sync_timeout->deleteLater(); sync_timeout = NULL; - if( sync_resize_pending ) + if (sync_resize_pending) performMoveResize(); - } +} -void Client::setElectricBorderMode( ElectricMaximizingMode mode ) - { +void Client::setElectricBorderMode(ElectricMaximizingMode mode) +{ electricMode = mode; - } +} ElectricMaximizingMode Client::electricBorderMode() const - { +{ return electricMode; - } +} bool Client::isElectricBorderMaximizing() const - { +{ return electricMaximizing; - } +} -void Client::setElectricBorderMaximizing( bool maximizing ) - { +void Client::setElectricBorderMaximizing(bool maximizing) +{ electricMaximizing = maximizing; - if( maximizing ) + if (maximizing) workspace()->showElectricBorderWindowOutline(); else workspace()->hideElectricBorderWindowOutline(); - } +} QRect Client::electricBorderMaximizeGeometry() - { +{ QRect ret; - switch( electricMode ) - { - case ElectricMaximizeMode: - { - if( maximizeMode() == MaximizeFull ) - ret = geometryRestore(); - else - ret = workspace()->clientArea( MaximizeArea, cursorPos() ,workspace()->currentDesktop() ); - break; - } - case ElectricLeftMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos() ,workspace()->currentDesktop() ); - ret = QRect( max.x(), max.y(), max.width()/2, max.height() ); - break; - } - case ElectricRightMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos() ,workspace()->currentDesktop() ); - ret = QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height() ); - break; - } - case ElectricTopLeftMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos(), workspace()->currentDesktop() ); - ret = QRect( max.x(), max.y(), max.width()/2, max.height()/2 ); - break; - } - case ElectricTopRightMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos(), workspace()->currentDesktop() ); - ret = QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height()/2 ); - break; - } - case ElectricBottomLeftMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos(), workspace()->currentDesktop() ); - ret = QRect( max.x(), max.y() + max.height()/2, max.width()/2, max.height()/2 ); - break; - } - case ElectricBottomRightMode: - { - QRect max = workspace()->clientArea( MaximizeArea, cursorPos(), workspace()->currentDesktop() ); - ret = QRect( max.x() + max.width()/2, max.y() + max.height()/2, max.width()/2, max.height()/2 ); - break; - } - } - return ret; + switch(electricMode) { + case ElectricMaximizeMode: { + if (maximizeMode() == MaximizeFull) + ret = geometryRestore(); + else + ret = workspace()->clientArea(MaximizeArea, cursorPos() , workspace()->currentDesktop()); + break; } + case ElectricLeftMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos() , workspace()->currentDesktop()); + ret = QRect(max.x(), max.y(), max.width() / 2, max.height()); + break; + } + case ElectricRightMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos() , workspace()->currentDesktop()); + ret = QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height()); + break; + } + case ElectricTopLeftMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos(), workspace()->currentDesktop()); + ret = QRect(max.x(), max.y(), max.width() / 2, max.height() / 2); + break; + } + case ElectricTopRightMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos(), workspace()->currentDesktop()); + ret = QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height() / 2); + break; + } + case ElectricBottomLeftMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos(), workspace()->currentDesktop()); + ret = QRect(max.x(), max.y() + max.height() / 2, max.width() / 2, max.height() / 2); + break; + } + case ElectricBottomRightMode: { + QRect max = workspace()->clientArea(MaximizeArea, cursorPos(), workspace()->currentDesktop()); + ret = QRect(max.x() + max.width() / 2, max.y() + max.height() / 2, max.width() / 2, max.height() / 2); + break; + } + } + return ret; +} -void Client::setQuickTileMode( QuickTileMode mode, bool keyboard ) - { +void Client::setQuickTileMode(QuickTileMode mode, bool keyboard) +{ // Only allow quick tile on a regular or maximized window - if( !isResizable() && maximizeMode() != MaximizeFull ) - return; + if (!isResizable() && maximizeMode() != MaximizeFull) + return; // restore from maximized so that it is possible to tile maximized windows with one hit or by dragging - if( maximizeMode() == MaximizeFull ) - { + if (maximizeMode() == MaximizeFull) { setMaximize(false, false); checkMaximizeGeometry(); @@ -3487,106 +3248,93 @@ void Client::setQuickTileMode( QuickTileMode mode, bool keyboard ) quick_tile_mode = QuickTileNone; // Do the actual tile. - switch( mode ) - { - case QuickTileLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y(), max.width()/2, max.height() ) ); - break; - } - case QuickTileRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height() ) ); - break; - } - case QuickTileTopLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y(), max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileTopRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileBottomLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y() + max.height()/2, max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileBottomRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y() + max.height()/2, max.width()/2, max.height()/2 ) ); - break; - } - } + switch(mode) { + case QuickTileLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y(), max.width() / 2, max.height())); + break; + } + case QuickTileRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height())); + break; + } + case QuickTileTopLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y(), max.width() / 2, max.height() / 2)); + break; + } + case QuickTileTopRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height() / 2)); + break; + } + case QuickTileBottomLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y() + max.height() / 2, max.width() / 2, max.height() / 2)); + break; + } + case QuickTileBottomRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y() + max.height() / 2, max.width() / 2, max.height() / 2)); + break; + } + } // Store the mode change quick_tile_mode = mode; return; - } + } // First, check if the requested tile negates the tile we're in now: move right when left or left when right // is the same as explicitly untiling this window, so allow it. - if( mode == QuickTileNone || - (quick_tile_mode == QuickTileLeft && mode == QuickTileRight) || - (quick_tile_mode == QuickTileRight && mode == QuickTileLeft) ) - { + if (mode == QuickTileNone || + (quick_tile_mode == QuickTileLeft && mode == QuickTileRight) || + (quick_tile_mode == QuickTileRight && mode == QuickTileLeft)) { // Untiling, so just restore geometry, and we're done. - setGeometry( geom_pretile ); + setGeometry(geom_pretile); checkWorkspacePosition(); // Just in case it's a different screen quick_tile_mode = QuickTileNone; return; - } - else - { + } else { QPoint whichScreen = keyboard ? geometry().center() : cursorPos(); // If trying to tile to the side that the window is already tiled to move the window to the next // screen if it exists, otherwise ignore the request to prevent corrupting geom_pretile. - if( quick_tile_mode == mode ) - { + if (quick_tile_mode == mode) { const int numScreens = Kephal::ScreenUtils::numScreens(); const int curScreen = screen(); int nextScreen = curScreen; QVarLengthArray screens(numScreens); - for( int i = 0; i < numScreens; ++i ) // Cache - screens[i] = Kephal::ScreenUtils::screenGeometry( i ); - for( int i = 0; i < numScreens; ++i ) - { - if( i == curScreen ) + for (int i = 0; i < numScreens; ++i) // Cache + screens[i] = Kephal::ScreenUtils::screenGeometry(i); + for (int i = 0; i < numScreens; ++i) { + if (i == curScreen) continue; - if((( mode == QuickTileLeft && - screens[i].center().x() < screens[nextScreen].center().x() ) || - ( mode == QuickTileRight && - screens[i].center().x() > screens[nextScreen].center().x() )) && - // Must be in horizontal line - ( screens[i].bottom() > screens[nextScreen].top() || - screens[i].top() < screens[nextScreen].bottom() )) + if (((mode == QuickTileLeft && + screens[i].center().x() < screens[nextScreen].center().x()) || + (mode == QuickTileRight && + screens[i].center().x() > screens[nextScreen].center().x())) && + // Must be in horizontal line + (screens[i].bottom() > screens[nextScreen].top() || + screens[i].top() < screens[nextScreen].bottom())) nextScreen = i; - } - if( nextScreen == curScreen ) + } + if (nextScreen == curScreen) return; // No other screens // Move to other screen geom_pretile.translate( screens[nextScreen].x() - screens[curScreen].x(), - screens[nextScreen].y() - screens[curScreen].y() ); + screens[nextScreen].y() - screens[curScreen].y()); whichScreen = screens[nextScreen].center(); // Swap sides - if( mode == QuickTileLeft ) + if (mode == QuickTileLeft) mode = QuickTileRight; else mode = QuickTileLeft; - } - else + } else // Not coming out of an existing tile, not shifting monitors, we're setting a brand new tile. // Store geometry first, so we can go out of this tile later. geom_pretile = geometry(); @@ -3597,48 +3345,41 @@ void Client::setQuickTileMode( QuickTileMode mode, bool keyboard ) quick_tile_mode = QuickTileNone; // Do the actual tile. - switch( mode ) - { - case QuickTileLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y(), max.width()/2, max.height() ) ); - break; - } - case QuickTileRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height() ) ); - break; - } - case QuickTileTopLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y(), max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileTopRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y(), max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileBottomLeft: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x(), max.y() + max.height()/2, max.width()/2, max.height()/2 ) ); - break; - } - case QuickTileBottomRight: - { - QRect max = workspace()->clientArea( MaximizeArea, whichScreen, desktop() ); - setGeometry( QRect( max.x() + max.width()/2, max.y() + max.height()/2, max.width()/2, max.height()/2 ) ); - break; - } - } + switch(mode) { + case QuickTileLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y(), max.width() / 2, max.height())); + break; + } + case QuickTileRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height())); + break; + } + case QuickTileTopLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y(), max.width() / 2, max.height() / 2)); + break; + } + case QuickTileTopRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y(), max.width() / 2, max.height() / 2)); + break; + } + case QuickTileBottomLeft: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x(), max.y() + max.height() / 2, max.width() / 2, max.height() / 2)); + break; + } + case QuickTileBottomRight: { + QRect max = workspace()->clientArea(MaximizeArea, whichScreen, desktop()); + setGeometry(QRect(max.x() + max.width() / 2, max.y() + max.height() / 2, max.width() / 2, max.height() / 2)); + break; + } + } // Store the mode change quick_tile_mode = mode; - } } +} } // namespace diff --git a/geometrytip.cpp b/geometrytip.cpp index e8777bac0..61c6cded3 100644 --- a/geometrytip.cpp +++ b/geometrytip.cpp @@ -24,53 +24,50 @@ along with this program. If not, see . namespace KWin { -GeometryTip::GeometryTip( const XSizeHints* xSizeHints, bool save_under ): - QLabel( 0 ) - { - setObjectName( QLatin1String( "kwingeometry" ) ); +GeometryTip::GeometryTip(const XSizeHints* xSizeHints, bool save_under): + QLabel(0) +{ + setObjectName(QLatin1String("kwingeometry")); setMargin(1); setIndent(0); setLineWidth(1); - setFrameStyle( QFrame::Raised | QFrame::StyledPanel ); - setAlignment( Qt::AlignCenter | Qt::AlignTop ); - setWindowFlags( Qt::X11BypassWindowManagerHint ); + setFrameStyle(QFrame::Raised | QFrame::StyledPanel); + setAlignment(Qt::AlignCenter | Qt::AlignTop); + setWindowFlags(Qt::X11BypassWindowManagerHint); sizeHints = xSizeHints; - if( save_under ) - { + if (save_under) { XSetWindowAttributes attr; attr.save_under = True; // use saveunder if possible to avoid weird effects in transparent mode - XChangeWindowAttributes( display(), winId(), CWSaveUnder, &attr ); - } + XChangeWindowAttributes(display(), winId(), CWSaveUnder, &attr); } +} GeometryTip::~GeometryTip() - { - } +{ +} -void GeometryTip::setGeometry( const QRect& geom ) - { +void GeometryTip::setGeometry(const QRect& geom) +{ int w = geom.width(); int h = geom.height(); - if (sizeHints) - { - if (sizeHints->flags & PResizeInc) - { - w = ( w - sizeHints->base_width ) / sizeHints->width_inc; - h = ( h - sizeHints->base_height ) / sizeHints->height_inc; - } + if (sizeHints) { + if (sizeHints->flags & PResizeInc) { + w = (w - sizeHints->base_width) / sizeHints->width_inc; + h = (h - sizeHints->base_height) / sizeHints->height_inc; } - - h = qMax( h, 0 ); // in case of isShade() and PBaseSize - QString pos; - pos.sprintf( "%+d,%+d
(%d x %d)", - geom.x(), geom.y(), w, h ); - setText( pos ); - adjustSize(); - move( geom.x() + ((geom.width() - width()) / 2), - geom.y() + ((geom.height() - height()) / 2) ); } + h = qMax(h, 0); // in case of isShade() and PBaseSize + QString pos; + pos.sprintf("%+d,%+d
(%d x %d)", + geom.x(), geom.y(), w, h); + setText(pos); + adjustSize(); + move(geom.x() + ((geom.width() - width()) / 2), + geom.y() + ((geom.height() - height()) / 2)); +} + } // namespace #include "geometrytip.moc" diff --git a/geometrytip.h b/geometrytip.h index 6f515aaf5..21959773d 100644 --- a/geometrytip.h +++ b/geometrytip.h @@ -28,16 +28,16 @@ namespace KWin { class GeometryTip: public QLabel - { +{ Q_OBJECT - public: - GeometryTip( const XSizeHints* xSizeHints, bool save_under ); - ~GeometryTip(); - void setGeometry( const QRect& geom ); +public: + GeometryTip(const XSizeHints* xSizeHints, bool save_under); + ~GeometryTip(); + void setGeometry(const QRect& geom); - private: - const XSizeHints* sizeHints; - }; +private: + const XSizeHints* sizeHints; +}; } // namespace diff --git a/group.cpp b/group.cpp index bf4f000a9..8ed40c197 100644 --- a/group.cpp +++ b/group.cpp @@ -62,136 +62,120 @@ namespace KWin static bool transiencyCheckNonExistent = false; bool performTransiencyCheck() - { +{ bool ret = true; ClientList clients = Workspace::self()->clients; - for( ClientList::ConstIterator it1 = clients.constBegin(); - it1 != clients.constEnd(); - ++it1 ) - { - if( (*it1)->deleting ) + for (ClientList::ConstIterator it1 = clients.constBegin(); + it1 != clients.constEnd(); + ++it1) { + if ((*it1)->deleting) continue; - if( (*it1)->in_group == NULL ) - { + if ((*it1)->in_group == NULL) { kDebug(1212) << "TC: " << *it1 << " in not in a group" << endl; ret = false; - } - else if( !(*it1)->in_group->members().contains( *it1 )) - { + } else if (!(*it1)->in_group->members().contains(*it1)) { kDebug(1212) << "TC: " << *it1 << " has a group " << (*it1)->in_group << " but group does not contain it" << endl; ret = false; - } - if( !(*it1)->isTransient()) - { - if( !(*it1)->mainClients().isEmpty()) - { + } + if (!(*it1)->isTransient()) { + if (!(*it1)->mainClients().isEmpty()) { kDebug(1212) << "TC: " << *it1 << " is not transient, has main clients:" << (*it1)->mainClients() << endl; ret = false; - } } - else - { + } else { ClientList mains = (*it1)->mainClients(); - for( ClientList::ConstIterator it2 = mains.constBegin(); - it2 != mains.constEnd(); - ++it2 ) - { - if( transiencyCheckNonExistent - && !Workspace::self()->clients.contains( *it2 ) - && !Workspace::self()->desktops.contains( *it2 )) - { + for (ClientList::ConstIterator it2 = mains.constBegin(); + it2 != mains.constEnd(); + ++it2) { + if (transiencyCheckNonExistent + && !Workspace::self()->clients.contains(*it2) + && !Workspace::self()->desktops.contains(*it2)) { kDebug(1212) << "TC:" << *it1 << " has non-existent main client "; kDebug(1212) << "TC2:" << *it2; // this may crash ret = false; continue; - } - if( !(*it2)->transients_list.contains( *it1 )) - { + } + if (!(*it2)->transients_list.contains(*it1)) { kdDebug(1212) << "TC:" << *it1 << " has main client " << *it2 << " but main client does not have it as a transient" << endl; ret = false; - } } } + } ClientList trans = (*it1)->transients_list; - for( ClientList::ConstIterator it2 = trans.constBegin(); - it2 != trans.constEnd(); - ++it2 ) - { - if( transiencyCheckNonExistent - && !Workspace::self()->clients.contains( *it2 ) - && !Workspace::self()->desktops.contains( *it2 )) - { + for (ClientList::ConstIterator it2 = trans.constBegin(); + it2 != trans.constEnd(); + ++it2) { + if (transiencyCheckNonExistent + && !Workspace::self()->clients.contains(*it2) + && !Workspace::self()->desktops.contains(*it2)) { kDebug(1212) << "TC:" << *it1 << " has non-existent transient "; kDebug(1212) << "TC2:" << *it2; // this may crash ret = false; continue; - } - if( !(*it2)->mainClients().contains( *it1 )) - { + } + if (!(*it2)->mainClients().contains(*it1)) { kdDebug(1212) << "TC:" << *it1 << " has transient " << *it2 << " but transient does not have it as a main client" << endl; ret = false; - } } } + } GroupList groups = Workspace::self()->groups; - for( GroupList::ConstIterator it1 = groups.constBegin(); - it1 != groups.constEnd(); - ++it1 ) - { + for (GroupList::ConstIterator it1 = groups.constBegin(); + it1 != groups.constEnd(); + ++it1) { ClientList members = (*it1)->members(); - for( ClientList::ConstIterator it2 = members.constBegin(); - it2 != members.constEnd(); - ++it2 ) - { - if( (*it2)->in_group != *it1 ) - { + for (ClientList::ConstIterator it2 = members.constBegin(); + it2 != members.constEnd(); + ++it2) { + if ((*it2)->in_group != *it1) { kDebug(1212) << "TC: Group " << *it1 << " contains client " << *it2 << " but client is not in that group" << endl; ret = false; - } } } - return ret; } + return ret; +} static QString transiencyCheckStartBt; static const Client* transiencyCheckClient; static int transiencyCheck = 0; -static void startTransiencyCheck( const QString& bt, const Client* c, bool ne ) - { - if( ++transiencyCheck == 1 ) - { +static void startTransiencyCheck(const QString& bt, const Client* c, bool ne) +{ + if (++transiencyCheck == 1) { transiencyCheckStartBt = bt; transiencyCheckClient = c; - } - if( ne ) - transiencyCheckNonExistent = true; } + if (ne) + transiencyCheckNonExistent = true; +} static void checkTransiency() - { - if( --transiencyCheck == 0 ) - { - if( !performTransiencyCheck()) - { +{ + if (--transiencyCheck == 0) { + if (!performTransiencyCheck()) { kDebug(1212) << "BT:" << transiencyCheckStartBt << endl; kDebug(1212) << "CLIENT:" << transiencyCheckClient << endl; abort(); - } - transiencyCheckNonExistent = false; } + transiencyCheckNonExistent = false; } +} class TransiencyChecker - { - public: - TransiencyChecker( const QString& bt, const Client*c ) { startTransiencyCheck( bt, c, false ); } - ~TransiencyChecker() { checkTransiency(); } - }; +{ +public: + TransiencyChecker(const QString& bt, const Client*c) { + startTransiencyCheck(bt, c, false); + } + ~TransiencyChecker() { + checkTransiency(); + } +}; void checkNonExistentClients() - { - startTransiencyCheck( kdBacktrace(), NULL, true ); +{ + startTransiencyCheck(kdBacktrace(), NULL, true); checkTransiency(); - } +} #define TRANSIENCY_CHECK( c ) TransiencyChecker transiency_checker( kdBacktrace(), c ) @@ -200,8 +184,8 @@ void checkNonExistentClients() #define TRANSIENCY_CHECK( c ) void checkNonExistentClients() - { - } +{ +} #endif @@ -209,282 +193,260 @@ void checkNonExistentClients() // Group //******************************************** -Group::Group( Window leader_P, Workspace* workspace_P ) - : leader_client( NULL ), - leader_wid( leader_P ), - _workspace( workspace_P ), - leader_info( NULL ), - user_time( -1U ), - refcount( 0 ) - { - if( leader_P != None ) - { - leader_client = workspace_P->findClient( WindowMatchPredicate( leader_P )); +Group::Group(Window leader_P, Workspace* workspace_P) + : leader_client(NULL), + leader_wid(leader_P), + _workspace(workspace_P), + leader_info(NULL), + user_time(-1U), + refcount(0) +{ + if (leader_P != None) { + leader_client = workspace_P->findClient(WindowMatchPredicate(leader_P)); unsigned long properties[ 2 ] = { 0, NET::WM2StartupId }; - leader_info = new NETWinInfo2( display(), leader_P, rootWindow(), - properties, 2 ); - } - effect_group = new EffectWindowGroupImpl( this ); - workspace()->addGroup( this, Allowed ); + leader_info = new NETWinInfo2(display(), leader_P, rootWindow(), + properties, 2); } + effect_group = new EffectWindowGroupImpl(this); + workspace()->addGroup(this, Allowed); +} Group::~Group() - { +{ delete leader_info; delete effect_group; - } +} QPixmap Group::icon() const - { - if( leader_client != NULL ) +{ + if (leader_client != NULL) return leader_client->icon(); - else if( leader_wid != None ) - { + else if (leader_wid != None) { QPixmap ic; - Client::readIcons( leader_wid, &ic, NULL, NULL, NULL ); + Client::readIcons(leader_wid, &ic, NULL, NULL, NULL); return ic; - } - return QPixmap(); } + return QPixmap(); +} QPixmap Group::miniIcon() const - { - if( leader_client != NULL ) +{ + if (leader_client != NULL) return leader_client->miniIcon(); - else if( leader_wid != None ) - { + else if (leader_wid != None) { QPixmap ic; - Client::readIcons( leader_wid, NULL, &ic, NULL, NULL ); + Client::readIcons(leader_wid, NULL, &ic, NULL, NULL); return ic; - } - return QPixmap(); } + return QPixmap(); +} QPixmap Group::bigIcon() const - { - if( leader_client != NULL ) +{ + if (leader_client != NULL) return leader_client->bigIcon(); - else if( leader_wid != None ) - { + else if (leader_wid != None) { QPixmap ic; - Client::readIcons( leader_wid, NULL, NULL, &ic, NULL ); + Client::readIcons(leader_wid, NULL, NULL, &ic, NULL); return ic; - } - return QPixmap(); } + return QPixmap(); +} QPixmap Group::hugeIcon() const - { - if( leader_client != NULL ) +{ + if (leader_client != NULL) return leader_client->hugeIcon(); - else if( leader_wid != None ) - { + else if (leader_wid != None) { QPixmap ic; - Client::readIcons( leader_wid, NULL, NULL, NULL, &ic ); + Client::readIcons(leader_wid, NULL, NULL, NULL, &ic); return ic; - } - return QPixmap(); } + return QPixmap(); +} -void Group::addMember( Client* member_P ) - { - TRANSIENCY_CHECK( member_P ); - _members.append( member_P ); +void Group::addMember(Client* member_P) +{ + TRANSIENCY_CHECK(member_P); + _members.append(member_P); // kDebug(1212) << "GROUPADD:" << this << ":" << member_P; // kDebug(1212) << kBacktrace(); - } +} -void Group::removeMember( Client* member_P ) - { - TRANSIENCY_CHECK( member_P ); +void Group::removeMember(Client* member_P) +{ + TRANSIENCY_CHECK(member_P); // kDebug(1212) << "GROUPREMOVE:" << this << ":" << member_P; // kDebug(1212) << kBacktrace(); - Q_ASSERT( _members.contains( member_P )); - _members.removeAll( member_P ); + Q_ASSERT(_members.contains(member_P)); + _members.removeAll(member_P); // there are cases when automatic deleting of groups must be delayed, // e.g. when removing a member and doing some operation on the possibly // other members of the group (which would be however deleted already // if there were no other members) - if( refcount == 0 && _members.isEmpty()) - { - workspace()->removeGroup( this, Allowed ); + if (refcount == 0 && _members.isEmpty()) { + workspace()->removeGroup(this, Allowed); delete this; - } } +} void Group::ref() - { +{ ++refcount; - } +} void Group::deref() - { - if( --refcount == 0 && _members.isEmpty()) - { - workspace()->removeGroup( this, Allowed ); +{ + if (--refcount == 0 && _members.isEmpty()) { + workspace()->removeGroup(this, Allowed); delete this; - } } +} -void Group::gotLeader( Client* leader_P ) - { - assert( leader_P->window() == leader_wid ); +void Group::gotLeader(Client* leader_P) +{ + assert(leader_P->window() == leader_wid); leader_client = leader_P; - } +} void Group::lostLeader() - { - assert( !_members.contains( leader_client )); +{ + assert(!_members.contains(leader_client)); leader_client = NULL; - if( _members.isEmpty()) - { - workspace()->removeGroup( this, Allowed ); + if (_members.isEmpty()) { + workspace()->removeGroup(this, Allowed); delete this; - } } +} void Group::getIcons() - { +{ // TODO - also needs adding the flag to NETWinInfo - } +} //*************************************** // Workspace //*************************************** -Group* Workspace::findGroup( Window leader ) const - { - assert( leader != None ); - for( GroupList::ConstIterator it = groups.constBegin(); - it != groups.constEnd(); - ++it ) - if( (*it)->leader() == leader ) +Group* Workspace::findGroup(Window leader) const +{ + assert(leader != None); + for (GroupList::ConstIterator it = groups.constBegin(); + it != groups.constEnd(); + ++it) + if ((*it)->leader() == leader) return *it; return NULL; - } +} // Client is group transient, but has no group set. Try to find // group with windows with the same client leader. -Group* Workspace::findClientLeaderGroup( const Client* c ) const - { - TRANSIENCY_CHECK( c ); +Group* Workspace::findClientLeaderGroup(const Client* c) const +{ + TRANSIENCY_CHECK(c); Group* ret = NULL; - for( ClientList::ConstIterator it = clients.constBegin(); - it != clients.constEnd(); - ++it ) - { - if( *it == c ) + for (ClientList::ConstIterator it = clients.constBegin(); + it != clients.constEnd(); + ++it) { + if (*it == c) continue; - if( (*it)->wmClientLeader() == c->wmClientLeader()) - { - if( ret == NULL || ret == (*it)->group()) + if ((*it)->wmClientLeader() == c->wmClientLeader()) { + if (ret == NULL || ret == (*it)->group()) ret = (*it)->group(); - else - { + else { // There are already two groups with the same client leader. // This most probably means the app uses group transients without // setting group for its windows. Merging the two groups is a bad // hack, but there's no really good solution for this case. ClientList old_group = (*it)->group()->members(); // old_group autodeletes when being empty - for( int pos = 0; - pos < old_group.count(); - ++pos ) - { + for (int pos = 0; + pos < old_group.count(); + ++pos) { Client* tmp = old_group[ pos ]; - if( tmp != c ) - tmp->changeClientLeaderGroup( ret ); - } + if (tmp != c) + tmp->changeClientLeaderGroup(ret); } } } - return ret; } + return ret; +} -void Workspace::updateMinimizedOfTransients( Client* c ) - { +void Workspace::updateMinimizedOfTransients(Client* c) +{ // if mainwindow is minimized or shaded, minimize transients too - if ( c->isMinimized() ) - { - for( ClientList::ConstIterator it = c->transients().constBegin(); - it != c->transients().constEnd(); - ++it ) - { + if (c->isMinimized()) { + for (ClientList::ConstIterator it = c->transients().constBegin(); + it != c->transients().constEnd(); + ++it) { if ((*it)->isModal()) continue; // there's no reason to hide modal dialogs with the main client - // but to keep them to eg. watch progress or whatever - if( !(*it)->isMinimized() - && !(*it)->isTopMenu() ) // topmenus are not minimized, they're hidden - { + // but to keep them to eg. watch progress or whatever + if (!(*it)->isMinimized() + && !(*it)->isTopMenu()) { // topmenus are not minimized, they're hidden (*it)->minimize(); - updateMinimizedOfTransients( (*it) ); - } - } - if( c->isModal()) // if a modal dialog is minimized, minimize its mainwindow too - { - foreach( Client* c2, c->mainClients()) - c2->minimize(); + updateMinimizedOfTransients((*it)); } } - else - { // else unmiminize the transients - for( ClientList::ConstIterator it = c->transients().constBegin(); - it != c->transients().constEnd(); - ++it ) - { - if( (*it)->isMinimized() - && !(*it)->isTopMenu()) - { + if (c->isModal()) { // if a modal dialog is minimized, minimize its mainwindow too + foreach (Client * c2, c->mainClients()) + c2->minimize(); + } + } else { + // else unmiminize the transients + for (ClientList::ConstIterator it = c->transients().constBegin(); + it != c->transients().constEnd(); + ++it) { + if ((*it)->isMinimized() + && !(*it)->isTopMenu()) { (*it)->unminimize(); - updateMinimizedOfTransients( (*it) ); - } - } - if( c->isModal()) - { - foreach( Client* c2, c->mainClients()) - c2->unminimize(); + updateMinimizedOfTransients((*it)); } } + if (c->isModal()) { + foreach (Client * c2, c->mainClients()) + c2->unminimize(); + } } +} /*! Sets the client \a c's transient windows' on_all_desktops property to \a on_all_desktops. */ -void Workspace::updateOnAllDesktopsOfTransients( Client* c ) - { - for( ClientList::ConstIterator it = c->transients().constBegin(); - it != c->transients().constEnd(); - ++it) - { - if( (*it)->isOnAllDesktops() != c->isOnAllDesktops()) - (*it)->setOnAllDesktops( c->isOnAllDesktops()); - } +void Workspace::updateOnAllDesktopsOfTransients(Client* c) +{ + for (ClientList::ConstIterator it = c->transients().constBegin(); + it != c->transients().constEnd(); + ++it) { + if ((*it)->isOnAllDesktops() != c->isOnAllDesktops()) + (*it)->setOnAllDesktops(c->isOnAllDesktops()); } +} /*! Sets the client \a c's transient windows' on_all_activities property to \a on_all_desktops. */ -void Workspace::updateOnAllActivitiesOfTransients( Client* c ) - { - for( ClientList::ConstIterator it = c->transients().constBegin(); - it != c->transients().constEnd(); - ++it) - { - if( (*it)->isOnAllActivities() != c->isOnAllActivities()) - (*it)->setOnAllActivities( c->isOnAllActivities()); - } +void Workspace::updateOnAllActivitiesOfTransients(Client* c) +{ + for (ClientList::ConstIterator it = c->transients().constBegin(); + it != c->transients().constEnd(); + ++it) { + if ((*it)->isOnAllActivities() != c->isOnAllActivities()) + (*it)->setOnAllActivities(c->isOnAllActivities()); } +} // A new window has been mapped. Check if it's not a mainwindow for some already existing transient window. -void Workspace::checkTransients( Window w ) - { - TRANSIENCY_CHECK( NULL ); - for( ClientList::ConstIterator it = clients.constBegin(); - it != clients.constEnd(); - ++it ) - (*it)->checkTransient( w ); - } +void Workspace::checkTransients(Window w) +{ + TRANSIENCY_CHECK(NULL); + for (ClientList::ConstIterator it = clients.constBegin(); + it != clients.constEnd(); + ++it) + (*it)->checkTransient(w); +} //**************************************** @@ -493,60 +455,60 @@ void Workspace::checkTransients( Window w ) // hacks for broken apps here // all resource classes are forced to be lowercase -bool Toplevel::resourceMatch( const Toplevel* c1, const Toplevel* c2 ) - { +bool Toplevel::resourceMatch(const Toplevel* c1, const Toplevel* c2) +{ // xv has "xv" as resource name, and different strings starting with "XV" as resource class - if( qstrncmp( c1->resourceClass(), "xv", 2 ) == 0 && c1->resourceName() == "xv" ) - return qstrncmp( c2->resourceClass(), "xv", 2 ) == 0 && c2->resourceName() == "xv"; + if (qstrncmp(c1->resourceClass(), "xv", 2) == 0 && c1->resourceName() == "xv") + return qstrncmp(c2->resourceClass(), "xv", 2) == 0 && c2->resourceName() == "xv"; // Mozilla has "Mozilla" as resource name, and different strings as resource class - if( c1->resourceName() == "mozilla" ) + if (c1->resourceName() == "mozilla") return c2->resourceName() == "mozilla"; return c1->resourceClass() == c2->resourceClass(); - } +} //**************************************** // Client //**************************************** -bool Client::belongToSameApplication( const Client* c1, const Client* c2, bool active_hack ) - { +bool Client::belongToSameApplication(const Client* c1, const Client* c2, bool active_hack) +{ bool same_app = false; // tests that definitely mean they belong together - if( c1 == c2 ) + if (c1 == c2) same_app = true; - else if( c1->isTransient() && c2->hasTransient( c1, true )) + else if (c1->isTransient() && c2->hasTransient(c1, true)) same_app = true; // c1 has c2 as mainwindow - else if( c2->isTransient() && c1->hasTransient( c2, true )) + else if (c2->isTransient() && c1->hasTransient(c2, true)) same_app = true; // c2 has c1 as mainwindow - else if( c1->group() == c2->group()) + else if (c1->group() == c2->group()) same_app = true; // same group - else if( c1->wmClientLeader() == c2->wmClientLeader() - && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), - && c2->wmClientLeader() != c2->window()) // don't use in this test then + else if (c1->wmClientLeader() == c2->wmClientLeader() + && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), + && c2->wmClientLeader() != c2->window()) // don't use in this test then same_app = true; // same client leader // tests that mean they most probably don't belong together - else if( c1->pid() != c2->pid() - || c1->wmClientMachine( false ) != c2->wmClientMachine( false )) + else if (c1->pid() != c2->pid() + || c1->wmClientMachine(false) != c2->wmClientMachine(false)) ; // different processes - else if( c1->wmClientLeader() != c2->wmClientLeader() - && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), - && c2->wmClientLeader() != c2->window()) // don't use in this test then + else if (c1->wmClientLeader() != c2->wmClientLeader() + && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), + && c2->wmClientLeader() != c2->window()) // don't use in this test then ; // different client leader - else if( !resourceMatch( c1, c2 )) + else if (!resourceMatch(c1, c2)) ; // different apps - else if( !sameAppWindowRoleMatch( c1, c2, active_hack )) + else if (!sameAppWindowRoleMatch(c1, c2, active_hack)) ; // "different" apps - else if( c1->pid() == 0 || c2->pid() == 0 ) + else if (c1->pid() == 0 || c2->pid() == 0) ; // old apps that don't have _NET_WM_PID, consider them different - // if they weren't found to match above + // if they weren't found to match above else same_app = true; // looks like it's the same app return same_app; - } +} // Non-transient windows with window role containing '#' are always // considered belonging to different applications (unless @@ -558,48 +520,45 @@ bool Client::belongToSameApplication( const Client* c1, const Client* c2, bool a // considered belonging to the same application. This is for // the cases when opening new mainwindow directly from the application, // e.g. 'Open New Window' in konqy ( active_hack == true ). -bool Client::sameAppWindowRoleMatch( const Client* c1, const Client* c2, bool active_hack ) - { - if( c1->isTransient()) - { - while( c1->transientFor() != NULL ) +bool Client::sameAppWindowRoleMatch(const Client* c1, const Client* c2, bool active_hack) +{ + if (c1->isTransient()) { + while (c1->transientFor() != NULL) c1 = c1->transientFor(); - if( c1->groupTransient()) + if (c1->groupTransient()) return c1->group() == c2->group(); #if 0 - // if a group transient is in its own group, it didn't possibly have a group, - // and therefore should be considered belonging to the same app like - // all other windows from the same app - || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; + // if a group transient is in its own group, it didn't possibly have a group, + // and therefore should be considered belonging to the same app like + // all other windows from the same app + || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; #endif - } - if( c2->isTransient()) - { - while( c2->transientFor() != NULL ) + } + if (c2->isTransient()) { + while (c2->transientFor() != NULL) c2 = c2->transientFor(); - if( c2->groupTransient()) + if (c2->groupTransient()) return c1->group() == c2->group(); #if 0 - || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; + || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; #endif - } - int pos1 = c1->windowRole().indexOf( '#' ); - int pos2 = c2->windowRole().indexOf( '#' ); - if(( pos1 >= 0 && pos2 >= 0 ) - || - // hacks here - // Mozilla has resourceName() and resourceClass() swapped - ( c1->resourceName() == "mozilla" && c2->resourceName() == "mozilla" )) - { - if( !active_hack ) // without the active hack for focus stealing prevention, + } + int pos1 = c1->windowRole().indexOf('#'); + int pos2 = c2->windowRole().indexOf('#'); + if ((pos1 >= 0 && pos2 >= 0) + || + // hacks here + // Mozilla has resourceName() and resourceClass() swapped + (c1->resourceName() == "mozilla" && c2->resourceName() == "mozilla")) { + if (!active_hack) // without the active hack for focus stealing prevention, return c1 == c2; // different mainwindows are always different apps - if( !c1->isActive() && !c2->isActive()) + if (!c1->isActive() && !c2->isActive()) return c1 == c2; else return true; - } - return true; } + return true; +} /* @@ -648,106 +607,97 @@ bool Client::sameAppWindowRoleMatch( const Client* c1, const Client* c2, bool ac */ void Client::readTransient() - { - TRANSIENCY_CHECK( this ); +{ + TRANSIENCY_CHECK(this); Window new_transient_for_id; - if( XGetTransientForHint( display(), window(), &new_transient_for_id )) - { + if (XGetTransientForHint(display(), window(), &new_transient_for_id)) { original_transient_for_id = new_transient_for_id; - new_transient_for_id = verifyTransientFor( new_transient_for_id, true ); - } - else - { + new_transient_for_id = verifyTransientFor(new_transient_for_id, true); + } else { original_transient_for_id = None; - new_transient_for_id = verifyTransientFor( None, false ); - } - setTransient( new_transient_for_id ); + new_transient_for_id = verifyTransientFor(None, false); } + setTransient(new_transient_for_id); +} -void Client::setTransient( Window new_transient_for_id ) - { - TRANSIENCY_CHECK( this ); - if( new_transient_for_id != transient_for_id ) - { +void Client::setTransient(Window new_transient_for_id) +{ + TRANSIENCY_CHECK(this); + if (new_transient_for_id != transient_for_id) { removeFromMainClients(); transient_for = NULL; transient_for_id = new_transient_for_id; - if( transient_for_id != None && !groupTransient()) - { - transient_for = workspace()->findClient( WindowMatchPredicate( transient_for_id )); - assert( transient_for != NULL ); // verifyTransient() had to check this - transient_for->addTransient( this ); - } // checkGroup() will check 'check_active_modal' - checkGroup( NULL, true ); // force, because transiency has changed - if( isTopMenu()) + if (transient_for_id != None && !groupTransient()) { + transient_for = workspace()->findClient(WindowMatchPredicate(transient_for_id)); + assert(transient_for != NULL); // verifyTransient() had to check this + transient_for->addTransient(this); + } // checkGroup() will check 'check_active_modal' + checkGroup(NULL, true); // force, because transiency has changed + if (isTopMenu()) workspace()->updateCurrentTopMenu(); - workspace()->updateClientLayer( this ); + workspace()->updateClientLayer(this); workspace()->resetUpdateToolWindowsTimer(); - } } +} void Client::removeFromMainClients() - { - TRANSIENCY_CHECK( this ); - if( transientFor() != NULL ) - transientFor()->removeTransient( this ); - if( groupTransient()) - { - for( ClientList::ConstIterator it = group()->members().constBegin(); - it != group()->members().constEnd(); - ++it ) - (*it)->removeTransient( this ); - } +{ + TRANSIENCY_CHECK(this); + if (transientFor() != NULL) + transientFor()->removeTransient(this); + if (groupTransient()) { + for (ClientList::ConstIterator it = group()->members().constBegin(); + it != group()->members().constEnd(); + ++it) + (*it)->removeTransient(this); } +} // *sigh* this transiency handling is madness :( // This one is called when destroying/releasing a window. // It makes sure this client is removed from all grouping // related lists. void Client::cleanGrouping() - { - TRANSIENCY_CHECK( this ); +{ + TRANSIENCY_CHECK(this); // kDebug(1212) << "CLEANGROUPING:" << this; -// for( ClientList::ConstIterator it = group()->members().begin(); +// for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // kDebug(1212) << "CL:" << *it; // ClientList mains; // mains = mainClients(); -// for( ClientList::ConstIterator it = mains.begin(); +// for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // kDebug(1212) << "MN:" << *it; removeFromMainClients(); // kDebug(1212) << "CLEANGROUPING2:" << this; -// for( ClientList::ConstIterator it = group()->members().begin(); +// for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // kDebug(1212) << "CL2:" << *it; // mains = mainClients(); -// for( ClientList::ConstIterator it = mains.begin(); +// for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // kDebug(1212) << "MN2:" << *it; - for( ClientList::ConstIterator it = transients_list.constBegin(); - it != transients_list.constEnd(); - ) - { - if( (*it)->transientFor() == this ) - { - removeTransient( *it ); + for (ClientList::ConstIterator it = transients_list.constBegin(); + it != transients_list.constEnd(); + ) { + if ((*it)->transientFor() == this) { + removeTransient(*it); it = transients_list.constBegin(); // restart, just in case something more has changed with the list - } - else + } else ++it; - } + } // kDebug(1212) << "CLEANGROUPING3:" << this; -// for( ClientList::ConstIterator it = group()->members().begin(); +// for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // kDebug(1212) << "CL3:" << *it; // mains = mainClients(); -// for( ClientList::ConstIterator it = mains.begin(); +// for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // kDebug(1212) << "MN3:" << *it; @@ -757,444 +707,411 @@ void Client::cleanGrouping() // were transient for 'this' group transient, which again // added 'this' to those transient lists :( ClientList group_members = group()->members(); - group()->removeMember( this ); + group()->removeMember(this); in_group = NULL; - for( ClientList::ConstIterator it = group_members.constBegin(); - it != group_members.constEnd(); - ++it ) - (*it)->removeTransient( this ); + for (ClientList::ConstIterator it = group_members.constBegin(); + it != group_members.constEnd(); + ++it) + (*it)->removeTransient(this); // kDebug(1212) << "CLEANGROUPING4:" << this; -// for( ClientList::ConstIterator it = group_members.begin(); +// for ( ClientList::ConstIterator it = group_members.begin(); // it != group_members.end(); // ++it ) // kDebug(1212) << "CL4:" << *it; - } +} // Make sure that no group transient is considered transient // for a window that is (directly or indirectly) transient for it // (including another group transients). // Non-group transients not causing loops are checked in verifyTransientFor(). void Client::checkGroupTransients() - { - TRANSIENCY_CHECK( this ); - for( ClientList::ConstIterator it1 = group()->members().constBegin(); - it1 != group()->members().constEnd(); - ++it1 ) - { - if( !(*it1)->groupTransient()) // check all group transients in the group +{ + TRANSIENCY_CHECK(this); + for (ClientList::ConstIterator it1 = group()->members().constBegin(); + it1 != group()->members().constEnd(); + ++it1) { + if (!(*it1)->groupTransient()) // check all group transients in the group continue; // TODO optimize to check only the changed ones? - for( ClientList::ConstIterator it2 = group()->members().constBegin(); - it2 != group()->members().constEnd(); - ++it2 ) // group transients can be transient only for others in the group, - { // so don't make them transient for the ones that are transient for it - if( *it1 == *it2 ) + for (ClientList::ConstIterator it2 = group()->members().constBegin(); + it2 != group()->members().constEnd(); + ++it2) { // group transients can be transient only for others in the group, + // so don't make them transient for the ones that are transient for it + if (*it1 == *it2) continue; - for( Client* cl = (*it2)->transientFor(); - cl != NULL; - cl = cl->transientFor()) - { - if( cl == *it1 ) - { // don't use removeTransient(), that would modify *it2 too - (*it2)->transients_list.removeAll( *it1 ); + for (Client* cl = (*it2)->transientFor(); + cl != NULL; + cl = cl->transientFor()) { + if (cl == *it1) { + // don't use removeTransient(), that would modify *it2 too + (*it2)->transients_list.removeAll(*it1); continue; - } } + } // if *it1 and *it2 are both group transients, and are transient for each other, // make only *it2 transient for *it1 (i.e. subwindow), as *it2 came later, // and should be therefore on top of *it1 // TODO This could possibly be optimized, it also requires hasTransient() to check for loops. - if( (*it2)->groupTransient() && (*it1)->hasTransient( *it2, true ) && (*it2)->hasTransient( *it1, true )) - (*it2)->transients_list.removeAll( *it1 ); + if ((*it2)->groupTransient() && (*it1)->hasTransient(*it2, true) && (*it2)->hasTransient(*it1, true)) + (*it2)->transients_list.removeAll(*it1); // if there are already windows W1 and W2, W2 being transient for W1, and group transient W3 // is added, make it transient only for W2, not for W1, because it's already indirectly // transient for it - the indirect transiency actually shouldn't break anything, // but it can lead to exponentially expensive operations (#95231) // TODO this is pretty slow as well - for( ClientList::ConstIterator it3 = group()->members().constBegin(); - it3 != group()->members().constEnd(); - ++it3 ) - { - if( *it1 == *it2 || *it2 == *it3 || *it1 == *it3 ) + for (ClientList::ConstIterator it3 = group()->members().constBegin(); + it3 != group()->members().constEnd(); + ++it3) { + if (*it1 == *it2 || *it2 == *it3 || *it1 == *it3) continue; - if( (*it2)->hasTransient( *it1, false ) && (*it3)->hasTransient( *it1, false )) - { - if( (*it2)->hasTransient( *it3, true )) - (*it2)->transients_list.removeAll( *it1 ); - if( (*it3)->hasTransient( *it2, true )) - (*it3)->transients_list.removeAll( *it1 ); - } + if ((*it2)->hasTransient(*it1, false) && (*it3)->hasTransient(*it1, false)) { + if ((*it2)->hasTransient(*it3, true)) + (*it2)->transients_list.removeAll(*it1); + if ((*it3)->hasTransient(*it2, true)) + (*it3)->transients_list.removeAll(*it1); } } } } +} /*! Check that the window is not transient for itself, and similar nonsense. */ -Window Client::verifyTransientFor( Window new_transient_for, bool defined ) - { +Window Client::verifyTransientFor(Window new_transient_for, bool defined) +{ Window new_property_value = new_transient_for; // make sure splashscreens are shown above all their app's windows, even though // they're in Normal layer - if( isSplash() && new_transient_for == None ) + if (isSplash() && new_transient_for == None) new_transient_for = rootWindow(); - if( new_transient_for == None ) - { - if( defined ) // sometimes WM_TRANSIENT_FOR is set to None, instead of root window + if (new_transient_for == None) { + if (defined) // sometimes WM_TRANSIENT_FOR is set to None, instead of root window new_property_value = new_transient_for = rootWindow(); else return None; - } - if( new_transient_for == window()) // pointing to self - { // also fix the property itself - kWarning( 1216 ) << "Client " << this << " has WM_TRANSIENT_FOR poiting to itself." ; + } + if (new_transient_for == window()) { // pointing to self + // also fix the property itself + kWarning(1216) << "Client " << this << " has WM_TRANSIENT_FOR poiting to itself." ; new_property_value = new_transient_for = rootWindow(); - } + } // The transient_for window may be embedded in another application, // so kwin cannot see it. Try to find the managed client for the // window and fix the transient_for property if possible. WId before_search = new_transient_for; - while( new_transient_for != None - && new_transient_for != rootWindow() - && !workspace()->findClient( WindowMatchPredicate( new_transient_for ))) - { + while (new_transient_for != None + && new_transient_for != rootWindow() + && !workspace()->findClient(WindowMatchPredicate(new_transient_for))) { Window root_return, parent_return; Window* wins = NULL; unsigned int nwins; int r = XQueryTree(display(), new_transient_for, &root_return, &parent_return, &wins, &nwins); - if ( wins ) + if (wins) XFree((void *) wins); - if ( r == 0) + if (r == 0) break; new_transient_for = parent_return; - } - if( Client* new_transient_for_client = workspace()->findClient( WindowMatchPredicate( new_transient_for ))) - { - if( new_transient_for != before_search ) - { - kDebug( 1212 ) << "Client " << this << " has WM_TRANSIENT_FOR poiting to non-toplevel window " - << before_search << ", child of " << new_transient_for_client << ", adjusting." << endl; + } + if (Client* new_transient_for_client = workspace()->findClient(WindowMatchPredicate(new_transient_for))) { + if (new_transient_for != before_search) { + kDebug(1212) << "Client " << this << " has WM_TRANSIENT_FOR poiting to non-toplevel window " + << before_search << ", child of " << new_transient_for_client << ", adjusting." << endl; new_property_value = new_transient_for; // also fix the property - } } - else + } else new_transient_for = before_search; // nice try // loop detection // group transients cannot cause loops, because they're considered transient only for non-transient // windows in the group int count = 20; Window loop_pos = new_transient_for; - while( loop_pos != None && loop_pos != rootWindow()) - { - Client* pos = workspace()->findClient( WindowMatchPredicate( loop_pos )); - if( pos == NULL ) + while (loop_pos != None && loop_pos != rootWindow()) { + Client* pos = workspace()->findClient(WindowMatchPredicate(loop_pos)); + if (pos == NULL) break; loop_pos = pos->transient_for_id; - if( --count == 0 || pos == this ) - { - kWarning( 1216 ) << "Client " << this << " caused WM_TRANSIENT_FOR loop." ; + if (--count == 0 || pos == this) { + kWarning(1216) << "Client " << this << " caused WM_TRANSIENT_FOR loop." ; new_transient_for = rootWindow(); - } } - if( new_transient_for != rootWindow() - && workspace()->findClient( WindowMatchPredicate( new_transient_for )) == NULL ) - { // it's transient for a specific window, but that window is not mapped - new_transient_for = rootWindow(); - } - if( new_property_value != original_transient_for_id ) - XSetTransientForHint( display(), window(), new_property_value ); - return new_transient_for; } + if (new_transient_for != rootWindow() + && workspace()->findClient(WindowMatchPredicate(new_transient_for)) == NULL) { + // it's transient for a specific window, but that window is not mapped + new_transient_for = rootWindow(); + } + if (new_property_value != original_transient_for_id) + XSetTransientForHint(display(), window(), new_property_value); + return new_transient_for; +} -void Client::addTransient( Client* cl ) - { - TRANSIENCY_CHECK( this ); - assert( !transients_list.contains( cl )); +void Client::addTransient(Client* cl) +{ + TRANSIENCY_CHECK(this); + assert(!transients_list.contains(cl)); // assert( !cl->hasTransient( this, true )); will be fixed in checkGroupTransients() - assert( cl != this ); - transients_list.append( cl ); - if( workspace()->mostRecentlyActivatedClient() == this && cl->isModal()) + assert(cl != this); + transients_list.append(cl); + if (workspace()->mostRecentlyActivatedClient() == this && cl->isModal()) check_active_modal = true; // kDebug(1212) << "ADDTRANS:" << this << ":" << cl; // kDebug(1212) << kBacktrace(); -// for( ClientList::ConstIterator it = transients_list.begin(); +// for ( ClientList::ConstIterator it = transients_list.begin(); // it != transients_list.end(); // ++it ) // kDebug(1212) << "AT:" << (*it); - } +} -void Client::removeTransient( Client* cl ) - { - TRANSIENCY_CHECK( this ); +void Client::removeTransient(Client* cl) +{ + TRANSIENCY_CHECK(this); // kDebug(1212) << "REMOVETRANS:" << this << ":" << cl; // kDebug(1212) << kBacktrace(); - transients_list.removeAll( cl ); + transients_list.removeAll(cl); // cl is transient for this, but this is going away // make cl group transient - if( cl->transientFor() == this ) - { + if (cl->transientFor() == this) { cl->transient_for_id = None; cl->transient_for = NULL; // SELI // SELI cl->setTransient( rootWindow()); - cl->setTransient( None ); - } + cl->setTransient(None); } +} // A new window has been mapped. Check if it's not a mainwindow for this already existing window. -void Client::checkTransient( Window w ) - { - TRANSIENCY_CHECK( this ); - if( original_transient_for_id != w ) +void Client::checkTransient(Window w) +{ + TRANSIENCY_CHECK(this); + if (original_transient_for_id != w) return; - w = verifyTransientFor( w, true ); - setTransient( w ); - } + w = verifyTransientFor(w, true); + setTransient(w); +} // returns true if cl is the transient_for window for this client, // or recursively the transient_for window -bool Client::hasTransient( const Client* cl, bool indirect ) const - { +bool Client::hasTransient(const Client* cl, bool indirect) const +{ // checkGroupTransients() uses this to break loops, so hasTransient() must detect them ConstClientList set; - return hasTransientInternal( cl, indirect, set ); - } + return hasTransientInternal(cl, indirect, set); +} -bool Client::hasTransientInternal( const Client* cl, bool indirect, ConstClientList& set ) const - { - if( cl->transientFor() != NULL ) - { - if( cl->transientFor() == this ) +bool Client::hasTransientInternal(const Client* cl, bool indirect, ConstClientList& set) const +{ + if (cl->transientFor() != NULL) { + if (cl->transientFor() == this) return true; - if( !indirect ) + if (!indirect) return false; - if( set.contains( cl )) + if (set.contains(cl)) return false; - set.append( cl ); - return hasTransientInternal( cl->transientFor(), indirect, set ); - } - if( !cl->isTransient()) + set.append(cl); + return hasTransientInternal(cl->transientFor(), indirect, set); + } + if (!cl->isTransient()) return false; - if( group() != cl->group()) + if (group() != cl->group()) return false; // cl is group transient, search from top - if( transients().contains( const_cast< Client* >( cl ))) + if (transients().contains(const_cast< Client* >(cl))) return true; - if( !indirect ) + if (!indirect) return false; - if( set.contains( this )) + if (set.contains(this)) return false; - set.append( this ); - for( ClientList::ConstIterator it = transients().constBegin(); - it != transients().constEnd(); - ++it ) - if( (*it)->hasTransientInternal( cl, indirect, set )) + set.append(this); + for (ClientList::ConstIterator it = transients().constBegin(); + it != transients().constEnd(); + ++it) + if ((*it)->hasTransientInternal(cl, indirect, set)) return true; return false; - } +} ClientList Client::mainClients() const - { - if( !isTransient()) +{ + if (!isTransient()) return ClientList(); - if( transientFor() != NULL ) - return ClientList() << const_cast< Client* >( transientFor()); + if (transientFor() != NULL) + return ClientList() << const_cast< Client* >(transientFor()); ClientList result; - for( ClientList::ConstIterator it = group()->members().constBegin(); - it != group()->members().constEnd(); - ++it ) - if((*it)->hasTransient( this, false )) - result.append( *it ); + for (ClientList::ConstIterator it = group()->members().constBegin(); + it != group()->members().constEnd(); + ++it) + if ((*it)->hasTransient(this, false)) + result.append(*it); return result; - } +} ClientList Client::allMainClients() const - { +{ ClientList result = mainClients(); - foreach( const Client* cl, result ) - result += cl->allMainClients(); + foreach (const Client * cl, result) + result += cl->allMainClients(); return result; - } +} -Client* Client::findModal( bool allow_itself ) - { - for( ClientList::ConstIterator it = transients().constBegin(); - it != transients().constEnd(); - ++it ) - if( Client* ret = (*it)->findModal( true )) +Client* Client::findModal(bool allow_itself) +{ + for (ClientList::ConstIterator it = transients().constBegin(); + it != transients().constEnd(); + ++it) + if (Client* ret = (*it)->findModal(true)) return ret; - if( isModal() && allow_itself ) + if (isModal() && allow_itself) return this; return NULL; - } +} // Client::window_group only holds the contents of the hint, // but it should be used only to find the group, not for anything else // Argument is only when some specific group needs to be set. -void Client::checkGroup( Group* set_group, bool force ) - { - TRANSIENCY_CHECK( this ); +void Client::checkGroup(Group* set_group, bool force) +{ + TRANSIENCY_CHECK(this); Group* old_group = in_group; - if( old_group != NULL ) + if (old_group != NULL) old_group->ref(); // turn off automatic deleting - if( set_group != NULL ) - { - if( set_group != in_group ) - { - if( in_group != NULL ) - in_group->removeMember( this ); + if (set_group != NULL) { + if (set_group != in_group) { + if (in_group != NULL) + in_group->removeMember(this); in_group = set_group; - in_group->addMember( this ); - } + in_group->addMember(this); } - else if( window_group != None ) - { - Group* new_group = workspace()->findGroup( window_group ); - if( transientFor() != NULL && transientFor()->group() != new_group ) - { // move the window to the right group (e.g. a dialog provided - // by different app, but transient for this one, so make it part of that group) + } else if (window_group != None) { + Group* new_group = workspace()->findGroup(window_group); + if (transientFor() != NULL && transientFor()->group() != new_group) { + // move the window to the right group (e.g. a dialog provided + // by different app, but transient for this one, so make it part of that group) new_group = transientFor()->group(); - } - if( new_group == NULL ) // doesn't exist yet - new_group = new Group( window_group, workspace()); - if( new_group != in_group ) - { - if( in_group != NULL ) - in_group->removeMember( this ); + } + if (new_group == NULL) // doesn't exist yet + new_group = new Group(window_group, workspace()); + if (new_group != in_group) { + if (in_group != NULL) + in_group->removeMember(this); in_group = new_group; - in_group->addMember( this ); - } + in_group->addMember(this); } - else - { - if( transientFor() != NULL ) - { // doesn't have window group set, but is transient for something - // so make it part of that group + } else { + if (transientFor() != NULL) { + // doesn't have window group set, but is transient for something + // so make it part of that group Group* new_group = transientFor()->group(); - if( new_group != in_group ) - { - if( in_group != NULL ) - in_group->removeMember( this ); + if (new_group != in_group) { + if (in_group != NULL) + in_group->removeMember(this); in_group = transientFor()->group(); - in_group->addMember( this ); - } + in_group->addMember(this); } - else if( groupTransient()) - { // group transient which actually doesn't have a group :( - // try creating group with other windows with the same client leader - Group* new_group = workspace()->findClientLeaderGroup( this ); - if( new_group == NULL ) - new_group = new Group( None, workspace()); - if( new_group != in_group ) - { - if( in_group != NULL ) - in_group->removeMember( this ); + } else if (groupTransient()) { + // group transient which actually doesn't have a group :( + // try creating group with other windows with the same client leader + Group* new_group = workspace()->findClientLeaderGroup(this); + if (new_group == NULL) + new_group = new Group(None, workspace()); + if (new_group != in_group) { + if (in_group != NULL) + in_group->removeMember(this); in_group = new_group; - in_group->addMember( this ); - } + in_group->addMember(this); } - else // Not transient without a group, put it in its client leader group. - { // This might be stupid if grouping was used for e.g. taskbar grouping - // or minimizing together the whole group, but as long as it is used - // only for dialogs it's better to keep windows from one app in one group. - Group* new_group = workspace()->findClientLeaderGroup( this ); - if( in_group != NULL && in_group != new_group ) - { - in_group->removeMember( this ); + } else { // Not transient without a group, put it in its client leader group. + // This might be stupid if grouping was used for e.g. taskbar grouping + // or minimizing together the whole group, but as long as it is used + // only for dialogs it's better to keep windows from one app in one group. + Group* new_group = workspace()->findClientLeaderGroup(this); + if (in_group != NULL && in_group != new_group) { + in_group->removeMember(this); in_group = NULL; - } - if( new_group == NULL ) - new_group = new Group( None, workspace() ); - if( in_group != new_group ) - { + } + if (new_group == NULL) + new_group = new Group(None, workspace()); + if (in_group != new_group) { in_group = new_group; - in_group->addMember( this ); - } + in_group->addMember(this); } } - if( in_group != old_group || force ) - { - for( ClientList::Iterator it = transients_list.begin(); - it != transients_list.end(); - ) - { // group transients in the old group are no longer transient for it - if( (*it)->groupTransient() && (*it)->group() != group()) - it = transients_list.erase( it ); + } + if (in_group != old_group || force) { + for (ClientList::Iterator it = transients_list.begin(); + it != transients_list.end(); + ) { + // group transients in the old group are no longer transient for it + if ((*it)->groupTransient() && (*it)->group() != group()) + it = transients_list.erase(it); else ++it; - } - if( groupTransient()) - { + } + if (groupTransient()) { // no longer transient for ones in the old group - if( old_group != NULL ) - { - for( ClientList::ConstIterator it = old_group->members().constBegin(); - it != old_group->members().constEnd(); - ++it ) - (*it)->removeTransient( this ); - } - // and make transient for all in the new group - for( ClientList::ConstIterator it = group()->members().constBegin(); - it != group()->members().constEnd(); - ++it ) - { - if( *it == this ) - break; // this means the window is only transient for windows mapped before it - (*it)->addTransient( this ); - } + if (old_group != NULL) { + for (ClientList::ConstIterator it = old_group->members().constBegin(); + it != old_group->members().constEnd(); + ++it) + (*it)->removeTransient(this); } + // and make transient for all in the new group + for (ClientList::ConstIterator it = group()->members().constBegin(); + it != group()->members().constEnd(); + ++it) { + if (*it == this) + break; // this means the window is only transient for windows mapped before it + (*it)->addTransient(this); + } + } // group transient splashscreens should be transient even for windows // in group mapped later - for( ClientList::ConstIterator it = group()->members().constBegin(); - it != group()->members().constEnd(); - ++it ) - { - if( !(*it)->isSplash()) + for (ClientList::ConstIterator it = group()->members().constBegin(); + it != group()->members().constEnd(); + ++it) { + if (!(*it)->isSplash()) continue; - if( !(*it)->groupTransient()) + if (!(*it)->groupTransient()) continue; - if( *it == this || hasTransient( *it, true )) // TODO indirect? + if (*it == this || hasTransient(*it, true)) // TODO indirect? continue; - addTransient( *it ); - } + addTransient(*it); } - if( old_group != NULL ) + } + if (old_group != NULL) old_group->deref(); // can be now deleted if empty checkGroupTransients(); checkActiveModal(); - workspace()->updateClientLayer( this ); - } + workspace()->updateClientLayer(this); +} // used by Workspace::findClientLeaderGroup() -void Client::changeClientLeaderGroup( Group* gr ) - { +void Client::changeClientLeaderGroup(Group* gr) +{ // transientFor() != NULL are in the group of their mainwindow, so keep them there - if( transientFor() != NULL ) + if (transientFor() != NULL) return; // also don't change the group for window which have group set - if( window_group ) + if (window_group) return; - checkGroup( gr ); // change group - } + checkGroup(gr); // change group +} bool Client::check_active_modal = false; void Client::checkActiveModal() - { +{ // if the active window got new modal transient, activate it. // cannot be done in AddTransient(), because there may temporarily // exist loops, breaking findModal Client* check_modal = workspace()->mostRecentlyActivatedClient(); - if( check_modal != NULL && check_modal->check_active_modal ) - { + if (check_modal != NULL && check_modal->check_active_modal) { Client* new_modal = check_modal->findModal(); - if( new_modal != NULL && new_modal != check_modal ) - { - if( !new_modal->isManaged()) + if (new_modal != NULL && new_modal != check_modal) { + if (!new_modal->isManaged()) return; // postpone check until end of manage() - workspace()->activateClient( new_modal ); - } - check_modal->check_active_modal = false; + workspace()->activateClient(new_modal); } + check_modal->check_active_modal = false; } +} } // namespace diff --git a/group.h b/group.h index b1a80129d..41e10a118 100644 --- a/group.h +++ b/group.h @@ -34,77 +34,77 @@ class Workspace; class EffectWindowGroupImpl; class Group - { - public: - Group( Window leader, Workspace* workspace ); - ~Group(); - Window leader() const; - const Client* leaderClient() const; - Client* leaderClient(); - const ClientList& members() const; - QPixmap icon() const; - QPixmap miniIcon() const; - QPixmap bigIcon() const; - QPixmap hugeIcon() const; - void addMember( Client* member ); - void removeMember( Client* member ); - void gotLeader( Client* leader ); - void lostLeader(); - Workspace* workspace(); - bool groupEvent( XEvent* e ); - void updateUserTime( Time time = CurrentTime ); - Time userTime() const; - void ref(); - void deref(); - EffectWindowGroupImpl* effectGroup(); - private: - void getIcons(); - void startupIdChanged(); - ClientList _members; - Client* leader_client; - Window leader_wid; - Workspace* _workspace; - NETWinInfo2* leader_info; - Time user_time; - int refcount; - EffectWindowGroupImpl* effect_group; - }; +{ +public: + Group(Window leader, Workspace* workspace); + ~Group(); + Window leader() const; + const Client* leaderClient() const; + Client* leaderClient(); + const ClientList& members() const; + QPixmap icon() const; + QPixmap miniIcon() const; + QPixmap bigIcon() const; + QPixmap hugeIcon() const; + void addMember(Client* member); + void removeMember(Client* member); + void gotLeader(Client* leader); + void lostLeader(); + Workspace* workspace(); + bool groupEvent(XEvent* e); + void updateUserTime(Time time = CurrentTime); + Time userTime() const; + void ref(); + void deref(); + EffectWindowGroupImpl* effectGroup(); +private: + void getIcons(); + void startupIdChanged(); + ClientList _members; + Client* leader_client; + Window leader_wid; + Workspace* _workspace; + NETWinInfo2* leader_info; + Time user_time; + int refcount; + EffectWindowGroupImpl* effect_group; +}; inline Window Group::leader() const - { +{ return leader_wid; - } +} inline const Client* Group::leaderClient() const - { +{ return leader_client; - } +} inline Client* Group::leaderClient() - { +{ return leader_client; - } +} inline const ClientList& Group::members() const - { +{ return _members; - } +} inline Workspace* Group::workspace() - { +{ return _workspace; - } +} inline Time Group::userTime() const - { +{ return user_time; - } +} inline EffectWindowGroupImpl* Group::effectGroup() - { +{ return effect_group; - } +} } // namespace diff --git a/kcmkwin/kwincompositing/ktimerdialog.cpp b/kcmkwin/kwincompositing/ktimerdialog.cpp index 61eab9b47..f8be2c172 100644 --- a/kcmkwin/kwincompositing/ktimerdialog.cpp +++ b/kcmkwin/kwincompositing/ktimerdialog.cpp @@ -37,95 +37,95 @@ #include "ktimerdialog.moc" -KTimerDialog::KTimerDialog( int msec, TimerStyle style, QWidget *parent, - const QString &caption, - int buttonMask, ButtonCode defaultButton, - bool separator, - const KGuiItem &user1, - const KGuiItem &user2, - const KGuiItem &user3 ) - : KDialog( parent ) +KTimerDialog::KTimerDialog(int msec, TimerStyle style, QWidget *parent, + const QString &caption, + int buttonMask, ButtonCode defaultButton, + bool separator, + const KGuiItem &user1, + const KGuiItem &user2, + const KGuiItem &user3) + : KDialog(parent) { - setCaption( caption ); - setButtons( (ButtonCodes)buttonMask ); - setDefaultButton( defaultButton ); - setButtonFocus( defaultButton ); // setDefaultButton() doesn't do this - showButtonSeparator( separator ); - setButtonGuiItem( User1, user1 ); - setButtonGuiItem( User2, user2 ); - setButtonGuiItem( User3, user3 ); + setCaption(caption); + setButtons((ButtonCodes)buttonMask); + setDefaultButton(defaultButton); + setButtonFocus(defaultButton); // setDefaultButton() doesn't do this + showButtonSeparator(separator); + setButtonGuiItem(User1, user1); + setButtonGuiItem(User2, user2); + setButtonGuiItem(User3, user3); - totalTimer = new QTimer( this ); - totalTimer->setSingleShot( true ); - updateTimer = new QTimer( this ); - updateTimer->setSingleShot( false ); + totalTimer = new QTimer(this); + totalTimer->setSingleShot(true); + updateTimer = new QTimer(this); + updateTimer->setSingleShot(false); msecTotal = msecRemaining = msec; updateInterval = 1000; tStyle = style; - KWindowSystem::setIcons( winId(), DesktopIcon("randr"), SmallIcon("randr") ); + KWindowSystem::setIcons(winId(), DesktopIcon("randr"), SmallIcon("randr")); // default to canceling the dialog on timeout - if ( buttonMask & Cancel ) + if (buttonMask & Cancel) buttonOnTimeout = Cancel; - connect( totalTimer, SIGNAL( timeout() ), SLOT( slotInternalTimeout() ) ); - connect( updateTimer, SIGNAL( timeout() ), SLOT( slotUpdateTime() ) ); + connect(totalTimer, SIGNAL(timeout()), SLOT(slotInternalTimeout())); + connect(updateTimer, SIGNAL(timeout()), SLOT(slotUpdateTime())); // create the widgets - mainWidget = new KVBox( this ); - timerWidget = new KHBox( mainWidget ); + mainWidget = new KVBox(this); + timerWidget = new KHBox(mainWidget); timerWidget->setSpacing(-1); - timerLabel = new QLabel( timerWidget ); - timerProgress = new QProgressBar( timerWidget ); - timerProgress->setRange( 0, msecTotal ); - timerProgress->setTextVisible( false ); + timerLabel = new QLabel(timerWidget); + timerProgress = new QProgressBar(timerWidget); + timerProgress->setRange(0, msecTotal); + timerProgress->setTextVisible(false); - KDialog::setMainWidget( mainWidget ); + KDialog::setMainWidget(mainWidget); - slotUpdateTime( false ); + slotUpdateTime(false); } KTimerDialog::~KTimerDialog() { } -void KTimerDialog::setVisible( bool visible ) +void KTimerDialog::setVisible(bool visible) { - KDialog::setVisible( visible ); - - if ( visible ) { - totalTimer->start( msecTotal ); - updateTimer->start( updateInterval ); + KDialog::setVisible(visible); + + if (visible) { + totalTimer->start(msecTotal); + updateTimer->start(updateInterval); } } int KTimerDialog::exec() { - totalTimer->start( msecTotal ); - updateTimer->start( updateInterval ); + totalTimer->start(msecTotal); + updateTimer->start(updateInterval); return KDialog::exec(); } -void KTimerDialog::setMainWidget( QWidget *widget ) +void KTimerDialog::setMainWidget(QWidget *widget) { // yuck, here goes. - KVBox *newWidget = new KVBox( this ); + KVBox *newWidget = new KVBox(this); newWidget->setSpacing(-1); - if ( widget->parentWidget() != mainWidget ) { - widget->setParent( newWidget); - } - timerWidget->setParent( newWidget); + if (widget->parentWidget() != mainWidget) { + widget->setParent(newWidget); + } + timerWidget->setParent(newWidget); delete mainWidget; mainWidget = newWidget; - KDialog::setMainWidget( mainWidget ); + KDialog::setMainWidget(mainWidget); } -void KTimerDialog::setRefreshInterval( int msec ) +void KTimerDialog::setRefreshInterval(int msec) { updateInterval = msec; - if ( updateTimer->isActive() ) - updateTimer->start( updateInterval ); + if (updateTimer->isActive()) + updateTimer->start(updateInterval); } int KTimerDialog::timeoutButton() const @@ -133,7 +133,7 @@ int KTimerDialog::timeoutButton() const return buttonOnTimeout; } -void KTimerDialog::setTimeoutButton( const ButtonCode newButton ) +void KTimerDialog::setTimeoutButton(const ButtonCode newButton) { buttonOnTimeout = newButton; } @@ -143,32 +143,32 @@ int KTimerDialog::timerStyle() const return tStyle; } -void KTimerDialog::setTimerStyle( const TimerStyle newStyle ) +void KTimerDialog::setTimerStyle(const TimerStyle newStyle) { tStyle = newStyle; } -void KTimerDialog::slotUpdateTime( bool update ) +void KTimerDialog::slotUpdateTime(bool update) { - if ( update ) - switch ( tStyle ) { - case CountDown: - msecRemaining -= updateInterval; - break; - case CountUp: - msecRemaining += updateInterval; - break; - case Manual: - break; + if (update) + switch(tStyle) { + case CountDown: + msecRemaining -= updateInterval; + break; + case CountUp: + msecRemaining += updateInterval; + break; + case Manual: + break; } - timerProgress->setValue( msecRemaining ); + timerProgress->setValue(msecRemaining); - timerLabel->setText( i18np("1 second remaining:","%1 seconds remaining:",msecRemaining/1000) ); + timerLabel->setText(i18np("1 second remaining:", "%1 seconds remaining:", msecRemaining / 1000)); } void KTimerDialog::slotInternalTimeout() { emit timerTimeout(); - slotButtonClicked( buttonOnTimeout ); + slotButtonClicked(buttonOnTimeout); } diff --git a/kcmkwin/kwincompositing/ktimerdialog.h b/kcmkwin/kwincompositing/ktimerdialog.h index dae0f0624..aadfea63a 100644 --- a/kcmkwin/kwincompositing/ktimerdialog.h +++ b/kcmkwin/kwincompositing/ktimerdialog.h @@ -36,7 +36,7 @@ class QLabel; * of time, and reports the time remaining to the user. * * The timer is capable of counting up or down, for any number of milliseconds. - * + * * The button which is activated upon timeout can be specified, as can the * update interval for the dialog box. * @@ -47,9 +47,9 @@ class QLabel; */ class KTimerDialog : public KDialog { - Q_OBJECT + Q_OBJECT - public: +public: /** * @li @p CountDown - The timer counts downwards from the seconds given. @@ -57,8 +57,7 @@ class KTimerDialog : public KDialog * @li @p Manual - The timer is not invoked; the caller must update the * progress. */ - enum TimerStyle - { + enum TimerStyle { CountDown, CountUp, Manual @@ -70,13 +69,13 @@ class KTimerDialog : public KDialog * * For the rest of the arguments, See @see KDialog . */ - explicit KTimerDialog( int msec, TimerStyle style=CountDown, QWidget *parent=0, - const QString &caption=QString(), - int buttonMask=Ok|Apply|Cancel, ButtonCode defaultButton=Ok, - bool separator=false, - const KGuiItem &user1=KGuiItem(), - const KGuiItem &user2=KGuiItem(), - const KGuiItem &user3=KGuiItem() ); + explicit KTimerDialog(int msec, TimerStyle style = CountDown, QWidget *parent = 0, + const QString &caption = QString(), + int buttonMask = Ok | Apply | Cancel, ButtonCode defaultButton = Ok, + bool separator = false, + const KGuiItem &user1 = KGuiItem(), + const KGuiItem &user2 = KGuiItem(), + const KGuiItem &user3 = KGuiItem()); /** * Destructor. @@ -86,12 +85,12 @@ class KTimerDialog : public KDialog /** * Execute the dialog modelessly - see @see QDialog . */ - virtual void setVisible( bool visible ); + virtual void setVisible(bool visible); /** * Set the refresh interval for the timer progress. Defaults to one second. */ - void setRefreshInterval( int msec ); + void setRefreshInterval(int msec); /** * Retrieves the @ref ButtonCode which will be activated once the timer @@ -103,7 +102,7 @@ class KTimerDialog : public KDialog * Sets the @ref ButtonCode to determine which button will be activated * once the timer times out. @see timeoutButton */ - void setTimeoutButton( ButtonCode newButton ); + void setTimeoutButton(ButtonCode newButton); /** * Retrieves the current @ref TimerStyle. @see setTimerStyle @@ -113,38 +112,38 @@ class KTimerDialog : public KDialog /** * Sets the @ref TimerStyle. @see timerStyle */ - void setTimerStyle( TimerStyle newStyle ); + void setTimerStyle(TimerStyle newStyle); /** * Overridden function which is used to set the main widget of the dialog. * @see KDialog::setMainWidget. */ - void setMainWidget( QWidget *widget ); + void setMainWidget(QWidget *widget); - Q_SIGNALS: +Q_SIGNALS: /** * Signal which is emitted once the timer has timed out. */ void timerTimeout(); - public Q_SLOTS: +public Q_SLOTS: /** * Execute the dialog modally - see @see QDialog . */ int exec(); - private Q_SLOTS: +private Q_SLOTS: /** * Updates the dialog with the current progress levels. */ - void slotUpdateTime( bool update = true ); + void slotUpdateTime(bool update = true); /** * The internal */ void slotInternalTimeout(); - private: +private: /** * Prepares the layout that manages the widgets of the dialog */ diff --git a/kcmkwin/kwincompositing/main.cpp b/kcmkwin/kwincompositing/main.cpp index e7e4ad087..71e759ca5 100644 --- a/kcmkwin/kwincompositing/main.cpp +++ b/kcmkwin/kwincompositing/main.cpp @@ -43,8 +43,8 @@ along with this program. If not, see . #include K_PLUGIN_FACTORY(KWinCompositingConfigFactory, - registerPlugin(); - ) + registerPlugin(); + ) K_EXPORT_PLUGIN(KWinCompositingConfigFactory("kcmkwincompositing")) namespace KWin @@ -52,31 +52,31 @@ namespace KWin ConfirmDialog::ConfirmDialog() : - KTimerDialog(10000, KTimerDialog::CountDown, 0, - i18n("Confirm Desktop Effects Change"), KTimerDialog::Ok|KTimerDialog::Cancel, - KTimerDialog::Cancel) - { - setObjectName( QLatin1String( "mainKTimerDialog" ) ); - setButtonGuiItem( KDialog::Ok, KGuiItem( i18n( "&Accept Configuration" ), "dialog-ok" )); - setButtonGuiItem( KDialog::Cancel, KGuiItem( i18n( "&Return to Previous Configuration" ), "dialog-cancel" )); + KTimerDialog(10000, KTimerDialog::CountDown, 0, + i18n("Confirm Desktop Effects Change"), KTimerDialog::Ok | KTimerDialog::Cancel, + KTimerDialog::Cancel) +{ + setObjectName(QLatin1String("mainKTimerDialog")); + setButtonGuiItem(KDialog::Ok, KGuiItem(i18n("&Accept Configuration"), "dialog-ok")); + setButtonGuiItem(KDialog::Cancel, KGuiItem(i18n("&Return to Previous Configuration"), "dialog-cancel")); - QLabel *label = new QLabel( i18n( "Desktop effects settings have changed.\n" - "Do you want to keep the new settings?\n" - "They will be automatically reverted in 10 seconds." ), this ); - label->setWordWrap( true ); - setMainWidget( label ); + QLabel *label = new QLabel(i18n("Desktop effects settings have changed.\n" + "Do you want to keep the new settings?\n" + "They will be automatically reverted in 10 seconds."), this); + label->setWordWrap(true); + setMainWidget(label); setWindowIcon(KIcon("preferences-desktop-effect")); - } +} KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList &) - : KCModule( KWinCompositingConfigFactory::componentData(), parent ) - , mKWinConfig(KSharedConfig::openConfig( "kwinrc" )) - , m_showConfirmDialog( false ) - , kwinInterface( NULL ) - { - KGlobal::locale()->insertCatalog( "kwin_effects" ); + : KCModule(KWinCompositingConfigFactory::componentData(), parent) + , mKWinConfig(KSharedConfig::openConfig("kwinrc")) + , m_showConfirmDialog(false) + , kwinInterface(NULL) +{ + KGlobal::locale()->insertCatalog("kwin_effects"); ui.setupUi(this); layout()->setMargin(0); ui.verticalSpacer->changeSize(20, KDialog::groupSpacingHint()); @@ -85,23 +85,23 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList ui.statusTitleWidget->hide(); // For future use - (void) I18N_NOOP( "Use GLSL shaders" ); + (void) I18N_NOOP("Use GLSL shaders"); #define OPENGL_INDEX 0 #define XRENDER_INDEX 1 #ifndef KWIN_HAVE_OPENGL_COMPOSITING - ui.compositingType->removeItem( OPENGL_INDEX ); - ui.glGroup->setEnabled( false ); + ui.compositingType->removeItem(OPENGL_INDEX); + ui.glGroup->setEnabled(false); #define OPENGL_INDEX -1 #define XRENDER_INDEX 0 #endif #ifndef KWIN_HAVE_XRENDER_COMPOSITING - ui.compositingType->removeItem( XRENDER_INDEX ); - ui.xrenderGroup->setEnabled( false ); + ui.compositingType->removeItem(XRENDER_INDEX); + ui.xrenderGroup->setEnabled(false); #define XRENDER_INDEX -1 #endif - kwinInterface = new OrgKdeKWinInterface( "org.kde.kwin", "/KWin", QDBusConnection::sessionBus() ); + kwinInterface = new OrgKdeKWinInterface("org.kde.kwin", "/KWin", QDBusConnection::sessionBus()); connect(ui.useCompositing, SIGNAL(toggled(bool)), this, SLOT(compositingEnabled(bool))); connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(currentTabChanged(int))); @@ -125,7 +125,7 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList connect(ui.unredirectFullscreen , SIGNAL(toggled(bool)), this, SLOT(changed())); connect(ui.glScaleFilter, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); connect(ui.xrScaleFilter, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); - + connect(ui.glDirect, SIGNAL(toggled(bool)), this, SLOT(changed())); connect(ui.glVSync, SIGNAL(toggled(bool)), this, SLOT(changed())); connect(ui.compositingStateButton, SIGNAL(clicked(bool)), kwinInterface, SLOT(toggleCompositing())); @@ -140,10 +140,9 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList // NOTICE: this is intended to workaround broken GL implementations that successfully segfault on glXQuery :-( KConfigGroup unsafeConfig(mKWinConfig, "Compositing"); - const bool glUnsafe = unsafeConfig.readEntry( "OpenGLIsUnsafe", false ); - if( !glUnsafe && CompositingPrefs::compositingPossible() ) - { - unsafeConfig.writeEntry( "OpenGLIsUnsafe", true ); + const bool glUnsafe = unsafeConfig.readEntry("OpenGLIsUnsafe", false); + if (!glUnsafe && CompositingPrefs::compositingPossible()) { + unsafeConfig.writeEntry("OpenGLIsUnsafe", true); unsafeConfig.sync(); // Driver-specific config detection @@ -152,11 +151,9 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList // Initialize the user interface with the config loaded from kwinrc. load(); - unsafeConfig.writeEntry( "OpenGLIsUnsafe", false ); + unsafeConfig.writeEntry("OpenGLIsUnsafe", false); unsafeConfig.sync(); - } - else - { + } else { // TODO: Add a "force recheck" button that removes the "OpenGLInUnsafe" flag ui.useCompositing->setEnabled(false); @@ -170,12 +167,12 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList ui.statusTitleWidget->setPixmap(KTitleWidget::InfoMessage, KTitleWidget::ImageLeft); ui.statusTitleWidget->show(); - setupCompositingState( false, false ); - } + setupCompositingState(false, false); + } KAboutData *about = new KAboutData(I18N_NOOP("kcmkwincompositing"), 0, - ki18n("KWin Desktop Effects Configuration Module"), - 0, KLocalizedString(), KAboutData::License_GPL, ki18n("(c) 2007 Rivo Laks")); + ki18n("KWin Desktop Effects Configuration Module"), + 0, KLocalizedString(), KAboutData::License_GPL, ki18n("(c) 2007 Rivo Laks")); about->addAuthor(ki18n("Rivo Laks"), KLocalizedString(), "rivolaks@hot.ee"); setAboutData(about); @@ -185,26 +182,26 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList QString boxswitch, presentwindows, coverswitch, flipswitch, slide, cube, fadedesktop; // window switcher services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_boxswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) boxswitch = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_presentwindows'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) presentwindows = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_coverswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) coverswitch = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_flipswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) flipswitch = services.first()->name(); // desktop switcher services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_slide'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) slide = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_cubeslide'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) cube = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_fadedesktop'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) fadedesktop = services.first()->name(); // init the combo boxes ui.windowSwitchingCombo->addItem(i18n("No Effect")); @@ -217,72 +214,66 @@ KWinCompositingConfig::KWinCompositingConfig(QWidget *parent, const QVariantList ui.desktopSwitchingCombo->addItem(slide); ui.desktopSwitchingCombo->addItem(cube); ui.desktopSwitchingCombo->addItem(fadedesktop); - } +} KWinCompositingConfig::~KWinCompositingConfig() - { - } +{ +} -void KWinCompositingConfig::reparseConfiguration( const QByteArray& conf ) - { - KSettings::Dispatcher::reparseConfiguration( conf ); - } +void KWinCompositingConfig::reparseConfiguration(const QByteArray& conf) +{ + KSettings::Dispatcher::reparseConfiguration(conf); +} -void KWinCompositingConfig::compositingEnabled( bool enabled ) - { +void KWinCompositingConfig::compositingEnabled(bool enabled) +{ // Enable the other configuration tabs only when compositing is enabled. ui.compositingOptionsContainer->setEnabled(enabled); ui.tabWidget->setTabEnabled(1, enabled); ui.tabWidget->setTabEnabled(2, enabled); - } +} -void KWinCompositingConfig::showConfirmDialog( bool reinitCompositing ) - { +void KWinCompositingConfig::showConfirmDialog(bool reinitCompositing) +{ bool revert = false; // Feel free to extend this to support several kwin instances (multihead) if you // think it makes sense. OrgKdeKWinInterface kwin("org.kde.kwin", "/KWin", QDBusConnection::sessionBus()); - if( reinitCompositing ? !kwin.compositingActive().value() : !kwin.waitForCompositingSetup().value() ) - { - KMessageBox::sorry( this, i18n( - "Failed to activate desktop effects using the given " - "configuration options. Settings will be reverted to their previous values.\n\n" - "Check your X configuration. You may also consider changing advanced options, " - "especially changing the compositing type." )); + if (reinitCompositing ? !kwin.compositingActive().value() : !kwin.waitForCompositingSetup().value()) { + KMessageBox::sorry(this, i18n( + "Failed to activate desktop effects using the given " + "configuration options. Settings will be reverted to their previous values.\n\n" + "Check your X configuration. You may also consider changing advanced options, " + "especially changing the compositing type.")); revert = true; - } - else - { + } else { ConfirmDialog confirm; - if( !confirm.exec()) + if (!confirm.exec()) revert = true; - else - { + else { // compositing is enabled now - setupCompositingState( kwinInterface->compositingActive() ); + setupCompositingState(kwinInterface->compositingActive()); checkLoadedEffects(); - } } - if( revert ) - { + } + if (revert) { // Revert settings KConfigGroup config(mKWinConfig, "Compositing"); config.deleteGroup(); QMap::const_iterator it = mPreviousConfig.constBegin(); - for(; it != mPreviousConfig.constEnd(); ++it) - { + for (; it != mPreviousConfig.constEnd(); ++it) { if (it.value().isEmpty()) continue; config.writeEntry(it.key(), it.value()); - } + } // Sync with KWin and reload configChanged(reinitCompositing); load(); - } } +} void KWinCompositingConfig::initEffectSelector() - { +{ // Find all .desktop files of the effects KService::List offers = KServiceTypeTrader::self()->query("KWin/Effect"); QList effectinfos = KPluginInfo::fromServices(offers); @@ -296,176 +287,165 @@ void KWinCompositingConfig::initEffectSelector() ui.effectSelector->addPlugins(effectinfos, KPluginSelector::ReadConfigFile, i18n("Demos"), "Demos", mTmpConfig); ui.effectSelector->addPlugins(effectinfos, KPluginSelector::ReadConfigFile, i18n("Tests"), "Tests", mTmpConfig); ui.effectSelector->addPlugins(effectinfos, KPluginSelector::ReadConfigFile, i18n("Tools"), "Tools", mTmpConfig); - } +} void KWinCompositingConfig::currentTabChanged(int tab) - { +{ // block signals to don't emit the changed()-signal by just switching the current tab blockSignals(true); // write possible changes done to synchronize effect checkboxes and selector // TODO: This segment is prone to fail when the UI is changed; // you'll most likely not think of the hard coded numbers here when just changing the order of the tabs. - if (tab == 0) - { + if (tab == 0) { // General tab was activated saveEffectsTab(); loadGeneralTab(); - } - else if ( tab == 1 ) - { + } else if (tab == 1) { // Effects tab was activated saveGeneralTab(); loadEffectsTab(); - } - - blockSignals(false); } + blockSignals(false); +} + void KWinCompositingConfig::loadGeneralTab() - { +{ KConfigGroup config(mKWinConfig, "Compositing"); bool enabled = config.readEntry("Enabled", mDefaultPrefs.recommendCompositing()); - ui.useCompositing->setChecked( enabled ); - ui.animationSpeedCombo->setCurrentIndex(config.readEntry("AnimationSpeed", 3 )); + ui.useCompositing->setChecked(enabled); + ui.animationSpeedCombo->setCurrentIndex(config.readEntry("AnimationSpeed", 3)); // Load effect settings KConfigGroup effectconfig(mTmpConfig, "Plugins"); #define LOAD_EFFECT_CONFIG(effectname) effectconfig.readEntry("kwin4_effect_" effectname "Enabled", true) int winManagementEnabled = LOAD_EFFECT_CONFIG("presentwindows") - + LOAD_EFFECT_CONFIG("desktopgrid") - + LOAD_EFFECT_CONFIG("dialogparent"); - if (winManagementEnabled > 0 && winManagementEnabled < 3) - { + + LOAD_EFFECT_CONFIG("desktopgrid") + + LOAD_EFFECT_CONFIG("dialogparent"); + if (winManagementEnabled > 0 && winManagementEnabled < 3) { ui.effectWinManagement->setTristate(true); ui.effectWinManagement->setCheckState(Qt::PartiallyChecked); - } - else + } else ui.effectWinManagement->setChecked(winManagementEnabled); ui.effectAnimations->setChecked(LOAD_EFFECT_CONFIG("minimizeanimation")); #undef LOAD_EFFECT_CONFIG // window switching // Set current option to "none" if no plugin is activated. - ui.windowSwitchingCombo->setCurrentIndex( 0 ); + ui.windowSwitchingCombo->setCurrentIndex(0); KConfigGroup boxswitchconfig(mKWinConfig, "Effect-BoxSwitch"); - if( effectEnabled( "boxswitch", effectconfig ) && boxswitchconfig.readEntry("TabBox", true)) - ui.windowSwitchingCombo->setCurrentIndex( 1 ); + if (effectEnabled("boxswitch", effectconfig) && boxswitchconfig.readEntry("TabBox", true)) + ui.windowSwitchingCombo->setCurrentIndex(1); KConfigGroup coverswitchconfig(mKWinConfig, "Effect-CoverSwitch"); - if( effectEnabled( "coverswitch", effectconfig ) && coverswitchconfig.readEntry("TabBox", false)) - ui.windowSwitchingCombo->setCurrentIndex( 3 ); + if (effectEnabled("coverswitch", effectconfig) && coverswitchconfig.readEntry("TabBox", false)) + ui.windowSwitchingCombo->setCurrentIndex(3); KConfigGroup flipswitchconfig(mKWinConfig, "Effect-FlipSwitch"); - if( effectEnabled( "flipswitch", effectconfig ) && flipswitchconfig.readEntry("TabBox", false)) - ui.windowSwitchingCombo->setCurrentIndex( 4 ); + if (effectEnabled("flipswitch", effectconfig) && flipswitchconfig.readEntry("TabBox", false)) + ui.windowSwitchingCombo->setCurrentIndex(4); KConfigGroup presentwindowsconfig(mKWinConfig, "Effect-PresentWindows"); - if( effectEnabled( "presentwindows", effectconfig ) && presentwindowsconfig.readEntry("TabBox", false) ) - ui.windowSwitchingCombo->setCurrentIndex( 2 ); + if (effectEnabled("presentwindows", effectconfig) && presentwindowsconfig.readEntry("TabBox", false)) + ui.windowSwitchingCombo->setCurrentIndex(2); // desktop switching // Set current option to "none" if no plugin is activated. - ui.desktopSwitchingCombo->setCurrentIndex( 0 ); - if( effectEnabled( "slide", effectconfig )) - ui.desktopSwitchingCombo->setCurrentIndex( 1 ); - if( effectEnabled( "cubeslide", effectconfig )) - ui.desktopSwitchingCombo->setCurrentIndex( 2 ); - if( effectEnabled( "fadedesktop", effectconfig )) - ui.desktopSwitchingCombo->setCurrentIndex( 3 ); + ui.desktopSwitchingCombo->setCurrentIndex(0); + if (effectEnabled("slide", effectconfig)) + ui.desktopSwitchingCombo->setCurrentIndex(1); + if (effectEnabled("cubeslide", effectconfig)) + ui.desktopSwitchingCombo->setCurrentIndex(2); + if (effectEnabled("fadedesktop", effectconfig)) + ui.desktopSwitchingCombo->setCurrentIndex(3); - if( enabled ) - setupCompositingState( kwinInterface->compositingActive() ); + if (enabled) + setupCompositingState(kwinInterface->compositingActive()); else - setupCompositingState( false, false ); - } + setupCompositingState(false, false); +} -void KWinCompositingConfig::setupCompositingState( bool active, bool enabled ) - { - if( !qgetenv( "KDE_FAILSAFE" ).isNull() ) +void KWinCompositingConfig::setupCompositingState(bool active, bool enabled) +{ + if (!qgetenv("KDE_FAILSAFE").isNull()) enabled = false; // compositing state QString stateIcon; QString stateText; QString stateButtonText; - if( enabled ) - { + if (enabled) { // check if compositing is active or suspended - if( active ) - { - stateIcon = QString( "dialog-ok-apply" ); - stateText = i18n( "Desktop effects are active" ); - stateButtonText = i18n( "Suspend Desktop Effects" ); - } - else - { - stateIcon = QString( "dialog-cancel" ); - stateText = i18n( "Desktop effects are temporarily disabled" ); - stateButtonText = i18n( "Resume Desktop Effects" ); - } + if (active) { + stateIcon = QString("dialog-ok-apply"); + stateText = i18n("Desktop effects are active"); + stateButtonText = i18n("Suspend Desktop Effects"); + } else { + stateIcon = QString("dialog-cancel"); + stateText = i18n("Desktop effects are temporarily disabled"); + stateButtonText = i18n("Resume Desktop Effects"); } - else - { + } else { // compositing is disabled - stateIcon = QString( "dialog-cancel" ); - stateText = i18n( "Desktop effects are disabled" ); - stateButtonText = i18n( "Resume Desktop Effects" ); - } - const int iconSize = (QApplication::fontMetrics().height() > 24) ? 32 : 22; - ui.compositingStateIcon->setPixmap( KIcon( stateIcon ).pixmap( iconSize, iconSize ) ); - ui.compositingStateLabel->setText( stateText ); - ui.compositingStateButton->setText( stateButtonText ); - ui.compositingStateIcon->setEnabled( enabled ); - ui.compositingStateLabel->setEnabled( enabled ); - ui.compositingStateButton->setEnabled( enabled ); + stateIcon = QString("dialog-cancel"); + stateText = i18n("Desktop effects are disabled"); + stateButtonText = i18n("Resume Desktop Effects"); } - -void KWinCompositingConfig::toogleSmoothScaleUi( int compositingType ) -{ - ui.glScaleFilter->setVisible( compositingType == OPENGL_INDEX ); - ui.xrScaleFilter->setVisible( compositingType == XRENDER_INDEX ); - ui.scaleMethodLabel->setBuddy( compositingType == XRENDER_INDEX ? ui.xrScaleFilter : ui.glScaleFilter ); + const int iconSize = (QApplication::fontMetrics().height() > 24) ? 32 : 22; + ui.compositingStateIcon->setPixmap(KIcon(stateIcon).pixmap(iconSize, iconSize)); + ui.compositingStateLabel->setText(stateText); + ui.compositingStateButton->setText(stateButtonText); + ui.compositingStateIcon->setEnabled(enabled); + ui.compositingStateLabel->setEnabled(enabled); + ui.compositingStateButton->setEnabled(enabled); } -bool KWinCompositingConfig::effectEnabled( const QString& effect, const KConfigGroup& cfg ) const - { +void KWinCompositingConfig::toogleSmoothScaleUi(int compositingType) +{ + ui.glScaleFilter->setVisible(compositingType == OPENGL_INDEX); + ui.xrScaleFilter->setVisible(compositingType == XRENDER_INDEX); + ui.scaleMethodLabel->setBuddy(compositingType == XRENDER_INDEX ? ui.xrScaleFilter : ui.glScaleFilter); +} + +bool KWinCompositingConfig::effectEnabled(const QString& effect, const KConfigGroup& cfg) const +{ KService::List services = KServiceTypeTrader::self()->query( - "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); - if( services.isEmpty()) + "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) return false; QVariant v = services.first()->property("X-KDE-PluginInfo-EnabledByDefault"); return cfg.readEntry("kwin4_effect_" + effect + "Enabled", v.toBool()); - } +} void KWinCompositingConfig::loadEffectsTab() - { +{ ui.effectSelector->load(); - } +} void KWinCompositingConfig::loadAdvancedTab() - { +{ KConfigGroup config(mKWinConfig, "Compositing"); QString backend = config.readEntry("Backend", "OpenGL"); ui.compositingType->setCurrentIndex((backend == "XRender") ? XRENDER_INDEX : 0); // 4 - off, 5 - shown, 6 - always, other are old values int hps = config.readEntry("HiddenPreviews", 5); - if( hps == 6 ) // always - ui.windowThumbnails->setCurrentIndex( 0 ); - else if( hps == 4 ) // never - ui.windowThumbnails->setCurrentIndex( 2 ); + if (hps == 6) // always + ui.windowThumbnails->setCurrentIndex(0); + else if (hps == 4) // never + ui.windowThumbnails->setCurrentIndex(2); else // shown, or default - ui.windowThumbnails->setCurrentIndex( 1 ); - ui.disableChecks->setChecked( config.readEntry( "DisableChecks", false )); - ui.unredirectFullscreen->setChecked( config.readEntry( "UnredirectFullscreen", true )); + ui.windowThumbnails->setCurrentIndex(1); + ui.disableChecks->setChecked(config.readEntry("DisableChecks", false)); + ui.unredirectFullscreen->setChecked(config.readEntry("UnredirectFullscreen", true)); ui.xrScaleFilter->setCurrentIndex((int)config.readEntry("XRenderSmoothScale", false)); ui.glScaleFilter->setCurrentIndex(config.readEntry("GLTextureFilter", 2)); - + ui.glDirect->setChecked(config.readEntry("GLDirect", mDefaultPrefs.enableDirectRendering())); ui.glVSync->setChecked(config.readEntry("GLVSync", mDefaultPrefs.enableVSync())); - toogleSmoothScaleUi( ui.compositingType->currentIndex() ); - } + toogleSmoothScaleUi(ui.compositingType->currentIndex()); +} void KWinCompositingConfig::load() - { +{ mKWinConfig->reparseConfiguration(); // Copy Plugins group to temp config file @@ -473,40 +453,39 @@ void KWinCompositingConfig::load() QMap::const_iterator it = entries.constBegin(); KConfigGroup tmpconfig(mTmpConfig, "Plugins"); tmpconfig.deleteGroup(); - for(; it != entries.constEnd(); ++it) + for (; it != entries.constEnd(); ++it) tmpconfig.writeEntry(it.key(), it.value()); loadGeneralTab(); loadEffectsTab(); loadAdvancedTab(); - emit changed( false ); - } + emit changed(false); +} void KWinCompositingConfig::saveGeneralTab() - { +{ KConfigGroup config(mKWinConfig, "Compositing"); // Check if any critical settings that need confirmation have changed - if(ui.useCompositing->isChecked() && - ui.useCompositing->isChecked() != config.readEntry("Enabled", mDefaultPrefs.recommendCompositing())) + if (ui.useCompositing->isChecked() && + ui.useCompositing->isChecked() != config.readEntry("Enabled", mDefaultPrefs.recommendCompositing())) m_showConfirmDialog = true; config.writeEntry("Enabled", ui.useCompositing->isChecked()); config.writeEntry("AnimationSpeed", ui.animationSpeedCombo->currentIndex()); // disable the compositing state if compositing was turned off - if( !ui.useCompositing->isChecked() ) - setupCompositingState( false, false ); + if (!ui.useCompositing->isChecked()) + setupCompositingState(false, false); // Save effects KConfigGroup effectconfig(mTmpConfig, "Plugins"); #define WRITE_EFFECT_CONFIG(effectname, widget) effectconfig.writeEntry("kwin4_effect_" effectname "Enabled", widget->isChecked()) - if (ui.effectWinManagement->checkState() != Qt::PartiallyChecked) - { + if (ui.effectWinManagement->checkState() != Qt::PartiallyChecked) { WRITE_EFFECT_CONFIG("presentwindows", ui.effectWinManagement); WRITE_EFFECT_CONFIG("desktopgrid", ui.effectWinManagement); WRITE_EFFECT_CONFIG("dialogparent", ui.effectWinManagement); - } + } // TODO: maybe also do some effect-specific configuration here, e.g. // enable/disable desktopgrid's animation according to this setting WRITE_EFFECT_CONFIG("minimizeanimation", ui.effectAnimations); @@ -517,106 +496,102 @@ void KWinCompositingConfig::saveGeneralTab() bool presentWindowSwitching = false; bool coverSwitch = false; bool flipSwitch = false; - switch( windowSwitcher ) - { - case 1: - boxSwitch = true; - break; - case 2: - presentWindowSwitching = true; - break; - case 3: - coverSwitch = true; - break; - case 4: - flipSwitch = true; - break; - default: - break; // nothing - } + switch(windowSwitcher) { + case 1: + boxSwitch = true; + break; + case 2: + presentWindowSwitching = true; + break; + case 3: + coverSwitch = true; + break; + case 4: + flipSwitch = true; + break; + default: + break; // nothing + } // activate effects if not active - if( boxSwitch ) + if (boxSwitch) effectconfig.writeEntry("kwin4_effect_boxswitchEnabled", true); - if( presentWindowSwitching ) + if (presentWindowSwitching) effectconfig.writeEntry("kwin4_effect_presentwindowsEnabled", true); - if( coverSwitch ) + if (coverSwitch) effectconfig.writeEntry("kwin4_effect_coverswitchEnabled", true); - if( flipSwitch ) + if (flipSwitch) effectconfig.writeEntry("kwin4_effect_flipswitchEnabled", true); - KConfigGroup boxswitchconfig( mKWinConfig, "Effect-BoxSwitch" ); - boxswitchconfig.writeEntry( "TabBox", boxSwitch ); + KConfigGroup boxswitchconfig(mKWinConfig, "Effect-BoxSwitch"); + boxswitchconfig.writeEntry("TabBox", boxSwitch); boxswitchconfig.sync(); - KConfigGroup presentwindowsconfig( mKWinConfig, "Effect-PresentWindows" ); - presentwindowsconfig.writeEntry( "TabBox", presentWindowSwitching ); + KConfigGroup presentwindowsconfig(mKWinConfig, "Effect-PresentWindows"); + presentwindowsconfig.writeEntry("TabBox", presentWindowSwitching); presentwindowsconfig.sync(); - KConfigGroup coverswitchconfig( mKWinConfig, "Effect-CoverSwitch" ); - coverswitchconfig.writeEntry( "TabBox", coverSwitch ); + KConfigGroup coverswitchconfig(mKWinConfig, "Effect-CoverSwitch"); + coverswitchconfig.writeEntry("TabBox", coverSwitch); coverswitchconfig.sync(); - KConfigGroup flipswitchconfig( mKWinConfig, "Effect-FlipSwitch" ); - flipswitchconfig.writeEntry( "TabBox", flipSwitch ); + KConfigGroup flipswitchconfig(mKWinConfig, "Effect-FlipSwitch"); + flipswitchconfig.writeEntry("TabBox", flipSwitch); flipswitchconfig.sync(); int desktopSwitcher = ui.desktopSwitchingCombo->currentIndex(); - switch( desktopSwitcher ) - { - case 0: - // no effect - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 1: - // slide - effectconfig.writeEntry("kwin4_effect_slideEnabled", true); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 2: - // cube - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", true); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 3: - // fadedesktop - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", true); - break; - } + switch(desktopSwitcher) { + case 0: + // no effect + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 1: + // slide + effectconfig.writeEntry("kwin4_effect_slideEnabled", true); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 2: + // cube + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", true); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 3: + // fadedesktop + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", true); + break; } +} void KWinCompositingConfig::saveEffectsTab() - { +{ ui.effectSelector->save(); - } +} bool KWinCompositingConfig::saveAdvancedTab() - { +{ bool advancedChanged = false; static const int hps[] = { 6 /*always*/, 5 /*shown*/, 4 /*never*/ }; KConfigGroup config(mKWinConfig, "Compositing"); - if( config.readEntry("Backend", "OpenGL") + if (config.readEntry("Backend", "OpenGL") != ((ui.compositingType->currentIndex() == 0) ? "OpenGL" : "XRender") - || config.readEntry("GLDirect", mDefaultPrefs.enableDirectRendering()) + || config.readEntry("GLDirect", mDefaultPrefs.enableDirectRendering()) != ui.glDirect->isChecked() - || config.readEntry("GLVSync", mDefaultPrefs.enableVSync()) != ui.glVSync->isChecked() - || config.readEntry("DisableChecks", false ) != ui.disableChecks->isChecked()) - { + || config.readEntry("GLVSync", mDefaultPrefs.enableVSync()) != ui.glVSync->isChecked() + || config.readEntry("DisableChecks", false) != ui.disableChecks->isChecked()) { m_showConfirmDialog = true; advancedChanged = true; - } - else if( config.readEntry("HiddenPreviews", 5) != hps[ ui.windowThumbnails->currentIndex() ] - || (int)config.readEntry("XRenderSmoothScale", false ) != ui.xrScaleFilter->currentIndex() - || config.readEntry("GLTextureFilter", 2 ) != ui.glScaleFilter->currentIndex()) + } else if (config.readEntry("HiddenPreviews", 5) != hps[ ui.windowThumbnails->currentIndex()] + || (int)config.readEntry("XRenderSmoothScale", false) != ui.xrScaleFilter->currentIndex() + || config.readEntry("GLTextureFilter", 2) != ui.glScaleFilter->currentIndex()) advancedChanged = true; config.writeEntry("Backend", (ui.compositingType->currentIndex() == OPENGL_INDEX) ? "OpenGL" : "XRender"); - config.writeEntry("HiddenPreviews", hps[ ui.windowThumbnails->currentIndex() ] ); + config.writeEntry("HiddenPreviews", hps[ ui.windowThumbnails->currentIndex()]); config.writeEntry("DisableChecks", ui.disableChecks->isChecked()); - config.writeEntry( "UnredirectFullscreen", ui.unredirectFullscreen->isChecked() ); + config.writeEntry("UnredirectFullscreen", ui.unredirectFullscreen->isChecked()); config.writeEntry("XRenderSmoothScale", ui.xrScaleFilter->currentIndex() == 1); config.writeEntry("GLTextureFilter", ui.glScaleFilter->currentIndex()); @@ -626,10 +601,10 @@ bool KWinCompositingConfig::saveAdvancedTab() return advancedChanged; - } +} void KWinCompositingConfig::save() - { +{ // Save current config. We'll use this for restoring in case something goes wrong. KConfigGroup config(mKWinConfig, "Compositing"); mPreviousConfig = config.entryMap(); @@ -637,18 +612,15 @@ void KWinCompositingConfig::save() // bah; tab content being dependent on the other is really bad; and // deprecated in the HIG for a reason. It is confusing! // Make sure we only call save on each tab once; as they are stateful due to the revert concept - if ( ui.tabWidget->currentIndex() == 0 ) // "General" tab was active - { + if (ui.tabWidget->currentIndex() == 0) { // "General" tab was active saveGeneralTab(); loadEffectsTab(); saveEffectsTab(); - } - else - { + } else { saveEffectsTab(); loadGeneralTab(); saveGeneralTab(); - } + } bool advancedChanged = saveAdvancedTab(); // Copy Plugins group from temp config to real config @@ -656,122 +628,115 @@ void KWinCompositingConfig::save() QMap::const_iterator it = entries.constBegin(); KConfigGroup realconfig(mKWinConfig, "Plugins"); realconfig.deleteGroup(); - for(; it != entries.constEnd(); ++it) + for (; it != entries.constEnd(); ++it) realconfig.writeEntry(it.key(), it.value()); - emit changed( false ); + emit changed(false); configChanged(advancedChanged); // This assumes that this KCM is running with the same environment variables as KWin // TODO: Detect KWIN_COMPOSE=N as well - if( !qgetenv( "KDE_FAILSAFE" ).isNull() && ui.useCompositing->isChecked() ) - { - KMessageBox::sorry( this, i18n( - "Your settings have been saved but as KDE is currently running in failsafe " - "mode desktop effects cannot be enabled at this time.\n\n" - "Please exit failsafe mode to enable desktop effects." )); + if (!qgetenv("KDE_FAILSAFE").isNull() && ui.useCompositing->isChecked()) { + KMessageBox::sorry(this, i18n( + "Your settings have been saved but as KDE is currently running in failsafe " + "mode desktop effects cannot be enabled at this time.\n\n" + "Please exit failsafe mode to enable desktop effects.")); m_showConfirmDialog = false; // Dangerous but there is no way to test if failsafe mode - } - - if(m_showConfirmDialog) - { - m_showConfirmDialog = false; - showConfirmDialog(advancedChanged); - } } + if (m_showConfirmDialog) { + m_showConfirmDialog = false; + showConfirmDialog(advancedChanged); + } +} + void KWinCompositingConfig::checkLoadedEffects() - { +{ // check for effects not supported by Backend or hardware // such effects are enabled but not returned by DBus method loadedEffects - QDBusMessage message = QDBusMessage::createMethodCall( "org.kde.kwin", "/KWin", "org.kde.KWin", "loadedEffects" ); - QDBusMessage reply = QDBusConnection::sessionBus().call( message ); - KConfigGroup effectConfig = KConfigGroup( mKWinConfig, "Compositing" ); - bool enabledAfter = effectConfig.readEntry( "Enabled", mDefaultPrefs.recommendCompositing() ); + QDBusMessage message = QDBusMessage::createMethodCall("org.kde.kwin", "/KWin", "org.kde.KWin", "loadedEffects"); + QDBusMessage reply = QDBusConnection::sessionBus().call(message); + KConfigGroup effectConfig = KConfigGroup(mKWinConfig, "Compositing"); + bool enabledAfter = effectConfig.readEntry("Enabled", mDefaultPrefs.recommendCompositing()); - if( reply.type() == QDBusMessage::ReplyMessage && enabledAfter && !getenv( "KDE_FAILSAFE" )) - { - effectConfig = KConfigGroup( mKWinConfig, "Plugins" ); + if (reply.type() == QDBusMessage::ReplyMessage && enabledAfter && !getenv("KDE_FAILSAFE")) { + effectConfig = KConfigGroup(mKWinConfig, "Plugins"); QStringList loadedEffects = reply.arguments()[0].toStringList(); QStringList effects = effectConfig.keyList(); QStringList disabledEffects = QStringList(); - foreach( QString effect, effects ) // krazy:exclude=foreach - { - QString temp = effect.mid( 13, effect.length() - 13 - 7 ); - effect.truncate( effect.length() - 7 ); - if( effectEnabled( temp, effectConfig ) && !loadedEffects.contains( effect ) ) - { + foreach (QString effect, effects) { // krazy:exclude=foreach + QString temp = effect.mid(13, effect.length() - 13 - 7); + effect.truncate(effect.length() - 7); + if (effectEnabled(temp, effectConfig) && !loadedEffects.contains(effect)) { disabledEffects << effect; - } - } - if( !disabledEffects.isEmpty() ) - { - KServiceTypeTrader* trader = KServiceTypeTrader::self(); - KService::List services; - QString message = i18n( "The following desktop effects could not be activated:" ); - message.append( "
    " ); - foreach( const QString &effect, disabledEffects ) - { - services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == '" + effect + '\''); - message.append( "
  • " ); - if( !services.isEmpty() ) - message.append( services.first()->name() ); - else - message.append( effect); - message.append( "
  • " ); - } - message.append( "
" ); - KNotification::event( "effectsnotsupported", message, QPixmap(), NULL, KNotification::CloseOnTimeout, KComponentData( "kwin" ) ); } } + if (!disabledEffects.isEmpty()) { + KServiceTypeTrader* trader = KServiceTypeTrader::self(); + KService::List services; + QString message = i18n("The following desktop effects could not be activated:"); + message.append("
    "); + foreach (const QString & effect, disabledEffects) { + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == '" + effect + '\''); + message.append("
  • "); + if (!services.isEmpty()) + message.append(services.first()->name()); + else + message.append(effect); + message.append("
  • "); + } + message.append("
"); + KNotification::event("effectsnotsupported", message, QPixmap(), NULL, KNotification::CloseOnTimeout, KComponentData("kwin")); + } } +} void KWinCompositingConfig::configChanged(bool reinitCompositing) - { +{ // Send signal to kwin mKWinConfig->sync(); // Send signal to all kwin instances QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", - reinitCompositing ? "reinitCompositing" : "reloadConfig"); + reinitCompositing ? "reinitCompositing" : "reloadConfig"); QDBusConnection::sessionBus().send(message); // HACK: We can't just do this here, due to the asynchronous nature of signals. // We also can't change reinitCompositing into a message (which would allow // callWithCallbac() to do this neater) due to multiple kwin instances. - if( !m_showConfirmDialog ) + if (!m_showConfirmDialog) QTimer::singleShot(1000, this, SLOT(checkLoadedEffects())); - } +} void KWinCompositingConfig::defaults() - { +{ ui.tabWidget->setCurrentIndex(0); ui.useCompositing->setChecked(mDefaultPrefs.recommendCompositing()); ui.effectWinManagement->setChecked(true); ui.effectAnimations->setChecked(true); - ui.windowSwitchingCombo->setCurrentIndex( 1 ); - ui.desktopSwitchingCombo->setCurrentIndex( 1 ); - ui.animationSpeedCombo->setCurrentIndex( 3 ); + ui.windowSwitchingCombo->setCurrentIndex(1); + ui.desktopSwitchingCombo->setCurrentIndex(1); + ui.animationSpeedCombo->setCurrentIndex(3); ui.effectSelector->defaults(); - ui.compositingType->setCurrentIndex( 0 ); - ui.windowThumbnails->setCurrentIndex( 1 ); - ui.disableChecks->setChecked( false ); - ui.unredirectFullscreen->setChecked( true ); - ui.xrScaleFilter->setCurrentIndex( 0 ); - ui.glScaleFilter->setCurrentIndex( 2 ); - ui.glDirect->setChecked( mDefaultPrefs.enableDirectRendering() ); - ui.glVSync->setChecked( mDefaultPrefs.enableVSync() ); - } + ui.compositingType->setCurrentIndex(0); + ui.windowThumbnails->setCurrentIndex(1); + ui.disableChecks->setChecked(false); + ui.unredirectFullscreen->setChecked(true); + ui.xrScaleFilter->setCurrentIndex(0); + ui.glScaleFilter->setCurrentIndex(2); + ui.glDirect->setChecked(mDefaultPrefs.enableDirectRendering()); + ui.glVSync->setChecked(mDefaultPrefs.enableVSync()); +} QString KWinCompositingConfig::quickHelp() const - { +{ return i18n("

Desktop Effects

"); - } +} } // namespace diff --git a/kcmkwin/kwincompositing/main.h b/kcmkwin/kwincompositing/main.h index b48499b8f..313db49d1 100644 --- a/kcmkwin/kwincompositing/main.h +++ b/kcmkwin/kwincompositing/main.h @@ -40,59 +40,59 @@ namespace KWin class ConfirmDialog : public KTimerDialog { -Q_OBJECT + Q_OBJECT public: ConfirmDialog(); }; class KWinCompositingConfig : public KCModule - { +{ Q_OBJECT - public: - KWinCompositingConfig(QWidget *parent, const QVariantList &args); - virtual ~KWinCompositingConfig(); +public: + KWinCompositingConfig(QWidget *parent, const QVariantList &args); + virtual ~KWinCompositingConfig(); - virtual QString quickHelp() const; + virtual QString quickHelp() const; - public slots: - virtual void compositingEnabled(bool enabled); - virtual void showConfirmDialog(bool reinitCompositing); - void currentTabChanged(int tab); +public slots: + virtual void compositingEnabled(bool enabled); + virtual void showConfirmDialog(bool reinitCompositing); + void currentTabChanged(int tab); - virtual void load(); - virtual void save(); - virtual void defaults(); - void reparseConfiguration(const QByteArray& conf); + virtual void load(); + virtual void save(); + virtual void defaults(); + void reparseConfiguration(const QByteArray& conf); - void loadGeneralTab(); - void loadEffectsTab(); - void loadAdvancedTab(); - void saveGeneralTab(); - void saveEffectsTab(); - bool saveAdvancedTab(); + void loadGeneralTab(); + void loadEffectsTab(); + void loadAdvancedTab(); + void saveGeneralTab(); + void saveEffectsTab(); + bool saveAdvancedTab(); - void checkLoadedEffects(); - void configChanged(bool reinitCompositing); - void initEffectSelector(); - void setupCompositingState( bool active, bool enabled = true ); - - private slots: - void toogleSmoothScaleUi( int compositingType ); + void checkLoadedEffects(); + void configChanged(bool reinitCompositing); + void initEffectSelector(); + void setupCompositingState(bool active, bool enabled = true); - private: - bool effectEnabled( const QString& effect, const KConfigGroup& cfg ) const; +private slots: + void toogleSmoothScaleUi(int compositingType); - KSharedConfigPtr mKWinConfig; - Ui::KWinCompositingConfig ui; - CompositingPrefs mDefaultPrefs; +private: + bool effectEnabled(const QString& effect, const KConfigGroup& cfg) const; - QMap mPreviousConfig; - KTemporaryFile mTmpConfigFile; - KSharedConfigPtr mTmpConfig; - bool m_showConfirmDialog; + KSharedConfigPtr mKWinConfig; + Ui::KWinCompositingConfig ui; + CompositingPrefs mDefaultPrefs; - OrgKdeKWinInterface* kwinInterface; - }; + QMap mPreviousConfig; + KTemporaryFile mTmpConfigFile; + KSharedConfigPtr mTmpConfig; + bool m_showConfirmDialog; + + OrgKdeKWinInterface* kwinInterface; +}; } // namespace diff --git a/kcmkwin/kwindecoration/buttons.cpp b/kcmkwin/kwindecoration/buttons.cpp index 5e25a0148..2d12244b7 100644 --- a/kcmkwin/kwindecoration/buttons.cpp +++ b/kcmkwin/kwindecoration/buttons.cpp @@ -1,17 +1,17 @@ /* - This is the new kwindecoration kcontrol module + This is the new kwindecoration kcontrol module - Copyright (c) 2009, Urs Wolfer - Copyright (c) 2004, Sandro Giessl - Copyright (c) 2001 - Karol Szwed - http://gallium.n3.net/ + Copyright (c) 2009, Urs Wolfer + Copyright (c) 2004, Sandro Giessl + Copyright (c) 2001 + Karol Szwed + http://gallium.n3.net/ - Supports new kwin configuration plugins, and titlebar button position - modification via dnd interface. + Supports new kwin configuration plugins, and titlebar button position + modification via dnd interface. - Based on original "kwintheme" (Window Borders) - Copyright (C) 2001 Rik Hemsley (rikkus) + Based on original "kwintheme" (Window Borders) + Copyright (C) 2001 Rik Hemsley (rikkus) 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 @@ -51,45 +51,44 @@ namespace KWin { ButtonDrag::ButtonDrag(Button btn) - : QMimeData() + : QMimeData() { - QByteArray data; - QDataStream stream(&data, QIODevice::WriteOnly); - stream << btn.name; - stream << btn.icon; - stream << btn.type.unicode(); - stream << (int) btn.duplicate; - stream << (int) btn.supported; - setData(BUTTONDRAGMIMETYPE, data); + QByteArray data; + QDataStream stream(&data, QIODevice::WriteOnly); + stream << btn.name; + stream << btn.icon; + stream << btn.type.unicode(); + stream << (int) btn.duplicate; + stream << (int) btn.supported; + setData(BUTTONDRAGMIMETYPE, data); } -bool ButtonDrag::canDecode( QDropEvent* e ) +bool ButtonDrag::canDecode(QDropEvent* e) { - return e->mimeData()->hasFormat(BUTTONDRAGMIMETYPE); + return e->mimeData()->hasFormat(BUTTONDRAGMIMETYPE); } -bool ButtonDrag::decode( QDropEvent* e, Button& btn ) +bool ButtonDrag::decode(QDropEvent* e, Button& btn) { - QByteArray data = e->mimeData()->data(BUTTONDRAGMIMETYPE); - if ( data.size() ) - { - e->accept(); - QDataStream stream(data); - stream >> btn.name; - stream >> btn.icon; - ushort type; - stream >> type; - btn.type = QChar(type); - int duplicate; - stream >> duplicate; - btn.duplicate = duplicate; - int supported; - stream >> supported; - btn.supported = supported; - return true; - } - return false; + QByteArray data = e->mimeData()->data(BUTTONDRAGMIMETYPE); + if (data.size()) { + e->accept(); + QDataStream stream(data); + stream >> btn.name; + stream >> btn.icon; + ushort type; + stream >> type; + btn.type = QChar(type); + int duplicate; + stream >> duplicate; + btn.duplicate = duplicate; + int supported; + stream >> supported; + btn.supported = supported; + return true; + } + return false; } @@ -98,11 +97,11 @@ Button::Button() } Button::Button(const QString& n, const QBitmap& i, QChar t, bool d, bool s) - : name(n), - icon(i), - type(t), - duplicate(d), - supported(s) + : name(n), + icon(i), + type(t), + duplicate(d), + supported(s) { } @@ -113,24 +112,24 @@ Button::~Button() // helper function to deal with the Button's bitmaps more easily... QPixmap bitmapPixmap(const QBitmap& bm, const QColor& color) { - QPixmap pm( bm.size() ); - pm.fill(Qt::white); - QPainter p(&pm); - p.setPen(color); - p.drawPixmap(0, 0, bm); - p.end(); - pm.setMask(pm.createMaskFromColor(Qt::white)); - return pm; + QPixmap pm(bm.size()); + pm.fill(Qt::white); + QPainter p(&pm); + p.setPen(color); + p.drawPixmap(0, 0, bm); + p.end(); + pm.setMask(pm.createMaskFromColor(Qt::white)); + return pm; } ButtonSource::ButtonSource(QWidget *parent) - : QListWidget(parent) + : QListWidget(parent) { - setDragEnabled(true); - setAcceptDrops(true); - setDropIndicatorShown(false); - setSortingEnabled(true); + setDragEnabled(true); + setAcceptDrops(true); + setDropIndicatorShown(false); + setSortingEnabled(true); } ButtonSource::~ButtonSource() @@ -139,92 +138,92 @@ ButtonSource::~ButtonSource() QSize ButtonSource::sizeHint() const { - // make the sizeHint height a bit smaller than the one of QListView... + // make the sizeHint height a bit smaller than the one of QListView... - ensurePolished(); + ensurePolished(); - QSize s; - if ( verticalScrollBar()->isVisible() ) - s.setWidth( s.width() + style()->pixelMetric(QStyle::PM_ScrollBarExtent) ); - s += QSize(frameWidth()*2,frameWidth()*2); + QSize s; + if (verticalScrollBar()->isVisible()) + s.setWidth(s.width() + style()->pixelMetric(QStyle::PM_ScrollBarExtent)); + s += QSize(frameWidth() * 2, frameWidth() * 2); - // size hint: 4 lines of text... - s.setHeight( s.height() + fontMetrics().lineSpacing()*3 ); + // size hint: 4 lines of text... + s.setHeight(s.height() + fontMetrics().lineSpacing() * 3); - return s; + return s; } void ButtonSource::hideAllButtons() { - for (int i = 0; i < count(); i++) { - item(i)->setHidden(true); - } + for (int i = 0; i < count(); i++) { + item(i)->setHidden(true); + } } void ButtonSource::showAllButtons() { - for (int i = 0; i < count(); i++) { - item(i)->setHidden(false); - } + for (int i = 0; i < count(); i++) { + item(i)->setHidden(false); + } } -void ButtonSource::showButton( QChar btn ) +void ButtonSource::showButton(QChar btn) { - for (int i = 0; i < count(); i++) { - ButtonSourceItem *buttonItem = dynamic_cast(item(i)); - if (buttonItem && buttonItem->button().type == btn) { - item(i)->setHidden(false); - return; - } - } + for (int i = 0; i < count(); i++) { + ButtonSourceItem *buttonItem = dynamic_cast(item(i)); + if (buttonItem && buttonItem->button().type == btn) { + item(i)->setHidden(false); + return; + } + } } -void ButtonSource::hideButton( QChar btn ) +void ButtonSource::hideButton(QChar btn) { - for (int i = 0; i < count(); i++) { - ButtonSourceItem *buttonItem = dynamic_cast(item(i)); - if (buttonItem && buttonItem->button().type == btn && !buttonItem->button().duplicate) { - item(i)->setHidden(true); - return; - } - } + for (int i = 0; i < count(); i++) { + ButtonSourceItem *buttonItem = dynamic_cast(item(i)); + if (buttonItem && buttonItem->button().type == btn && !buttonItem->button().duplicate) { + item(i)->setHidden(true); + return; + } + } } void ButtonSource::dragMoveEvent(QDragMoveEvent *e) { - e->setAccepted(ButtonDrag::canDecode(e)); + e->setAccepted(ButtonDrag::canDecode(e)); } void ButtonSource::dragEnterEvent(QDragEnterEvent *e) { - e->setAccepted(ButtonDrag::canDecode(e)); + e->setAccepted(ButtonDrag::canDecode(e)); } void ButtonSource::dropEvent(QDropEvent *e) { - if (ButtonDrag::canDecode(e)) { - emit dropped(); - e->accept(); - } else { - e->ignore(); - } + if (ButtonDrag::canDecode(e)) { + emit dropped(); + e->accept(); + } else { + e->ignore(); + } } void ButtonSource::mousePressEvent(QMouseEvent *e) { - ButtonSourceItem *i = dynamic_cast(itemAt(e->pos())); + ButtonSourceItem *i = dynamic_cast(itemAt(e->pos())); - if (i) { - ButtonDrag *bd = new ButtonDrag(i->button()); - QDrag *drag = new QDrag(this); - drag->setMimeData(bd); - drag->setPixmap(bitmapPixmap(i->button().icon, palette().color(QPalette::WindowText))); - drag->exec(); - } + if (i) { + ButtonDrag *bd = new ButtonDrag(i->button()); + QDrag *drag = new QDrag(this); + drag->setMimeData(bd); + drag->setPixmap(bitmapPixmap(i->button().icon, palette().color(QPalette::WindowText))); + drag->exec(); + } } ButtonDropSiteItem::ButtonDropSiteItem(const Button& btn) - : m_button(btn) + : m_button(btn) { } @@ -234,398 +233,398 @@ ButtonDropSiteItem::~ButtonDropSiteItem() Button ButtonDropSiteItem::button() { - return m_button; + return m_button; } int ButtonDropSiteItem::width() { -// return m_button.icon.width(); - return 20; +// return m_button.icon.width(); + return 20; } int ButtonDropSiteItem::height() { -// return m_button.icon.height(); - return 20; +// return m_button.icon.height(); + return 20; } void ButtonDropSiteItem::draw(QPainter *p, const QPalette& cg, const QRect &r) { - if (m_button.supported) - p->setPen(cg.color(QPalette::WindowText) ); - else - p->setPen( cg.color(QPalette::Disabled, QPalette::WindowText) ); - QBitmap &i = m_button.icon; - p->drawPixmap(r.left()+(r.width()-i.width())/2, r.top()+(r.height()-i.height())/2, i); + if (m_button.supported) + p->setPen(cg.color(QPalette::WindowText)); + else + p->setPen(cg.color(QPalette::Disabled, QPalette::WindowText)); + QBitmap &i = m_button.icon; + p->drawPixmap(r.left() + (r.width() - i.width()) / 2, r.top() + (r.height() - i.height()) / 2, i); } ButtonDropSite::ButtonDropSite(QWidget* parent) - : QFrame( parent ), - m_selected(0) + : QFrame(parent), + m_selected(0) { - setAcceptDrops( true ); - setFrameShape( WinPanel ); - setFrameShadow( Raised ); - setMinimumHeight( 26 ); - setMaximumHeight( 26 ); - setMinimumWidth( 250 ); // Ensure buttons will fit - setCursor(Qt::OpenHandCursor); + setAcceptDrops(true); + setFrameShape(WinPanel); + setFrameShadow(Raised); + setMinimumHeight(26); + setMaximumHeight(26); + setMinimumWidth(250); // Ensure buttons will fit + setCursor(Qt::OpenHandCursor); } ButtonDropSite::~ButtonDropSite() { - clearLeft(); - clearRight(); + clearLeft(); + clearRight(); } void ButtonDropSite::clearLeft() { - while (!buttonsLeft.isEmpty() ) { - ButtonDropSiteItem *item = buttonsLeft.first(); - if (removeButton(item) ) { - emit buttonRemoved(item->button().type); - delete item; - } - } + while (!buttonsLeft.isEmpty()) { + ButtonDropSiteItem *item = buttonsLeft.first(); + if (removeButton(item)) { + emit buttonRemoved(item->button().type); + delete item; + } + } } void ButtonDropSite::clearRight() { - while (!buttonsRight.isEmpty() ) { - ButtonDropSiteItem *item = buttonsRight.first(); - if (removeButton(item) ) { - emit buttonRemoved(item->button().type); - delete item; - } - } + while (!buttonsRight.isEmpty()) { + ButtonDropSiteItem *item = buttonsRight.first(); + if (removeButton(item)) { + emit buttonRemoved(item->button().type); + delete item; + } + } } -void ButtonDropSite::dragMoveEvent( QDragMoveEvent* e ) +void ButtonDropSite::dragMoveEvent(QDragMoveEvent* e) { - QPoint p = e->pos(); - if (leftDropArea().contains(p) || rightDropArea().contains(p) || buttonAt(p) ) { - e->accept(); + QPoint p = e->pos(); + if (leftDropArea().contains(p) || rightDropArea().contains(p) || buttonAt(p)) { + e->accept(); - // 2 pixel wide drop visualizer... - QRect r = contentsRect(); - int x = -1; - if (leftDropArea().contains(p) ) { - x = leftDropArea().left(); - } else if (rightDropArea().contains(p) ) { - x = rightDropArea().right()+1; - } else { - ButtonDropSiteItem *item = buttonAt(p); - if (item) { - if (p.x() < item->rect.left()+item->rect.width()/2 ) { - x = item->rect.left(); - } else { - x = item->rect.right()+1; - } - } - } - if (x != -1) { - QRect tmpRect(x, r.y(), 2, r.height() ); - if (tmpRect != m_oldDropVisualizer) { - cleanDropVisualizer(); - m_oldDropVisualizer = tmpRect; - update(tmpRect); - } - } + // 2 pixel wide drop visualizer... + QRect r = contentsRect(); + int x = -1; + if (leftDropArea().contains(p)) { + x = leftDropArea().left(); + } else if (rightDropArea().contains(p)) { + x = rightDropArea().right() + 1; + } else { + ButtonDropSiteItem *item = buttonAt(p); + if (item) { + if (p.x() < item->rect.left() + item->rect.width() / 2) { + x = item->rect.left(); + } else { + x = item->rect.right() + 1; + } + } + } + if (x != -1) { + QRect tmpRect(x, r.y(), 2, r.height()); + if (tmpRect != m_oldDropVisualizer) { + cleanDropVisualizer(); + m_oldDropVisualizer = tmpRect; + update(tmpRect); + } + } - } else { - e->ignore(); + } else { + e->ignore(); - cleanDropVisualizer(); - } + cleanDropVisualizer(); + } } void ButtonDropSite::cleanDropVisualizer() { - if (m_oldDropVisualizer.isValid()) - { - QRect rect = m_oldDropVisualizer; - m_oldDropVisualizer = QRect(); // rect is invalid - update(rect); - } + if (m_oldDropVisualizer.isValid()) { + QRect rect = m_oldDropVisualizer; + m_oldDropVisualizer = QRect(); // rect is invalid + update(rect); + } } -void ButtonDropSite::dragEnterEvent( QDragEnterEvent* e ) +void ButtonDropSite::dragEnterEvent(QDragEnterEvent* e) { - if ( ButtonDrag::canDecode( e ) ) - e->accept(); + if (ButtonDrag::canDecode(e)) + e->accept(); } -void ButtonDropSite::dragLeaveEvent( QDragLeaveEvent* /* e */ ) +void ButtonDropSite::dragLeaveEvent(QDragLeaveEvent* /* e */) { - cleanDropVisualizer(); + cleanDropVisualizer(); } -void ButtonDropSite::dropEvent( QDropEvent* e ) +void ButtonDropSite::dropEvent(QDropEvent* e) { - cleanDropVisualizer(); + cleanDropVisualizer(); - QPoint p = e->pos(); + QPoint p = e->pos(); - // collect information where to insert the dropped button - ButtonList *buttonList = 0; - int buttonPosition; + // collect information where to insert the dropped button + ButtonList *buttonList = 0; + int buttonPosition; - if (leftDropArea().contains(p) ) { - buttonList = &buttonsLeft; - buttonPosition = buttonsLeft.size(); - } else if (rightDropArea().contains(p) ) { - buttonList = &buttonsRight; - buttonPosition = 0; - } else { - ButtonDropSiteItem *aboveItem = buttonAt(p); - if (!aboveItem) - return; // invalid drop. hasn't occurred _over_ a button (or left/right dropArea), return... + if (leftDropArea().contains(p)) { + buttonList = &buttonsLeft; + buttonPosition = buttonsLeft.size(); + } else if (rightDropArea().contains(p)) { + buttonList = &buttonsRight; + buttonPosition = 0; + } else { + ButtonDropSiteItem *aboveItem = buttonAt(p); + if (!aboveItem) + return; // invalid drop. hasn't occurred _over_ a button (or left/right dropArea), return... - int pos; - if (!getItemPos(aboveItem, buttonList, pos) ) { - // didn't find the aboveItem. unlikely to happen since buttonAt() already seems to have found - // something valid. anyway... - return; - } + int pos; + if (!getItemPos(aboveItem, buttonList, pos)) { + // didn't find the aboveItem. unlikely to happen since buttonAt() already seems to have found + // something valid. anyway... + return; + } - // got the list and the aboveItem position. now determine if the item should be inserted - // before aboveItem or after aboveItem. - QRect aboveItemRect = aboveItem->rect; - if (!aboveItemRect.isValid() ) - return; + // got the list and the aboveItem position. now determine if the item should be inserted + // before aboveItem or after aboveItem. + QRect aboveItemRect = aboveItem->rect; + if (!aboveItemRect.isValid()) + return; - if (p.x() < aboveItemRect.left()+aboveItemRect.width()/2 ) { - // insert before the item - buttonPosition = pos; - } else { - buttonPosition = pos + 1; - } - } + if (p.x() < aboveItemRect.left() + aboveItemRect.width() / 2) { + // insert before the item + buttonPosition = pos; + } else { + buttonPosition = pos + 1; + } + } - // know where to insert the button. now see if we can use an existing item (drag within the widget = move) - // orneed to create a new one - ButtonDropSiteItem *buttonItem = 0; - if (e->source() == this && m_selected) { - ButtonList *oldList = 0; - int oldPos; - if (getItemPos(m_selected, oldList, oldPos) ) { - if (oldPos == buttonPosition && oldList == buttonList) - return; // button didn't change its position during the drag... + // know where to insert the button. now see if we can use an existing item (drag within the widget = move) + // orneed to create a new one + ButtonDropSiteItem *buttonItem = 0; + if (e->source() == this && m_selected) { + ButtonList *oldList = 0; + int oldPos; + if (getItemPos(m_selected, oldList, oldPos)) { + if (oldPos == buttonPosition && oldList == buttonList) + return; // button didn't change its position during the drag... - oldList->removeAt(oldPos); - buttonItem = m_selected; + oldList->removeAt(oldPos); + buttonItem = m_selected; - // If we're inserting to the right of oldPos, in the same list, - // better adjust the index.. - if (buttonList == oldList && buttonPosition > oldPos) - --buttonPosition; - } else { - return; // m_selected not found, return... - } - } else { - // create new button from the drop object... - Button btn; - if (ButtonDrag::decode(e, btn) ) { - buttonItem = new ButtonDropSiteItem(btn); - } else { - return; // something has gone wrong while we were trying to decode the drop event - } - } + // If we're inserting to the right of oldPos, in the same list, + // better adjust the index.. + if (buttonList == oldList && buttonPosition > oldPos) + --buttonPosition; + } else { + return; // m_selected not found, return... + } + } else { + // create new button from the drop object... + Button btn; + if (ButtonDrag::decode(e, btn)) { + buttonItem = new ButtonDropSiteItem(btn); + } else { + return; // something has gone wrong while we were trying to decode the drop event + } + } - // now the item can actually be inserted into the list! :) - (*buttonList).insert(buttonPosition, buttonItem); - emit buttonAdded(buttonItem->button().type); - emit changed(); - recalcItemGeometry(); - update(); + // now the item can actually be inserted into the list! :) + (*buttonList).insert(buttonPosition, buttonItem); + emit buttonAdded(buttonItem->button().type); + emit changed(); + recalcItemGeometry(); + update(); } bool ButtonDropSite::getItemPos(ButtonDropSiteItem *item, ButtonList* &list, int &pos) { - if (!item) - return false; + if (!item) + return false; - pos = buttonsLeft.indexOf(item); // try the left list first... - if (pos >= 0) { - list = &buttonsLeft; - return true; - } + pos = buttonsLeft.indexOf(item); // try the left list first... + if (pos >= 0) { + list = &buttonsLeft; + return true; + } - pos = buttonsRight.indexOf(item); // try the right list... - if (pos >= 0) { - list = &buttonsRight; - return true; - } + pos = buttonsRight.indexOf(item); // try the right list... + if (pos >= 0) { + list = &buttonsRight; + return true; + } - list = 0; - pos = -1; - return false; + list = 0; + pos = -1; + return false; } QRect ButtonDropSite::leftDropArea() { - // return a 10 pixel drop area... - QRect r = contentsRect(); + // return a 10 pixel drop area... + QRect r = contentsRect(); - int leftButtonsWidth = calcButtonListWidth(buttonsLeft); - return QRect(r.left()+leftButtonsWidth, r.top(), 10, r.height() ); + int leftButtonsWidth = calcButtonListWidth(buttonsLeft); + return QRect(r.left() + leftButtonsWidth, r.top(), 10, r.height()); } QRect ButtonDropSite::rightDropArea() { - // return a 10 pixel drop area... - QRect r = contentsRect(); + // return a 10 pixel drop area... + QRect r = contentsRect(); - int rightButtonsWidth = calcButtonListWidth(buttonsRight); - return QRect(r.right()-rightButtonsWidth-10, r.top(), 10, r.height() ); + int rightButtonsWidth = calcButtonListWidth(buttonsRight); + return QRect(r.right() - rightButtonsWidth - 10, r.top(), 10, r.height()); } -void ButtonDropSite::mousePressEvent( QMouseEvent* e ) +void ButtonDropSite::mousePressEvent(QMouseEvent* e) { - QDrag *drag = new QDrag(this); - m_selected = buttonAt(e->pos() ); - if (m_selected) { - ButtonDrag *bd = new ButtonDrag(m_selected->button()); - drag->setMimeData(bd); - drag->setPixmap(bitmapPixmap(m_selected->button().icon, palette().color(QPalette::WindowText))); - drag->exec(); - } + QDrag *drag = new QDrag(this); + m_selected = buttonAt(e->pos()); + if (m_selected) { + ButtonDrag *bd = new ButtonDrag(m_selected->button()); + drag->setMimeData(bd); + drag->setPixmap(bitmapPixmap(m_selected->button().icon, palette().color(QPalette::WindowText))); + drag->exec(); + } } void ButtonDropSite::resizeEvent(QResizeEvent*) { - recalcItemGeometry(); + recalcItemGeometry(); } void ButtonDropSite::recalcItemGeometry() { - QRect r = contentsRect(); + QRect r = contentsRect(); - // update the geometry of the items in the left button list - int offset = r.left(); - for (ButtonList::const_iterator it = buttonsLeft.constBegin(); it != buttonsLeft.constEnd(); ++it) { - int w = (*it)->width(); - (*it)->rect = QRect(offset, r.top(), w, (*it)->height() ); - offset += w; - } + // update the geometry of the items in the left button list + int offset = r.left(); + for (ButtonList::const_iterator it = buttonsLeft.constBegin(); it != buttonsLeft.constEnd(); ++it) { + int w = (*it)->width(); + (*it)->rect = QRect(offset, r.top(), w, (*it)->height()); + offset += w; + } - // the right button list... - offset = r.right() - calcButtonListWidth(buttonsRight); - for (ButtonList::const_iterator it = buttonsRight.constBegin(); it != buttonsRight.constEnd(); ++it) { - int w = (*it)->width(); - (*it)->rect = QRect(offset, r.top(), w, (*it)->height() ); - offset += w; - } + // the right button list... + offset = r.right() - calcButtonListWidth(buttonsRight); + for (ButtonList::const_iterator it = buttonsRight.constBegin(); it != buttonsRight.constEnd(); ++it) { + int w = (*it)->width(); + (*it)->rect = QRect(offset, r.top(), w, (*it)->height()); + offset += w; + } } -ButtonDropSiteItem *ButtonDropSite::buttonAt(QPoint p) { - // try to find the item in the left button list - for (ButtonList::const_iterator it = buttonsLeft.constBegin(); it != buttonsLeft.constEnd(); ++it) { - if ( (*it)->rect.contains(p) ) { - return *it; - } - } +ButtonDropSiteItem *ButtonDropSite::buttonAt(QPoint p) +{ + // try to find the item in the left button list + for (ButtonList::const_iterator it = buttonsLeft.constBegin(); it != buttonsLeft.constEnd(); ++it) { + if ((*it)->rect.contains(p)) { + return *it; + } + } - // try to find the item in the right button list - for (ButtonList::const_iterator it = buttonsRight.constBegin(); it != buttonsRight.constEnd(); ++it) { - if ( (*it)->rect.contains(p) ) { - return *it; - } - } + // try to find the item in the right button list + for (ButtonList::const_iterator it = buttonsRight.constBegin(); it != buttonsRight.constEnd(); ++it) { + if ((*it)->rect.contains(p)) { + return *it; + } + } - return 0; + return 0; } -bool ButtonDropSite::removeButton(ButtonDropSiteItem *item) { - if (!item) - return false; +bool ButtonDropSite::removeButton(ButtonDropSiteItem *item) +{ + if (!item) + return false; - // try to remove the item from the left button list - if (buttonsLeft.removeAll(item) >= 1) { - return true; - } + // try to remove the item from the left button list + if (buttonsLeft.removeAll(item) >= 1) { + return true; + } - // try to remove the item from the right button list - if (buttonsRight.removeAll(item) >= 1) { - return true; - } + // try to remove the item from the right button list + if (buttonsRight.removeAll(item) >= 1) { + return true; + } - return false; + return false; } int ButtonDropSite::calcButtonListWidth(const ButtonList& btns) { - int w = 0; - for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { - w += (*it)->width(); - } + int w = 0; + for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { + w += (*it)->width(); + } - return w; + return w; } bool ButtonDropSite::removeSelectedButton() { - bool succ = removeButton(m_selected); - if (succ) { - emit buttonRemoved(m_selected->button().type); - emit changed(); - delete m_selected; - m_selected = 0; - recalcItemGeometry(); - update(); // repaint... - } + bool succ = removeButton(m_selected); + if (succ) { + emit buttonRemoved(m_selected->button().type); + emit changed(); + delete m_selected; + m_selected = 0; + recalcItemGeometry(); + update(); // repaint... + } - return succ; + return succ; } void ButtonDropSite::drawButtonList(QPainter *p, const ButtonList& btns, int offset) { - for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { - QRect itemRect = (*it)->rect; - if (itemRect.isValid() ) { - (*it)->draw(p, palette(), itemRect); - } - offset += (*it)->width(); - } + for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { + QRect itemRect = (*it)->rect; + if (itemRect.isValid()) { + (*it)->draw(p, palette(), itemRect); + } + offset += (*it)->width(); + } } -void ButtonDropSite::paintEvent( QPaintEvent* /*pe*/ ) +void ButtonDropSite::paintEvent(QPaintEvent* /*pe*/) { - QPainter p( this ); - int leftoffset = calcButtonListWidth( buttonsLeft ); - int rightoffset = calcButtonListWidth( buttonsRight ); - int offset = 3; + QPainter p(this); + int leftoffset = calcButtonListWidth(buttonsLeft); + int rightoffset = calcButtonListWidth(buttonsRight); + int offset = 3; - QRect r = contentsRect(); + QRect r = contentsRect(); - // Shrink by 1 - r.translate(1 + leftoffset, 1); - r.setWidth( r.width() - 2 - leftoffset - rightoffset ); - r.setHeight( r.height() - 2 ); + // Shrink by 1 + r.translate(1 + leftoffset, 1); + r.setWidth(r.width() - 2 - leftoffset - rightoffset); + r.setHeight(r.height() - 2); - drawButtonList( &p, buttonsLeft, offset ); + drawButtonList(&p, buttonsLeft, offset); - QColor c1(palette().color(QPalette::Mid)); - p.fillRect( r, c1 ); - p.setPen(palette().color(QPalette::WindowText)); - p.setFont(KGlobalSettings::windowTitleFont()); - p.drawText( r.adjusted(4, 0, -4, 0), Qt::AlignLeft | Qt::AlignVCenter, i18n("KDE") ); + QColor c1(palette().color(QPalette::Mid)); + p.fillRect(r, c1); + p.setPen(palette().color(QPalette::WindowText)); + p.setFont(KGlobalSettings::windowTitleFont()); + p.drawText(r.adjusted(4, 0, -4, 0), Qt::AlignLeft | Qt::AlignVCenter, i18n("KDE")); - offset = geometry().width() - 3 - rightoffset; - drawButtonList( &p, buttonsRight, offset ); + offset = geometry().width() - 3 - rightoffset; + drawButtonList(&p, buttonsRight, offset); - if (m_oldDropVisualizer.isValid() ) - { - p.fillRect(m_oldDropVisualizer, Qt::Dense4Pattern); - } + if (m_oldDropVisualizer.isValid()) { + p.fillRect(m_oldDropVisualizer, Qt::Dense4Pattern); + } } ButtonSourceItem::ButtonSourceItem(QListWidget * parent, const Button& btn) - : QListWidgetItem(parent), - m_button(btn) + : QListWidgetItem(parent), + m_button(btn) { - setButton(btn); + setButton(btn); } ButtonSourceItem::~ButtonSourceItem() @@ -634,21 +633,21 @@ ButtonSourceItem::~ButtonSourceItem() void ButtonSourceItem::setButton(const Button& btn) { - m_button = btn; - if (btn.supported) { - setText(btn.name); - setIcon(bitmapPixmap(btn.icon, QApplication::palette().color(QPalette::Text))); - setForeground(QApplication::palette().brush(QPalette::Text)); - } else { - setText(i18n("%1 (unavailable)", btn.name) ); - setIcon(bitmapPixmap(btn.icon, QApplication::palette().color(QPalette::Disabled, QPalette::Text))); - setForeground(QApplication::palette().brush(QPalette::Disabled, QPalette::Text)); - } + m_button = btn; + if (btn.supported) { + setText(btn.name); + setIcon(bitmapPixmap(btn.icon, QApplication::palette().color(QPalette::Text))); + setForeground(QApplication::palette().brush(QPalette::Text)); + } else { + setText(i18n("%1 (unavailable)", btn.name)); + setIcon(bitmapPixmap(btn.icon, QApplication::palette().color(QPalette::Disabled, QPalette::Text))); + setForeground(QApplication::palette().brush(QPalette::Disabled, QPalette::Text)); + } } Button ButtonSourceItem::button() const { - return m_button; + return m_button; } @@ -656,154 +655,155 @@ ButtonPositionWidget::ButtonPositionWidget(QWidget *parent) : QWidget(parent), m_factory(0) { - QVBoxLayout *layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - QLabel* label = new QLabel( this ); - m_dropSite = new ButtonDropSite( this ); - label->setWordWrap( true ); - label->setText( i18n( "To add or remove titlebar buttons, simply drag items " - "between the available item list and the titlebar preview. Similarly, " - "drag items within the titlebar preview to re-position them.") ); - m_buttonSource = new ButtonSource(this); - m_buttonSource->setObjectName( QLatin1String("button_source" )); + QLabel* label = new QLabel(this); + m_dropSite = new ButtonDropSite(this); + label->setWordWrap(true); + label->setText(i18n("To add or remove titlebar buttons, simply drag items " + "between the available item list and the titlebar preview. Similarly, " + "drag items within the titlebar preview to re-position them.")); + m_buttonSource = new ButtonSource(this); + m_buttonSource->setObjectName(QLatin1String("button_source")); - layout->addWidget(label); - layout->addWidget(m_dropSite); - layout->addWidget(m_buttonSource); + layout->addWidget(label); + layout->addWidget(m_dropSite); + layout->addWidget(m_buttonSource); - connect( m_dropSite, SIGNAL(buttonAdded(QChar)), m_buttonSource, SLOT(hideButton(QChar)) ); - connect( m_dropSite, SIGNAL(buttonRemoved(QChar)), m_buttonSource, SLOT(showButton(QChar)) ); - connect( m_buttonSource, SIGNAL(dropped()), m_dropSite, SLOT(removeSelectedButton()) ); + connect(m_dropSite, SIGNAL(buttonAdded(QChar)), m_buttonSource, SLOT(hideButton(QChar))); + connect(m_dropSite, SIGNAL(buttonRemoved(QChar)), m_buttonSource, SLOT(showButton(QChar))); + connect(m_buttonSource, SIGNAL(dropped()), m_dropSite, SLOT(removeSelectedButton())); - connect( m_dropSite, SIGNAL(changed()), SIGNAL(changed()) ); + connect(m_dropSite, SIGNAL(changed()), SIGNAL(changed())); - // insert all possible buttons into the source (backwards to keep the preferred order...) - bool dummy; - m_supportedButtons = "MSHIAX_FBLR"; // support all buttons - new ButtonSourceItem(m_buttonSource, getButton('R', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('L', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('B', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('F', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('X', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('A', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('I', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('H', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('S', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('M', dummy) ); - new ButtonSourceItem(m_buttonSource, getButton('_', dummy) ); + // insert all possible buttons into the source (backwards to keep the preferred order...) + bool dummy; + m_supportedButtons = "MSHIAX_FBLR"; // support all buttons + new ButtonSourceItem(m_buttonSource, getButton('R', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('L', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('B', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('F', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('X', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('A', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('I', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('H', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('S', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('M', dummy)); + new ButtonSourceItem(m_buttonSource, getButton('_', dummy)); } ButtonPositionWidget::~ButtonPositionWidget() { } -Button ButtonPositionWidget::getButton(QChar type, bool& success) { - success = true; +Button ButtonPositionWidget::getButton(QChar type, bool& success) +{ + success = true; - if (type == 'R') { - QBitmap bmp = QBitmap::fromData(QSize( resize_width, resize_height ), resize_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Resize"), bmp, 'R', false, m_supportedButtons.contains('R') ); - } else if (type == 'L') { - QBitmap bmp = QBitmap::fromData(QSize( shade_width, shade_height ), shade_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Shade"), bmp, 'L', false, m_supportedButtons.contains('L') ); - } else if (type == 'B') { - QBitmap bmp = QBitmap::fromData(QSize( keepbelowothers_width, keepbelowothers_height ), keepbelowothers_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Keep Below Others"), bmp, 'B', false, m_supportedButtons.contains('B') ); - } else if (type == 'F') { - QBitmap bmp = QBitmap::fromData(QSize( keepaboveothers_width, keepaboveothers_height ), keepaboveothers_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Keep Above Others"), bmp, 'F', false, m_supportedButtons.contains('F') ); - } else if (type == 'X') { - QBitmap bmp = QBitmap::fromData(QSize( close_width, close_height ), close_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Close"), bmp, 'X', false, m_supportedButtons.contains('X') ); - } else if (type == 'A') { - QBitmap bmp = QBitmap::fromData(QSize( maximize_width, maximize_height ), maximize_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Maximize"), bmp, 'A', false, m_supportedButtons.contains('A') ); - } else if (type == 'I') { - QBitmap bmp = QBitmap::fromData(QSize( minimize_width, minimize_height ), minimize_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Minimize"), bmp, 'I', false, m_supportedButtons.contains('I') ); - } else if (type == 'H') { - QBitmap bmp = QBitmap::fromData(QSize( help_width, help_height ), help_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Help"), bmp, 'H', false, m_supportedButtons.contains('H') ); - } else if (type == 'S') { - QBitmap bmp = QBitmap::fromData(QSize( onalldesktops_width, onalldesktops_height ), onalldesktops_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("On All Desktops"), bmp, 'S', false, m_supportedButtons.contains('S') ); - } else if (type == 'M') { - QBitmap bmp = QBitmap::fromData(QSize( menu_width, menu_height ), menu_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("Menu"), bmp, 'M', false, m_supportedButtons.contains('M') ); - } else if (type == '_') { - QBitmap bmp = QBitmap::fromData(QSize( spacer_width, spacer_height ), spacer_bits); - bmp.createMaskFromColor(Qt::white); - return Button(i18n("--- spacer ---"), bmp, '_', true, m_supportedButtons.contains('_') ); - } else { - success = false; - return Button(); - } + if (type == 'R') { + QBitmap bmp = QBitmap::fromData(QSize(resize_width, resize_height), resize_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Resize"), bmp, 'R', false, m_supportedButtons.contains('R')); + } else if (type == 'L') { + QBitmap bmp = QBitmap::fromData(QSize(shade_width, shade_height), shade_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Shade"), bmp, 'L', false, m_supportedButtons.contains('L')); + } else if (type == 'B') { + QBitmap bmp = QBitmap::fromData(QSize(keepbelowothers_width, keepbelowothers_height), keepbelowothers_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Keep Below Others"), bmp, 'B', false, m_supportedButtons.contains('B')); + } else if (type == 'F') { + QBitmap bmp = QBitmap::fromData(QSize(keepaboveothers_width, keepaboveothers_height), keepaboveothers_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Keep Above Others"), bmp, 'F', false, m_supportedButtons.contains('F')); + } else if (type == 'X') { + QBitmap bmp = QBitmap::fromData(QSize(close_width, close_height), close_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Close"), bmp, 'X', false, m_supportedButtons.contains('X')); + } else if (type == 'A') { + QBitmap bmp = QBitmap::fromData(QSize(maximize_width, maximize_height), maximize_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Maximize"), bmp, 'A', false, m_supportedButtons.contains('A')); + } else if (type == 'I') { + QBitmap bmp = QBitmap::fromData(QSize(minimize_width, minimize_height), minimize_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Minimize"), bmp, 'I', false, m_supportedButtons.contains('I')); + } else if (type == 'H') { + QBitmap bmp = QBitmap::fromData(QSize(help_width, help_height), help_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Help"), bmp, 'H', false, m_supportedButtons.contains('H')); + } else if (type == 'S') { + QBitmap bmp = QBitmap::fromData(QSize(onalldesktops_width, onalldesktops_height), onalldesktops_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("On All Desktops"), bmp, 'S', false, m_supportedButtons.contains('S')); + } else if (type == 'M') { + QBitmap bmp = QBitmap::fromData(QSize(menu_width, menu_height), menu_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("Menu"), bmp, 'M', false, m_supportedButtons.contains('M')); + } else if (type == '_') { + QBitmap bmp = QBitmap::fromData(QSize(spacer_width, spacer_height), spacer_bits); + bmp.createMaskFromColor(Qt::white); + return Button(i18n("--- spacer ---"), bmp, '_', true, m_supportedButtons.contains('_')); + } else { + success = false; + return Button(); + } } QString ButtonPositionWidget::buttonsLeft() const { - ButtonList btns = m_dropSite->buttonsLeft; - QString btnString = ""; - for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { - btnString.append( (*it)->button().type ); - } - return btnString; + ButtonList btns = m_dropSite->buttonsLeft; + QString btnString = ""; + for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { + btnString.append((*it)->button().type); + } + return btnString; } QString ButtonPositionWidget::buttonsRight() const { - ButtonList btns = m_dropSite->buttonsRight; - QString btnString = ""; - for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { - btnString.append( (*it)->button().type ); - } - return btnString; + ButtonList btns = m_dropSite->buttonsRight; + QString btnString = ""; + for (ButtonList::const_iterator it = btns.constBegin(); it != btns.constEnd(); ++it) { + btnString.append((*it)->button().type); + } + return btnString; } void ButtonPositionWidget::setButtonsLeft(const QString &buttons) { - // to keep the button lists consistent, first remove all left buttons, then add buttons again... - m_dropSite->clearLeft(); + // to keep the button lists consistent, first remove all left buttons, then add buttons again... + m_dropSite->clearLeft(); - for (int i = 0; i < buttons.length(); ++i) { - bool succ = false; - Button btn = getButton(buttons[i], succ); - if (succ) { - m_dropSite->buttonsLeft.append(new ButtonDropSiteItem(btn) ); - m_buttonSource->hideButton(btn.type); - } - } - m_dropSite->recalcItemGeometry(); - m_dropSite->update(); + for (int i = 0; i < buttons.length(); ++i) { + bool succ = false; + Button btn = getButton(buttons[i], succ); + if (succ) { + m_dropSite->buttonsLeft.append(new ButtonDropSiteItem(btn)); + m_buttonSource->hideButton(btn.type); + } + } + m_dropSite->recalcItemGeometry(); + m_dropSite->update(); } void ButtonPositionWidget::setButtonsRight(const QString &buttons) { - // to keep the button lists consistent, first remove all left buttons, then add buttons again... - m_dropSite->clearRight(); + // to keep the button lists consistent, first remove all left buttons, then add buttons again... + m_dropSite->clearRight(); - for (int i = 0; i < buttons.length(); ++i) { - bool succ = false; - Button btn = getButton(buttons[i], succ); - if (succ) { - m_dropSite->buttonsRight.append(new ButtonDropSiteItem(btn) ); - m_buttonSource->hideButton(btn.type); - } - } - m_dropSite->recalcItemGeometry(); - m_dropSite->update(); + for (int i = 0; i < buttons.length(); ++i) { + bool succ = false; + Button btn = getButton(buttons[i], succ); + if (succ) { + m_dropSite->buttonsRight.append(new ButtonDropSiteItem(btn)); + m_buttonSource->hideButton(btn.type); + } + } + m_dropSite->recalcItemGeometry(); + m_dropSite->update(); } } // namespace KWin diff --git a/kcmkwin/kwindecoration/buttons.h b/kcmkwin/kwindecoration/buttons.h index 1d61b5c1b..1eaa298ef 100644 --- a/kcmkwin/kwindecoration/buttons.h +++ b/kcmkwin/kwindecoration/buttons.h @@ -1,17 +1,17 @@ /* - This is the new kwindecoration kcontrol module + This is the new kwindecoration kcontrol module - Copyright (c) 2009, Urs Wolfer - Copyright (c) 2004, Sandro Giessl - Copyright (c) 2001 - Karol Szwed - http://gallium.n3.net/ + Copyright (c) 2009, Urs Wolfer + Copyright (c) 2004, Sandro Giessl + Copyright (c) 2001 + Karol Szwed + http://gallium.n3.net/ - Supports new kwin configuration plugins, and titlebar button position - modification via dnd interface. + Supports new kwin configuration plugins, and titlebar button position + modification via dnd interface. - Based on original "kwintheme" (Window Borders) - Copyright (C) 2001 Rik Hemsley (rikkus) + Based on original "kwintheme" (Window Borders) + Copyright (C) 2001 Rik Hemsley (rikkus) 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 @@ -46,26 +46,26 @@ namespace KWin */ class Button { - public: - Button(); - Button(const QString& name, const QBitmap& icon, QChar type, bool duplicate, bool supported); - virtual ~Button(); +public: + Button(); + Button(const QString& name, const QBitmap& icon, QChar type, bool duplicate, bool supported); + virtual ~Button(); - QString name; - QBitmap icon; - QChar type; - bool duplicate; - bool supported; + QString name; + QBitmap icon; + QChar type; + bool duplicate; + bool supported; }; class ButtonDrag : public QMimeData { - public: - ButtonDrag(Button btn); - ~ButtonDrag() {} +public: + ButtonDrag(Button btn); + ~ButtonDrag() {} - static bool canDecode( QDropEvent* e ); - static bool decode( QDropEvent* e, Button& btn ); + static bool canDecode(QDropEvent* e); + static bool decode(QDropEvent* e, Button& btn); }; /** @@ -73,20 +73,20 @@ class ButtonDrag : public QMimeData */ class ButtonDropSiteItem { - public: - ButtonDropSiteItem(const Button& btn); - ~ButtonDropSiteItem(); +public: + ButtonDropSiteItem(const Button& btn); + ~ButtonDropSiteItem(); - Button button(); + Button button(); - QRect rect; - int width(); - int height(); + QRect rect; + int width(); + int height(); - void draw(QPainter *p, const QPalette& cg, const QRect &rect); + void draw(QPainter *p, const QPalette& cg, const QRect &rect); - private: - Button m_button; +private: + Button m_button; }; /** @@ -94,14 +94,14 @@ class ButtonDropSiteItem */ class ButtonSourceItem : public QListWidgetItem { - public: - ButtonSourceItem(QListWidget * parent, const Button& btn); - virtual ~ButtonSourceItem(); +public: + ButtonSourceItem(QListWidget * parent, const Button& btn); + virtual ~ButtonSourceItem(); - void setButton(const Button& btn); - Button button() const; - private: - Button m_button; + void setButton(const Button& btn); + Button button() const; +private: + Button m_button; }; /** @@ -109,28 +109,28 @@ class ButtonSourceItem : public QListWidgetItem */ class ButtonSource : public QListWidget { - Q_OBJECT + Q_OBJECT - public: - ButtonSource(QWidget *parent = 0); - virtual ~ButtonSource(); +public: + ButtonSource(QWidget *parent = 0); + virtual ~ButtonSource(); - QSize sizeHint() const; + QSize sizeHint() const; - void hideAllButtons(); - void showAllButtons(); - - void dragMoveEvent(QDragMoveEvent *e); - void dragEnterEvent(QDragEnterEvent *e); - void dropEvent(QDropEvent *e); - void mousePressEvent(QMouseEvent *e); - - signals: - void dropped(); + void hideAllButtons(); + void showAllButtons(); - public slots: - void hideButton(QChar btn); - void showButton(QChar btn); + void dragMoveEvent(QDragMoveEvent *e); + void dragEnterEvent(QDragEnterEvent *e); + void dropEvent(QDropEvent *e); + void mousePressEvent(QMouseEvent *e); + +signals: + void dropped(); + +public slots: + void hideButton(QChar btn); + void showButton(QChar btn); }; typedef QList ButtonList; @@ -140,82 +140,82 @@ typedef QList ButtonList; */ class ButtonDropSite: public QFrame { - Q_OBJECT + Q_OBJECT - public: - explicit ButtonDropSite(QWidget* parent = 0); - ~ButtonDropSite(); +public: + explicit ButtonDropSite(QWidget* parent = 0); + ~ButtonDropSite(); - // Allow external classes access our buttons - ensure buttons are - // not duplicated however. - ButtonList buttonsLeft; - ButtonList buttonsRight; - void clearLeft(); - void clearRight(); + // Allow external classes access our buttons - ensure buttons are + // not duplicated however. + ButtonList buttonsLeft; + ButtonList buttonsRight; + void clearLeft(); + void clearRight(); - void resizeEvent(QResizeEvent* e); - void dragEnterEvent(QDragEnterEvent* e); - void dragMoveEvent(QDragMoveEvent* e); - void dragLeaveEvent(QDragLeaveEvent* e); - void dropEvent(QDropEvent* e); - void mousePressEvent(QMouseEvent* e); ///< Starts dragging a button... - void paintEvent(QPaintEvent* p); + void resizeEvent(QResizeEvent* e); + void dragEnterEvent(QDragEnterEvent* e); + void dragMoveEvent(QDragMoveEvent* e); + void dragLeaveEvent(QDragLeaveEvent* e); + void dropEvent(QDropEvent* e); + void mousePressEvent(QMouseEvent* e); ///< Starts dragging a button... + void paintEvent(QPaintEvent* p); - signals: - void buttonAdded(QChar btn); - void buttonRemoved(QChar btn); - void changed(); +signals: + void buttonAdded(QChar btn); + void buttonRemoved(QChar btn); + void changed(); - public slots: - bool removeSelectedButton(); ///< This slot is called after we drop on the item listbox... - void recalcItemGeometry(); ///< Call this whenever the item list changes... updates the items' rect property +public slots: + bool removeSelectedButton(); ///< This slot is called after we drop on the item listbox... + void recalcItemGeometry(); ///< Call this whenever the item list changes... updates the items' rect property - protected: - ButtonDropSiteItem *buttonAt(QPoint p); - bool removeButton(ButtonDropSiteItem *item); - int calcButtonListWidth(const ButtonList& buttons); ///< Computes the total space the buttons will take in the titlebar - void drawButtonList(QPainter *p, const ButtonList& buttons, int offset); +protected: + ButtonDropSiteItem *buttonAt(QPoint p); + bool removeButton(ButtonDropSiteItem *item); + int calcButtonListWidth(const ButtonList& buttons); ///< Computes the total space the buttons will take in the titlebar + void drawButtonList(QPainter *p, const ButtonList& buttons, int offset); - QRect leftDropArea(); - QRect rightDropArea(); + QRect leftDropArea(); + QRect rightDropArea(); - private: - /** - * Try to find the item. If found, set its list and index and return true, else return false - */ - bool getItemPos(ButtonDropSiteItem *item, ButtonList* &list, int &pos); +private: + /** + * Try to find the item. If found, set its list and index and return true, else return false + */ + bool getItemPos(ButtonDropSiteItem *item, ButtonList* &list, int &pos); - void cleanDropVisualizer(); - QRect m_oldDropVisualizer; + void cleanDropVisualizer(); + QRect m_oldDropVisualizer; - ButtonDropSiteItem *m_selected; + ButtonDropSiteItem *m_selected; }; class ButtonPositionWidget : public QWidget { - Q_OBJECT + Q_OBJECT - public: - explicit ButtonPositionWidget(QWidget *parent = 0); - ~ButtonPositionWidget(); +public: + explicit ButtonPositionWidget(QWidget *parent = 0); + ~ButtonPositionWidget(); - QString buttonsLeft() const; - QString buttonsRight() const; - void setButtonsLeft(const QString &buttons); - void setButtonsRight(const QString &buttons); + QString buttonsLeft() const; + QString buttonsRight() const; + void setButtonsLeft(const QString &buttons); + void setButtonsRight(const QString &buttons); - signals: - void changed(); +signals: + void changed(); - private: - void clearButtonList(const ButtonList& btns); - Button getButton(QChar type, bool& success); +private: + void clearButtonList(const ButtonList& btns); + Button getButton(QChar type, bool& success); - ButtonDropSite* m_dropSite; - ButtonSource *m_buttonSource; + ButtonDropSite* m_dropSite; + ButtonSource *m_buttonSource; - KDecorationFactory *m_factory; - QString m_supportedButtons; + KDecorationFactory *m_factory; + QString m_supportedButtons; }; } // namespace KWin diff --git a/kcmkwin/kwindecoration/buttonsconfigdialog.cpp b/kcmkwin/kwindecoration/buttonsconfigdialog.cpp index 260fc3a3c..96cee7005 100644 --- a/kcmkwin/kwindecoration/buttonsconfigdialog.cpp +++ b/kcmkwin/kwindecoration/buttonsconfigdialog.cpp @@ -27,86 +27,86 @@ along with this program. If not, see . namespace KWin { -KWinDecorationButtonsConfigForm::KWinDecorationButtonsConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinDecorationButtonsConfigForm::KWinDecorationButtonsConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinDecorationButtonsConfigDialog::KWinDecorationButtonsConfigDialog( bool customPositions, bool showTooltips, QString buttonsLeft, QString buttonsRight, QWidget* parent, Qt::WFlags flags ) - : KDialog( parent, flags ) - , m_customPositions( customPositions ) - , m_showTooltip( showTooltips ) - , m_buttonsLeft( buttonsLeft ) - , m_buttonsRight( buttonsRight ) - { - m_ui = new KWinDecorationButtonsConfigForm( this ); - setWindowTitle( i18n("Buttons") ); - setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default | KDialog::Reset ); - enableButton( KDialog::Reset, false ); +KWinDecorationButtonsConfigDialog::KWinDecorationButtonsConfigDialog(bool customPositions, bool showTooltips, QString buttonsLeft, QString buttonsRight, QWidget* parent, Qt::WFlags flags) + : KDialog(parent, flags) + , m_customPositions(customPositions) + , m_showTooltip(showTooltips) + , m_buttonsLeft(buttonsLeft) + , m_buttonsRight(buttonsRight) +{ + m_ui = new KWinDecorationButtonsConfigForm(this); + setWindowTitle(i18n("Buttons")); + setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default | KDialog::Reset); + enableButton(KDialog::Reset, false); QVBoxLayout* layout = new QVBoxLayout; - layout->addWidget( m_ui ); + layout->addWidget(m_ui); - QWidget* main = new QWidget( this ); - main->setLayout( layout ); - setMainWidget( main ); + QWidget* main = new QWidget(this); + main->setLayout(layout); + setMainWidget(main); - connect( m_ui->buttonPositionWidget, SIGNAL(changed()), this, SLOT(changed())); - connect( m_ui->showToolTipsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( m_ui->useCustomButtonPositionsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( this, SIGNAL(defaultClicked()), this, SLOT(slotDefaultClicked())); - connect( this, SIGNAL(resetClicked()), this, SLOT(slotResetClicked())); + connect(m_ui->buttonPositionWidget, SIGNAL(changed()), this, SLOT(changed())); + connect(m_ui->showToolTipsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->useCustomButtonPositionsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(this, SIGNAL(defaultClicked()), this, SLOT(slotDefaultClicked())); + connect(this, SIGNAL(resetClicked()), this, SLOT(slotResetClicked())); slotResetClicked(); - } +} KWinDecorationButtonsConfigDialog::~KWinDecorationButtonsConfigDialog() - { - } +{ +} bool KWinDecorationButtonsConfigDialog::customPositions() const - { +{ return m_ui->useCustomButtonPositionsCheckBox->isChecked(); - } +} bool KWinDecorationButtonsConfigDialog::showTooltips() const - { +{ return m_ui->showToolTipsCheckBox->isChecked(); - } +} QString KWinDecorationButtonsConfigDialog::buttonsLeft() const - { +{ return m_ui->buttonPositionWidget->buttonsLeft(); - } +} QString KWinDecorationButtonsConfigDialog::buttonsRight() const - { +{ return m_ui->buttonPositionWidget->buttonsRight(); - } +} void KWinDecorationButtonsConfigDialog::changed() - { - enableButton( KDialog::Reset, true ); - } +{ + enableButton(KDialog::Reset, true); +} void KWinDecorationButtonsConfigDialog::slotDefaultClicked() - { - m_ui->useCustomButtonPositionsCheckBox->setChecked( false ); - m_ui->showToolTipsCheckBox->setChecked( true ); - m_ui->buttonPositionWidget->setButtonsLeft( KDecorationOptions::defaultTitleButtonsLeft() ); - m_ui->buttonPositionWidget->setButtonsRight( KDecorationOptions::defaultTitleButtonsRight() ); +{ + m_ui->useCustomButtonPositionsCheckBox->setChecked(false); + m_ui->showToolTipsCheckBox->setChecked(true); + m_ui->buttonPositionWidget->setButtonsLeft(KDecorationOptions::defaultTitleButtonsLeft()); + m_ui->buttonPositionWidget->setButtonsRight(KDecorationOptions::defaultTitleButtonsRight()); changed(); - } +} void KWinDecorationButtonsConfigDialog::slotResetClicked() - { - m_ui->useCustomButtonPositionsCheckBox->setChecked( m_customPositions ); - m_ui->showToolTipsCheckBox->setChecked( m_showTooltip ); - m_ui->buttonPositionWidget->setButtonsLeft( m_buttonsLeft ); - m_ui->buttonPositionWidget->setButtonsRight( m_buttonsRight ); +{ + m_ui->useCustomButtonPositionsCheckBox->setChecked(m_customPositions); + m_ui->showToolTipsCheckBox->setChecked(m_showTooltip); + m_ui->buttonPositionWidget->setButtonsLeft(m_buttonsLeft); + m_ui->buttonPositionWidget->setButtonsRight(m_buttonsRight); changed(); - enableButton( KDialog::Reset, false ); - } + enableButton(KDialog::Reset, false); +} } // namespace KWin diff --git a/kcmkwin/kwindecoration/buttonsconfigdialog.h b/kcmkwin/kwindecoration/buttonsconfigdialog.h index fdeffe48b..f9a334f2d 100644 --- a/kcmkwin/kwindecoration/buttonsconfigdialog.h +++ b/kcmkwin/kwindecoration/buttonsconfigdialog.h @@ -32,33 +32,33 @@ class KWinDecorationButtonsConfigForm : public QWidget, public Ui::KWinDecoratio { Q_OBJECT - public: - explicit KWinDecorationButtonsConfigForm( QWidget* parent ); +public: + explicit KWinDecorationButtonsConfigForm(QWidget* parent); }; class KWinDecorationButtonsConfigDialog : public KDialog { Q_OBJECT - public: - KWinDecorationButtonsConfigDialog( bool customPositions, bool showTooltips, QString buttonsLeft, QString buttonsRight, QWidget* parent = 0, Qt::WFlags flags = 0 ); - ~KWinDecorationButtonsConfigDialog(); +public: + KWinDecorationButtonsConfigDialog(bool customPositions, bool showTooltips, QString buttonsLeft, QString buttonsRight, QWidget* parent = 0, Qt::WFlags flags = 0); + ~KWinDecorationButtonsConfigDialog(); - bool customPositions() const; - bool showTooltips() const; - QString buttonsLeft() const; - QString buttonsRight() const; + bool customPositions() const; + bool showTooltips() const; + QString buttonsLeft() const; + QString buttonsRight() const; - private slots: - void changed(); - void slotDefaultClicked(); - void slotResetClicked(); +private slots: + void changed(); + void slotDefaultClicked(); + void slotResetClicked(); - private: - KWinDecorationButtonsConfigForm* m_ui; - bool m_customPositions; - bool m_showTooltip; - QString m_buttonsLeft; - QString m_buttonsRight; +private: + KWinDecorationButtonsConfigForm* m_ui; + bool m_customPositions; + bool m_showTooltip; + QString m_buttonsLeft; + QString m_buttonsRight; }; } // namespace KWin diff --git a/kcmkwin/kwindecoration/configdialog.cpp b/kcmkwin/kwindecoration/configdialog.cpp index 0defa3d9d..a85c7d1c7 100644 --- a/kcmkwin/kwindecoration/configdialog.cpp +++ b/kcmkwin/kwindecoration/configdialog.cpp @@ -28,139 +28,131 @@ along with this program. If not, see . namespace KWin { -static const char* const border_names[ KDecorationDefines::BordersCount ] = - { - I18N_NOOP2( "@item:inlistbox Border size:", "Tiny" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Normal" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Large" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Very Large" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Huge" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Very Huge" ), - I18N_NOOP2( "@item:inlistbox Border size:", "Oversized" ) - }; +static const char* const border_names[ KDecorationDefines::BordersCount ] = { + I18N_NOOP2("@item:inlistbox Border size:", "Tiny"), + I18N_NOOP2("@item:inlistbox Border size:", "Normal"), + I18N_NOOP2("@item:inlistbox Border size:", "Large"), + I18N_NOOP2("@item:inlistbox Border size:", "Very Large"), + I18N_NOOP2("@item:inlistbox Border size:", "Huge"), + I18N_NOOP2("@item:inlistbox Border size:", "Very Huge"), + I18N_NOOP2("@item:inlistbox Border size:", "Oversized") +}; -KWinAuroraeConfigForm::KWinAuroraeConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinAuroraeConfigForm::KWinAuroraeConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinDecorationConfigForm::KWinDecorationConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinDecorationConfigForm::KWinDecorationConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinDecorationConfigDialog::KWinDecorationConfigDialog( QString deco, const QList& borderSizes, - KDecorationDefines::BorderSize size, - QWidget* parent, Qt::WFlags flags ) - : KDialog( parent, flags ) - , m_borderSizes( borderSizes ) - , m_kwinConfig( KSharedConfig::openConfig( "kwinrc" ) ) - , m_pluginObject( 0 ) - , m_pluginConfigWidget( 0 ) - { - m_ui = new KWinDecorationConfigForm( this ); - setWindowTitle( i18n("Decoration Options") ); - setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default | KDialog::Reset ); - enableButton( KDialog::Reset, false ); +KWinDecorationConfigDialog::KWinDecorationConfigDialog(QString deco, const QList& borderSizes, + KDecorationDefines::BorderSize size, + QWidget* parent, Qt::WFlags flags) + : KDialog(parent, flags) + , m_borderSizes(borderSizes) + , m_kwinConfig(KSharedConfig::openConfig("kwinrc")) + , m_pluginObject(0) + , m_pluginConfigWidget(0) +{ + m_ui = new KWinDecorationConfigForm(this); + setWindowTitle(i18n("Decoration Options")); + setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default | KDialog::Reset); + enableButton(KDialog::Reset, false); QVBoxLayout* layout = new QVBoxLayout; - layout->addWidget( m_ui ); + layout->addWidget(m_ui); - KLibrary library( styleToConfigLib( deco ) ); - if (library.load()) - { + KLibrary library(styleToConfigLib(deco)); + if (library.load()) { KLibrary::void_function_ptr alloc_ptr = library.resolveFunction("allocate_config"); - if (alloc_ptr != NULL) - { - allocatePlugin = (QObject* (*)(KConfigGroup& conf, QWidget* parent))alloc_ptr; - KConfigGroup config( m_kwinConfig, "Style" ); - m_pluginConfigWidget = new KVBox( this ); - m_pluginObject = (QObject*)(allocatePlugin( config, m_pluginConfigWidget )); + if (alloc_ptr != NULL) { + allocatePlugin = (QObject * (*)(KConfigGroup & conf, QWidget * parent))alloc_ptr; + KConfigGroup config(m_kwinConfig, "Style"); + m_pluginConfigWidget = new KVBox(this); + m_pluginObject = (QObject*)(allocatePlugin(config, m_pluginConfigWidget)); // connect required signals and slots together... - connect( this, SIGNAL(accepted()), this, SLOT(slotAccepted()) ); - connect( m_pluginObject, SIGNAL(changed()), this, SLOT(slotSelectionChanged()) ); - connect( this, SIGNAL(pluginSave(KConfigGroup&)), m_pluginObject, SLOT(save(KConfigGroup &)) ); - connect( this, SIGNAL(defaultClicked()), m_pluginObject, SLOT(defaults()) ); - connect( this, SIGNAL(defaultClicked()), SLOT(slotDefault()) ); - } + connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted())); + connect(m_pluginObject, SIGNAL(changed()), this, SLOT(slotSelectionChanged())); + connect(this, SIGNAL(pluginSave(KConfigGroup&)), m_pluginObject, SLOT(save(KConfigGroup &))); + connect(this, SIGNAL(defaultClicked()), m_pluginObject, SLOT(defaults())); + connect(this, SIGNAL(defaultClicked()), SLOT(slotDefault())); } + } - if( m_pluginConfigWidget ) - { - layout->addWidget( m_pluginConfigWidget ); - } + if (m_pluginConfigWidget) { + layout->addWidget(m_pluginConfigWidget); + } - if( borderSizes.count() >= 2 ) - { - foreach( const QVariant& borderSize, borderSizes ) - { + if (borderSizes.count() >= 2) { + foreach (const QVariant & borderSize, borderSizes) { KDecorationDefines::BorderSize currentSize = - static_cast( borderSize.toInt() ); - m_ui->bordersCombo->addItem(i18nc("@item:inlistbox Border size:", border_names[currentSize]), borderSizeToIndex(currentSize, borderSizes) ); - } - m_ui->bordersCombo->setCurrentIndex( borderSizeToIndex( size, borderSizes ) ); + static_cast(borderSize.toInt()); + m_ui->bordersCombo->addItem(i18nc("@item:inlistbox Border size:", border_names[currentSize]), borderSizeToIndex(currentSize, borderSizes)); } - else - { + m_ui->bordersCombo->setCurrentIndex(borderSizeToIndex(size, borderSizes)); + } else { m_ui->bordersCombo->hide(); m_ui->borderLabel->hide(); - } - - QWidget* main = new QWidget( this ); - main->setLayout( layout ); - setMainWidget( main ); } + QWidget* main = new QWidget(this); + main->setLayout(layout); + setMainWidget(main); +} + KWinDecorationConfigDialog::~KWinDecorationConfigDialog() - { +{ delete m_pluginObject; - } +} KDecorationDefines::BorderSize KWinDecorationConfigDialog::borderSize() const - { - if( m_borderSizes.count() >= 2 ) - return (KDecorationDefines::BorderSize)m_borderSizes.at( m_ui->bordersCombo->currentIndex() ).toInt(); +{ + if (m_borderSizes.count() >= 2) + return (KDecorationDefines::BorderSize)m_borderSizes.at(m_ui->bordersCombo->currentIndex()).toInt(); return KDecorationDefines::BorderNormal; - } +} -int KWinDecorationConfigDialog::borderSizeToIndex( KDecorationDefines::BorderSize size, const QList< QVariant >& sizes ) - { +int KWinDecorationConfigDialog::borderSizeToIndex(KDecorationDefines::BorderSize size, const QList< QVariant >& sizes) +{ int pos = 0; - for( QList< QVariant >::ConstIterator it = sizes.constBegin(); + for (QList< QVariant >::ConstIterator it = sizes.constBegin(); it != sizes.constEnd(); - ++it, ++pos ) - if( size <= (*it).toInt() ) + ++it, ++pos) + if (size <= (*it).toInt()) break; return pos; - } +} void KWinDecorationConfigDialog::slotAccepted() - { - KConfigGroup config( m_kwinConfig, "Style" ); - emit pluginSave( config ); +{ + KConfigGroup config(m_kwinConfig, "Style"); + emit pluginSave(config); config.sync(); - } +} void KWinDecorationConfigDialog::slotSelectionChanged() - { - enableButton( KDialog::Reset, true ); - } +{ + enableButton(KDialog::Reset, true); +} -QString KWinDecorationConfigDialog::styleToConfigLib( const QString& styleLib ) const - { - if( styleLib.startsWith( QLatin1String( "kwin3_" ))) - return "kwin_" + styleLib.mid( 6 ) + "_config"; +QString KWinDecorationConfigDialog::styleToConfigLib(const QString& styleLib) const +{ + if (styleLib.startsWith(QLatin1String("kwin3_"))) + return "kwin_" + styleLib.mid(6) + "_config"; else return styleLib + "_config"; - } +} void KWinDecorationConfigDialog::slotDefault() - { - if( m_borderSizes.count() >= 2 ) - m_ui->bordersCombo->setCurrentIndex( borderSizeToIndex( BorderNormal, m_borderSizes ) ); - } +{ + if (m_borderSizes.count() >= 2) + m_ui->bordersCombo->setCurrentIndex(borderSizeToIndex(BorderNormal, m_borderSizes)); +} } // namespace KWin diff --git a/kcmkwin/kwindecoration/configdialog.h b/kcmkwin/kwindecoration/configdialog.h index 8fa3cb04a..f07befc80 100644 --- a/kcmkwin/kwindecoration/configdialog.h +++ b/kcmkwin/kwindecoration/configdialog.h @@ -32,49 +32,49 @@ class KWinAuroraeConfigForm : public QWidget, public Ui::KWinAuroraeConfigForm { Q_OBJECT - public: - explicit KWinAuroraeConfigForm( QWidget* parent ); +public: + explicit KWinAuroraeConfigForm(QWidget* parent); }; class KWinDecorationConfigForm : public QWidget, public Ui::KWinDecorationConfigForm { Q_OBJECT - public: - explicit KWinDecorationConfigForm( QWidget* parent ); +public: + explicit KWinDecorationConfigForm(QWidget* parent); }; class KWinDecorationConfigDialog : public KDialog, public KDecorationDefines { Q_OBJECT - public: - KWinDecorationConfigDialog( QString decoLib, const QList& borderSizes, - KDecorationDefines::BorderSize size, QWidget* parent = 0, - Qt::WFlags flags = 0 ); - ~KWinDecorationConfigDialog(); +public: + KWinDecorationConfigDialog(QString decoLib, const QList& borderSizes, + KDecorationDefines::BorderSize size, QWidget* parent = 0, + Qt::WFlags flags = 0); + ~KWinDecorationConfigDialog(); KDecorationDefines::BorderSize borderSize() const; - signals: - void pluginSave( KConfigGroup& group ); +signals: + void pluginSave(KConfigGroup& group); - private slots: - void slotSelectionChanged(); - void slotAccepted(); - void slotDefault(); +private slots: + void slotSelectionChanged(); + void slotAccepted(); + void slotDefault(); - private: - int borderSizeToIndex( KDecorationDefines::BorderSize size, const QList& sizes ); - QString styleToConfigLib( const QString& styleLib ) const; +private: + int borderSizeToIndex(KDecorationDefines::BorderSize size, const QList& sizes); + QString styleToConfigLib(const QString& styleLib) const; - private: - KWinDecorationConfigForm* m_ui; - QList m_borderSizes; - KSharedConfigPtr m_kwinConfig; +private: + KWinDecorationConfigForm* m_ui; + QList m_borderSizes; + KSharedConfigPtr m_kwinConfig; - QObject* (*allocatePlugin)( KConfigGroup& conf, QWidget* parent ); - QObject* m_pluginObject; - QWidget* m_pluginConfigWidget; + QObject*(*allocatePlugin)(KConfigGroup& conf, QWidget* parent); + QObject* m_pluginObject; + QWidget* m_pluginConfigWidget; }; } // namespace KWin diff --git a/kcmkwin/kwindecoration/decorationdelegate.cpp b/kcmkwin/kwindecoration/decorationdelegate.cpp index dbfe7fb44..d0712de06 100644 --- a/kcmkwin/kwindecoration/decorationdelegate.cpp +++ b/kcmkwin/kwindecoration/decorationdelegate.cpp @@ -28,37 +28,35 @@ namespace KWin const int margin = 5; -DecorationDelegate::DecorationDelegate( QObject* parent ) - : QStyledItemDelegate( parent ) - { - } +DecorationDelegate::DecorationDelegate(QObject* parent) + : QStyledItemDelegate(parent) +{ +} DecorationDelegate::~DecorationDelegate() - { - } +{ +} -void DecorationDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const - { +void DecorationDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +{ // highlight selected item - QApplication::style()->drawControl( QStyle::CE_ItemViewItem, &option, painter ); + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &option, painter); - QPixmap pixmap = index.model()->data( index, DecorationModel::PixmapRole ).value(); + QPixmap pixmap = index.model()->data(index, DecorationModel::PixmapRole).value(); - const QSize previewArea = option.rect.size() - QSize( 2*margin, 2*margin ); - if( pixmap.isNull() || pixmap.size() != previewArea ) - { - emit regeneratePreview( static_cast< const QSortFilterProxyModel* >( index.model() )->mapToSource( index ), - previewArea ); - } - else - painter->drawPixmap( option.rect.topLeft() + QPoint( margin, margin ), pixmap ); - } + const QSize previewArea = option.rect.size() - QSize(2 * margin, 2 * margin); + if (pixmap.isNull() || pixmap.size() != previewArea) { + emit regeneratePreview(static_cast< const QSortFilterProxyModel* >(index.model())->mapToSource(index), + previewArea); + } else + painter->drawPixmap(option.rect.topLeft() + QPoint(margin, margin), pixmap); +} -QSize DecorationDelegate::sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const - { - Q_UNUSED( option ) - Q_UNUSED( index ) - return QSize( 450, 150 ); - } +QSize DecorationDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + Q_UNUSED(option) + Q_UNUSED(index) + return QSize(450, 150); +} } // namespace KWin diff --git a/kcmkwin/kwindecoration/decorationdelegate.h b/kcmkwin/kwindecoration/decorationdelegate.h index 6e883b9d0..e849d9f41 100644 --- a/kcmkwin/kwindecoration/decorationdelegate.h +++ b/kcmkwin/kwindecoration/decorationdelegate.h @@ -29,15 +29,15 @@ namespace KWin class DecorationDelegate : public QStyledItemDelegate { Q_OBJECT - public: - DecorationDelegate( QObject* parent = 0 ); - ~DecorationDelegate(); +public: + DecorationDelegate(QObject* parent = 0); + ~DecorationDelegate(); - virtual void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const; - virtual QSize sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const; + virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + virtual QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; - signals: - void regeneratePreview( const QModelIndex& index, const QSize& size ) const; +signals: + void regeneratePreview(const QModelIndex& index, const QSize& size) const; }; } // namespace KWin diff --git a/kcmkwin/kwindecoration/decorationmodel.cpp b/kcmkwin/kwindecoration/decorationmodel.cpp index 580352dc3..d211dc4c6 100644 --- a/kcmkwin/kwindecoration/decorationmodel.cpp +++ b/kcmkwin/kwindecoration/decorationmodel.cpp @@ -41,377 +41,356 @@ along with this program. If not, see . namespace KWin { -DecorationModel::DecorationModel( KSharedConfigPtr config, QObject* parent ) - : QAbstractListModel( parent ) - , m_plugins( new KDecorationPreviewPlugins( config ) ) - , m_preview( new KDecorationPreview() ) - , m_customButtons( false ) - , m_leftButtons( QString() ) - , m_rightButtons( QString() ) - , m_theme( new Aurorae::AuroraeTheme( this ) ) - , m_scene( new Aurorae::AuroraeScene( m_theme, QString(), QString(), true, this ) ) - , m_renderWidget( new QWidget( 0 ) ) - { - m_config = KSharedConfig::openConfig( "auroraerc" ); - m_scene->setIcon( KIcon( "xorg" ) ); +DecorationModel::DecorationModel(KSharedConfigPtr config, QObject* parent) + : QAbstractListModel(parent) + , m_plugins(new KDecorationPreviewPlugins(config)) + , m_preview(new KDecorationPreview()) + , m_customButtons(false) + , m_leftButtons(QString()) + , m_rightButtons(QString()) + , m_theme(new Aurorae::AuroraeTheme(this)) + , m_scene(new Aurorae::AuroraeScene(m_theme, QString(), QString(), true, this)) + , m_renderWidget(new QWidget(0)) +{ + m_config = KSharedConfig::openConfig("auroraerc"); + m_scene->setIcon(KIcon("xorg")); findDecorations(); - } +} DecorationModel::~DecorationModel() - { +{ delete m_preview; delete m_plugins; delete m_renderWidget; - } +} void DecorationModel::reload() - { +{ m_decorations.clear(); findDecorations(); - } +} // Find all theme desktop files in all 'data' dirs owned by kwin. // And insert these into a DecorationInfo structure void DecorationModel::findDecorations() - { +{ beginResetModel(); const QStringList dirList = KGlobal::dirs()->findDirs("data", "kwin"); - foreach( const QString &dir, dirList ) - { - QDir d( dir ); - if( d.exists() ) - { - foreach( const QFileInfo& fi, d.entryInfoList() ) - { - const QString filename( fi.absoluteFilePath() ); - if( KDesktopFile::isDesktopFile(filename) ) - { - const KDesktopFile desktopFile( filename ); - const QString libName = desktopFile.desktopGroup().readEntry( "X-KDE-Library" ); + foreach (const QString & dir, dirList) { + QDir d(dir); + if (d.exists()) { + foreach (const QFileInfo & fi, d.entryInfoList()) { + const QString filename(fi.absoluteFilePath()); + if (KDesktopFile::isDesktopFile(filename)) { + const KDesktopFile desktopFile(filename); + const QString libName = desktopFile.desktopGroup().readEntry("X-KDE-Library"); - if( !libName.isEmpty() && libName.startsWith( QLatin1String( "kwin3_" ) ) ) - { - if( libName == "kwin3_aurorae" ) - { + if (!libName.isEmpty() && libName.startsWith(QLatin1String("kwin3_"))) { + if (libName == "kwin3_aurorae") { // read the Aurorae themes findAuroraeThemes(); continue; - } + } DecorationModelData data; data.name = desktopFile.readName(); data.libraryName = libName; data.type = DecorationModelData::NativeDecoration; data.borderSize = KDecorationDefines::BorderNormal; - metaData( data, desktopFile ); + metaData(data, desktopFile); m_decorations.append(data); - } } } } } - qSort( m_decorations.begin(), m_decorations.end(), DecorationModelData::less ); - endResetModel(); } + qSort(m_decorations.begin(), m_decorations.end(), DecorationModelData::less); + endResetModel(); +} void DecorationModel::findAuroraeThemes() - { +{ // get all desktop themes QStringList themes = KGlobal::dirs()->findAllResources("data", - "aurorae/themes/*/metadata.desktop", - KStandardDirs::NoDuplicates); - foreach(const QString &theme, themes) - { - int themeSepIndex = theme.lastIndexOf( '/', -1 ); - QString themeRoot = theme.left( themeSepIndex ); - int themeNameSepIndex = themeRoot.lastIndexOf( '/', -1 ); - QString packageName = themeRoot.right( themeRoot.length() - themeNameSepIndex - 1 ); + "aurorae/themes/*/metadata.desktop", + KStandardDirs::NoDuplicates); + foreach (const QString & theme, themes) { + int themeSepIndex = theme.lastIndexOf('/', -1); + QString themeRoot = theme.left(themeSepIndex); + int themeNameSepIndex = themeRoot.lastIndexOf('/', -1); + QString packageName = themeRoot.right(themeRoot.length() - themeNameSepIndex - 1); - KDesktopFile df( theme ); + KDesktopFile df(theme); QString name = df.readName(); - if( name.isEmpty() ) - { + if (name.isEmpty()) { name = packageName; - } + } DecorationModelData data; data.name = name; data.libraryName = "kwin3_aurorae"; data.type = DecorationModelData::AuroraeDecoration; data.auroraeName = packageName; - KConfigGroup config( m_config, data.auroraeName ); - data.borderSize = (KDecorationDefines::BorderSize)config.readEntry< int >( "BorderSize", KDecorationDefines::BorderNormal ); - data.buttonSize = (KDecorationDefines::BorderSize)config.readEntry< int >( "ButtonSize", KDecorationDefines::BorderNormal ); - metaData( data, df ); + KConfigGroup config(m_config, data.auroraeName); + data.borderSize = (KDecorationDefines::BorderSize)config.readEntry< int >("BorderSize", KDecorationDefines::BorderNormal); + data.buttonSize = (KDecorationDefines::BorderSize)config.readEntry< int >("ButtonSize", KDecorationDefines::BorderNormal); + metaData(data, df); m_decorations.append(data); - } } +} -void DecorationModel::metaData( DecorationModelData& data, const KDesktopFile& df ) - { +void DecorationModel::metaData(DecorationModelData& data, const KDesktopFile& df) +{ data.comment = df.readComment(); - data.author = df.desktopGroup().readEntry( "X-KDE-PluginInfo-Author", QString() ); - data.email = df.desktopGroup().readEntry( "X-KDE-PluginInfo-Email", QString() ); - data.version = df.desktopGroup().readEntry( "X-KDE-PluginInfo-Version", QString() ); - data.license = df.desktopGroup().readEntry( "X-KDE-PluginInfo-License", QString() ); - data.website = df.desktopGroup().readEntry( "X-KDE-PluginInfo-Website", QString() ); - } + data.author = df.desktopGroup().readEntry("X-KDE-PluginInfo-Author", QString()); + data.email = df.desktopGroup().readEntry("X-KDE-PluginInfo-Email", QString()); + data.version = df.desktopGroup().readEntry("X-KDE-PluginInfo-Version", QString()); + data.license = df.desktopGroup().readEntry("X-KDE-PluginInfo-License", QString()); + data.website = df.desktopGroup().readEntry("X-KDE-PluginInfo-Website", QString()); +} -int DecorationModel::rowCount( const QModelIndex& parent ) const - { - Q_UNUSED( parent ) +int DecorationModel::rowCount(const QModelIndex& parent) const +{ + Q_UNUSED(parent) return m_decorations.count(); - } +} -QVariant DecorationModel::data( const QModelIndex& index, int role ) const - { - if( !index.isValid() ) +QVariant DecorationModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid()) return QVariant(); - switch( role ) - { - case Qt::DisplayRole: - case NameRole: - return m_decorations[ index.row() ].name; - case LibraryNameRole: - return m_decorations[ index.row() ].libraryName; - case PixmapRole: - return m_decorations[ index.row() ].preview; - case TypeRole: - return m_decorations[ index.row() ].type; - case AuroraeNameRole: - return m_decorations[ index.row() ].auroraeName; - case PackageDescriptionRole: - return m_decorations[ index.row() ].comment; - case PackageAuthorRole: - return m_decorations[ index.row() ].author; - case PackageEmailRole: - return m_decorations[ index.row() ].email; - case PackageWebsiteRole: - return m_decorations[ index.row() ].website; - case PackageVersionRole: - return m_decorations[ index.row() ].version; - case PackageLicenseRole: - return m_decorations[ index.row() ].license; - case BorderSizeRole: - return static_cast< int >( m_decorations[ index.row() ].borderSize ); - case BorderSizesRole: - { - QList< QVariant > sizes; - if( m_plugins->loadPlugin( m_decorations[ index.row() ].libraryName ) && - m_plugins->factory() != NULL ) - { - foreach( KDecorationDefines::BorderSize size, m_plugins->factory()->borderSizes() ) // krazy:exclude=foreach - sizes << int(size) ; - } - return sizes; - } - case ButtonSizeRole: - if( m_decorations[ index.row() ].type == DecorationModelData::AuroraeDecoration ) - return static_cast< int >( m_decorations[ index.row() ].buttonSize ); - else - return QVariant(); - default: - return QVariant(); + switch(role) { + case Qt::DisplayRole: + case NameRole: + return m_decorations[ index.row()].name; + case LibraryNameRole: + return m_decorations[ index.row()].libraryName; + case PixmapRole: + return m_decorations[ index.row()].preview; + case TypeRole: + return m_decorations[ index.row()].type; + case AuroraeNameRole: + return m_decorations[ index.row()].auroraeName; + case PackageDescriptionRole: + return m_decorations[ index.row()].comment; + case PackageAuthorRole: + return m_decorations[ index.row()].author; + case PackageEmailRole: + return m_decorations[ index.row()].email; + case PackageWebsiteRole: + return m_decorations[ index.row()].website; + case PackageVersionRole: + return m_decorations[ index.row()].version; + case PackageLicenseRole: + return m_decorations[ index.row()].license; + case BorderSizeRole: + return static_cast< int >(m_decorations[ index.row()].borderSize); + case BorderSizesRole: { + QList< QVariant > sizes; + if (m_plugins->loadPlugin(m_decorations[ index.row()].libraryName) && + m_plugins->factory() != NULL) { + foreach (KDecorationDefines::BorderSize size, m_plugins->factory()->borderSizes()) // krazy:exclude=foreach + sizes << int(size) ; } + return sizes; } + case ButtonSizeRole: + if (m_decorations[ index.row()].type == DecorationModelData::AuroraeDecoration) + return static_cast< int >(m_decorations[ index.row()].buttonSize); + else + return QVariant(); + default: + return QVariant(); + } +} bool DecorationModel::setData(const QModelIndex& index, const QVariant& value, int role) - { - if( !index.isValid() || ( role != BorderSizeRole && role != ButtonSizeRole ) ) - return QAbstractItemModel::setData( index, value, role ); +{ + if (!index.isValid() || (role != BorderSizeRole && role != ButtonSizeRole)) + return QAbstractItemModel::setData(index, value, role); - if( role == BorderSizeRole ) - { - m_decorations[ index.row() ].borderSize = (KDecorationDefines::BorderSize)value.toInt(); - if( m_decorations[ index.row() ].type == DecorationModelData::AuroraeDecoration ) - { - KConfigGroup config( m_config, m_decorations[ index.row() ].auroraeName ); - config.writeEntry( "BorderSize", value.toInt() ); + if (role == BorderSizeRole) { + m_decorations[ index.row()].borderSize = (KDecorationDefines::BorderSize)value.toInt(); + if (m_decorations[ index.row()].type == DecorationModelData::AuroraeDecoration) { + KConfigGroup config(m_config, m_decorations[ index.row()].auroraeName); + config.writeEntry("BorderSize", value.toInt()); config.sync(); - } - emit dataChanged( index, index ); - regeneratePreview( index ); - return true; } - if( role == ButtonSizeRole && m_decorations[ index.row() ].type == DecorationModelData::AuroraeDecoration ) - { - m_decorations[ index.row() ].buttonSize = (KDecorationDefines::BorderSize)value.toInt(); - KConfigGroup config( m_config, m_decorations[ index.row() ].auroraeName ); - config.writeEntry( "ButtonSize", value.toInt() ); - config.sync(); - emit dataChanged( index, index ); - regeneratePreview( index ); + emit dataChanged(index, index); + regeneratePreview(index); return true; - } - return QAbstractItemModel::setData( index, value, role ); } + if (role == ButtonSizeRole && m_decorations[ index.row()].type == DecorationModelData::AuroraeDecoration) { + m_decorations[ index.row()].buttonSize = (KDecorationDefines::BorderSize)value.toInt(); + KConfigGroup config(m_config, m_decorations[ index.row()].auroraeName); + config.writeEntry("ButtonSize", value.toInt()); + config.sync(); + emit dataChanged(index, index); + regeneratePreview(index); + return true; + } + return QAbstractItemModel::setData(index, value, role); +} -void DecorationModel::changeButtons( bool custom, const QString& left, const QString& right ) - { +void DecorationModel::changeButtons(bool custom, const QString& left, const QString& right) +{ bool regenerate = (custom != m_customButtons); - if( !regenerate && custom ) + if (!regenerate && custom) regenerate = (left != m_leftButtons) || (right != m_rightButtons); m_customButtons = custom; m_leftButtons = left; m_rightButtons = right; - if( regenerate ) + if (regenerate) regeneratePreviews(); - } +} void DecorationModel::setButtons(bool custom, const QString& left, const QString& right) - { +{ m_customButtons = custom; m_leftButtons = left; m_rightButtons = right; - } +} void DecorationModel::regeneratePreviews() - { +{ QList::iterator it = m_decorations.begin(); - for( int i=0; i%1" ).arg( data.name ); + QString html = QString("%1").arg(data.name); - if( !data.author.isEmpty() ) - { - QString authorCaption = i18nc( "Caption to decoration preview, %1 author name", - "by %1", data.author ); + if (!data.author.isEmpty()) { + QString authorCaption = i18nc("Caption to decoration preview, %1 author name", + "by %1", data.author); - html += QString( "
%2" ) - .arg( KGlobalSettings::smallestReadableFont().pointSize() ) - .arg( authorCaption ); - } + html += QString("
%2") + .arg(KGlobalSettings::smallestReadableFont().pointSize()) + .arg(authorCaption); + } - QColor color = QApplication::palette().brush( QPalette::Text ).color(); - html = QString( "
%2
" ).arg( color.name() ).arg( html ); + QColor color = QApplication::palette().brush(QPalette::Text).color(); + html = QString("
%2
").arg(color.name()).arg(html); - document.setHtml( html ); + document.setHtml(html); const int margin = 5; - switch( data.type ) - { - case DecorationModelData::NativeDecoration: - m_plugins->reset( KDecoration::SettingDecoration ); - if ( m_plugins->loadPlugin( data.libraryName ) && - m_preview->recreateDecoration( m_plugins ) ) - m_preview->enablePreview(); - else - m_preview->disablePreview(); - m_plugins->destroyPreviousPlugin(); - m_preview->resize( size ); - m_preview->setTempButtons( m_plugins, m_customButtons, m_leftButtons, m_rightButtons ); - m_preview->setTempBorderSize( m_plugins, data.borderSize ); - data.preview = m_preview->preview( &document, m_renderWidget ); - break; - case DecorationModelData::AuroraeDecoration: - { - QPixmap pix( size ); - pix.fill( Qt::transparent ); - KConfig conf( "aurorae/themes/" + data.auroraeName + '/' + data.auroraeName + "rc", KConfig::FullConfig, "data" ); - m_theme->loadTheme( data.auroraeName, conf ); - m_theme->setBorderSize( data.borderSize ); - m_theme->setButtonSize( data.buttonSize ); - m_scene->setButtons( m_customButtons ? m_leftButtons : m_theme->defaultButtonsLeft(), - m_customButtons ? m_rightButtons : m_theme->defaultButtonsRight()); - int left, top, right, bottom; - m_theme->borders( left, top, right, bottom, false ); - int padLeft, padRight, padTop, padBottom; - m_theme->padding( padLeft, padTop, padRight, padBottom ); - top = qMin( int( top * .9 ), 30 ); - int xoffset = qMin( qMax( 10, QApplication::isRightToLeft() ? left : right ), 30 ); - m_scene->setSceneRect( 0, 0 , - size.width() - xoffset - 20 + padLeft + padRight, - size.height() - top - 20 + padLeft + padRight ); - m_scene->setActive( false, false ); - m_scene->addTab( i18n( "Inactive Window" ) ); - m_scene->updateLayout(); - QPainter painter( &pix ); - QRect rect = QRectF( QPointF( 10 + xoffset - padLeft, 10 - padTop ), m_scene->sceneRect().size() ).toRect(); - m_scene->render( &painter, QStyle::visualRect( QApplication::layoutDirection(), pix.rect(), rect )); - m_scene->setActive( true, false ); - m_scene->setCaption( i18n( "Active Window" ) ); - rect = QRectF( QPointF( 10 - padLeft, top + 10 - padTop ), m_scene->sceneRect().size() ).toRect(); - m_scene->render( &painter, QStyle::visualRect( QApplication::layoutDirection(), pix.rect(), rect )); + switch(data.type) { + case DecorationModelData::NativeDecoration: + m_plugins->reset(KDecoration::SettingDecoration); + if (m_plugins->loadPlugin(data.libraryName) && + m_preview->recreateDecoration(m_plugins)) + m_preview->enablePreview(); + else + m_preview->disablePreview(); + m_plugins->destroyPreviousPlugin(); + m_preview->resize(size); + m_preview->setTempButtons(m_plugins, m_customButtons, m_leftButtons, m_rightButtons); + m_preview->setTempBorderSize(m_plugins, data.borderSize); + data.preview = m_preview->preview(&document, m_renderWidget); + break; + case DecorationModelData::AuroraeDecoration: { + QPixmap pix(size); + pix.fill(Qt::transparent); + KConfig conf("aurorae/themes/" + data.auroraeName + '/' + data.auroraeName + "rc", KConfig::FullConfig, "data"); + m_theme->loadTheme(data.auroraeName, conf); + m_theme->setBorderSize(data.borderSize); + m_theme->setButtonSize(data.buttonSize); + m_scene->setButtons(m_customButtons ? m_leftButtons : m_theme->defaultButtonsLeft(), + m_customButtons ? m_rightButtons : m_theme->defaultButtonsRight()); + int left, top, right, bottom; + m_theme->borders(left, top, right, bottom, false); + int padLeft, padRight, padTop, padBottom; + m_theme->padding(padLeft, padTop, padRight, padBottom); + top = qMin(int(top * .9), 30); + int xoffset = qMin(qMax(10, QApplication::isRightToLeft() ? left : right), 30); + m_scene->setSceneRect(0, 0 , + size.width() - xoffset - 20 + padLeft + padRight, + size.height() - top - 20 + padLeft + padRight); + m_scene->setActive(false, false); + m_scene->addTab(i18n("Inactive Window")); + m_scene->updateLayout(); + QPainter painter(&pix); + QRect rect = QRectF(QPointF(10 + xoffset - padLeft, 10 - padTop), m_scene->sceneRect().size()).toRect(); + m_scene->render(&painter, QStyle::visualRect(QApplication::layoutDirection(), pix.rect(), rect)); + m_scene->setActive(true, false); + m_scene->setCaption(i18n("Active Window")); + rect = QRectF(QPointF(10 - padLeft, top + 10 - padTop), m_scene->sceneRect().size()).toRect(); + m_scene->render(&painter, QStyle::visualRect(QApplication::layoutDirection(), pix.rect(), rect)); - const int width = rect.width() - left - right - padLeft - padRight; - const int height = rect.height() - top - bottom -padTop - padBottom; - m_renderWidget->setGeometry( 0, 0, width, height ); - painter.save(); - const QPoint topLeft = QStyle::visualRect( QApplication::layoutDirection(), pix.rect(), rect ).topLeft() + - QPoint( left + padLeft, top + padTop ); - m_renderWidget->render( &painter, topLeft ); - painter.restore(); - //Enable word-wrap - document.setTextWidth( width - margin * 2 ); - painter.save(); - painter.translate( topLeft ); - document.drawContents( &painter, QRectF( margin, margin, width - margin * 2, height - margin * 2 )); - painter.restore(); - data.preview = pix; - break; - } - default: - // nothing - break; - } - emit dataChanged( index, index ); + const int width = rect.width() - left - right - padLeft - padRight; + const int height = rect.height() - top - bottom - padTop - padBottom; + m_renderWidget->setGeometry(0, 0, width, height); + painter.save(); + const QPoint topLeft = QStyle::visualRect(QApplication::layoutDirection(), pix.rect(), rect).topLeft() + + QPoint(left + padLeft, top + padTop); + m_renderWidget->render(&painter, topLeft); + painter.restore(); + //Enable word-wrap + document.setTextWidth(width - margin * 2); + painter.save(); + painter.translate(topLeft); + document.drawContents(&painter, QRectF(margin, margin, width - margin * 2, height - margin * 2)); + painter.restore(); + data.preview = pix; + break; } - -void DecorationModel::regeneratePreview( const QModelIndex& index ) - { - regeneratePreview( index, m_decorations.at( index.row() ).preview.size() ); + default: + // nothing + break; } + emit dataChanged(index, index); +} -QModelIndex DecorationModel::indexOfLibrary( const QString& libraryName ) const - { - for( int i=0; i m_decorations; - KDecorationPlugins* m_plugins; - KDecorationPreview* m_preview; - bool m_customButtons; - QString m_leftButtons; - QString m_rightButtons; - Aurorae::AuroraeTheme* m_theme; - Aurorae::AuroraeScene* m_scene; - KSharedConfigPtr m_config; - QWidget* m_renderWidget; +private: + void findDecorations(); + void findAuroraeThemes(); + void regeneratePreviews(); + void metaData(DecorationModelData& data, const KDesktopFile& df); + QList m_decorations; + KDecorationPlugins* m_plugins; + KDecorationPreview* m_preview; + bool m_customButtons; + QString m_leftButtons; + QString m_rightButtons; + Aurorae::AuroraeTheme* m_theme; + Aurorae::AuroraeScene* m_scene; + KSharedConfigPtr m_config; + QWidget* m_renderWidget; }; } // namespace KWin diff --git a/kcmkwin/kwindecoration/kwindecoration.cpp b/kcmkwin/kwindecoration/kwindecoration.cpp index 9927053ef..8c8ae6144 100644 --- a/kcmkwin/kwindecoration/kwindecoration.cpp +++ b/kcmkwin/kwindecoration/kwindecoration.cpp @@ -46,62 +46,62 @@ // KCModule plugin interface // ========================= K_PLUGIN_FACTORY(KWinDecoFactory, - registerPlugin(); - ) + registerPlugin(); + ) K_EXPORT_PLUGIN(KWinDecoFactory("kcmkwindecoration")) namespace KWin { -KWinDecorationForm::KWinDecorationForm( QWidget* parent ) - : QWidget( parent ) +KWinDecorationForm::KWinDecorationForm(QWidget* parent) + : QWidget(parent) { - setupUi( this ); + setupUi(this); } KWinDecorationModule::KWinDecorationModule(QWidget* parent, const QVariantList &) : KCModule(KWinDecoFactory::componentData(), parent) , kwinConfig(KSharedConfig::openConfig("kwinrc")) - , m_showTooltips( false ) - , m_customPositions( false ) - , m_leftButtons( QString() ) - , m_rightButtons( QString() ) - , m_configLoaded( false ) + , m_showTooltips(false) + , m_customPositions(false) + , m_leftButtons(QString()) + , m_rightButtons(QString()) + , m_configLoaded(false) { - m_ui = new KWinDecorationForm( this ); - DecorationDelegate* delegate = new DecorationDelegate( this ); - m_ui->decorationList->setItemDelegate( delegate ); - m_ui->configureDecorationButton->setIcon( KIcon( "configure" ) ); - m_ui->configureButtonsButton->setIcon( KIcon( "configure" ) ); - m_ui->ghnsButton->setIcon( KIcon( "get-hot-new-stuff" ) ); - QVBoxLayout* layout = new QVBoxLayout( this ); - layout->addWidget( m_ui ); + m_ui = new KWinDecorationForm(this); + DecorationDelegate* delegate = new DecorationDelegate(this); + m_ui->decorationList->setItemDelegate(delegate); + m_ui->configureDecorationButton->setIcon(KIcon("configure")); + m_ui->configureButtonsButton->setIcon(KIcon("configure")); + m_ui->ghnsButton->setIcon(KIcon("get-hot-new-stuff")); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_ui); - KConfigGroup style( kwinConfig, "Style"); + KConfigGroup style(kwinConfig, "Style"); // Set up the decoration lists and other UI settings - m_model = new DecorationModel( kwinConfig, this ); - m_proxyModel = new QSortFilterProxyModel( this ); - m_proxyModel->setSourceModel( m_model ); - m_proxyModel->setFilterCaseSensitivity( Qt::CaseInsensitive ); - m_ui->decorationList->setModel( m_proxyModel ); + m_model = new DecorationModel(kwinConfig, this); + m_proxyModel = new QSortFilterProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); + m_ui->decorationList->setModel(m_proxyModel); - readConfig( style ); + readConfig(style); - connect( m_ui->decorationList->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(slotSelectionChanged()) ); - connect( m_ui->configureButtonsButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureButtons())); - connect( m_ui->ghnsButton, SIGNAL(clicked(bool)), SLOT(slotGHNSClicked()) ); - connect( m_ui->searchEdit, SIGNAL(textChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString))); - connect( delegate, SIGNAL(regeneratePreview(QModelIndex,QSize)), - m_model, SLOT(regeneratePreview(QModelIndex,QSize))); - connect( m_ui->configureDecorationButton, SIGNAL(clicked(bool)), SLOT(slotConfigureDecoration())); + connect(m_ui->decorationList->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(slotSelectionChanged())); + connect(m_ui->configureButtonsButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureButtons())); + connect(m_ui->ghnsButton, SIGNAL(clicked(bool)), SLOT(slotGHNSClicked())); + connect(m_ui->searchEdit, SIGNAL(textChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString))); + connect(delegate, SIGNAL(regeneratePreview(QModelIndex, QSize)), + m_model, SLOT(regeneratePreview(QModelIndex, QSize))); + connect(m_ui->configureDecorationButton, SIGNAL(clicked(bool)), SLOT(slotConfigureDecoration())); KAboutData *about = - new KAboutData(I18N_NOOP("kcmkwindecoration"), 0, - ki18n("Window Decoration Control Module"), - 0, KLocalizedString(), KAboutData::License_GPL, - ki18n("(c) 2001 Karol Szwed")); + new KAboutData(I18N_NOOP("kcmkwindecoration"), 0, + ki18n("Window Decoration Control Module"), + 0, KLocalizedString(), KAboutData::License_GPL, + ki18n("(c) 2001 Karol Szwed")); about->addAuthor(ki18n("Karol Szwed"), KLocalizedString(), "gallium@kde.org"); setAboutData(about); } @@ -119,45 +119,40 @@ void KWinDecorationModule::slotSelectionChanged() // Reads the kwin config settings, and sets all UI controls to those settings // Updating the config plugin if required -void KWinDecorationModule::readConfig( const KConfigGroup & conf ) +void KWinDecorationModule::readConfig(const KConfigGroup & conf) { m_showTooltips = conf.readEntry("ShowToolTips", true); // Find the corresponding decoration name to that of // the current plugin library name - QString libraryName = conf.readEntry("PluginLib", - ((QPixmap::defaultDepth() > 8) ? "kwin3_oxygen" : "kwin3_plastik")); + QString libraryName = conf.readEntry("PluginLib", + ((QPixmap::defaultDepth() > 8) ? "kwin3_oxygen" : "kwin3_plastik")); - if( libraryName.isEmpty() ) - { // Selected decoration doesn't exist, use the default - libraryName = ( ( QPixmap::defaultDepth() > 8 ) ? "kwin3_oxygen" : "kwin3_plastik" ); - } + if (libraryName.isEmpty()) { + // Selected decoration doesn't exist, use the default + libraryName = ((QPixmap::defaultDepth() > 8) ? "kwin3_oxygen" : "kwin3_plastik"); + } - const int bsize = conf.readEntry( "BorderSize", (int)BorderNormal ); + const int bsize = conf.readEntry("BorderSize", (int)BorderNormal); BorderSize borderSize = BorderNormal; - if( bsize >= BorderTiny && bsize < BordersCount ) - borderSize = static_cast< BorderSize >( bsize ); - if( libraryName == "kwin3_aurorae" ) - { - KConfig auroraeConfig( "auroraerc" ); - KConfigGroup group( &auroraeConfig, "Engine"); - const QString themeName = group.readEntry( "ThemeName", "example-deco" ); - const QModelIndex index = m_proxyModel->mapFromSource( m_model->indexOfAuroraeName( themeName ) ); - if( index.isValid() ) - { - m_ui->decorationList->setCurrentIndex( index ); - } + if (bsize >= BorderTiny && bsize < BordersCount) + borderSize = static_cast< BorderSize >(bsize); + if (libraryName == "kwin3_aurorae") { + KConfig auroraeConfig("auroraerc"); + KConfigGroup group(&auroraeConfig, "Engine"); + const QString themeName = group.readEntry("ThemeName", "example-deco"); + const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfAuroraeName(themeName)); + if (index.isValid()) { + m_ui->decorationList->setCurrentIndex(index); } - else - { - const QModelIndex index = m_proxyModel->mapFromSource( m_model->indexOfLibrary( libraryName ) ); - if( index.isValid() ) - { - m_model->setBorderSize( index, borderSize ); - m_ui->decorationList->setCurrentIndex( index ); - } + } else { + const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfLibrary(libraryName)); + if (index.isValid()) { + m_model->setBorderSize(index, borderSize); + m_ui->decorationList->setCurrentIndex(index); } + } // Buttons tab // ============ @@ -166,42 +161,40 @@ void KWinDecorationModule::readConfig( const KConfigGroup & conf ) m_leftButtons = conf.readEntry("ButtonsOnLeft", KDecorationOptions::defaultTitleButtonsLeft()); // Help, Minimize, Maximize and Close are default on RHS m_rightButtons = conf.readEntry("ButtonsOnRight", KDecorationOptions::defaultTitleButtonsRight()); - if( m_configLoaded ) - m_model->changeButtons( m_customPositions, m_leftButtons, m_rightButtons ); - else - { + if (m_configLoaded) + m_model->changeButtons(m_customPositions, m_leftButtons, m_rightButtons); + else { m_configLoaded = true; - m_model->setButtons( m_customPositions, m_leftButtons, m_rightButtons ); - } + m_model->setButtons(m_customPositions, m_leftButtons, m_rightButtons); + } emit KCModule::changed(false); } // Writes the selected user configuration to the kwin config file -void KWinDecorationModule::writeConfig( KConfigGroup & conf ) +void KWinDecorationModule::writeConfig(KConfigGroup & conf) { - const QModelIndex index = m_proxyModel->mapToSource( m_ui->decorationList->currentIndex() ); - const QString libName = m_model->data( index, DecorationModel::LibraryNameRole ).toString(); + const QModelIndex index = m_proxyModel->mapToSource(m_ui->decorationList->currentIndex()); + const QString libName = m_model->data(index, DecorationModel::LibraryNameRole).toString(); // General settings conf.writeEntry("PluginLib", libName); - conf.writeEntry("CustomButtonPositions", m_customPositions ); - conf.writeEntry("ShowToolTips", m_showTooltips ); + conf.writeEntry("CustomButtonPositions", m_customPositions); + conf.writeEntry("ShowToolTips", m_showTooltips); // Button settings - conf.writeEntry("ButtonsOnLeft", m_leftButtons ); - conf.writeEntry("ButtonsOnRight", m_rightButtons ); - conf.writeEntry( "BorderSize", - static_cast( m_model->data( index, DecorationModel::BorderSizeRole ).toInt())); + conf.writeEntry("ButtonsOnLeft", m_leftButtons); + conf.writeEntry("ButtonsOnRight", m_rightButtons); + conf.writeEntry("BorderSize", + static_cast(m_model->data(index, DecorationModel::BorderSizeRole).toInt())); - if( m_model->data( index, DecorationModel::TypeRole ).toInt() == DecorationModelData::AuroraeDecoration ) - { - KConfig auroraeConfig( "auroraerc" ); - KConfigGroup group( &auroraeConfig, "Engine"); - group.writeEntry( "ThemeName", m_model->data( index, DecorationModel::AuroraeNameRole ).toString() ); + if (m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration) { + KConfig auroraeConfig("auroraerc"); + KConfigGroup group(&auroraeConfig, "Engine"); + group.writeEntry("ThemeName", m_model->data(index, DecorationModel::AuroraeNameRole).toString()); group.sync(); - } + } // We saved, so tell kcmodule that there have been no new user changes made. emit KCModule::changed(false); @@ -211,17 +204,17 @@ void KWinDecorationModule::writeConfig( KConfigGroup & conf ) // Virutal functions required by KCModule void KWinDecorationModule::load() { - const KConfigGroup config( kwinConfig, "Style" ); + const KConfigGroup config(kwinConfig, "Style"); // Reset by re-reading the config - readConfig( config ); + readConfig(config); } void KWinDecorationModule::save() { - KConfigGroup config( kwinConfig, "Style" ); - writeConfig( config ); + KConfigGroup config(kwinConfig, "Style"); + writeConfig(config); config.sync(); // Send signal to all kwin instances @@ -236,119 +229,107 @@ void KWinDecorationModule::defaults() // Set the KDE defaults m_customPositions = false; m_showTooltips = true; - const QModelIndex index = m_proxyModel->mapFromSource( m_model->indexOfName( i18n("Oxygen") ) ); - if( index.isValid() ) - m_ui->decorationList->setCurrentIndex( index ); + const QModelIndex index = m_proxyModel->mapFromSource(m_model->indexOfName(i18n("Oxygen"))); + if (index.isValid()) + m_ui->decorationList->setCurrentIndex(index); m_leftButtons = KDecorationOptions::defaultTitleButtonsLeft(); m_rightButtons = KDecorationOptions::defaultTitleButtonsRight(); - m_model->changeButtons( m_customPositions, m_leftButtons, m_rightButtons ); + m_model->changeButtons(m_customPositions, m_leftButtons, m_rightButtons); - emit changed( true ); + emit changed(true); } QString KWinDecorationModule::quickHelp() const { - return i18n( "

Window Manager Decoration

" - "

This module allows you to choose the window border decorations, " - "as well as titlebar button positions and custom decoration options.

" - "To choose a theme for your window decoration click on its name and apply your choice by clicking the \"Apply\" button below." - " If you do not want to apply your choice you can click the \"Reset\" button to discard your changes." - "

You can configure each theme. There are different options specific for each theme.

" - "

On the \"Buttons\" tab check the \"Use custom titlebar button positions\" box " - "and you can change the positions of the buttons to your liking.

" ); + return i18n("

Window Manager Decoration

" + "

This module allows you to choose the window border decorations, " + "as well as titlebar button positions and custom decoration options.

" + "To choose a theme for your window decoration click on its name and apply your choice by clicking the \"Apply\" button below." + " If you do not want to apply your choice you can click the \"Reset\" button to discard your changes." + "

You can configure each theme. There are different options specific for each theme.

" + "

On the \"Buttons\" tab check the \"Use custom titlebar button positions\" box " + "and you can change the positions of the buttons to your liking.

"); } void KWinDecorationModule::slotConfigureButtons() { - QPointer< KWinDecorationButtonsConfigDialog > configDialog = new KWinDecorationButtonsConfigDialog( m_customPositions, m_showTooltips, m_leftButtons, m_rightButtons, this ); - if( configDialog->exec() == KDialog::Accepted ) - { + QPointer< KWinDecorationButtonsConfigDialog > configDialog = new KWinDecorationButtonsConfigDialog(m_customPositions, m_showTooltips, m_leftButtons, m_rightButtons, this); + if (configDialog->exec() == KDialog::Accepted) { m_customPositions = configDialog->customPositions(); m_showTooltips = configDialog->showTooltips(); m_leftButtons = configDialog->buttonsLeft(); m_rightButtons = configDialog->buttonsRight(); - m_model->changeButtons( m_customPositions, m_leftButtons, m_rightButtons ); - emit changed( true ); - } + m_model->changeButtons(m_customPositions, m_leftButtons, m_rightButtons); + emit changed(true); + } delete configDialog; } void KWinDecorationModule::slotGHNSClicked() - { - QPointer downloadDialog = new KNS3::DownloadDialog( "aurorae.knsrc", this ); - if( downloadDialog->exec() == KDialog::Accepted ) - { - if( !downloadDialog->changedEntries().isEmpty() ) - { - const QModelIndex index = m_proxyModel->mapToSource( m_ui->decorationList->currentIndex() ); - const QString libraryName = m_model->data( index, DecorationModel::LibraryNameRole ).toString(); - bool aurorae = m_model->data( index, DecorationModel::TypeRole ).toInt() == DecorationModelData::AuroraeDecoration; - const QString auroraeName = m_model->data( index, DecorationModel::AuroraeNameRole ).toString(); +{ + QPointer downloadDialog = new KNS3::DownloadDialog("aurorae.knsrc", this); + if (downloadDialog->exec() == KDialog::Accepted) { + if (!downloadDialog->changedEntries().isEmpty()) { + const QModelIndex index = m_proxyModel->mapToSource(m_ui->decorationList->currentIndex()); + const QString libraryName = m_model->data(index, DecorationModel::LibraryNameRole).toString(); + bool aurorae = m_model->data(index, DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration; + const QString auroraeName = m_model->data(index, DecorationModel::AuroraeNameRole).toString(); m_model->reload(); - if( aurorae ) - { - const QModelIndex proxyIndex = m_proxyModel->mapFromSource( m_model->indexOfAuroraeName( auroraeName ) ); - if( proxyIndex.isValid() ) - m_ui->decorationList->setCurrentIndex( proxyIndex ); - } - else - { - const QModelIndex proxyIndex = m_proxyModel->mapFromSource( m_model->indexOfLibrary( libraryName ) ); - if( proxyIndex.isValid() ) - m_ui->decorationList->setCurrentIndex( proxyIndex ); - } + if (aurorae) { + const QModelIndex proxyIndex = m_proxyModel->mapFromSource(m_model->indexOfAuroraeName(auroraeName)); + if (proxyIndex.isValid()) + m_ui->decorationList->setCurrentIndex(proxyIndex); + } else { + const QModelIndex proxyIndex = m_proxyModel->mapFromSource(m_model->indexOfLibrary(libraryName)); + if (proxyIndex.isValid()) + m_ui->decorationList->setCurrentIndex(proxyIndex); } } - delete downloadDialog; } + delete downloadDialog; +} void KWinDecorationModule::slotConfigureDecoration() - { - const QModelIndex index = m_proxyModel->mapToSource( m_ui->decorationList->currentIndex() ); +{ + const QModelIndex index = m_proxyModel->mapToSource(m_ui->decorationList->currentIndex()); bool reload = false; - if( index.data( DecorationModel::TypeRole ).toInt() == DecorationModelData::AuroraeDecoration ) - { - QPointer< KDialog > dlg = new KDialog( this ); - dlg->setCaption( i18n( "Decoration Options" ) ); - dlg->setButtons( KDialog::Ok | KDialog::Cancel ); - KWinAuroraeConfigForm *form = new KWinAuroraeConfigForm( dlg ); - dlg->setMainWidget( form ); - form->borderSizesCombo->setCurrentIndex( index.data( DecorationModel::BorderSizeRole ).toInt() ); - form->buttonSizesCombo->setCurrentIndex( index.data( DecorationModel::ButtonSizeRole ).toInt() ); - if( dlg->exec() == KDialog::Accepted ) - { - m_model->setData( index, form->borderSizesCombo->currentIndex(), DecorationModel::BorderSizeRole ); - m_model->setData( index, form->buttonSizesCombo->currentIndex(), DecorationModel::ButtonSizeRole ); + if (index.data(DecorationModel::TypeRole).toInt() == DecorationModelData::AuroraeDecoration) { + QPointer< KDialog > dlg = new KDialog(this); + dlg->setCaption(i18n("Decoration Options")); + dlg->setButtons(KDialog::Ok | KDialog::Cancel); + KWinAuroraeConfigForm *form = new KWinAuroraeConfigForm(dlg); + dlg->setMainWidget(form); + form->borderSizesCombo->setCurrentIndex(index.data(DecorationModel::BorderSizeRole).toInt()); + form->buttonSizesCombo->setCurrentIndex(index.data(DecorationModel::ButtonSizeRole).toInt()); + if (dlg->exec() == KDialog::Accepted) { + m_model->setData(index, form->borderSizesCombo->currentIndex(), DecorationModel::BorderSizeRole); + m_model->setData(index, form->buttonSizesCombo->currentIndex(), DecorationModel::ButtonSizeRole); reload = true; - } - delete dlg; } - else - { - QString name = index.data( DecorationModel::LibraryNameRole ).toString(); - QList< QVariant > borderSizes = index.data( DecorationModel::BorderSizesRole ).toList(); + delete dlg; + } else { + QString name = index.data(DecorationModel::LibraryNameRole).toString(); + QList< QVariant > borderSizes = index.data(DecorationModel::BorderSizesRole).toList(); const KDecorationDefines::BorderSize size = - static_cast( index.data( DecorationModel::BorderSizeRole ).toInt() ); + static_cast(index.data(DecorationModel::BorderSizeRole).toInt()); QPointer< KWinDecorationConfigDialog > configDialog = - new KWinDecorationConfigDialog( name, borderSizes, size, this ); - if( configDialog->exec() == KDialog::Accepted ) - { - m_model->setData( index, configDialog->borderSize(), DecorationModel::BorderSizeRole ); + new KWinDecorationConfigDialog(name, borderSizes, size, this); + if (configDialog->exec() == KDialog::Accepted) { + m_model->setData(index, configDialog->borderSize(), DecorationModel::BorderSizeRole); reload = true; - } + } delete configDialog; - } - if( reload ) - { + } + if (reload) { // Send signal to all kwin instances QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); - } } +} } // namespace KWin diff --git a/kcmkwin/kwindecoration/kwindecoration.h b/kcmkwin/kwindecoration/kwindecoration.h index cfb009992..6ef19c04c 100644 --- a/kcmkwin/kwindecoration/kwindecoration.h +++ b/kcmkwin/kwindecoration/kwindecoration.h @@ -48,51 +48,51 @@ class KWinDecorationForm : public QWidget, public Ui::KWinDecorationForm { Q_OBJECT - public: - explicit KWinDecorationForm( QWidget* parent ); +public: + explicit KWinDecorationForm(QWidget* parent); }; class KWinDecorationModule : public KCModule, public KDecorationDefines { Q_OBJECT - public: - KWinDecorationModule(QWidget* parent, const QVariantList &); - ~KWinDecorationModule(); +public: + KWinDecorationModule(QWidget* parent, const QVariantList &); + ~KWinDecorationModule(); - virtual void load(); - virtual void save(); - virtual void defaults(); + virtual void load(); + virtual void save(); + virtual void defaults(); - QString quickHelp() const; + QString quickHelp() const; - signals: - void pluginLoad( const KConfigGroup& conf ); - void pluginSave( KConfigGroup &conf ); - void pluginDefaults(); +signals: + void pluginLoad(const KConfigGroup& conf); + void pluginSave(KConfigGroup &conf); + void pluginDefaults(); - protected slots: - // Allows us to turn "save" on - void slotSelectionChanged(); - void slotConfigureButtons(); - void slotGHNSClicked(); - void slotConfigureDecoration(); +protected slots: + // Allows us to turn "save" on + void slotSelectionChanged(); + void slotConfigureButtons(); + void slotGHNSClicked(); + void slotConfigureDecoration(); - private: - void readConfig( const KConfigGroup& conf ); - void writeConfig( KConfigGroup &conf ); +private: + void readConfig(const KConfigGroup& conf); + void writeConfig(KConfigGroup &conf); - KSharedConfigPtr kwinConfig; + KSharedConfigPtr kwinConfig; - KWinDecorationForm* m_ui; - bool m_showTooltips; - bool m_customPositions; - QString m_leftButtons; - QString m_rightButtons; + KWinDecorationForm* m_ui; + bool m_showTooltips; + bool m_customPositions; + QString m_leftButtons; + QString m_rightButtons; - DecorationModel* m_model; - QSortFilterProxyModel* m_proxyModel; - bool m_configLoaded; + DecorationModel* m_model; + QSortFilterProxyModel* m_proxyModel; + bool m_configLoaded; }; } //namespace diff --git a/kcmkwin/kwindecoration/pixmaps.h b/kcmkwin/kwindecoration/pixmaps.h index 5a687b04d..994875e1e 100644 --- a/kcmkwin/kwindecoration/pixmaps.h +++ b/kcmkwin/kwindecoration/pixmaps.h @@ -1,27 +1,27 @@ -/* - This is the new kwindecoration kcontrol module +/* + This is the new kwindecoration kcontrol module - Copyright (c) 2004, Sandro Giessl - Copyright (c) 2001 - Karol Szwed - http://gallium.n3.net/ + Copyright (c) 2004, Sandro Giessl + Copyright (c) 2001 + Karol Szwed + http://gallium.n3.net/ - Supports new kwin configuration plugins, and titlebar button position - modification via dnd interface. + Supports new kwin configuration plugins, and titlebar button position + modification via dnd interface. - Based on original "kwintheme" (Window Borders) - Copyright (C) 2001 Rik Hemsley (rikkus) + Based on original "kwintheme" (Window Borders) + Copyright (C) 2001 Rik Hemsley (rikkus) 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. @@ -37,78 +37,89 @@ #define close_width 12 #define close_height 12 static unsigned char close_bits[] = { - 0x00, 0x00, 0x06, 0x06, 0x0e, 0x07, 0x9c, 0x03, 0xf8, 0x01, 0xf0, 0x00, - 0xf0, 0x00, 0xf8, 0x01, 0x9c, 0x03, 0x0e, 0x07, 0x06, 0x06, 0x00, 0x00 }; + 0x00, 0x00, 0x06, 0x06, 0x0e, 0x07, 0x9c, 0x03, 0xf8, 0x01, 0xf0, 0x00, + 0xf0, 0x00, 0xf8, 0x01, 0x9c, 0x03, 0x0e, 0x07, 0x06, 0x06, 0x00, 0x00 +}; // help.xbm: #define help_width 12 #define help_height 12 static unsigned char help_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0xfc, 0x01, 0x8c, 0x01, 0xc0, 0x01, - 0xe0, 0x00, 0x60, 0x00, 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0x00 }; + 0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0xfc, 0x01, 0x8c, 0x01, 0xc0, 0x01, + 0xe0, 0x00, 0x60, 0x00, 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0x00 +}; // keepaboveothers.xbm: #define keepaboveothers_width 12 #define keepaboveothers_height 12 static unsigned char keepaboveothers_bits[] = { - 0x00, 0x00, 0x60, 0x00, 0xf0, 0x00, 0xf8, 0x01, 0x60, 0x00, 0xfe, 0x07, - 0xfe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + 0x00, 0x00, 0x60, 0x00, 0xf0, 0x00, 0xf8, 0x01, 0x60, 0x00, 0xfe, 0x07, + 0xfe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; // keepbelowothers.xbm: #define keepbelowothers_width 12 #define keepbelowothers_height 12 static unsigned char keepbelowothers_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x07, - 0xfe, 0x07, 0x60, 0x00, 0xf8, 0x01, 0xf0, 0x00, 0x60, 0x00, 0x00, 0x00 }; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x07, + 0xfe, 0x07, 0x60, 0x00, 0xf8, 0x01, 0xf0, 0x00, 0x60, 0x00, 0x00, 0x00 +}; // maximize.xbm: #define maximize_width 12 #define maximize_height 12 static unsigned char maximize_bits[] = { - 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, - 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0xfe, 0x07, 0x00, 0x00 }; + 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, + 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0xfe, 0x07, 0x00, 0x00 +}; // menu.xbm: #define menu_width 12 #define menu_height 12 static unsigned char menu_bits[] = { - 0x00, 0x00, 0xfc, 0x03, 0xf4, 0x02, 0x04, 0x02, 0xf4, 0x02, 0x04, 0x02, - 0xf4, 0x02, 0x04, 0x02, 0xf4, 0x02, 0x04, 0x02, 0xfc, 0x03, 0x00, 0x00 }; + 0x00, 0x00, 0xfc, 0x03, 0xf4, 0x02, 0x04, 0x02, 0xf4, 0x02, 0x04, 0x02, + 0xf4, 0x02, 0x04, 0x02, 0xf4, 0x02, 0x04, 0x02, 0xfc, 0x03, 0x00, 0x00 +}; // minimize.xbm: #define minimize_width 12 #define minimize_height 12 static unsigned char minimize_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x00, 0x00 }; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x00, 0x00 +}; // onalldesktops.xbm: #define onalldesktops_width 12 #define onalldesktops_height 12 static unsigned char onalldesktops_bits[] = { - 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0xfe, 0x07, - 0xfe, 0x07, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0x00 }; + 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0xfe, 0x07, + 0xfe, 0x07, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0x00 +}; // resize.xbm: #define resize_width 12 #define resize_height 12 static unsigned char resize_bits[] = { - 0x00, 0x00, 0xfe, 0x07, 0x42, 0x04, 0x42, 0x04, 0x42, 0x04, 0x42, 0x04, - 0x7e, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0xfe, 0x07, 0x00, 0x00 }; + 0x00, 0x00, 0xfe, 0x07, 0x42, 0x04, 0x42, 0x04, 0x42, 0x04, 0x42, 0x04, + 0x7e, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0xfe, 0x07, 0x00, 0x00 +}; // shade.xbm: #define shade_width 12 #define shade_height 12 static unsigned char shade_bits[] = { - 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + 0x00, 0x00, 0xfe, 0x07, 0xfe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; // spacer.xbm: #define spacer_width 12 #define spacer_height 12 static unsigned char spacer_bits[] = { - 0x00, 0x00, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x54, 0x03, - 0xac, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x00, 0x00 }; + 0x00, 0x00, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x54, 0x03, + 0xac, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x04, 0x02, 0x00, 0x00 +}; // vim: ts=4 diff --git a/kcmkwin/kwindecoration/preview.cpp b/kcmkwin/kwindecoration/preview.cpp index ed484da2c..a3d425674 100644 --- a/kcmkwin/kwindecoration/preview.cpp +++ b/kcmkwin/kwindecoration/preview.cpp @@ -40,49 +40,46 @@ #include #include -KDecorationPreview::KDecorationPreview( QWidget* parent ) - : QWidget( parent ) - { +KDecorationPreview::KDecorationPreview(QWidget* parent) + : QWidget(parent) +{ options = new KDecorationPreviewOptions; - bridge[Active] = new KDecorationPreviewBridge( this, true ); - bridge[Inactive] = new KDecorationPreviewBridge( this, false ); + bridge[Active] = new KDecorationPreviewBridge(this, true); + bridge[Inactive] = new KDecorationPreviewBridge(this, false); deco[Active] = deco[Inactive] = NULL; - no_preview = new QLabel( i18n( "No preview available.\n" - "Most probably there\n" - "was a problem loading the plugin." ), this ); + no_preview = new QLabel(i18n("No preview available.\n" + "Most probably there\n" + "was a problem loading the plugin."), this); - no_preview->setAlignment( Qt::AlignCenter ); + no_preview->setAlignment(Qt::AlignCenter); - setMinimumSize( 100, 100 ); - no_preview->resize( size()); - } + setMinimumSize(100, 100); + no_preview->resize(size()); +} KDecorationPreview::~KDecorationPreview() - { - for ( int i = 0; i < NumWindows; i++ ) - { +{ + for (int i = 0; i < NumWindows; i++) { delete deco[i]; delete bridge[i]; - } + } delete options; +} + +bool KDecorationPreview::recreateDecoration(KDecorationPlugins* plugins) +{ + for (int i = 0; i < NumWindows; i++) { + delete deco[i]; // deletes also window + deco[i] = plugins->createDecoration(bridge[i]); + deco[i]->init(); } -bool KDecorationPreview::recreateDecoration( KDecorationPlugins* plugins ) - { - for ( int i = 0; i < NumWindows; i++ ) - { - delete deco[i]; // deletes also window - deco[i] = plugins->createDecoration( bridge[i] ); - deco[i]->init(); - } - - if( deco[Active] == NULL || deco[Inactive] == NULL ) - { + if (deco[Active] == NULL || deco[Inactive] == NULL) { return false; - } + } positionPreviews(); //deco[Inactive]->widget()->show(); @@ -91,506 +88,491 @@ bool KDecorationPreview::recreateDecoration( KDecorationPlugins* plugins ) //deco[Inactive]->widget()->render( this, deco[Inactive]->widget()->mapToParent( QPoint(0,0) ) ); return true; - } +} void KDecorationPreview::enablePreview() - { +{ no_preview->hide(); - } +} void KDecorationPreview::disablePreview() - { +{ delete deco[Active]; delete deco[Inactive]; deco[Active] = deco[Inactive] = NULL; no_preview->show(); - } +} -void KDecorationPreview::paintEvent( QPaintEvent* e ) - { - Q_UNUSED( e ); - QPainter painter( this ); - QPoint delta = mapTo( window(), QPoint(0, 0) ); +void KDecorationPreview::paintEvent(QPaintEvent* e) +{ + Q_UNUSED(e); + QPainter painter(this); + QPoint delta = mapTo(window(), QPoint(0, 0)); - if ( deco[Inactive] ) - { + if (deco[Inactive]) { QWidget *w = deco[Inactive]->widget(); - w->render( &painter, delta + w->mapToParent( QPoint(0, 0) ) ); - } - if ( deco[Active] ) - { - QWidget *w = deco[Active]->widget(); - w->render( &painter, delta + w->mapToParent( QPoint(0, 0) ) ); - } + w->render(&painter, delta + w->mapToParent(QPoint(0, 0))); } - -QPixmap KDecorationPreview::preview( QTextDocument* document, QWidget* widget ) - { - Q_UNUSED( document ); - Q_UNUSED( widget ); - QPixmap pixmap( size() ); - pixmap.fill( Qt::transparent ); - - if ( deco[Inactive] ) - { - QWidget *w = deco[Inactive]->widget(); - w->render( &pixmap, w->mapToParent( QPoint(0, 0) ) ); - } - if ( deco[Active] ) - { + if (deco[Active]) { QWidget *w = deco[Active]->widget(); - w->render( &pixmap, w->mapToParent( QPoint(0, 0) ) ); - } + w->render(&painter, delta + w->mapToParent(QPoint(0, 0))); + } +} + +QPixmap KDecorationPreview::preview(QTextDocument* document, QWidget* widget) +{ + Q_UNUSED(document); + Q_UNUSED(widget); + QPixmap pixmap(size()); + pixmap.fill(Qt::transparent); + + if (deco[Inactive]) { + QWidget *w = deco[Inactive]->widget(); + w->render(&pixmap, w->mapToParent(QPoint(0, 0))); + } + if (deco[Active]) { + QWidget *w = deco[Active]->widget(); + w->render(&pixmap, w->mapToParent(QPoint(0, 0))); + } return pixmap; - } +} -void KDecorationPreview::resizeEvent( QResizeEvent* e ) - { - QWidget::resizeEvent( e ); +void KDecorationPreview::resizeEvent(QResizeEvent* e) +{ + QWidget::resizeEvent(e); positionPreviews(); - } +} void KDecorationPreview::positionPreviews() - { +{ int titleBarHeight, leftBorder, rightBorder, xoffset, dummy1, dummy2, dummy3; QRect geometry; QSize size; - no_preview->resize( this->size() ); + no_preview->resize(this->size()); - if ( !deco[Active] || !deco[Inactive] ) + if (!deco[Active] || !deco[Inactive]) return; // don't have more than one reference to the same dummy variable in one borders() call. - deco[Active]->borders( dummy1, dummy2, titleBarHeight, dummy3 ); - deco[Inactive]->borders( leftBorder, rightBorder, dummy1, dummy2 ); + deco[Active]->borders(dummy1, dummy2, titleBarHeight, dummy3); + deco[Inactive]->borders(leftBorder, rightBorder, dummy1, dummy2); - titleBarHeight = qMin( int( titleBarHeight * .9 ), 30 ); - xoffset = qMin( qMax( 10, QApplication::isRightToLeft() - ? leftBorder : rightBorder ), 30 ); + titleBarHeight = qMin(int(titleBarHeight * .9), 30); + xoffset = qMin(qMax(10, QApplication::isRightToLeft() + ? leftBorder : rightBorder), 30); // Resize the active window - size = QSize( width() - xoffset, height() - titleBarHeight ) - .expandedTo( deco[Active]->minimumSize() ); - geometry = QRect( QPoint( 0, titleBarHeight ), size ); + size = QSize(width() - xoffset, height() - titleBarHeight) + .expandedTo(deco[Active]->minimumSize()); + geometry = QRect(QPoint(0, titleBarHeight), size); if (KDecorationUnstable *unstable = qobject_cast(deco[Active])) { int padLeft, padRight, padTop, padBottom; unstable->padding(padLeft, padRight, padTop, padBottom); geometry.adjust(-padLeft, -padTop, padRight, padBottom); } geometry.adjust(10, 10, -10, -10); - deco[Active]->widget()->setGeometry( QStyle::visualRect( this->layoutDirection(), this->rect(), geometry ) ); + deco[Active]->widget()->setGeometry(QStyle::visualRect(this->layoutDirection(), this->rect(), geometry)); // Resize the inactive window - size = QSize( width() - xoffset, height() - titleBarHeight ) - .expandedTo( deco[Inactive]->minimumSize() ); - geometry = QRect( QPoint( xoffset, 0 ), size ); + size = QSize(width() - xoffset, height() - titleBarHeight) + .expandedTo(deco[Inactive]->minimumSize()); + geometry = QRect(QPoint(xoffset, 0), size); if (KDecorationUnstable *unstable = qobject_cast(deco[Inactive])) { int padLeft, padRight, padTop, padBottom; unstable->padding(padLeft, padRight, padTop, padBottom); geometry.adjust(-padLeft, -padTop, padRight, padBottom); } geometry.adjust(10, 10, -10, -10); - deco[Inactive]->widget()->setGeometry( QStyle::visualRect( this->layoutDirection(), this->rect(), geometry ) ); - } + deco[Inactive]->widget()->setGeometry(QStyle::visualRect(this->layoutDirection(), this->rect(), geometry)); +} -void KDecorationPreview::setPreviewMask( const QRegion& reg, int mode, bool active ) - { +void KDecorationPreview::setPreviewMask(const QRegion& reg, int mode, bool active) +{ QWidget *widget = active ? deco[Active]->widget() : deco[Inactive]->widget(); // FRAME duped from client.cpp - if( mode == Unsorted ) - { - XShapeCombineRegion( QX11Info::display(), widget->winId(), ShapeBounding, 0, 0, - reg.handle(), ShapeSet ); - } - else - { + if (mode == Unsorted) { + XShapeCombineRegion(QX11Info::display(), widget->winId(), ShapeBounding, 0, 0, + reg.handle(), ShapeSet); + } else { QVector< QRect > rects = reg.rects(); - XRectangle* xrects = new XRectangle[ rects.count() ]; - for( int i = 0; - i < rects.count(); - ++i ) - { + XRectangle* xrects = new XRectangle[ rects.count()]; + for (int i = 0; + i < rects.count(); + ++i) { xrects[ i ].x = rects[ i ].x(); xrects[ i ].y = rects[ i ].y(); xrects[ i ].width = rects[ i ].width(); xrects[ i ].height = rects[ i ].height(); - } - XShapeCombineRectangles( QX11Info::display(), widget->winId(), ShapeBounding, 0, 0, - xrects, rects.count(), ShapeSet, mode ); - delete[] xrects; } - if( active ) - mask = reg; // keep shape of the active window for unobscuredRegion() + XShapeCombineRectangles(QX11Info::display(), widget->winId(), ShapeBounding, 0, 0, + xrects, rects.count(), ShapeSet, mode); + delete[] xrects; } + if (active) + mask = reg; // keep shape of the active window for unobscuredRegion() +} -QRect KDecorationPreview::windowGeometry( bool active ) const - { +QRect KDecorationPreview::windowGeometry(bool active) const +{ QWidget *widget = active ? deco[Active]->widget() : deco[Inactive]->widget(); return widget->geometry(); - } +} void KDecorationPreview::setTempBorderSize(KDecorationPlugins* plugin, KDecorationDefines::BorderSize size) - { +{ options->setCustomBorderSize(size); - if (plugin->factory()->reset(KDecorationDefines::SettingBorder) ) - { + if (plugin->factory()->reset(KDecorationDefines::SettingBorder)) { // can't handle the change, recreate decorations then recreateDecoration(plugin); - } - else - { + } else { // handles the update, only update position... positionPreviews(); - } } +} void KDecorationPreview::setTempButtons(KDecorationPlugins* plugin, bool customEnabled, const QString &left, const QString &right) - { +{ options->setCustomTitleButtonsEnabled(customEnabled); options->setCustomTitleButtons(left, right); - if (plugin->factory()->reset(KDecorationDefines::SettingButtons) ) - { + if (plugin->factory()->reset(KDecorationDefines::SettingButtons)) { // can't handle the change, recreate decorations then recreateDecoration(plugin); - } - else - { + } else { // handles the update, only update position... positionPreviews(); - } } +} -QRegion KDecorationPreview::unobscuredRegion( bool active, const QRegion& r ) const - { - if( active ) // this one is not obscured +QRegion KDecorationPreview::unobscuredRegion(bool active, const QRegion& r) const +{ + if (active) // this one is not obscured return r; - else - { + else { // copied from KWin core's code QRegion ret = r; QRegion r2 = mask; - if( r2.isEmpty()) - r2 = QRegion( windowGeometry( true )); - r2.translate( windowGeometry( true ).x() - windowGeometry( false ).x(), - windowGeometry( true ).y() - windowGeometry( false ).y()); + if (r2.isEmpty()) + r2 = QRegion(windowGeometry(true)); + r2.translate(windowGeometry(true).x() - windowGeometry(false).x(), + windowGeometry(true).y() - windowGeometry(false).y()); ret -= r2; return ret; - } } +} -KDecorationPreviewBridge::KDecorationPreviewBridge( KDecorationPreview* p, bool a ) - : preview( p ), active( a ) - { - } +KDecorationPreviewBridge::KDecorationPreviewBridge(KDecorationPreview* p, bool a) + : preview(p), active(a) +{ +} QWidget* KDecorationPreviewBridge::initialParentWidget() const - { +{ return preview; - } +} Qt::WFlags KDecorationPreviewBridge::initialWFlags() const - { +{ return 0; - } +} bool KDecorationPreviewBridge::isActive() const - { +{ return active; - } +} bool KDecorationPreviewBridge::isCloseable() const - { +{ return true; - } +} bool KDecorationPreviewBridge::isMaximizable() const - { +{ return true; - } +} KDecoration::MaximizeMode KDecorationPreviewBridge::maximizeMode() const - { +{ return KDecoration::MaximizeRestore; - } +} bool KDecorationPreviewBridge::isMinimizable() const - { +{ return true; - } +} bool KDecorationPreviewBridge::providesContextHelp() const - { +{ return true; - } +} int KDecorationPreviewBridge::desktop() const - { +{ return 1; - } +} bool KDecorationPreviewBridge::isModal() const - { +{ return false; - } +} bool KDecorationPreviewBridge::isShadeable() const - { +{ return true; - } +} bool KDecorationPreviewBridge::isShade() const - { +{ return false; - } +} bool KDecorationPreviewBridge::isSetShade() const - { +{ return false; - } +} bool KDecorationPreviewBridge::keepAbove() const - { +{ return false; - } +} bool KDecorationPreviewBridge::keepBelow() const - { +{ return false; - } +} bool KDecorationPreviewBridge::isMovable() const - { +{ return true; - } +} bool KDecorationPreviewBridge::isResizable() const - { +{ return true; - } +} -NET::WindowType KDecorationPreviewBridge::windowType( unsigned long ) const - { +NET::WindowType KDecorationPreviewBridge::windowType(unsigned long) const +{ return NET::Normal; - } +} QIcon KDecorationPreviewBridge::icon() const - { - return KIcon( "xorg" ); - } +{ + return KIcon("xorg"); +} QString KDecorationPreviewBridge::caption() const - { - return active ? i18n( "Active Window" ) : i18n( "Inactive Window" ); - } +{ + return active ? i18n("Active Window") : i18n("Inactive Window"); +} -void KDecorationPreviewBridge::processMousePressEvent( QMouseEvent* ) - { - } +void KDecorationPreviewBridge::processMousePressEvent(QMouseEvent*) +{ +} -void KDecorationPreviewBridge::showWindowMenu( const QRect &) - { - } +void KDecorationPreviewBridge::showWindowMenu(const QRect &) +{ +} -void KDecorationPreviewBridge::showWindowMenu( const QPoint & ) - { - } +void KDecorationPreviewBridge::showWindowMenu(const QPoint &) +{ +} -void KDecorationPreviewBridge::performWindowOperation( WindowOperation ) - { - } +void KDecorationPreviewBridge::performWindowOperation(WindowOperation) +{ +} -void KDecorationPreviewBridge::setMask( const QRegion& reg, int mode ) - { - preview->setPreviewMask( reg, mode, active ); - } +void KDecorationPreviewBridge::setMask(const QRegion& reg, int mode) +{ + preview->setPreviewMask(reg, mode, active); +} bool KDecorationPreviewBridge::isPreview() const - { +{ return true; - } +} QRect KDecorationPreviewBridge::geometry() const - { - return preview->windowGeometry( active ); - } +{ + return preview->windowGeometry(active); +} QRect KDecorationPreviewBridge::iconGeometry() const - { +{ return QRect(); - } +} -QRegion KDecorationPreviewBridge::unobscuredRegion( const QRegion& r ) const - { - return preview->unobscuredRegion( active, r ); - } +QRegion KDecorationPreviewBridge::unobscuredRegion(const QRegion& r) const +{ + return preview->unobscuredRegion(active, r); +} WId KDecorationPreviewBridge::windowId() const - { +{ return 0; // no decorated window - } +} void KDecorationPreviewBridge::closeWindow() - { - } +{ +} -void KDecorationPreviewBridge::maximize( MaximizeMode ) - { - } +void KDecorationPreviewBridge::maximize(MaximizeMode) +{ +} void KDecorationPreviewBridge::minimize() - { - } +{ +} void KDecorationPreviewBridge::showContextHelp() - { - } +{ +} -void KDecorationPreviewBridge::setDesktop( int ) - { - } +void KDecorationPreviewBridge::setDesktop(int) +{ +} void KDecorationPreviewBridge::titlebarDblClickOperation() - { - } +{ +} -void KDecorationPreviewBridge::titlebarMouseWheelOperation( int ) - { - } +void KDecorationPreviewBridge::titlebarMouseWheelOperation(int) +{ +} -void KDecorationPreviewBridge::setShade( bool ) - { - } +void KDecorationPreviewBridge::setShade(bool) +{ +} -void KDecorationPreviewBridge::setKeepAbove( bool ) - { - } +void KDecorationPreviewBridge::setKeepAbove(bool) +{ +} -void KDecorationPreviewBridge::setKeepBelow( bool ) - { - } +void KDecorationPreviewBridge::setKeepBelow(bool) +{ +} int KDecorationPreviewBridge::currentDesktop() const - { +{ return 1; - } +} -void KDecorationPreviewBridge::grabXServer( bool ) - { - } +void KDecorationPreviewBridge::grabXServer(bool) +{ +} bool KDecorationPreviewBridge::compositingActive() const - { +{ return KWindowSystem::compositingActive(); - } +} QRect KDecorationPreviewBridge::transparentRect() const - { +{ return QRect(); - } +} // Window tabbing bool KDecorationPreviewBridge::isClientGroupActive() - { +{ return active; - } +} QList< ClientGroupItem > KDecorationPreviewBridge::clientGroupItems() const - { +{ return QList< ClientGroupItem >() << ClientGroupItem( - active ? "Active Window" : "Inactive Window", icon() ); - } + active ? "Active Window" : "Inactive Window", icon()); +} -long KDecorationPreviewBridge::itemId( int ) - { +long KDecorationPreviewBridge::itemId(int) +{ return 0; - } +} int KDecorationPreviewBridge::visibleClientGroupItem() - { +{ return 0; - } +} -void KDecorationPreviewBridge::setVisibleClientGroupItem( int ) - { - } +void KDecorationPreviewBridge::setVisibleClientGroupItem(int) +{ +} -void KDecorationPreviewBridge::moveItemInClientGroup( int, int ) - { - } +void KDecorationPreviewBridge::moveItemInClientGroup(int, int) +{ +} -void KDecorationPreviewBridge::moveItemToClientGroup( long, int ) - { - } +void KDecorationPreviewBridge::moveItemToClientGroup(long, int) +{ +} -void KDecorationPreviewBridge::removeFromClientGroup( int, const QRect& ) - { - } +void KDecorationPreviewBridge::removeFromClientGroup(int, const QRect&) +{ +} -void KDecorationPreviewBridge::closeClientGroupItem( int ) - { - } +void KDecorationPreviewBridge::closeClientGroupItem(int) +{ +} void KDecorationPreviewBridge::closeAllInClientGroup() - { - } +{ +} -void KDecorationPreviewBridge::displayClientMenu( int, const QPoint& ) - { - } +void KDecorationPreviewBridge::displayClientMenu(int, const QPoint&) +{ +} -KDecoration::WindowOperation KDecorationPreviewBridge::buttonToWindowOperation( Qt::MouseButtons ) - { +KDecoration::WindowOperation KDecorationPreviewBridge::buttonToWindowOperation(Qt::MouseButtons) +{ return KDecoration::NoOp; - } +} KDecorationPreviewOptions::KDecorationPreviewOptions() - { +{ customBorderSize = BordersCount; // invalid customButtonsChanged = false; // invalid customButtons = true; customTitleButtonsLeft.clear(); // invalid customTitleButtonsRight.clear(); // invalid updateSettings(); - } +} KDecorationPreviewOptions::~KDecorationPreviewOptions() - { - } +{ +} unsigned long KDecorationPreviewOptions::updateSettings() - { - KConfig cfg( "kwinrc" ); +{ + KConfig cfg("kwinrc"); unsigned long changed = 0; - changed |= KDecorationOptions::updateSettings( &cfg ); + changed |= KDecorationOptions::updateSettings(&cfg); // set custom border size/buttons if (customBorderSize != BordersCount) - setBorderSize( customBorderSize ); + setBorderSize(customBorderSize); if (customButtonsChanged) - setCustomButtonPositions( customButtons ); + setCustomButtonPositions(customButtons); if (customButtons) { - if (!customTitleButtonsLeft.isNull() ) - setTitleButtonsLeft( customTitleButtonsLeft ); - if (!customTitleButtonsRight.isNull() ) - setTitleButtonsRight( customTitleButtonsRight ); + if (!customTitleButtonsLeft.isNull()) + setTitleButtonsLeft(customTitleButtonsLeft); + if (!customTitleButtonsRight.isNull()) + setTitleButtonsRight(customTitleButtonsRight); } else { - setTitleButtonsLeft( KDecorationOptions::defaultTitleButtonsLeft()); - setTitleButtonsRight( KDecorationOptions::defaultTitleButtonsRight()); + setTitleButtonsLeft(KDecorationOptions::defaultTitleButtonsLeft()); + setTitleButtonsRight(KDecorationOptions::defaultTitleButtonsRight()); } return changed; - } +} void KDecorationPreviewOptions::setCustomBorderSize(BorderSize size) - { +{ customBorderSize = size; updateSettings(); - } +} void KDecorationPreviewOptions::setCustomTitleButtonsEnabled(bool enabled) { @@ -601,16 +583,16 @@ void KDecorationPreviewOptions::setCustomTitleButtonsEnabled(bool enabled) } void KDecorationPreviewOptions::setCustomTitleButtons(const QString &left, const QString &right) - { +{ customTitleButtonsLeft = left; customTitleButtonsRight = right; updateSettings(); - } +} -bool KDecorationPreviewPlugins::provides( Requirement ) - { +bool KDecorationPreviewPlugins::provides(Requirement) +{ return false; - } +} #include "preview.moc" diff --git a/kcmkwin/kwindecoration/preview.h b/kcmkwin/kwindecoration/preview.h index e87a9bc83..2679fead9 100644 --- a/kcmkwin/kwindecoration/preview.h +++ b/kcmkwin/kwindecoration/preview.h @@ -37,138 +37,138 @@ class KDecorationPreviewOptions; class KDecorationPreview : public QWidget - { +{ Q_OBJECT - public: - // Note: Windows can't be added or removed without making changes to - // the code, since parts of it assume there's just an active - // and an inactive window. - enum Windows { Inactive = 0, Active, NumWindows }; +public: + // Note: Windows can't be added or removed without making changes to + // the code, since parts of it assume there's just an active + // and an inactive window. + enum Windows { Inactive = 0, Active, NumWindows }; - KDecorationPreview( QWidget* parent = NULL ); - virtual ~KDecorationPreview(); - bool recreateDecoration( KDecorationPlugins* plugin ); - void enablePreview(); - void disablePreview(); - void setPreviewMask( const QRegion&, int, bool ); - QRegion unobscuredRegion( bool, const QRegion& ) const; - QRect windowGeometry( bool ) const; - void setTempBorderSize(KDecorationPlugins* plugin, KDecorationDefines::BorderSize size); - void setTempButtons(KDecorationPlugins* plugin, bool customEnabled, const QString &left, const QString &right); - QPixmap preview(QTextDocument* document, QWidget* widget); - protected: - virtual void paintEvent( QPaintEvent* ); - virtual void resizeEvent( QResizeEvent* ); - private: - void positionPreviews(); - KDecorationPreviewOptions* options; - KDecorationPreviewBridge* bridge[NumWindows]; - KDecoration* deco[NumWindows]; - QLabel* no_preview; - QRegion mask; - }; + KDecorationPreview(QWidget* parent = NULL); + virtual ~KDecorationPreview(); + bool recreateDecoration(KDecorationPlugins* plugin); + void enablePreview(); + void disablePreview(); + void setPreviewMask(const QRegion&, int, bool); + QRegion unobscuredRegion(bool, const QRegion&) const; + QRect windowGeometry(bool) const; + void setTempBorderSize(KDecorationPlugins* plugin, KDecorationDefines::BorderSize size); + void setTempButtons(KDecorationPlugins* plugin, bool customEnabled, const QString &left, const QString &right); + QPixmap preview(QTextDocument* document, QWidget* widget); +protected: + virtual void paintEvent(QPaintEvent*); + virtual void resizeEvent(QResizeEvent*); +private: + void positionPreviews(); + KDecorationPreviewOptions* options; + KDecorationPreviewBridge* bridge[NumWindows]; + KDecoration* deco[NumWindows]; + QLabel* no_preview; + QRegion mask; +}; class KDecorationPreviewBridge : public KDecorationBridgeUnstable - { - public: - KDecorationPreviewBridge( KDecorationPreview* preview, bool active ); - virtual bool isActive() const; - virtual bool isCloseable() const; - virtual bool isMaximizable() const; - virtual MaximizeMode maximizeMode() const; - virtual bool isMinimizable() const; - virtual bool providesContextHelp() const; - virtual int desktop() const; - virtual bool isModal() const; - virtual bool isShadeable() const; - virtual bool isShade() const; - virtual bool isSetShade() const; - virtual bool keepAbove() const; - virtual bool keepBelow() const; - virtual bool isMovable() const; - virtual bool isResizable() const; - virtual NET::WindowType windowType( unsigned long supported_types ) const; - virtual QIcon icon() const; - virtual QString caption() const; - virtual void processMousePressEvent( QMouseEvent* ); - virtual void showWindowMenu( const QRect &); - virtual void showWindowMenu( const QPoint & ); - virtual void performWindowOperation( WindowOperation ); - virtual void setMask( const QRegion&, int ); - virtual bool isPreview() const; - virtual QRect geometry() const; - virtual QRect iconGeometry() const; - virtual QRegion unobscuredRegion( const QRegion& r ) const; - virtual WId windowId() const; - virtual void closeWindow(); - virtual void maximize( MaximizeMode mode ); - virtual void minimize(); - virtual void showContextHelp(); - virtual void setDesktop( int desktop ); - virtual void titlebarDblClickOperation(); - virtual void titlebarMouseWheelOperation( int delta ); - virtual void setShade( bool set ); - virtual void setKeepAbove( bool ); - virtual void setKeepBelow( bool ); - virtual int currentDesktop() const; - virtual QWidget* initialParentWidget() const; - virtual Qt::WFlags initialWFlags() const; - virtual void grabXServer( bool grab ); +{ +public: + KDecorationPreviewBridge(KDecorationPreview* preview, bool active); + virtual bool isActive() const; + virtual bool isCloseable() const; + virtual bool isMaximizable() const; + virtual MaximizeMode maximizeMode() const; + virtual bool isMinimizable() const; + virtual bool providesContextHelp() const; + virtual int desktop() const; + virtual bool isModal() const; + virtual bool isShadeable() const; + virtual bool isShade() const; + virtual bool isSetShade() const; + virtual bool keepAbove() const; + virtual bool keepBelow() const; + virtual bool isMovable() const; + virtual bool isResizable() const; + virtual NET::WindowType windowType(unsigned long supported_types) const; + virtual QIcon icon() const; + virtual QString caption() const; + virtual void processMousePressEvent(QMouseEvent*); + virtual void showWindowMenu(const QRect &); + virtual void showWindowMenu(const QPoint &); + virtual void performWindowOperation(WindowOperation); + virtual void setMask(const QRegion&, int); + virtual bool isPreview() const; + virtual QRect geometry() const; + virtual QRect iconGeometry() const; + virtual QRegion unobscuredRegion(const QRegion& r) const; + virtual WId windowId() const; + virtual void closeWindow(); + virtual void maximize(MaximizeMode mode); + virtual void minimize(); + virtual void showContextHelp(); + virtual void setDesktop(int desktop); + virtual void titlebarDblClickOperation(); + virtual void titlebarMouseWheelOperation(int delta); + virtual void setShade(bool set); + virtual void setKeepAbove(bool); + virtual void setKeepBelow(bool); + virtual int currentDesktop() const; + virtual QWidget* initialParentWidget() const; + virtual Qt::WFlags initialWFlags() const; + virtual void grabXServer(bool grab); - virtual bool compositingActive() const; - virtual QRect transparentRect() const; + virtual bool compositingActive() const; + virtual QRect transparentRect() const; - // Window tabbing - virtual bool isClientGroupActive(); - virtual QList< ClientGroupItem > clientGroupItems() const; - virtual long itemId( int index ); - virtual int visibleClientGroupItem(); - virtual void setVisibleClientGroupItem( int index ); - virtual void moveItemInClientGroup( int index, int before ); - virtual void moveItemToClientGroup( long itemId, int before ); - virtual void removeFromClientGroup( int index, const QRect& newGeom ); - virtual void closeClientGroupItem( int index ); - virtual void closeAllInClientGroup(); - virtual void displayClientMenu( int index, const QPoint& pos ); - virtual WindowOperation buttonToWindowOperation( Qt::MouseButtons button ); + // Window tabbing + virtual bool isClientGroupActive(); + virtual QList< ClientGroupItem > clientGroupItems() const; + virtual long itemId(int index); + virtual int visibleClientGroupItem(); + virtual void setVisibleClientGroupItem(int index); + virtual void moveItemInClientGroup(int index, int before); + virtual void moveItemToClientGroup(long itemId, int before); + virtual void removeFromClientGroup(int index, const QRect& newGeom); + virtual void closeClientGroupItem(int index); + virtual void closeAllInClientGroup(); + virtual void displayClientMenu(int index, const QPoint& pos); + virtual WindowOperation buttonToWindowOperation(Qt::MouseButtons button); - private: - KDecorationPreview* preview; - bool active; - }; +private: + KDecorationPreview* preview; + bool active; +}; class KDecorationPreviewOptions : public KDecorationOptions - { - public: - KDecorationPreviewOptions(); - virtual ~KDecorationPreviewOptions(); - virtual unsigned long updateSettings(); +{ +public: + KDecorationPreviewOptions(); + virtual ~KDecorationPreviewOptions(); + virtual unsigned long updateSettings(); - void setCustomBorderSize(BorderSize size); - void setCustomTitleButtonsEnabled(bool enabled); - void setCustomTitleButtons(const QString &left, const QString &right); + void setCustomBorderSize(BorderSize size); + void setCustomTitleButtonsEnabled(bool enabled); + void setCustomTitleButtons(const QString &left, const QString &right); - private: - BorderSize customBorderSize; - bool customButtonsChanged; - bool customButtons; - QString customTitleButtonsLeft; - QString customTitleButtonsRight; - }; +private: + BorderSize customBorderSize; + bool customButtonsChanged; + bool customButtons; + QString customTitleButtonsLeft; + QString customTitleButtonsRight; +}; class KDecorationPreviewPlugins : public KDecorationPlugins - { - public: - KDecorationPreviewPlugins(const KSharedConfigPtr &cfg); - virtual bool provides( Requirement ); - }; +{ +public: + KDecorationPreviewPlugins(const KSharedConfigPtr &cfg); + virtual bool provides(Requirement); +}; inline KDecorationPreviewPlugins::KDecorationPreviewPlugins(const KSharedConfigPtr &cfg) - : KDecorationPlugins( cfg ) - { - } + : KDecorationPlugins(cfg) +{ +} #endif diff --git a/kcmkwin/kwindesktop/desktopnameswidget.cpp b/kcmkwin/kwindesktop/desktopnameswidget.cpp index 8cb0911a3..21b180526 100644 --- a/kcmkwin/kwindesktop/desktopnameswidget.cpp +++ b/kcmkwin/kwindesktop/desktopnameswidget.cpp @@ -30,101 +30,94 @@ along with this program. If not, see . namespace KWin { -DesktopNamesWidget::DesktopNamesWidget( QWidget *parent ) - : QWidget( parent ) - , m_maxDesktops( 0 ) - { +DesktopNamesWidget::DesktopNamesWidget(QWidget *parent) + : QWidget(parent) + , m_maxDesktops(0) +{ m_namesLayout = new QGridLayout; - m_namesLayout->setMargin( 0 ); + m_namesLayout->setMargin(0); - setLayout( m_namesLayout ); - } + setLayout(m_namesLayout); +} DesktopNamesWidget::~DesktopNamesWidget() - { - } +{ +} -void DesktopNamesWidget::numberChanged( int number ) - { - if( (number < 1) || (number > m_maxDesktops) ) +void DesktopNamesWidget::numberChanged(int number) +{ + if ((number < 1) || (number > m_maxDesktops)) return; - if( m_nameInputs.size() != number ) - { - if( number < m_nameInputs.size() ) - { + if (m_nameInputs.size() != number) { + if (number < m_nameInputs.size()) { // remove widgets - while( number != m_nameInputs.size() ) - { + while (number != m_nameInputs.size()) { KLineEdit* edit = m_nameInputs.last(); m_nameInputs.removeLast(); delete edit; QLabel* label = m_nameLabels.last(); m_nameLabels.removeLast(); delete label; - } } - else - { + } else { // add widgets - while( number != m_nameInputs.size() ) - { + while (number != m_nameInputs.size()) { int desktop = m_nameInputs.size(); - QLabel* label = new QLabel( i18n( "Desktop %1:", desktop+1 ), this ); - KLineEdit* edit = new KLineEdit( this ); - label->setWhatsThis( i18n( "Here you can enter the name for desktop %1", desktop+1 ) ); - edit->setWhatsThis( i18n( "Here you can enter the name for desktop %1", desktop+1 ) ); + QLabel* label = new QLabel(i18n("Desktop %1:", desktop + 1), this); + KLineEdit* edit = new KLineEdit(this); + label->setWhatsThis(i18n("Here you can enter the name for desktop %1", desktop + 1)); + edit->setWhatsThis(i18n("Here you can enter the name for desktop %1", desktop + 1)); - m_namesLayout->addWidget( label, desktop % 10, 0 + 2 * (desktop >= 10), 1, 1 ); - m_namesLayout->addWidget( edit, desktop % 10, 1 + 2 * (desktop >= 10), 1, 1 ); + m_namesLayout->addWidget(label, desktop % 10, 0 + 2 *(desktop >= 10), 1, 1); + m_namesLayout->addWidget(edit, desktop % 10, 1 + 2 *(desktop >= 10), 1, 1); m_nameInputs << edit; m_nameLabels << label; - setDefaultName( desktop +1 ); - if( desktop > 1 ) - { - setTabOrder( m_nameInputs[desktop - 1], m_nameInputs[desktop] ); - } - connect( edit, SIGNAL(textChanged(const QString&)), SIGNAL( changed() )); + setDefaultName(desktop + 1); + if (desktop > 1) { + setTabOrder(m_nameInputs[desktop - 1], m_nameInputs[desktop]); } + connect(edit, SIGNAL(textChanged(const QString&)), SIGNAL(changed())); } } } +} QString DesktopNamesWidget::name(int desktop) - { - if( (desktop < 1) || (desktop > m_maxDesktops) || (desktop > m_nameInputs.size()) ) +{ + if ((desktop < 1) || (desktop > m_maxDesktops) || (desktop > m_nameInputs.size())) return QString(); return m_nameInputs[ desktop -1 ]->text(); - } +} -void DesktopNamesWidget::setName( int desktop, QString desktopName ) - { - if( (desktop < 1) || (desktop > m_maxDesktops) || (desktop > m_nameInputs.size()) ) +void DesktopNamesWidget::setName(int desktop, QString desktopName) +{ + if ((desktop < 1) || (desktop > m_maxDesktops) || (desktop > m_nameInputs.size())) return; - m_nameInputs[ desktop-1 ]->setText( desktopName ); - } + m_nameInputs[ desktop-1 ]->setText(desktopName); +} -void DesktopNamesWidget::setDefaultName( int desktop ) - { - if( (desktop < 1) || (desktop > m_maxDesktops) ) +void DesktopNamesWidget::setDefaultName(int desktop) +{ + if ((desktop < 1) || (desktop > m_maxDesktops)) return; - QString name = m_desktopConfig->cachedDesktopName( desktop ); - if( name.isEmpty() ) + QString name = m_desktopConfig->cachedDesktopName(desktop); + if (name.isEmpty()) name = i18n("Desktop %1", desktop); - m_nameInputs[ desktop -1 ]->setText( name ); - } + m_nameInputs[ desktop -1 ]->setText(name); +} void DesktopNamesWidget::setMaxDesktops(int maxDesktops) - { +{ m_maxDesktops = maxDesktops; - } +} -void DesktopNamesWidget::setDesktopConfig( KWinDesktopConfig* desktopConfig) - { +void DesktopNamesWidget::setDesktopConfig(KWinDesktopConfig* desktopConfig) +{ m_desktopConfig = desktopConfig; - } +} } // namespace diff --git a/kcmkwin/kwindesktop/desktopnameswidget.h b/kcmkwin/kwindesktop/desktopnameswidget.h index 81f46eae7..fccf0663e 100644 --- a/kcmkwin/kwindesktop/desktopnameswidget.h +++ b/kcmkwin/kwindesktop/desktopnameswidget.h @@ -35,27 +35,27 @@ class KWinDesktopConfig; class DesktopNamesWidget : public QWidget { Q_OBJECT - public: - DesktopNamesWidget( QWidget *parent ); - ~DesktopNamesWidget(); - QString name( int desktop ); - void setName( int desktop, QString desktopName ); - void setDefaultName( int desktop ); - void setMaxDesktops( int maxDesktops ); - void setDesktopConfig( KWinDesktopConfig *desktopConfig ); +public: + DesktopNamesWidget(QWidget *parent); + ~DesktopNamesWidget(); + QString name(int desktop); + void setName(int desktop, QString desktopName); + void setDefaultName(int desktop); + void setMaxDesktops(int maxDesktops); + void setDesktopConfig(KWinDesktopConfig *desktopConfig); - signals: - void changed(); +signals: + void changed(); - public slots: - void numberChanged( int number ); +public slots: + void numberChanged(int number); - private: - QList< QLabel* > m_nameLabels; - QList< KLineEdit* > m_nameInputs; - QGridLayout* m_namesLayout; - int m_maxDesktops; - KWinDesktopConfig *m_desktopConfig; +private: + QList< QLabel* > m_nameLabels; + QList< KLineEdit* > m_nameInputs; + QGridLayout* m_namesLayout; + int m_maxDesktops; + KWinDesktopConfig *m_desktopConfig; }; } // namespace diff --git a/kcmkwin/kwindesktop/main.cpp b/kcmkwin/kwindesktop/main.cpp index 15b08adea..ee5c50455 100644 --- a/kcmkwin/kwindesktop/main.cpp +++ b/kcmkwin/kwindesktop/main.cpp @@ -42,111 +42,110 @@ along with this program. If not, see . #include -K_PLUGIN_FACTORY( KWinDesktopConfigFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( KWinDesktopConfigFactory( "kcm_kwindesktop" )) +K_PLUGIN_FACTORY(KWinDesktopConfigFactory, registerPlugin();) +K_EXPORT_PLUGIN(KWinDesktopConfigFactory("kcm_kwindesktop")) namespace KWin { -KWinDesktopConfigForm::KWinDesktopConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinDesktopConfigForm::KWinDesktopConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinDesktopConfig::KWinDesktopConfig( QWidget* parent, const QVariantList& args ) - : KCModule( KWinDesktopConfigFactory::componentData(), parent, args ) - , m_config( KSharedConfig::openConfig( "kwinrc" )) - , m_actionCollection( NULL ) - , m_switchDesktopCollection( NULL ) - { +KWinDesktopConfig::KWinDesktopConfig(QWidget* parent, const QVariantList& args) + : KCModule(KWinDesktopConfigFactory::componentData(), parent, args) + , m_config(KSharedConfig::openConfig("kwinrc")) + , m_actionCollection(NULL) + , m_switchDesktopCollection(NULL) +{ init(); - } +} void KWinDesktopConfig::init() - { - m_ui = new KWinDesktopConfigForm( this ); +{ + m_ui = new KWinDesktopConfigForm(this); // TODO: there has to be a way to add the shortcuts editor to the ui file - m_editor = new KShortcutsEditor( m_ui, KShortcutsEditor::GlobalAction ); - m_ui->editorFrame->setLayout( new QVBoxLayout() ); - m_ui->editorFrame->layout()->setMargin( 0 ); - m_ui->editorFrame->layout()->addWidget( m_editor ); + m_editor = new KShortcutsEditor(m_ui, KShortcutsEditor::GlobalAction); + m_ui->editorFrame->setLayout(new QVBoxLayout()); + m_ui->editorFrame->layout()->setMargin(0); + m_ui->editorFrame->layout()->addWidget(m_editor); - m_ui->desktopNames->setDesktopConfig( this ); - m_ui->desktopNames->setMaxDesktops( maxDesktops ); - m_ui->desktopNames->numberChanged( defaultDesktops ); + m_ui->desktopNames->setDesktopConfig(this); + m_ui->desktopNames->setMaxDesktops(maxDesktops); + m_ui->desktopNames->numberChanged(defaultDesktops); // number of rows are still missing in Plasma - hide them for now // TODO: bring them back when trunk is open and bug Plasma devs ;-) m_ui->label->hide(); m_ui->rowsSpinBox->hide(); - QVBoxLayout* layout = new QVBoxLayout( this ); - layout->addWidget( m_ui ); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_ui); - setQuickHelp( i18n("

Multiple Desktops

In this module, you can configure how many virtual desktops you want and how these should be labeled.")); + setQuickHelp(i18n("

Multiple Desktops

In this module, you can configure how many virtual desktops you want and how these should be labeled.")); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); - m_actionCollection->setConfigGroup( "Desktop Switching" ); - m_actionCollection->setConfigGlobal( true ); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); + m_actionCollection->setConfigGroup("Desktop Switching"); + m_actionCollection->setConfigGlobal(true); - m_switchDesktopCollection = new KActionCollection( this, KComponentData("kwin") ); - m_switchDesktopCollection->setConfigGroup( "Desktop Switching" ); - m_switchDesktopCollection->setConfigGlobal( true ); + m_switchDesktopCollection = new KActionCollection(this, KComponentData("kwin")); + m_switchDesktopCollection->setConfigGroup("Desktop Switching"); + m_switchDesktopCollection->setConfigGlobal(true); // actions for switch desktop collection - other action is filled dynamically - KAction* a = qobject_cast(m_switchDesktopCollection->addAction( "Switch to Next Desktop" )); + KAction* a = qobject_cast(m_switchDesktopCollection->addAction("Switch to Next Desktop")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch to Next Desktop" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch to Next Desktop")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - a = qobject_cast(m_switchDesktopCollection->addAction( "Switch to Previous Desktop" )); + a = qobject_cast(m_switchDesktopCollection->addAction("Switch to Previous Desktop")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch to Previous Desktop" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch to Previous Desktop")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - a = qobject_cast(m_switchDesktopCollection->addAction( "Switch One Desktop to the Right" )); + a = qobject_cast(m_switchDesktopCollection->addAction("Switch One Desktop to the Right")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch One Desktop to the Right" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch One Desktop to the Right")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - a = qobject_cast(m_switchDesktopCollection->addAction( "Switch One Desktop to the Left" )); + a = qobject_cast(m_switchDesktopCollection->addAction("Switch One Desktop to the Left")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch One Desktop to the Left" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch One Desktop to the Left")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - a = qobject_cast(m_switchDesktopCollection->addAction( "Switch One Desktop Up" )); + a = qobject_cast(m_switchDesktopCollection->addAction("Switch One Desktop Up")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch One Desktop Up" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch One Desktop Up")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - a = qobject_cast(m_switchDesktopCollection->addAction( "Switch One Desktop Down" )); + a = qobject_cast(m_switchDesktopCollection->addAction("Switch One Desktop Down")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Switch One Desktop Down" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + a->setText(i18n("Switch One Desktop Down")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); - m_editor->addCollection( m_switchDesktopCollection, i18n( "Desktop Switching" ) ); + m_editor->addCollection(m_switchDesktopCollection, i18n("Desktop Switching")); #ifdef Q_WS_X11 // get number of desktops - NETRootInfo info( QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames ); + NETRootInfo info(QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames); int n = info.numberOfDesktops(); - for( int i=1; i<=n; ++i ) - { + for (int i = 1; i <= n; ++i) { KAction* a = qobject_cast(m_actionCollection->addAction(QString("Switch to Desktop %1").arg(i))); a->setProperty("isConfigurationAction", true); - a->setText( i18n("Switch to Desktop %1", i) ); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); - } + a->setText(i18n("Switch to Desktop %1", i)); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); + } // This should be after the "Switch to Desktop %1" loop. It HAS to be // there after numberSpinBox is connected to slotChangeShortcuts. We would // overwrite the users settings if not, m_ui->numberSpinBox->setValue(n); - m_editor->addCollection( m_actionCollection, i18n( "Desktop Switching" ) ); + m_editor->addCollection(m_actionCollection, i18n("Desktop Switching")); #endif // search the effect names @@ -157,13 +156,13 @@ void KWinDesktopConfig::init() QString cube; QString fadedesktop; services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_slide'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) slide = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_cubeslide'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) cube = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_fadedesktop'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) fadedesktop = services.first()->name(); m_ui->effectComboBox->addItem(i18n("No Animation")); @@ -172,24 +171,24 @@ void KWinDesktopConfig::init() m_ui->effectComboBox->addItem(fadedesktop); // effect config and info button - m_ui->effectInfoButton->setIcon( KIcon( "dialog-information" )); - m_ui->effectConfigButton->setIcon( KIcon( "configure" )); + m_ui->effectInfoButton->setIcon(KIcon("dialog-information")); + m_ui->effectConfigButton->setIcon(KIcon("configure")); - connect( m_ui->rowsSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( m_ui->numberSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( m_ui->numberSpinBox, SIGNAL(valueChanged(int)), SLOT(slotChangeShortcuts(int))); - connect( m_ui->activityCheckBox, SIGNAL(stateChanged(int)), SLOT(changed())); - connect( m_ui->desktopNames, SIGNAL(changed()), SLOT(changed())); - connect( m_ui->popupInfoCheckBox, SIGNAL(toggled(bool)), SLOT(changed())); - connect( m_ui->popupHideSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( m_ui->desktopLayoutIndicatorCheckBox, SIGNAL(stateChanged(int)), SLOT(changed())); - connect( m_ui->wrapAroundBox, SIGNAL(stateChanged(int)), SLOT(changed())); - connect( m_editor, SIGNAL(keyChange()), SLOT(changed())); - connect( m_ui->allShortcutsCheckBox, SIGNAL(stateChanged(int)), SLOT(slotShowAllShortcuts())); - connect( m_ui->effectComboBox, SIGNAL(currentIndexChanged(int)), SLOT(changed())); - connect( m_ui->effectComboBox, SIGNAL(currentIndexChanged(int)), SLOT(slotEffectSelectionChanged(int))); - connect( m_ui->effectInfoButton, SIGNAL(clicked()), SLOT(slotAboutEffectClicked())); - connect( m_ui->effectConfigButton, SIGNAL(clicked()), SLOT(slotConfigureEffectClicked())); + connect(m_ui->rowsSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(m_ui->numberSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(m_ui->numberSpinBox, SIGNAL(valueChanged(int)), SLOT(slotChangeShortcuts(int))); + connect(m_ui->activityCheckBox, SIGNAL(stateChanged(int)), SLOT(changed())); + connect(m_ui->desktopNames, SIGNAL(changed()), SLOT(changed())); + connect(m_ui->popupInfoCheckBox, SIGNAL(toggled(bool)), SLOT(changed())); + connect(m_ui->popupHideSpinBox, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(m_ui->desktopLayoutIndicatorCheckBox, SIGNAL(stateChanged(int)), SLOT(changed())); + connect(m_ui->wrapAroundBox, SIGNAL(stateChanged(int)), SLOT(changed())); + connect(m_editor, SIGNAL(keyChange()), SLOT(changed())); + connect(m_ui->allShortcutsCheckBox, SIGNAL(stateChanged(int)), SLOT(slotShowAllShortcuts())); + connect(m_ui->effectComboBox, SIGNAL(currentIndexChanged(int)), SLOT(changed())); + connect(m_ui->effectComboBox, SIGNAL(currentIndexChanged(int)), SLOT(slotEffectSelectionChanged(int))); + connect(m_ui->effectInfoButton, SIGNAL(clicked()), SLOT(slotAboutEffectClicked())); + connect(m_ui->effectConfigButton, SIGNAL(clicked()), SLOT(slotConfigureEffectClicked())); // Begin check for immutable - taken from old desktops kcm #ifdef Q_WS_X11 @@ -198,211 +197,201 @@ void KWinDesktopConfig::init() int kwin_screen_number = 0; #endif - m_config = KSharedConfig::openConfig( "kwinrc" ); + m_config = KSharedConfig::openConfig("kwinrc"); QByteArray groupname; - if( kwin_screen_number == 0 ) + if (kwin_screen_number == 0) groupname = "Desktops"; else - groupname = "Desktops-screen-" + QByteArray::number ( kwin_screen_number ); + groupname = "Desktops-screen-" + QByteArray::number(kwin_screen_number); - if( m_config->isGroupImmutable( groupname ) ) - { + if (m_config->isGroupImmutable(groupname)) { m_ui->nameGroup->setEnabled(false); //number of desktops widgets m_ui->numberLabel->setEnabled(false); m_ui->numberSpinBox->setEnabled(false); - } - else - { + } else { KConfigGroup cfgGroup(m_config.data(), groupname.constData()); - if( cfgGroup.isEntryImmutable( "Number" ) ) - { + if (cfgGroup.isEntryImmutable("Number")) { //number of desktops widgets m_ui->numberLabel->setEnabled(false); m_ui->numberSpinBox->setEnabled(false); - } } - // End check for immutable } + // End check for immutable +} KWinDesktopConfig::~KWinDesktopConfig() - { +{ undo(); - } +} void KWinDesktopConfig::defaults() - { +{ // TODO: plasma stuff - m_ui->numberSpinBox->setValue( defaultDesktops ); - m_ui->desktopNames->numberChanged( defaultDesktops ); - for( int i=1; i<=maxDesktops; i++ ) - { - m_desktopNames[i-1] = i18n( "Desktop %1", i ); - if( i <= defaultDesktops ) - m_ui->desktopNames->setDefaultName( i ); - } + m_ui->numberSpinBox->setValue(defaultDesktops); + m_ui->desktopNames->numberChanged(defaultDesktops); + for (int i = 1; i <= maxDesktops; i++) { + m_desktopNames[i-1] = i18n("Desktop %1", i); + if (i <= defaultDesktops) + m_ui->desktopNames->setDefaultName(i); + } // popup info - m_ui->popupInfoCheckBox->setChecked( false ); - m_ui->popupHideSpinBox->setValue( 1000 ); - m_ui->desktopLayoutIndicatorCheckBox->setChecked( true ); + m_ui->popupInfoCheckBox->setChecked(false); + m_ui->popupHideSpinBox->setValue(1000); + m_ui->desktopLayoutIndicatorCheckBox->setChecked(true); - m_ui->effectComboBox->setCurrentIndex( 1 ); + m_ui->effectComboBox->setCurrentIndex(1); - m_ui->wrapAroundBox->setChecked( true ); + m_ui->wrapAroundBox->setChecked(true); m_editor->allDefault(); emit changed(true); - } +} void KWinDesktopConfig::load() - { +{ // This method is called on reset(). So undo all changes. undo(); #ifdef Q_WS_X11 // get number of desktops - NETRootInfo info( QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames ); + NETRootInfo info(QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames); - for( int i = 1; i <= maxDesktops; i++ ) - { - QString name = QString::fromUtf8( info.desktopName(i) ); + for (int i = 1; i <= maxDesktops; i++) { + QString name = QString::fromUtf8(info.desktopName(i)); m_desktopNames << name; - m_ui->desktopNames->setName( i, name ); - } + m_ui->desktopNames->setName(i, name); + } #endif // Popup info - KConfigGroup popupInfo( m_config, "PopupInfo" ); - m_ui->popupInfoCheckBox->setChecked( popupInfo.readEntry( "ShowPopup", false )); - m_ui->popupHideSpinBox->setValue( popupInfo.readEntry( "PopupHideDelay", 1000 )); - m_ui->desktopLayoutIndicatorCheckBox->setChecked( !popupInfo.readEntry( "TextOnly", false) ); + KConfigGroup popupInfo(m_config, "PopupInfo"); + m_ui->popupInfoCheckBox->setChecked(popupInfo.readEntry("ShowPopup", false)); + m_ui->popupHideSpinBox->setValue(popupInfo.readEntry("PopupHideDelay", 1000)); + m_ui->desktopLayoutIndicatorCheckBox->setChecked(!popupInfo.readEntry("TextOnly", false)); // Wrap Around on screen edge - KConfigGroup windowConfig( m_config, "Windows" ); - m_ui->wrapAroundBox->setChecked( windowConfig.readEntry( "RollOverDesktops", true ) ); + KConfigGroup windowConfig(m_config, "Windows"); + m_ui->wrapAroundBox->setChecked(windowConfig.readEntry("RollOverDesktops", true)); // Effect for desktop switching // Set current option to "none" if no plugin is activated. - KConfigGroup effectconfig( m_config, "Plugins" ); - m_ui->effectComboBox->setCurrentIndex( 0 ); - if( effectEnabled( "slide", effectconfig )) - m_ui->effectComboBox->setCurrentIndex( 1 ); - if( effectEnabled( "cubeslide", effectconfig )) - m_ui->effectComboBox->setCurrentIndex( 2 ); - if( effectEnabled( "fadedesktop", effectconfig )) - m_ui->effectComboBox->setCurrentIndex( 3 ); - slotEffectSelectionChanged( m_ui->effectComboBox->currentIndex() ); + KConfigGroup effectconfig(m_config, "Plugins"); + m_ui->effectComboBox->setCurrentIndex(0); + if (effectEnabled("slide", effectconfig)) + m_ui->effectComboBox->setCurrentIndex(1); + if (effectEnabled("cubeslide", effectconfig)) + m_ui->effectComboBox->setCurrentIndex(2); + if (effectEnabled("fadedesktop", effectconfig)) + m_ui->effectComboBox->setCurrentIndex(3); + slotEffectSelectionChanged(m_ui->effectComboBox->currentIndex()); // TODO: plasma stuff - QDBusInterface interface( "org.kde.plasma-desktop", "/App" ); - if( interface.isValid() ) - { - bool perVirtualDesktopViews = interface.call( "perVirtualDesktopViews" ).arguments().first().toBool(); - m_ui->activityCheckBox->setEnabled( true ); - m_ui->activityCheckBox->setChecked( perVirtualDesktopViews ); - } - else - m_ui->activityCheckBox->setEnabled( false ); + QDBusInterface interface("org.kde.plasma-desktop", "/App"); + if (interface.isValid()) { + bool perVirtualDesktopViews = interface.call("perVirtualDesktopViews").arguments().first().toBool(); + m_ui->activityCheckBox->setEnabled(true); + m_ui->activityCheckBox->setChecked(perVirtualDesktopViews); + } else + m_ui->activityCheckBox->setEnabled(false); emit changed(false); - } +} void KWinDesktopConfig::save() - { +{ // TODO: plasma stuff #ifdef Q_WS_X11 - NETRootInfo info( QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames ); + NETRootInfo info(QX11Info::display(), NET::NumberOfDesktops | NET::DesktopNames); // set desktop names - for( int i = 1; i <= maxDesktops; i++ ) - { + for (int i = 1; i <= maxDesktops; i++) { QString desktopName = m_desktopNames[ i -1 ]; - if( i <= m_ui->numberSpinBox->value() ) - desktopName = m_ui->desktopNames->name( i ); - info.setDesktopName( i, desktopName.toUtf8()); + if (i <= m_ui->numberSpinBox->value()) + desktopName = m_ui->desktopNames->name(i); + info.setDesktopName(i, desktopName.toUtf8()); info.activate(); - } + } // set number of desktops - info.setNumberOfDesktops( m_ui->numberSpinBox->value() ); + info.setNumberOfDesktops(m_ui->numberSpinBox->value()); info.activate(); XSync(QX11Info::display(), false); #endif // Popup info - KConfigGroup popupInfo( m_config, "PopupInfo" ); - popupInfo.writeEntry( "ShowPopup", m_ui->popupInfoCheckBox->isChecked() ); - popupInfo.writeEntry( "PopupHideDelay", m_ui->popupHideSpinBox->value() ); - popupInfo.writeEntry( "TextOnly", !m_ui->desktopLayoutIndicatorCheckBox->isChecked() ); + KConfigGroup popupInfo(m_config, "PopupInfo"); + popupInfo.writeEntry("ShowPopup", m_ui->popupInfoCheckBox->isChecked()); + popupInfo.writeEntry("PopupHideDelay", m_ui->popupHideSpinBox->value()); + popupInfo.writeEntry("TextOnly", !m_ui->desktopLayoutIndicatorCheckBox->isChecked()); // Wrap Around on screen edge - KConfigGroup windowConfig( m_config, "Windows" ); - windowConfig.writeEntry( "RollOverDesktops", m_ui->wrapAroundBox->isChecked() ); + KConfigGroup windowConfig(m_config, "Windows"); + windowConfig.writeEntry("RollOverDesktops", m_ui->wrapAroundBox->isChecked()); // Effect desktop switching - KConfigGroup effectconfig( m_config, "Plugins" ); + KConfigGroup effectconfig(m_config, "Plugins"); int desktopSwitcher = m_ui->effectComboBox->currentIndex(); - switch( desktopSwitcher ) - { - case 0: - // no effect - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 1: - // slide - effectconfig.writeEntry("kwin4_effect_slideEnabled", true); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 2: - // cube - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", true); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); - break; - case 3: - // fadedesktop - effectconfig.writeEntry("kwin4_effect_slideEnabled", false); - effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); - effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", true); - break; - } + switch(desktopSwitcher) { + case 0: + // no effect + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 1: + // slide + effectconfig.writeEntry("kwin4_effect_slideEnabled", true); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 2: + // cube + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", true); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", false); + break; + case 3: + // fadedesktop + effectconfig.writeEntry("kwin4_effect_slideEnabled", false); + effectconfig.writeEntry("kwin4_effect_cubeslideEnabled", false); + effectconfig.writeEntry("kwin4_effect_fadedesktopEnabled", true); + break; + } m_editor->save(); m_config->sync(); // Send signal to all kwin instances - QDBusMessage message = QDBusMessage::createSignal( "/KWin", "org.kde.KWin", "reloadConfig" ); - QDBusConnection::sessionBus().send( message ); + QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); - QDBusInterface interface( "org.kde.plasma-desktop", "/App" ); - interface.call( "setPerVirtualDesktopViews", ( m_ui->activityCheckBox->isChecked() ) ); + QDBusInterface interface("org.kde.plasma-desktop", "/App"); + interface.call("setPerVirtualDesktopViews", (m_ui->activityCheckBox->isChecked())); emit changed(false); - } +} void KWinDesktopConfig::undo() - { +{ // The global shortcuts editor makes changes active immediately. In case // of undo we have to undo them manually m_editor->undoChanges(); - } +} -QString KWinDesktopConfig::cachedDesktopName( int desktop ) - { - if( desktop > m_desktopNames.size() ) +QString KWinDesktopConfig::cachedDesktopName(int desktop) +{ + if (desktop > m_desktopNames.size()) return QString(); return m_desktopNames[ desktop -1 ]; - } +} -QString KWinDesktopConfig::extrapolatedShortcut( int desktop ) const - { +QString KWinDesktopConfig::extrapolatedShortcut(int desktop) const +{ if (!desktop || desktop > m_actionCollection->count()) return QString(); @@ -415,28 +404,22 @@ QString KWinDesktopConfig::extrapolatedShortcut( int desktop ) const before = beforeAction->globalShortcut(KAction::DefaultShortcut).toString(); QString seq; - if ( before.contains( QRegExp("F[0-9]{1,2}") ) ) - { - if (desktop < 13) // 10? + if (before.contains(QRegExp("F[0-9]{1,2}"))) { + if (desktop < 13) // 10? seq = QString("F%1").arg(desktop); - else if ( !before.contains("Shift") ) + else if (!before.contains("Shift")) seq = "Shift+" + QString("F%1").arg(desktop - 10); - } - else if ( before.contains( QRegExp("[0-9]") ) ) - { + } else if (before.contains(QRegExp("[0-9]"))) { if (desktop == 10) seq = '0'; - else if (desktop > 10) - { - if ( !before.contains("Shift") ) + else if (desktop > 10) { + if (!before.contains("Shift")) seq = "Shift+" + QString::number(desktop == 20 ? 0 : (desktop - 10)); - } - else + } else seq = QString::number(desktop); } - if ( !seq.isEmpty() ) - { + if (!seq.isEmpty()) { if (before.contains("Ctrl")) seq.prepend("Ctrl+"); if (before.contains("Alt")) @@ -445,122 +428,111 @@ QString KWinDesktopConfig::extrapolatedShortcut( int desktop ) const seq.prepend("Shift+"); if (before.contains("Meta")) seq.prepend("Meta+"); - } - return seq; } + return seq; +} -void KWinDesktopConfig::slotChangeShortcuts( int number ) - { - if( (number < 1) || (number > maxDesktops) ) +void KWinDesktopConfig::slotChangeShortcuts(int number) +{ + if ((number < 1) || (number > maxDesktops)) return; - if( m_ui->allShortcutsCheckBox->isChecked() ) + if (m_ui->allShortcutsCheckBox->isChecked()) number = maxDesktops; - while( number != m_actionCollection->count() ) - { - if( number < m_actionCollection->count() ) - { + while (number != m_actionCollection->count()) { + if (number < m_actionCollection->count()) { // Remove the action from the action collection. The action itself // will still exist because that's the way kwin currently works. // No need to remove/forget it. See kwinbindings. KAction *a = qobject_cast( - m_actionCollection->takeAction( m_actionCollection->actions().last() )); + m_actionCollection->takeAction(m_actionCollection->actions().last())); // Remove any associated global shortcut. Set it to "" a->setGlobalShortcut( - KShortcut(), - KAction::ActiveShortcut, - KAction::NoAutoloading); + KShortcut(), + KAction::ActiveShortcut, + KAction::NoAutoloading); m_ui->messageLabel->hide(); delete a; - } - else - { + } else { // add desktop int desktop = m_actionCollection->count() + 1; KAction* action = qobject_cast(m_actionCollection->addAction(QString("Switch to Desktop %1").arg(desktop))); action->setProperty("isConfigurationAction", true); - action->setText( i18n("Switch to Desktop %1", desktop) ); - action->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); + action->setText(i18n("Switch to Desktop %1", desktop)); + action->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); QString shortcutString = extrapolatedShortcut(desktop); - if (shortcutString.isEmpty()) - { - m_ui->messageLabel->setText(i18n( "No suitable Shortcut for Desktop %1 found", desktop )); + if (shortcutString.isEmpty()) { + m_ui->messageLabel->setText(i18n("No suitable Shortcut for Desktop %1 found", desktop)); m_ui->messageLabel->show(); - } - else - { + } else { KShortcut shortcut(shortcutString); - if (!shortcut.primary().isEmpty() || KGlobalAccel::self()->isGlobalShortcutAvailable(shortcut.primary())) - { - action->setGlobalShortcut( shortcut, KAction::ActiveShortcut, KAction::NoAutoloading ); - m_ui->messageLabel->setText(i18n( "Assigned global Shortcut \"%1\" to Desktop %2", shortcutString, desktop )); + if (!shortcut.primary().isEmpty() || KGlobalAccel::self()->isGlobalShortcutAvailable(shortcut.primary())) { + action->setGlobalShortcut(shortcut, KAction::ActiveShortcut, KAction::NoAutoloading); + m_ui->messageLabel->setText(i18n("Assigned global Shortcut \"%1\" to Desktop %2", shortcutString, desktop)); m_ui->messageLabel->show(); - } - else - { - m_ui->messageLabel->setText(i18n( "Shortcut conflict: Could not set Shortcut %1 for Desktop %2", shortcutString, desktop )); + } else { + m_ui->messageLabel->setText(i18n("Shortcut conflict: Could not set Shortcut %1 for Desktop %2", shortcutString, desktop)); m_ui->messageLabel->show(); - } } } } - m_editor->clearCollections(); - m_editor->addCollection( m_switchDesktopCollection, i18n( "Desktop Switching" ) ); - m_editor->addCollection( m_actionCollection, i18n( "Desktop Switching" ) ); } + m_editor->clearCollections(); + m_editor->addCollection(m_switchDesktopCollection, i18n("Desktop Switching")); + m_editor->addCollection(m_actionCollection, i18n("Desktop Switching")); +} void KWinDesktopConfig::slotShowAllShortcuts() - { - slotChangeShortcuts( m_ui->numberSpinBox->value() ); - } +{ + slotChangeShortcuts(m_ui->numberSpinBox->value()); +} -void KWinDesktopConfig::slotEffectSelectionChanged( int index ) - { +void KWinDesktopConfig::slotEffectSelectionChanged(int index) +{ bool enabled = false; - if( index != 0 ) + if (index != 0) enabled = true; - m_ui->effectInfoButton->setEnabled( enabled ); + m_ui->effectInfoButton->setEnabled(enabled); // only cube has config dialog - if( index != 2 ) + if (index != 2) enabled = false; - m_ui->effectConfigButton->setEnabled( enabled ); - } + m_ui->effectConfigButton->setEnabled(enabled); +} -bool KWinDesktopConfig::effectEnabled( const QString& effect, const KConfigGroup& cfg ) const - { +bool KWinDesktopConfig::effectEnabled(const QString& effect, const KConfigGroup& cfg) const +{ KService::List services = KServiceTypeTrader::self()->query( - "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); - if( services.isEmpty()) + "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) return false; QVariant v = services.first()->property("X-KDE-PluginInfo-EnabledByDefault"); return cfg.readEntry("kwin4_effect_" + effect + "Enabled", v.toBool()); - } +} void KWinDesktopConfig::slotAboutEffectClicked() - { +{ KServiceTypeTrader* trader = KServiceTypeTrader::self(); KService::List services; QString effect; - switch( m_ui->effectComboBox->currentIndex() ) - { - case 1: - effect = "slide"; - break; - case 2: - effect = "cubeslide"; - break; - case 3: - effect = "fadedesktop"; - break; - default: - return; - } - services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); - if( services.isEmpty() ) + switch(m_ui->effectComboBox->currentIndex()) { + case 1: + effect = "slide"; + break; + case 2: + effect = "cubeslide"; + break; + case 3: + effect = "fadedesktop"; + break; + default: return; - KPluginInfo pluginInfo( services.first() ); + } + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) + return; + KPluginInfo pluginInfo(services.first()); const QString name = pluginInfo.name(); const QString comment = pluginInfo.comment(); @@ -572,60 +544,53 @@ void KWinDesktopConfig::slotAboutEffectClicked() const QString icon = pluginInfo.icon(); KAboutData aboutData(name.toUtf8(), name.toUtf8(), ki18n(name.toUtf8()), version.toUtf8(), ki18n(comment.toUtf8()), KAboutLicense::byKeyword(license).key(), ki18n(QByteArray()), ki18n(QByteArray()), website.toLatin1()); - aboutData.setProgramIconName( icon ); + aboutData.setProgramIconName(icon); const QStringList authors = author.split(','); const QStringList emails = email.split(','); int i = 0; - if( authors.count() == emails.count() ) - { - foreach( const QString &author, authors ) - { - if( !author.isEmpty() ) - { + if (authors.count() == emails.count()) { + foreach (const QString & author, authors) { + if (!author.isEmpty()) { aboutData.addAuthor(ki18n(author.toUtf8()), ki18n(QByteArray()), emails[i].toUtf8(), 0); - } - i++; } + i++; } - QPointer aboutPlugin = new KAboutApplicationDialog( &aboutData, this ); + } + QPointer aboutPlugin = new KAboutApplicationDialog(&aboutData, this); aboutPlugin->exec(); delete aboutPlugin; - } +} void KWinDesktopConfig::slotConfigureEffectClicked() - { +{ QString effect; - switch( m_ui->effectComboBox->currentIndex() ) - { - case 2: - effect = "cubeslide_config"; - break; - default: - return; - } - KCModuleProxy* proxy = new KCModuleProxy( effect ); - QPointer< KDialog > configDialog = new KDialog( this ); - configDialog->setWindowTitle( m_ui->effectComboBox->currentText() ); - configDialog->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default ); + switch(m_ui->effectComboBox->currentIndex()) { + case 2: + effect = "cubeslide_config"; + break; + default: + return; + } + KCModuleProxy* proxy = new KCModuleProxy(effect); + QPointer< KDialog > configDialog = new KDialog(this); + configDialog->setWindowTitle(m_ui->effectComboBox->currentText()); + configDialog->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default); connect(configDialog, SIGNAL(defaultClicked()), proxy, SLOT(defaults())); - QWidget *showWidget = new QWidget( configDialog ); + QWidget *showWidget = new QWidget(configDialog); QVBoxLayout *layout = new QVBoxLayout; - showWidget->setLayout( layout ); - layout->addWidget( proxy ); - layout->insertSpacing( -1, KDialog::marginHint() ); - configDialog->setMainWidget( showWidget ); + showWidget->setLayout(layout); + layout->addWidget(proxy); + layout->insertSpacing(-1, KDialog::marginHint()); + configDialog->setMainWidget(showWidget); - if( configDialog->exec() == QDialog::Accepted ) - { + if (configDialog->exec() == QDialog::Accepted) { proxy->save(); - } - else - { + } else { proxy->load(); - } - delete configDialog; } + delete configDialog; +} } // namespace diff --git a/kcmkwin/kwindesktop/main.h b/kcmkwin/kwindesktop/main.h index 077c47b78..969e9ff5d 100644 --- a/kcmkwin/kwindesktop/main.h +++ b/kcmkwin/kwindesktop/main.h @@ -36,55 +36,55 @@ static const int maxDesktops = 20; static const int defaultDesktops = 4; class KWinDesktopConfigForm : public QWidget, public Ui::KWinDesktopConfigForm - { +{ Q_OBJECT - public: - explicit KWinDesktopConfigForm( QWidget* parent ); - }; +public: + explicit KWinDesktopConfigForm(QWidget* parent); +}; class KWinDesktopConfig : public KCModule - { +{ Q_OBJECT - public: - explicit KWinDesktopConfig( QWidget* parent, const QVariantList& args ); - ~KWinDesktopConfig(); - QString cachedDesktopName( int desktop ); +public: + explicit KWinDesktopConfig(QWidget* parent, const QVariantList& args); + ~KWinDesktopConfig(); + QString cachedDesktopName(int desktop); - // undo all changes - void undo(); + // undo all changes + void undo(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private slots: - void slotChangeShortcuts( int number ); - void slotShowAllShortcuts(); - void slotEffectSelectionChanged( int index ); - void slotAboutEffectClicked(); - void slotConfigureEffectClicked(); +private slots: + void slotChangeShortcuts(int number); + void slotShowAllShortcuts(); + void slotEffectSelectionChanged(int index); + void slotAboutEffectClicked(); + void slotConfigureEffectClicked(); - private: - void init(); - bool effectEnabled( const QString& effect, const KConfigGroup& cfg ) const; - QString extrapolatedShortcut( int desktop ) const; +private: + void init(); + bool effectEnabled(const QString& effect, const KConfigGroup& cfg) const; + QString extrapolatedShortcut(int desktop) const; - private: - KWinDesktopConfigForm* m_ui; - KSharedConfigPtr m_config; - // cache for desktop names given by NETRootInfo - // needed as the widget only stores the names for actual number of desktops - QStringList m_desktopNames; - // Collection for switching desktops like ctrl+f1 - KActionCollection* m_actionCollection; - // Collection for next, previous, up, down desktop - KActionCollection* m_switchDesktopCollection; - KShortcutsEditor* m_editor; - }; +private: + KWinDesktopConfigForm* m_ui; + KSharedConfigPtr m_config; + // cache for desktop names given by NETRootInfo + // needed as the widget only stores the names for actual number of desktops + QStringList m_desktopNames; + // Collection for switching desktops like ctrl+f1 + KActionCollection* m_actionCollection; + // Collection for next, previous, up, down desktop + KActionCollection* m_switchDesktopCollection; + KShortcutsEditor* m_editor; +}; } // namespace diff --git a/kcmkwin/kwinoptions/main.cpp b/kcmkwin/kwinoptions/main.cpp index 5ace6e3e6..7cd1ef092 100644 --- a/kcmkwin/kwinoptions/main.cpp +++ b/kcmkwin/kwinoptions/main.cpp @@ -42,114 +42,114 @@ K_PLUGIN_FACTORY_DECLARATION(KWinOptionsFactory) class KFocusConfigStandalone : public KFocusConfig { Q_OBJECT - public: - KFocusConfigStandalone(QWidget* parent, const QVariantList &) - : KFocusConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) - {} +public: + KFocusConfigStandalone(QWidget* parent, const QVariantList &) + : KFocusConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) + {} }; class KMovingConfigStandalone : public KMovingConfig { Q_OBJECT - public: - KMovingConfigStandalone(QWidget* parent, const QVariantList &) - : KMovingConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) - {} +public: + KMovingConfigStandalone(QWidget* parent, const QVariantList &) + : KMovingConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) + {} }; class KAdvancedConfigStandalone : public KAdvancedConfig { Q_OBJECT - public: - KAdvancedConfigStandalone(QWidget* parent, const QVariantList &) - : KAdvancedConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) - {} +public: + KAdvancedConfigStandalone(QWidget* parent, const QVariantList &) + : KAdvancedConfig(true, new KConfig("kwinrc"), KWinOptionsFactory::componentData(), parent) + {} }; KWinOptions::KWinOptions(QWidget *parent, const QVariantList &) - : KCModule(KWinOptionsFactory::componentData(), parent) + : KCModule(KWinOptionsFactory::componentData(), parent) { - mConfig = new KConfig( "kwinrc", KConfig::IncludeGlobals ); + mConfig = new KConfig("kwinrc", KConfig::IncludeGlobals); - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setMargin(0); - tab = new KTabWidget(this); - layout->addWidget(tab); + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setMargin(0); + tab = new KTabWidget(this); + layout->addWidget(tab); - mFocus = new KFocusConfig(false, mConfig, componentData(), this); - mFocus->setObjectName( QLatin1String("KWin Focus Config" )); - tab->addTab(mFocus, i18n("&Focus")); - connect(mFocus, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mFocus = new KFocusConfig(false, mConfig, componentData(), this); + mFocus->setObjectName(QLatin1String("KWin Focus Config")); + tab->addTab(mFocus, i18n("&Focus")); + connect(mFocus, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - mTitleBarActions = new KTitleBarActionsConfig(false, mConfig, componentData(), this); - mTitleBarActions->setObjectName( QLatin1String("KWin TitleBar Actions" )); - tab->addTab(mTitleBarActions, i18n("&Titlebar Actions")); - connect(mTitleBarActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mTitleBarActions = new KTitleBarActionsConfig(false, mConfig, componentData(), this); + mTitleBarActions->setObjectName(QLatin1String("KWin TitleBar Actions")); + tab->addTab(mTitleBarActions, i18n("&Titlebar Actions")); + connect(mTitleBarActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - mWindowActions = new KWindowActionsConfig(false, mConfig, componentData(), this); - mWindowActions->setObjectName( QLatin1String("KWin Window Actions" )); - tab->addTab(mWindowActions, i18n("Window Actio&ns")); - connect(mWindowActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mWindowActions = new KWindowActionsConfig(false, mConfig, componentData(), this); + mWindowActions->setObjectName(QLatin1String("KWin Window Actions")); + tab->addTab(mWindowActions, i18n("Window Actio&ns")); + connect(mWindowActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - mMoving = new KMovingConfig(false, mConfig, componentData(), this); - mMoving->setObjectName( QLatin1String("KWin Moving" )); - tab->addTab(mMoving, i18n("&Moving")); - connect(mMoving, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mMoving = new KMovingConfig(false, mConfig, componentData(), this); + mMoving->setObjectName(QLatin1String("KWin Moving")); + tab->addTab(mMoving, i18n("&Moving")); + connect(mMoving, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - mAdvanced = new KAdvancedConfig(false, mConfig, componentData(), this); - mAdvanced->setObjectName( QLatin1String("KWin Advanced" )); - tab->addTab(mAdvanced, i18n("Ad&vanced")); - connect(mAdvanced, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mAdvanced = new KAdvancedConfig(false, mConfig, componentData(), this); + mAdvanced->setObjectName(QLatin1String("KWin Advanced")); + tab->addTab(mAdvanced, i18n("Ad&vanced")); + connect(mAdvanced, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - KAboutData *about = - new KAboutData(I18N_NOOP("kcmkwinoptions"), 0, ki18n("Window Behavior Configuration Module"), - 0, KLocalizedString(), KAboutData::License_GPL, - ki18n("(c) 1997 - 2002 KWin and KControl Authors")); + KAboutData *about = + new KAboutData(I18N_NOOP("kcmkwinoptions"), 0, ki18n("Window Behavior Configuration Module"), + 0, KLocalizedString(), KAboutData::License_GPL, + ki18n("(c) 1997 - 2002 KWin and KControl Authors")); - about->addAuthor(ki18n("Matthias Ettrich"),KLocalizedString(),"ettrich@kde.org"); - about->addAuthor(ki18n("Waldo Bastian"),KLocalizedString(),"bastian@kde.org"); - about->addAuthor(ki18n("Cristian Tibirna"),KLocalizedString(),"tibirna@kde.org"); - about->addAuthor(ki18n("Matthias Kalle Dalheimer"),KLocalizedString(),"kalle@kde.org"); - about->addAuthor(ki18n("Daniel Molkentin"),KLocalizedString(),"molkentin@kde.org"); - about->addAuthor(ki18n("Wynn Wilkes"),KLocalizedString(),"wynnw@caldera.com"); - about->addAuthor(ki18n("Pat Dowler"),KLocalizedString(),"dowler@pt1B1106.FSH.UVic.CA"); - about->addAuthor(ki18n("Bernd Wuebben"),KLocalizedString(),"wuebben@kde.org"); - about->addAuthor(ki18n("Matthias Hoelzer-Kluepfel"),KLocalizedString(),"hoelzer@kde.org"); - setAboutData(about); + about->addAuthor(ki18n("Matthias Ettrich"), KLocalizedString(), "ettrich@kde.org"); + about->addAuthor(ki18n("Waldo Bastian"), KLocalizedString(), "bastian@kde.org"); + about->addAuthor(ki18n("Cristian Tibirna"), KLocalizedString(), "tibirna@kde.org"); + about->addAuthor(ki18n("Matthias Kalle Dalheimer"), KLocalizedString(), "kalle@kde.org"); + about->addAuthor(ki18n("Daniel Molkentin"), KLocalizedString(), "molkentin@kde.org"); + about->addAuthor(ki18n("Wynn Wilkes"), KLocalizedString(), "wynnw@caldera.com"); + about->addAuthor(ki18n("Pat Dowler"), KLocalizedString(), "dowler@pt1B1106.FSH.UVic.CA"); + about->addAuthor(ki18n("Bernd Wuebben"), KLocalizedString(), "wuebben@kde.org"); + about->addAuthor(ki18n("Matthias Hoelzer-Kluepfel"), KLocalizedString(), "hoelzer@kde.org"); + setAboutData(about); } KWinOptions::~KWinOptions() { - delete mConfig; + delete mConfig; } void KWinOptions::load() { - mConfig->reparseConfiguration(); - mFocus->load(); - mTitleBarActions->load(); - mWindowActions->load(); - mMoving->load(); - mAdvanced->load(); - emit KCModule::changed( false ); + mConfig->reparseConfiguration(); + mFocus->load(); + mTitleBarActions->load(); + mWindowActions->load(); + mMoving->load(); + mAdvanced->load(); + emit KCModule::changed(false); } void KWinOptions::save() { - mFocus->save(); - mTitleBarActions->save(); - mWindowActions->save(); - mMoving->save(); - mAdvanced->save(); + mFocus->save(); + mTitleBarActions->save(); + mWindowActions->save(); + mMoving->save(); + mAdvanced->save(); - emit KCModule::changed( false ); - // Send signal to kwin - mConfig->sync(); - // Send signal to all kwin instances - QDBusMessage message = + emit KCModule::changed(false); + // Send signal to kwin + mConfig->sync(); + // Send signal to all kwin instances + QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + QDBusConnection::sessionBus().send(message); } @@ -157,96 +157,96 @@ void KWinOptions::save() void KWinOptions::defaults() { - mFocus->defaults(); - mTitleBarActions->defaults(); - mWindowActions->defaults(); - mMoving->defaults(); - mAdvanced->defaults(); + mFocus->defaults(); + mTitleBarActions->defaults(); + mWindowActions->defaults(); + mMoving->defaults(); + mAdvanced->defaults(); } QString KWinOptions::quickHelp() const { - return i18n("

Window Behavior

Here you can customize the way windows behave when being" - " moved, resized or clicked on. You can also specify a focus policy as well as a placement" - " policy for new windows.

" - "

Please note that this configuration will not take effect if you do not use" - " KWin as your window manager. If you do use a different window manager, please refer to its documentation" - " for how to customize window behavior.

"); + return i18n("

Window Behavior

Here you can customize the way windows behave when being" + " moved, resized or clicked on. You can also specify a focus policy as well as a placement" + " policy for new windows.

" + "

Please note that this configuration will not take effect if you do not use" + " KWin as your window manager. If you do use a different window manager, please refer to its documentation" + " for how to customize window behavior.

"); } void KWinOptions::moduleChanged(bool state) { - emit KCModule::changed(state); + emit KCModule::changed(state); } KActionsOptions::KActionsOptions(QWidget *parent, const QVariantList &) - : KCModule(KWinOptionsFactory::componentData(), parent) + : KCModule(KWinOptionsFactory::componentData(), parent) { - mConfig = new KConfig( "kwinrc", KConfig::IncludeGlobals ); + mConfig = new KConfig("kwinrc", KConfig::IncludeGlobals); - QVBoxLayout *layout = new QVBoxLayout(this); - layout->setMargin(0); - tab = new KTabWidget(this); - layout->addWidget(tab); + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setMargin(0); + tab = new KTabWidget(this); + layout->addWidget(tab); - mTitleBarActions = new KTitleBarActionsConfig(false, mConfig, componentData(), this); - mTitleBarActions->setObjectName( QLatin1String("KWin TitleBar Actions" )); - tab->addTab(mTitleBarActions, i18n("&Titlebar Actions")); - connect(mTitleBarActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mTitleBarActions = new KTitleBarActionsConfig(false, mConfig, componentData(), this); + mTitleBarActions->setObjectName(QLatin1String("KWin TitleBar Actions")); + tab->addTab(mTitleBarActions, i18n("&Titlebar Actions")); + connect(mTitleBarActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); - mWindowActions = new KWindowActionsConfig(false, mConfig, componentData(), this); - mWindowActions->setObjectName( QLatin1String("KWin Window Actions" )); - tab->addTab(mWindowActions, i18n("Window Actio&ns")); - connect(mWindowActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); + mWindowActions = new KWindowActionsConfig(false, mConfig, componentData(), this); + mWindowActions->setObjectName(QLatin1String("KWin Window Actions")); + tab->addTab(mWindowActions, i18n("Window Actio&ns")); + connect(mWindowActions, SIGNAL(changed(bool)), this, SLOT(moduleChanged(bool))); } KActionsOptions::~KActionsOptions() { - delete mConfig; + delete mConfig; } void KActionsOptions::load() { - mTitleBarActions->load(); - mWindowActions->load(); - emit KCModule::changed( false ); + mTitleBarActions->load(); + mWindowActions->load(); + emit KCModule::changed(false); } void KActionsOptions::save() { - mTitleBarActions->save(); - mWindowActions->save(); + mTitleBarActions->save(); + mWindowActions->save(); - emit KCModule::changed( false ); - // Send signal to kwin - mConfig->sync(); - // Send signal to all kwin instances - QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + emit KCModule::changed(false); + // Send signal to kwin + mConfig->sync(); + // Send signal to all kwin instances + QDBusMessage message = + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); } void KActionsOptions::defaults() { - mTitleBarActions->defaults(); - mWindowActions->defaults(); + mTitleBarActions->defaults(); + mWindowActions->defaults(); } void KActionsOptions::moduleChanged(bool state) { - emit KCModule::changed(state); + emit KCModule::changed(state); } K_PLUGIN_FACTORY_DEFINITION(KWinOptionsFactory, - registerPlugin("kwinactions"); - registerPlugin("kwinfocus"); - registerPlugin("kwinmoving"); - registerPlugin("kwinadvanced"); - registerPlugin("kwinoptions"); - ) + registerPlugin("kwinactions"); + registerPlugin("kwinfocus"); + registerPlugin("kwinmoving"); + registerPlugin("kwinadvanced"); + registerPlugin("kwinoptions"); + ) K_EXPORT_PLUGIN(KWinOptionsFactory("kcmkwm")) #include "main.moc" diff --git a/kcmkwin/kwinoptions/main.h b/kcmkwin/kwinoptions/main.h index a1c6945bd..c9ec3ac0e 100644 --- a/kcmkwin/kwinoptions/main.h +++ b/kcmkwin/kwinoptions/main.h @@ -37,63 +37,63 @@ class KMovingConfig; class KWinOptions : public KCModule { - Q_OBJECT + Q_OBJECT public: - KWinOptions(QWidget *parent, const QVariantList &args); - virtual ~KWinOptions(); + KWinOptions(QWidget *parent, const QVariantList &args); + virtual ~KWinOptions(); - void load(); - void save(); - void defaults(); - QString quickHelp() const; + void load(); + void save(); + void defaults(); + QString quickHelp() const; protected slots: - void moduleChanged(bool state); + void moduleChanged(bool state); private: - KTabWidget *tab; + KTabWidget *tab; - KFocusConfig *mFocus; - KTitleBarActionsConfig *mTitleBarActions; - KWindowActionsConfig *mWindowActions; - KMovingConfig *mMoving; - KAdvancedConfig *mAdvanced; + KFocusConfig *mFocus; + KTitleBarActionsConfig *mTitleBarActions; + KWindowActionsConfig *mWindowActions; + KMovingConfig *mMoving; + KAdvancedConfig *mAdvanced; - KConfig *mConfig; + KConfig *mConfig; }; class KActionsOptions : public KCModule { - Q_OBJECT + Q_OBJECT public: - KActionsOptions(QWidget *parent, const QVariantList &args); - virtual ~KActionsOptions(); + KActionsOptions(QWidget *parent, const QVariantList &args); + virtual ~KActionsOptions(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected slots: - void moduleChanged(bool state); + void moduleChanged(bool state); private: - KTabWidget *tab; + KTabWidget *tab; - KTitleBarActionsConfig *mTitleBarActions; - KWindowActionsConfig *mWindowActions; + KTitleBarActionsConfig *mTitleBarActions; + KWindowActionsConfig *mWindowActions; - KConfig *mConfig; + KConfig *mConfig; }; #endif diff --git a/kcmkwin/kwinoptions/mouse.cpp b/kcmkwin/kwinoptions/mouse.cpp index 431c23ca1..fa1f7daab 100644 --- a/kcmkwin/kwinoptions/mouse.cpp +++ b/kcmkwin/kwinoptions/mouse.cpp @@ -48,364 +48,370 @@ #include "mouse.moc" -namespace { +namespace +{ char const * const cnf_Max[] = { - "MaximizeButtonLeftClickCommand", - "MaximizeButtonMiddleClickCommand", - "MaximizeButtonRightClickCommand", + "MaximizeButtonLeftClickCommand", + "MaximizeButtonMiddleClickCommand", + "MaximizeButtonRightClickCommand", }; char const * const tbl_Max[] = { - "Maximize", - "Maximize (vertical only)", - "Maximize (horizontal only)", - "" }; + "Maximize", + "Maximize (vertical only)", + "Maximize (horizontal only)", + "" +}; QPixmap maxButtonPixmaps[3]; void createMaxButtonPixmaps() { - char const * maxButtonXpms[][3 + 13] = { - {0, 0, 0, - "...............", - ".......#.......", - "......###......", - ".....#####.....", - "..#....#....#..", - ".##....#....##.", - "###############", - ".##....#....##.", - "..#....#....#..", - ".....#####.....", - "......###......", - ".......#.......", - "..............."}, - {0, 0, 0, - "...............", - ".......#.......", - "......###......", - ".....#####.....", - ".......#.......", - ".......#.......", - ".......#.......", - ".......#.......", - ".......#.......", - ".....#####.....", - "......###......", - ".......#.......", - "..............."}, - {0, 0, 0, - "...............", - "...............", - "...............", - "...............", - "..#.........#..", - ".##.........##.", - "###############", - ".##.........##.", - "..#.........#..", - "...............", - "...............", - "...............", - "..............."}, - }; + char const * maxButtonXpms[][3 + 13] = { + { + 0, 0, 0, + "...............", + ".......#.......", + "......###......", + ".....#####.....", + "..#....#....#..", + ".##....#....##.", + "###############", + ".##....#....##.", + "..#....#....#..", + ".....#####.....", + "......###......", + ".......#.......", + "..............." + }, + { + 0, 0, 0, + "...............", + ".......#.......", + "......###......", + ".....#####.....", + ".......#.......", + ".......#.......", + ".......#.......", + ".......#.......", + ".......#.......", + ".....#####.....", + "......###......", + ".......#.......", + "..............." + }, + { + 0, 0, 0, + "...............", + "...............", + "...............", + "...............", + "..#.........#..", + ".##.........##.", + "###############", + ".##.........##.", + "..#.........#..", + "...............", + "...............", + "...............", + "..............." + }, + }; - QByteArray baseColor(". c " + KColorScheme(QPalette::Active, KColorScheme::View).background().color().name().toAscii()); - QByteArray textColor("# c " + KColorScheme(QPalette::Active, KColorScheme::View).foreground().color().name().toAscii()); - for (int t = 0; t < 3; ++t) - { - maxButtonXpms[t][0] = "15 13 2 1"; - maxButtonXpms[t][1] = baseColor.constData(); - maxButtonXpms[t][2] = textColor.constData(); - maxButtonPixmaps[t] = QPixmap(maxButtonXpms[t]); - maxButtonPixmaps[t].setMask(maxButtonPixmaps[t].createHeuristicMask()); - } + QByteArray baseColor(". c " + KColorScheme(QPalette::Active, KColorScheme::View).background().color().name().toAscii()); + QByteArray textColor("# c " + KColorScheme(QPalette::Active, KColorScheme::View).foreground().color().name().toAscii()); + for (int t = 0; t < 3; ++t) { + maxButtonXpms[t][0] = "15 13 2 1"; + maxButtonXpms[t][1] = baseColor.constData(); + maxButtonXpms[t][2] = textColor.constData(); + maxButtonPixmaps[t] = QPixmap(maxButtonXpms[t]); + maxButtonPixmaps[t].setMask(maxButtonPixmaps[t].createHeuristicMask()); + } } } // namespace void KTitleBarActionsConfig::paletteChanged() { - createMaxButtonPixmaps(); - for (int b = 0; b < 3; ++b) - for (int t = 0; t < 3; ++t) - coMax[b]->setItemIcon(t, maxButtonPixmaps[t]); + createMaxButtonPixmaps(); + for (int b = 0; b < 3; ++b) + for (int t = 0; t < 3; ++t) + coMax[b]->setItemIcon(t, maxButtonPixmaps[t]); } -KTitleBarActionsConfig::KTitleBarActionsConfig (bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) - : KCModule(inst, parent), config(_config), standAlone(_standAlone) +KTitleBarActionsConfig::KTitleBarActionsConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) + : KCModule(inst, parent), config(_config), standAlone(_standAlone) { - QString strWin1, strWin2, strWin3, strAllKey, strAll1, strAll2, strAll3; - QGridLayout *grid; - QGroupBox *box; - QLabel *label; - QString strMouseButton1, strMouseButton3; - QString txtButton1, txtButton3; - QStringList items; - bool leftHandedMouse = ( KGlobalSettings::mouseSettings().handed == KGlobalSettings::KMouseSettings::LeftHanded); + QString strWin1, strWin2, strWin3, strAllKey, strAll1, strAll2, strAll3; + QGridLayout *grid; + QGroupBox *box; + QLabel *label; + QString strMouseButton1, strMouseButton3; + QString txtButton1, txtButton3; + QStringList items; + bool leftHandedMouse = (KGlobalSettings::mouseSettings().handed == KGlobalSettings::KMouseSettings::LeftHanded); - QVBoxLayout *layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); -/** Titlebar doubleclick ************/ + /** Titlebar doubleclick ************/ - QWidget *titlebarActions = new QWidget(this); - QGridLayout *gLayout = new QGridLayout(titlebarActions); - layout->addWidget( titlebarActions ); + QWidget *titlebarActions = new QWidget(this); + QGridLayout *gLayout = new QGridLayout(titlebarActions); + layout->addWidget(titlebarActions); - KComboBox* combo = new KComboBox(this); - combo->addItem(i18nc("@item:inlistbox behavior on double click", "Maximize")); - combo->addItem(i18n("Maximize (vertical only)")); - combo->addItem(i18n("Maximize (horizontal only)")); - combo->addItem(i18nc("@item:inlistbox behavior on double click", "Minimize")); - combo->addItem(i18n("Shade")); - combo->addItem(i18n("Lower")); - combo->addItem(i18nc("@item:inlistbox behavior on double click", "Close")); - combo->addItem(i18nc("@item:inlistbox behavior on double click", "On All Desktops")); - combo->addItem(i18n("Nothing")); - combo->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiDbl = combo; - combo->setWhatsThis( i18n("Behavior on double click into the titlebar.")); + KComboBox* combo = new KComboBox(this); + combo->addItem(i18nc("@item:inlistbox behavior on double click", "Maximize")); + combo->addItem(i18n("Maximize (vertical only)")); + combo->addItem(i18n("Maximize (horizontal only)")); + combo->addItem(i18nc("@item:inlistbox behavior on double click", "Minimize")); + combo->addItem(i18n("Shade")); + combo->addItem(i18n("Lower")); + combo->addItem(i18nc("@item:inlistbox behavior on double click", "Close")); + combo->addItem(i18nc("@item:inlistbox behavior on double click", "On All Desktops")); + combo->addItem(i18n("Nothing")); + combo->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiDbl = combo; + combo->setWhatsThis(i18n("Behavior on double click into the titlebar.")); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(i18n("&Titlebar double-click:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gLayout->addWidget(label, 0, 0); - gLayout->addWidget(combo, 0, 1); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(i18n("&Titlebar double-click:"), this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gLayout->addWidget(label, 0, 0); + gLayout->addWidget(combo, 0, 1); -/** Mouse Wheel Events **************/ - // Titlebar and frame mouse Wheel - KComboBox* comboW = new KComboBox(this); - comboW->addItem(i18n("Raise/Lower")); - comboW->addItem(i18n("Shade/Unshade")); - comboW->addItem(i18n("Maximize/Restore")); - comboW->addItem(i18n("Keep Above/Below")); - comboW->addItem(i18n("Move to Previous/Next Desktop")); - comboW->addItem(i18n("Change Opacity")); - comboW->addItem(i18n("Switch to Window Tab to the Left/Right")); - comboW->addItem(i18n("Nothing")); - comboW->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); - connect(comboW, SIGNAL(activated(int)), SLOT(changed())); - coTiAct4 = comboW; - comboW->setWhatsThis( i18n("Handle mouse wheel events")); + /** Mouse Wheel Events **************/ + // Titlebar and frame mouse Wheel + KComboBox* comboW = new KComboBox(this); + comboW->addItem(i18n("Raise/Lower")); + comboW->addItem(i18n("Shade/Unshade")); + comboW->addItem(i18n("Maximize/Restore")); + comboW->addItem(i18n("Keep Above/Below")); + comboW->addItem(i18n("Move to Previous/Next Desktop")); + comboW->addItem(i18n("Change Opacity")); + comboW->addItem(i18n("Switch to Window Tab to the Left/Right")); + comboW->addItem(i18n("Nothing")); + comboW->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); + connect(comboW, SIGNAL(activated(int)), SLOT(changed())); + coTiAct4 = comboW; + comboW->setWhatsThis(i18n("Handle mouse wheel events")); - comboW->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(i18n("Titlebar wheel event:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(comboW); - gLayout->addWidget(label, 1, 0); - gLayout->addWidget(comboW, 1, 1); + comboW->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(i18n("Titlebar wheel event:"), this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(comboW); + gLayout->addWidget(label, 1, 0); + gLayout->addWidget(comboW, 1, 1); -/** Titlebar and frame **************/ + /** Titlebar and frame **************/ - box = new QGroupBox(i18n("Titlebar && Frame"), this); - layout->addWidget(box); - box->setObjectName(QString::fromLatin1("Titlebar and Frame")); - box->setWhatsThis( i18n("Here you can customize mouse click behavior when clicking on the" - " titlebar or the frame of a window.") ); + box = new QGroupBox(i18n("Titlebar && Frame"), this); + layout->addWidget(box); + box->setObjectName(QString::fromLatin1("Titlebar and Frame")); + box->setWhatsThis(i18n("Here you can customize mouse click behavior when clicking on the" + " titlebar or the frame of a window.")); - grid = new QGridLayout(box); + grid = new QGridLayout(box); - strMouseButton1 = i18n("Left button:"); - txtButton1 = i18n("In this row you can customize left click behavior when clicking into" - " the titlebar or the frame."); + strMouseButton1 = i18n("Left button:"); + txtButton1 = i18n("In this row you can customize left click behavior when clicking into" + " the titlebar or the frame."); - strMouseButton3 = i18n("Right button:"); - txtButton3 = i18n("In this row you can customize right click behavior when clicking into" - " the titlebar or the frame." ); + strMouseButton3 = i18n("Right button:"); + txtButton3 = i18n("In this row you can customize right click behavior when clicking into" + " the titlebar or the frame."); - if ( leftHandedMouse ) - { - qSwap(strMouseButton1, strMouseButton3); - qSwap(txtButton1, txtButton3); - } + if (leftHandedMouse) { + qSwap(strMouseButton1, strMouseButton3); + qSwap(txtButton1, txtButton3); + } - label = new QLabel(strMouseButton1, box); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - grid->addWidget(label, 1, 0); - label->setWhatsThis( txtButton1); + label = new QLabel(strMouseButton1, box); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + grid->addWidget(label, 1, 0); + label->setWhatsThis(txtButton1); - label = new QLabel(i18n("Middle button:"), box); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - grid->addWidget(label, 2, 0); - label->setWhatsThis( i18n("In this row you can customize middle click behavior when clicking into" - " the titlebar or the frame.") ); + label = new QLabel(i18n("Middle button:"), box); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + grid->addWidget(label, 2, 0); + label->setWhatsThis(i18n("In this row you can customize middle click behavior when clicking into" + " the titlebar or the frame.")); - label = new QLabel(strMouseButton3, box); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - grid->addWidget(label, 3, 0); - label->setWhatsThis( txtButton3); + label = new QLabel(strMouseButton3, box); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + grid->addWidget(label, 3, 0); + label->setWhatsThis(txtButton3); - label = new QLabel(i18n("Active"), box); - grid->addWidget(label, 0, 1); - label->setAlignment(Qt::AlignCenter); - label->setWhatsThis( i18n("In this column you can customize mouse clicks into the titlebar" - " or the frame of an active window.") ); + label = new QLabel(i18n("Active"), box); + grid->addWidget(label, 0, 1); + label->setAlignment(Qt::AlignCenter); + label->setWhatsThis(i18n("In this column you can customize mouse clicks into the titlebar" + " or the frame of an active window.")); - // Titlebar and frame, active, mouse button 1 - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 1, 1); - combo->addItem(i18n("Raise")); - combo->addItem(i18n("Lower")); - combo->addItem(i18n("Operations Menu")); - combo->addItem(i18n("Toggle Raise & Lower")); - combo->addItem(i18n("Close")); - combo->addItem(i18n("Start Window Tab Drag")); - combo->addItem(i18n("Nothing")); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiAct1 = combo; + // Titlebar and frame, active, mouse button 1 + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 1, 1); + combo->addItem(i18n("Raise")); + combo->addItem(i18n("Lower")); + combo->addItem(i18n("Operations Menu")); + combo->addItem(i18n("Toggle Raise & Lower")); + combo->addItem(i18n("Close")); + combo->addItem(i18n("Start Window Tab Drag")); + combo->addItem(i18n("Nothing")); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiAct1 = combo; - txtButton1 = i18n("Behavior on left click into the titlebar or frame of an " - "active window."); + txtButton1 = i18n("Behavior on left click into the titlebar or frame of an " + "active window."); - txtButton3 = i18n("Behavior on right click into the titlebar or frame of an " - "active window."); + txtButton3 = i18n("Behavior on right click into the titlebar or frame of an " + "active window."); - // Be nice to left handed users - if ( leftHandedMouse ) qSwap(txtButton1, txtButton3); + // Be nice to left handed users + if (leftHandedMouse) qSwap(txtButton1, txtButton3); - combo->setWhatsThis( txtButton1); + combo->setWhatsThis(txtButton1); - // Titlebar and frame, active, mouse button 2 + // Titlebar and frame, active, mouse button 2 - items << i18n("Raise") - << i18n("Lower") - << i18n("Operations Menu") - << i18n("Toggle Raise & Lower") - << i18n("Close") - << i18n("Start Window Tab Drag") - << i18n("Nothing") - << i18n("Shade"); + items << i18n("Raise") + << i18n("Lower") + << i18n("Operations Menu") + << i18n("Toggle Raise & Lower") + << i18n("Close") + << i18n("Start Window Tab Drag") + << i18n("Nothing") + << i18n("Shade"); - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 2, 1); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiAct2 = combo; - combo->setWhatsThis( i18n("Behavior on middle click into the titlebar or frame of an active window.")); + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 2, 1); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiAct2 = combo; + combo->setWhatsThis(i18n("Behavior on middle click into the titlebar or frame of an active window.")); - // Titlebar and frame, active, mouse button 3 - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 3, 1); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiAct3 = combo; - combo->setWhatsThis( txtButton3 ); + // Titlebar and frame, active, mouse button 3 + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 3, 1); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiAct3 = combo; + combo->setWhatsThis(txtButton3); - txtButton1 = i18n("Behavior on left click into the titlebar or frame of an " - "inactive window."); + txtButton1 = i18n("Behavior on left click into the titlebar or frame of an " + "inactive window."); - txtButton3 = i18n("Behavior on right click into the titlebar or frame of an " - "inactive window."); + txtButton3 = i18n("Behavior on right click into the titlebar or frame of an " + "inactive window."); - // Be nice to left handed users - if ( leftHandedMouse ) qSwap(txtButton1, txtButton3); + // Be nice to left handed users + if (leftHandedMouse) qSwap(txtButton1, txtButton3); - label = new QLabel(i18n("Inactive"), box); - grid->addWidget(label, 0, 2); - label->setAlignment(Qt::AlignCenter); - label->setWhatsThis( i18n("In this column you can customize mouse clicks into the titlebar" - " or the frame of an inactive window.") ); + label = new QLabel(i18n("Inactive"), box); + grid->addWidget(label, 0, 2); + label->setAlignment(Qt::AlignCenter); + label->setWhatsThis(i18n("In this column you can customize mouse clicks into the titlebar" + " or the frame of an inactive window.")); - items.clear(); - items << i18n("Activate & Raise") - << i18n("Activate & Lower") - << i18n("Activate") - << i18n("Shade") - << i18n("Operations Menu") - << i18n("Raise") - << i18n("Lower") - << i18n("Close") - << i18n("Start Window Tab Drag") - << i18n("Nothing"); + items.clear(); + items << i18n("Activate & Raise") + << i18n("Activate & Lower") + << i18n("Activate") + << i18n("Shade") + << i18n("Operations Menu") + << i18n("Raise") + << i18n("Lower") + << i18n("Close") + << i18n("Start Window Tab Drag") + << i18n("Nothing"); - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 1, 2); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiInAct1 = combo; - combo->setWhatsThis( txtButton1); + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 1, 2); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiInAct1 = combo; + combo->setWhatsThis(txtButton1); - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 2, 2); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiInAct2 = combo; - combo->setWhatsThis( i18n("Behavior on middle click into the titlebar or frame of an inactive window.")); + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 2, 2); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiInAct2 = combo; + combo->setWhatsThis(i18n("Behavior on middle click into the titlebar or frame of an inactive window.")); - combo = new KComboBox(box); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - grid->addWidget(combo, 3, 2); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coTiInAct3 = combo; - combo->setWhatsThis( txtButton3); + combo = new KComboBox(box); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + grid->addWidget(combo, 3, 2); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coTiInAct3 = combo; + combo->setWhatsThis(txtButton3); -/** Maximize Button ******************/ + /** Maximize Button ******************/ - box = new QGroupBox(i18n("Maximize Button"), this); - layout->addWidget(box); - box->setObjectName(QString::fromLatin1("Maximize Button")); - box->setWhatsThis( - i18n("Here you can customize behavior when clicking on the maximize button.") ); + box = new QGroupBox(i18n("Maximize Button"), this); + layout->addWidget(box); + box->setObjectName(QString::fromLatin1("Maximize Button")); + box->setWhatsThis( + i18n("Here you can customize behavior when clicking on the maximize button.")); - QHBoxLayout* hlayout = new QHBoxLayout(box); + QHBoxLayout* hlayout = new QHBoxLayout(box); - QString strMouseButton[] = { - i18n("Left button:"), - i18n("Middle button:"), - i18n("Right button:")}; + QString strMouseButton[] = { + i18n("Left button:"), + i18n("Middle button:"), + i18n("Right button:") + }; - QString txtButton[] = { - i18n("Behavior on left click onto the maximize button." ), - i18n("Behavior on middle click onto the maximize button." ), - i18n("Behavior on right click onto the maximize button." )}; + QString txtButton[] = { + i18n("Behavior on left click onto the maximize button."), + i18n("Behavior on middle click onto the maximize button."), + i18n("Behavior on right click onto the maximize button.") + }; - if ( leftHandedMouse ) // Be nice to lefties - { - qSwap(strMouseButton[0], strMouseButton[2]); - qSwap(txtButton[0], txtButton[2]); - } + if (leftHandedMouse) { // Be nice to lefties + qSwap(strMouseButton[0], strMouseButton[2]); + qSwap(txtButton[0], txtButton[2]); + } - createMaxButtonPixmaps(); - for (int b = 0; b < 3; ++b) - { - if (b != 0) hlayout->addItem(new QSpacerItem(5, 5, QSizePolicy::MinimumExpanding, QSizePolicy::Minimum)); // Spacer + createMaxButtonPixmaps(); + for (int b = 0; b < 3; ++b) { + if (b != 0) hlayout->addItem(new QSpacerItem(5, 5, QSizePolicy::MinimumExpanding, QSizePolicy::Minimum)); // Spacer - QLabel * label = new QLabel(strMouseButton[b], box); - hlayout->addWidget(label); - label->setWhatsThis( txtButton[b] ); - label->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Minimum ); + QLabel * label = new QLabel(strMouseButton[b], box); + hlayout->addWidget(label); + label->setWhatsThis(txtButton[b]); + label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); - coMax[b] = new ToolTipComboBox(box, tbl_Max); - hlayout->addWidget(coMax[b]); - for (int t = 0; t < 3; ++t) coMax[b]->addItem(maxButtonPixmaps[t], QString()); - connect(coMax[b], SIGNAL(activated(int)), SLOT(changed())); - connect(coMax[b], SIGNAL(activated(int)), coMax[b], SLOT(changed())); - coMax[b]->setWhatsThis( txtButton[b] ); - coMax[b]->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Minimum ); - } + coMax[b] = new ToolTipComboBox(box, tbl_Max); + hlayout->addWidget(coMax[b]); + for (int t = 0; t < 3; ++t) coMax[b]->addItem(maxButtonPixmaps[t], QString()); + connect(coMax[b], SIGNAL(activated(int)), SLOT(changed())); + connect(coMax[b], SIGNAL(activated(int)), coMax[b], SLOT(changed())); + coMax[b]->setWhatsThis(txtButton[b]); + coMax[b]->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); + } - connect(KGlobalSettings::self(), SIGNAL(kdisplayPaletteChanged()), SLOT(paletteChanged())); + connect(KGlobalSettings::self(), SIGNAL(kdisplayPaletteChanged()), SLOT(paletteChanged())); - layout->addStretch(); + layout->addStretch(); - load(); + load(); } KTitleBarActionsConfig::~KTitleBarActionsConfig() { - if (standAlone) - delete config; + if (standAlone) + delete config; } // do NOT change the texts below, they are written to config file @@ -421,7 +427,8 @@ const char* const tbl_TiDbl[] = { "Close", "OnAllDesktops", "Nothing", - "" }; + "" +}; const char* const tbl_TiAc[] = { "Raise", @@ -432,7 +439,8 @@ const char* const tbl_TiAc[] = { "Start window tab drag", "Nothing", "Shade", - "" }; + "" +}; const char* const tbl_TiInAc[] = { "Activate and raise", @@ -445,25 +453,29 @@ const char* const tbl_TiInAc[] = { "Close", "Start window tab drag", "Nothing", - "" }; + "" +}; const char* const tbl_Win[] = { "Activate, raise and pass click", "Activate and pass click", "Activate", "Activate and raise", - "" }; - + "" +}; + const char* const tbl_WinWheel[] = { "Scroll", "Activate and scroll", "Activate, raise and scroll", - "" }; + "" +}; const char* const tbl_AllKey[] = { "Meta", "Alt", - "" }; + "" +}; const char* const tbl_All[] = { "Move", @@ -474,7 +486,8 @@ const char* const tbl_All[] = { "Lower", "Minimize", "Nothing", - "" }; + "" +}; const char* tbl_TiWAc[] = { "Raise/Lower", @@ -485,7 +498,8 @@ const char* tbl_TiWAc[] = { "Change Opacity", "Switch to Window Tab to the Left/Right", "Nothing", - "" }; + "" +}; const char* tbl_AllW[] = { "Raise/Lower", @@ -496,492 +510,485 @@ const char* tbl_AllW[] = { "Change Opacity", "Switch to Window Tab to the Left/Right", "Nothing", - "" }; + "" +}; -static const char* tbl_num_lookup( const char* const arr[], int pos ) +static const char* tbl_num_lookup(const char* const arr[], int pos) { - for( int i = 0; - arr[ i ][ 0 ] != '\0' && pos >= 0; - ++i ) - { - if( pos == 0 ) + for (int i = 0; + arr[ i ][ 0 ] != '\0' && pos >= 0; + ++i) { + if (pos == 0) return arr[ i ]; --pos; } abort(); // should never happen this way } -static int tbl_txt_lookup( const char* const arr[], const char* txt ) +static int tbl_txt_lookup(const char* const arr[], const char* txt) { int pos = 0; - for( int i = 0; - arr[ i ][ 0 ] != '\0'; - ++i ) - { - if( qstricmp( txt, arr[ i ] ) == 0 ) + for (int i = 0; + arr[ i ][ 0 ] != '\0'; + ++i) { + if (qstricmp(txt, arr[ i ]) == 0) return pos; ++pos; } return 0; } -void KTitleBarActionsConfig::setComboText( KComboBox* combo, const char*txt ) +void KTitleBarActionsConfig::setComboText(KComboBox* combo, const char*txt) { - if( combo == coTiDbl ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_TiDbl, txt )); - else if( combo == coTiAct1 || combo == coTiAct2 || combo == coTiAct3 ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_TiAc, txt )); - else if( combo == coTiInAct1 || combo == coTiInAct2 || combo == coTiInAct3 ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_TiInAc, txt )); - else if( combo == coTiAct4 ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_TiWAc, txt )); - else if( combo == coMax[0] || combo == coMax[1] || combo == coMax[2] ) - { - combo->setCurrentIndex( tbl_txt_lookup( tbl_Max, txt )); + if (combo == coTiDbl) + combo->setCurrentIndex(tbl_txt_lookup(tbl_TiDbl, txt)); + else if (combo == coTiAct1 || combo == coTiAct2 || combo == coTiAct3) + combo->setCurrentIndex(tbl_txt_lookup(tbl_TiAc, txt)); + else if (combo == coTiInAct1 || combo == coTiInAct2 || combo == coTiInAct3) + combo->setCurrentIndex(tbl_txt_lookup(tbl_TiInAc, txt)); + else if (combo == coTiAct4) + combo->setCurrentIndex(tbl_txt_lookup(tbl_TiWAc, txt)); + else if (combo == coMax[0] || combo == coMax[1] || combo == coMax[2]) { + combo->setCurrentIndex(tbl_txt_lookup(tbl_Max, txt)); static_cast(combo)->changed(); - } - else + } else abort(); } -const char* KTitleBarActionsConfig::functionTiDbl( int i ) +const char* KTitleBarActionsConfig::functionTiDbl(int i) { - return tbl_num_lookup( tbl_TiDbl, i ); + return tbl_num_lookup(tbl_TiDbl, i); } -const char* KTitleBarActionsConfig::functionTiAc( int i ) +const char* KTitleBarActionsConfig::functionTiAc(int i) { - return tbl_num_lookup( tbl_TiAc, i ); + return tbl_num_lookup(tbl_TiAc, i); } -const char* KTitleBarActionsConfig::functionTiInAc( int i ) +const char* KTitleBarActionsConfig::functionTiInAc(int i) { - return tbl_num_lookup( tbl_TiInAc, i ); + return tbl_num_lookup(tbl_TiInAc, i); } const char* KTitleBarActionsConfig::functionTiWAc(int i) { - return tbl_num_lookup( tbl_TiWAc, i ); + return tbl_num_lookup(tbl_TiWAc, i); } -const char* KTitleBarActionsConfig::functionMax( int i ) +const char* KTitleBarActionsConfig::functionMax(int i) { - return tbl_num_lookup( tbl_Max, i ); + return tbl_num_lookup(tbl_Max, i); } -void KTitleBarActionsConfig::showEvent( QShowEvent *ev ) +void KTitleBarActionsConfig::showEvent(QShowEvent *ev) { - if ( !standAlone ) { + if (!standAlone) { // Workaround KCModule::showEvent() calling load(), see bug 163817 - QWidget::showEvent( ev ); + QWidget::showEvent(ev); return; } - KCModule::showEvent( ev ); + KCModule::showEvent(ev); } void KTitleBarActionsConfig::load() { - KConfigGroup windowsConfig(config, "Windows"); - setComboText(coTiDbl, windowsConfig.readEntry("TitlebarDoubleClickCommand","Maximize").toAscii()); - for (int t = 0; t < 3; ++t) - setComboText(coMax[t],windowsConfig.readEntry(cnf_Max[t], tbl_Max[t]).toAscii()); + KConfigGroup windowsConfig(config, "Windows"); + setComboText(coTiDbl, windowsConfig.readEntry("TitlebarDoubleClickCommand", "Maximize").toAscii()); + for (int t = 0; t < 3; ++t) + setComboText(coMax[t], windowsConfig.readEntry(cnf_Max[t], tbl_Max[t]).toAscii()); - KConfigGroup cg(config, "MouseBindings"); - setComboText(coTiAct1,cg.readEntry("CommandActiveTitlebar1","Raise").toAscii()); - setComboText(coTiAct2,cg.readEntry("CommandActiveTitlebar2","Start Window Tab Drag").toAscii()); - setComboText(coTiAct3,cg.readEntry("CommandActiveTitlebar3","Operations menu").toAscii()); - setComboText(coTiAct4,cg.readEntry("CommandTitlebarWheel","Switch to Window Tab to the Left/Right").toAscii()); - setComboText(coTiInAct1,cg.readEntry("CommandInactiveTitlebar1","Activate and raise").toAscii()); - setComboText(coTiInAct2,cg.readEntry("CommandInactiveTitlebar2","Start Window Tab Drag").toAscii()); - setComboText(coTiInAct3,cg.readEntry("CommandInactiveTitlebar3","Operations menu").toAscii()); + KConfigGroup cg(config, "MouseBindings"); + setComboText(coTiAct1, cg.readEntry("CommandActiveTitlebar1", "Raise").toAscii()); + setComboText(coTiAct2, cg.readEntry("CommandActiveTitlebar2", "Start Window Tab Drag").toAscii()); + setComboText(coTiAct3, cg.readEntry("CommandActiveTitlebar3", "Operations menu").toAscii()); + setComboText(coTiAct4, cg.readEntry("CommandTitlebarWheel", "Switch to Window Tab to the Left/Right").toAscii()); + setComboText(coTiInAct1, cg.readEntry("CommandInactiveTitlebar1", "Activate and raise").toAscii()); + setComboText(coTiInAct2, cg.readEntry("CommandInactiveTitlebar2", "Start Window Tab Drag").toAscii()); + setComboText(coTiInAct3, cg.readEntry("CommandInactiveTitlebar3", "Operations menu").toAscii()); } void KTitleBarActionsConfig::save() { - KConfigGroup windowsConfig(config, "Windows"); - windowsConfig.writeEntry("TitlebarDoubleClickCommand", functionTiDbl( coTiDbl->currentIndex() ) ); - for (int t = 0; t < 3; ++t) - windowsConfig.writeEntry(cnf_Max[t], functionMax(coMax[t]->currentIndex())); + KConfigGroup windowsConfig(config, "Windows"); + windowsConfig.writeEntry("TitlebarDoubleClickCommand", functionTiDbl(coTiDbl->currentIndex())); + for (int t = 0; t < 3; ++t) + windowsConfig.writeEntry(cnf_Max[t], functionMax(coMax[t]->currentIndex())); - KConfigGroup cg(config, "MouseBindings"); - cg.writeEntry("CommandActiveTitlebar1", functionTiAc(coTiAct1->currentIndex())); - cg.writeEntry("CommandActiveTitlebar2", functionTiAc(coTiAct2->currentIndex())); - cg.writeEntry("CommandActiveTitlebar3", functionTiAc(coTiAct3->currentIndex())); - cg.writeEntry("CommandInactiveTitlebar1", functionTiInAc(coTiInAct1->currentIndex())); - cg.writeEntry("CommandTitlebarWheel", functionTiWAc(coTiAct4->currentIndex())); - cg.writeEntry("CommandInactiveTitlebar2", functionTiInAc(coTiInAct2->currentIndex())); - cg.writeEntry("CommandInactiveTitlebar3", functionTiInAc(coTiInAct3->currentIndex())); - - if (standAlone) - { - config->sync(); - // Send signal to all kwin instances - QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + KConfigGroup cg(config, "MouseBindings"); + cg.writeEntry("CommandActiveTitlebar1", functionTiAc(coTiAct1->currentIndex())); + cg.writeEntry("CommandActiveTitlebar2", functionTiAc(coTiAct2->currentIndex())); + cg.writeEntry("CommandActiveTitlebar3", functionTiAc(coTiAct3->currentIndex())); + cg.writeEntry("CommandInactiveTitlebar1", functionTiInAc(coTiInAct1->currentIndex())); + cg.writeEntry("CommandTitlebarWheel", functionTiWAc(coTiAct4->currentIndex())); + cg.writeEntry("CommandInactiveTitlebar2", functionTiInAc(coTiInAct2->currentIndex())); + cg.writeEntry("CommandInactiveTitlebar3", functionTiInAc(coTiInAct3->currentIndex())); - } + if (standAlone) { + config->sync(); + // Send signal to all kwin instances + QDBusMessage message = + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); + + } } void KTitleBarActionsConfig::defaults() { - setComboText(coTiDbl, "Shade"); - setComboText(coTiAct1,"Raise"); - setComboText(coTiAct2,"Start Window Tab Drag"); - setComboText(coTiAct3,"Operations menu"); - setComboText(coTiAct4,"Switch to Window Tab to the Left/Right"); - setComboText(coTiInAct1,"Activate and raise"); - setComboText(coTiInAct2,"Start Window Tab Drag"); - setComboText(coTiInAct3,"Operations menu"); - for (int t = 0; t < 3; ++t) - setComboText(coMax[t], tbl_Max[t]); + setComboText(coTiDbl, "Shade"); + setComboText(coTiAct1, "Raise"); + setComboText(coTiAct2, "Start Window Tab Drag"); + setComboText(coTiAct3, "Operations menu"); + setComboText(coTiAct4, "Switch to Window Tab to the Left/Right"); + setComboText(coTiInAct1, "Activate and raise"); + setComboText(coTiInAct2, "Start Window Tab Drag"); + setComboText(coTiInAct3, "Operations menu"); + for (int t = 0; t < 3; ++t) + setComboText(coMax[t], tbl_Max[t]); } -KWindowActionsConfig::KWindowActionsConfig (bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) - : KCModule(inst, parent), config(_config), standAlone(_standAlone) +KWindowActionsConfig::KWindowActionsConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) + : KCModule(inst, parent), config(_config), standAlone(_standAlone) { - QString strWin1, strWin2, strWin3, strWinWheel, strAllKey, strAll1, strAll2, strAll3, strAllW; - QGroupBox *box; - QString strMouseButton1, strMouseButton2, strMouseButton3, strMouseWheel; - QString txtButton1, txtButton2, txtButton3, txtWheel; - QStringList items; - bool leftHandedMouse = ( KGlobalSettings::mouseSettings().handed == KGlobalSettings::KMouseSettings::LeftHanded); + QString strWin1, strWin2, strWin3, strWinWheel, strAllKey, strAll1, strAll2, strAll3, strAllW; + QGroupBox *box; + QString strMouseButton1, strMouseButton2, strMouseButton3, strMouseWheel; + QString txtButton1, txtButton2, txtButton3, txtWheel; + QStringList items; + bool leftHandedMouse = (KGlobalSettings::mouseSettings().handed == KGlobalSettings::KMouseSettings::LeftHanded); - QVBoxLayout *layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); -/** Inactive inner window ******************/ + /** Inactive inner window ******************/ - box = new QGroupBox(i18n("Inactive Inner Window"), this); - layout->addWidget(box); - box->setObjectName(QString::fromLatin1("Inactive Inner Window")); - box->setWhatsThis( i18n("Here you can customize mouse click behavior when clicking on an inactive" - " inner window ('inner' means: not titlebar, not frame).") ); + box = new QGroupBox(i18n("Inactive Inner Window"), this); + layout->addWidget(box); + box->setObjectName(QString::fromLatin1("Inactive Inner Window")); + box->setWhatsThis(i18n("Here you can customize mouse click behavior when clicking on an inactive" + " inner window ('inner' means: not titlebar, not frame).")); - QGridLayout *gridLayout = new QGridLayout(box); + QGridLayout *gridLayout = new QGridLayout(box); - strMouseButton1 = i18n("Left button:"); - txtButton1 = i18n("In this row you can customize left click behavior when clicking into" - " the titlebar or the frame."); + strMouseButton1 = i18n("Left button:"); + txtButton1 = i18n("In this row you can customize left click behavior when clicking into" + " the titlebar or the frame."); - strMouseButton2 = i18n("Middle button:"); - txtButton2 = i18n("In this row you can customize middle click behavior when clicking into" - " the titlebar or the frame." ); + strMouseButton2 = i18n("Middle button:"); + txtButton2 = i18n("In this row you can customize middle click behavior when clicking into" + " the titlebar or the frame."); - strMouseButton3 = i18n("Right button:"); - txtButton3 = i18n("In this row you can customize right click behavior when clicking into" - " the titlebar or the frame." ); - - strMouseWheel = i18n("Wheel"); + strMouseButton3 = i18n("Right button:"); + txtButton3 = i18n("In this row you can customize right click behavior when clicking into" + " the titlebar or the frame."); - if ( leftHandedMouse ) - { - qSwap(strMouseButton1, strMouseButton3); - qSwap(txtButton1, txtButton3); - } + strMouseWheel = i18n("Wheel"); - strWin1 = i18n("In this row you can customize left click behavior when clicking into" - " an inactive inner window ('inner' means: not titlebar, not frame)."); + if (leftHandedMouse) { + qSwap(strMouseButton1, strMouseButton3); + qSwap(txtButton1, txtButton3); + } - strWin2 = i18n("In this row you can customize middle click behavior when clicking into" - " an inactive inner window ('inner' means: not titlebar, not frame)."); + strWin1 = i18n("In this row you can customize left click behavior when clicking into" + " an inactive inner window ('inner' means: not titlebar, not frame)."); - strWin3 = i18n("In this row you can customize right click behavior when clicking into" - " an inactive inner window ('inner' means: not titlebar, not frame)."); - - strWinWheel = i18n("In this row you can customize behavior when scrolling into" - " an inactive inner window ('inner' means: not titlebar, not frame)."); + strWin2 = i18n("In this row you can customize middle click behavior when clicking into" + " an inactive inner window ('inner' means: not titlebar, not frame)."); - // Be nice to lefties - if ( leftHandedMouse ) qSwap(strWin1, strWin3); + strWin3 = i18n("In this row you can customize right click behavior when clicking into" + " an inactive inner window ('inner' means: not titlebar, not frame)."); - items.clear(); - items << i18n("Activate, Raise & Pass Click") - << i18n("Activate & Pass Click") - << i18n("Activate") - << i18n("Activate & Raise"); + strWinWheel = i18n("In this row you can customize behavior when scrolling into" + " an inactive inner window ('inner' means: not titlebar, not frame)."); - KComboBox* combo = new KComboBox(box); - coWin1 = combo; - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - combo->setWhatsThis( strWin1 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - QLabel* label = new QLabel(strMouseButton1, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 0, 0); - gridLayout->addWidget(combo, 0, 1); + // Be nice to lefties + if (leftHandedMouse) qSwap(strWin1, strWin3); - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coWin2 = combo; - combo->setWhatsThis( strWin2 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseButton2, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 1, 0); - gridLayout->addWidget(combo, 1, 1); + items.clear(); + items << i18n("Activate, Raise & Pass Click") + << i18n("Activate & Pass Click") + << i18n("Activate") + << i18n("Activate & Raise"); - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coWin3 = combo; - combo->setWhatsThis( strWin3 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseButton3, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 2, 0); - gridLayout->addWidget(combo, 2, 1); - - items.clear(); - items << i18n("Scroll") - << i18n("Activate & Scroll") - << i18n("Activate, Raise & Scroll"); - - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coWinWheel = combo; - combo->setWhatsThis( strWinWheel ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseWheel, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 3, 0); - gridLayout->addWidget(combo, 3, 1); - - + KComboBox* combo = new KComboBox(box); + coWin1 = combo; + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + combo->setWhatsThis(strWin1); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + QLabel* label = new QLabel(strMouseButton1, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 0, 0); + gridLayout->addWidget(combo, 0, 1); + + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coWin2 = combo; + combo->setWhatsThis(strWin2); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseButton2, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 1, 0); + gridLayout->addWidget(combo, 1, 1); + + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coWin3 = combo; + combo->setWhatsThis(strWin3); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseButton3, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 2, 0); + gridLayout->addWidget(combo, 2, 1); + + items.clear(); + items << i18n("Scroll") + << i18n("Activate & Scroll") + << i18n("Activate, Raise & Scroll"); + + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coWinWheel = combo; + combo->setWhatsThis(strWinWheel); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseWheel, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 3, 0); + gridLayout->addWidget(combo, 3, 1); -/** Inner window, titlebar and frame **************/ - - box = new QGroupBox(i18n("Inner Window, Titlebar && Frame"), this); - layout->addWidget(box); - box->setObjectName(QString::fromLatin1("Inner Window, Titlebar and Frame")); - box->setWhatsThis( i18n("Here you can customize KDE's behavior when clicking somewhere into" - " a window while pressing a modifier key.")); - - QHBoxLayout* innerLay=new QHBoxLayout(box); - QHBoxLayout* fLay=new QHBoxLayout; - gridLayout = new QGridLayout; - innerLay->addLayout(fLay); - innerLay->addLayout(gridLayout); - - // Labels - strMouseButton1 = i18n("Left button:"); - strAll1 = i18n("In this row you can customize left click behavior when clicking into" - " the titlebar or the frame."); - - strMouseButton2 = i18n("Middle button:"); - strAll2 = i18n("In this row you can customize middle click behavior when clicking into" - " the titlebar or the frame." ); - - strMouseButton3 = i18n("Right button:"); - strAll3 = i18n("In this row you can customize right click behavior when clicking into" - " the titlebar or the frame." ); - - if ( leftHandedMouse ) - { - qSwap(strMouseButton1, strMouseButton3); - qSwap(strAll1, strAll3); - } - - // Combo's - combo = new KComboBox(box); - combo->addItem(i18n("Meta")); - combo->addItem(i18n("Alt")); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coAllKey = combo; - combo->setWhatsThis( i18n("Here you select whether holding the Meta key or Alt key " - "will allow you to perform the following actions.") ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(i18n("Modifier key:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - fLay->addWidget(label); - fLay->addWidget(combo); - fLay->addWidget(new QLabel(" + ", this)); - items.clear(); - items << i18n("Move") - << i18n("Activate, Raise and Move") - << i18n("Toggle Raise & Lower") - << i18n("Resize") - << i18n("Raise") - << i18n("Lower") - << i18n("Minimize") - << i18n("Nothing"); + /** Inner window, titlebar and frame **************/ - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coAll1 = combo; - combo->setWhatsThis( strAll1 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseButton1, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 0, 0); - gridLayout->addWidget(combo, 0, 1); + box = new QGroupBox(i18n("Inner Window, Titlebar && Frame"), this); + layout->addWidget(box); + box->setObjectName(QString::fromLatin1("Inner Window, Titlebar and Frame")); + box->setWhatsThis(i18n("Here you can customize KDE's behavior when clicking somewhere into" + " a window while pressing a modifier key.")); + + QHBoxLayout* innerLay = new QHBoxLayout(box); + QHBoxLayout* fLay = new QHBoxLayout; + gridLayout = new QGridLayout; + innerLay->addLayout(fLay); + innerLay->addLayout(gridLayout); + + // Labels + strMouseButton1 = i18n("Left button:"); + strAll1 = i18n("In this row you can customize left click behavior when clicking into" + " the titlebar or the frame."); + + strMouseButton2 = i18n("Middle button:"); + strAll2 = i18n("In this row you can customize middle click behavior when clicking into" + " the titlebar or the frame."); + + strMouseButton3 = i18n("Right button:"); + strAll3 = i18n("In this row you can customize right click behavior when clicking into" + " the titlebar or the frame."); + + if (leftHandedMouse) { + qSwap(strMouseButton1, strMouseButton3); + qSwap(strAll1, strAll3); + } + + // Combo's + combo = new KComboBox(box); + combo->addItem(i18n("Meta")); + combo->addItem(i18n("Alt")); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coAllKey = combo; + combo->setWhatsThis(i18n("Here you select whether holding the Meta key or Alt key " + "will allow you to perform the following actions.")); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(i18n("Modifier key:"), this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + fLay->addWidget(label); + fLay->addWidget(combo); + fLay->addWidget(new QLabel(" + ", this)); - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coAll2 = combo; - combo->setWhatsThis( strAll2 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseButton2, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 1, 0); - gridLayout->addWidget(combo, 1, 1); + items.clear(); + items << i18n("Move") + << i18n("Activate, Raise and Move") + << i18n("Toggle Raise & Lower") + << i18n("Resize") + << i18n("Raise") + << i18n("Lower") + << i18n("Minimize") + << i18n("Nothing"); - combo = new KComboBox(box); - combo->addItems(items); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coAll3 = combo; - combo->setWhatsThis( strAll3 ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(strMouseButton3, this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 2, 0); - gridLayout->addWidget(combo, 2, 1); + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coAll1 = combo; + combo->setWhatsThis(strAll1); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseButton1, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 0, 0); + gridLayout->addWidget(combo, 0, 1); - combo = new KComboBox(box); - combo->addItem(i18n("Raise/Lower")); - combo->addItem(i18n("Shade/Unshade")); - combo->addItem(i18n("Maximize/Restore")); - combo->addItem(i18n("Keep Above/Below")); - combo->addItem(i18n("Move to Previous/Next Desktop")); - combo->addItem(i18n("Change Opacity")); - combo->addItem(i18n("Switch to Window Tab to the Left/Right")); - combo->addItem(i18n("Nothing")); - connect(combo, SIGNAL(activated(int)), SLOT(changed())); - coAllW = combo; - combo->setWhatsThis( i18n("Here you can customize KDE's behavior when scrolling with the mouse wheel" - " in a window while pressing the modifier key.") ); - combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - label = new QLabel(i18n("Mouse wheel:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); - label->setBuddy(combo); - gridLayout->addWidget(label, 3, 0); - gridLayout->addWidget(combo, 3, 1); + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coAll2 = combo; + combo->setWhatsThis(strAll2); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseButton2, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 1, 0); + gridLayout->addWidget(combo, 1, 1); + + combo = new KComboBox(box); + combo->addItems(items); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coAll3 = combo; + combo->setWhatsThis(strAll3); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(strMouseButton3, this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 2, 0); + gridLayout->addWidget(combo, 2, 1); - layout->addStretch(); - load(); + combo = new KComboBox(box); + combo->addItem(i18n("Raise/Lower")); + combo->addItem(i18n("Shade/Unshade")); + combo->addItem(i18n("Maximize/Restore")); + combo->addItem(i18n("Keep Above/Below")); + combo->addItem(i18n("Move to Previous/Next Desktop")); + combo->addItem(i18n("Change Opacity")); + combo->addItem(i18n("Switch to Window Tab to the Left/Right")); + combo->addItem(i18n("Nothing")); + connect(combo, SIGNAL(activated(int)), SLOT(changed())); + coAllW = combo; + combo->setWhatsThis(i18n("Here you can customize KDE's behavior when scrolling with the mouse wheel" + " in a window while pressing the modifier key.")); + combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + label = new QLabel(i18n("Mouse wheel:"), this); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); + label->setBuddy(combo); + gridLayout->addWidget(label, 3, 0); + gridLayout->addWidget(combo, 3, 1); + + + layout->addStretch(); + load(); } KWindowActionsConfig::~KWindowActionsConfig() { - if (standAlone) - delete config; + if (standAlone) + delete config; } -void KWindowActionsConfig::setComboText( KComboBox* combo, const char*txt ) +void KWindowActionsConfig::setComboText(KComboBox* combo, const char*txt) { - if( combo == coWin1 || combo == coWin2 || combo == coWin3 ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_Win, txt )); + if (combo == coWin1 || combo == coWin2 || combo == coWin3) + combo->setCurrentIndex(tbl_txt_lookup(tbl_Win, txt)); else if (combo == coWinWheel) - combo->setCurrentIndex( tbl_txt_lookup( tbl_WinWheel, txt )); - else if( combo == coAllKey ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_AllKey, txt )); - else if( combo == coAll1 || combo == coAll2 || combo == coAll3 ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_All, txt )); - else if( combo == coAllW ) - combo->setCurrentIndex( tbl_txt_lookup( tbl_AllW, txt )); + combo->setCurrentIndex(tbl_txt_lookup(tbl_WinWheel, txt)); + else if (combo == coAllKey) + combo->setCurrentIndex(tbl_txt_lookup(tbl_AllKey, txt)); + else if (combo == coAll1 || combo == coAll2 || combo == coAll3) + combo->setCurrentIndex(tbl_txt_lookup(tbl_All, txt)); + else if (combo == coAllW) + combo->setCurrentIndex(tbl_txt_lookup(tbl_AllW, txt)); else abort(); } -const char* KWindowActionsConfig::functionWin( int i ) +const char* KWindowActionsConfig::functionWin(int i) { - return tbl_num_lookup( tbl_Win, i ); + return tbl_num_lookup(tbl_Win, i); } -const char* KWindowActionsConfig::functionWinWheel (int i) +const char* KWindowActionsConfig::functionWinWheel(int i) { - return tbl_num_lookup( tbl_WinWheel, i); + return tbl_num_lookup(tbl_WinWheel, i); } -const char* KWindowActionsConfig::functionAllKey( int i ) +const char* KWindowActionsConfig::functionAllKey(int i) { - return tbl_num_lookup( tbl_AllKey, i ); + return tbl_num_lookup(tbl_AllKey, i); } -const char* KWindowActionsConfig::functionAll( int i ) +const char* KWindowActionsConfig::functionAll(int i) { - return tbl_num_lookup( tbl_All, i ); + return tbl_num_lookup(tbl_All, i); } const char* KWindowActionsConfig::functionAllW(int i) { - return tbl_num_lookup( tbl_AllW, i ); + return tbl_num_lookup(tbl_AllW, i); } -void KWindowActionsConfig::showEvent( QShowEvent *ev ) +void KWindowActionsConfig::showEvent(QShowEvent *ev) { - if ( !standAlone ) { - QWidget::showEvent( ev ); + if (!standAlone) { + QWidget::showEvent(ev); return; } - KCModule::showEvent( ev ); + KCModule::showEvent(ev); } void KWindowActionsConfig::load() { - KConfigGroup cg(config, "MouseBindings"); - setComboText(coWin1,cg.readEntry("CommandWindow1","Activate, raise and pass click").toAscii()); - setComboText(coWin2,cg.readEntry("CommandWindow2","Activate and pass click").toAscii()); - setComboText(coWin3,cg.readEntry("CommandWindow3","Activate and pass click").toAscii()); - setComboText(coWinWheel, cg.readEntry("CommandWindowWheel", "Scroll").toAscii()); - setComboText(coAllKey,cg.readEntry("CommandAllKey","Alt").toAscii()); - setComboText(coAll1,cg.readEntry("CommandAll1","Move").toAscii()); - setComboText(coAll2,cg.readEntry("CommandAll2","Toggle raise and lower").toAscii()); - setComboText(coAll3,cg.readEntry("CommandAll3","Resize").toAscii()); - setComboText(coAllW,cg.readEntry("CommandAllWheel","Nothing").toAscii()); + KConfigGroup cg(config, "MouseBindings"); + setComboText(coWin1, cg.readEntry("CommandWindow1", "Activate, raise and pass click").toAscii()); + setComboText(coWin2, cg.readEntry("CommandWindow2", "Activate and pass click").toAscii()); + setComboText(coWin3, cg.readEntry("CommandWindow3", "Activate and pass click").toAscii()); + setComboText(coWinWheel, cg.readEntry("CommandWindowWheel", "Scroll").toAscii()); + setComboText(coAllKey, cg.readEntry("CommandAllKey", "Alt").toAscii()); + setComboText(coAll1, cg.readEntry("CommandAll1", "Move").toAscii()); + setComboText(coAll2, cg.readEntry("CommandAll2", "Toggle raise and lower").toAscii()); + setComboText(coAll3, cg.readEntry("CommandAll3", "Resize").toAscii()); + setComboText(coAllW, cg.readEntry("CommandAllWheel", "Nothing").toAscii()); } void KWindowActionsConfig::save() { - KConfigGroup cg(config, "MouseBindings"); - cg.writeEntry("CommandWindow1", functionWin(coWin1->currentIndex())); - cg.writeEntry("CommandWindow2", functionWin(coWin2->currentIndex())); - cg.writeEntry("CommandWindow3", functionWin(coWin3->currentIndex())); - cg.writeEntry("CommandWindowWheel", functionWinWheel(coWinWheel->currentIndex())); - cg.writeEntry("CommandAllKey", functionAllKey(coAllKey->currentIndex())); - cg.writeEntry("CommandAll1", functionAll(coAll1->currentIndex())); - cg.writeEntry("CommandAll2", functionAll(coAll2->currentIndex())); - cg.writeEntry("CommandAll3", functionAll(coAll3->currentIndex())); - cg.writeEntry("CommandAllWheel", functionAllW(coAllW->currentIndex())); - - if (standAlone) - { - config->sync(); - // Send signal to all kwin instances - QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); - } + KConfigGroup cg(config, "MouseBindings"); + cg.writeEntry("CommandWindow1", functionWin(coWin1->currentIndex())); + cg.writeEntry("CommandWindow2", functionWin(coWin2->currentIndex())); + cg.writeEntry("CommandWindow3", functionWin(coWin3->currentIndex())); + cg.writeEntry("CommandWindowWheel", functionWinWheel(coWinWheel->currentIndex())); + cg.writeEntry("CommandAllKey", functionAllKey(coAllKey->currentIndex())); + cg.writeEntry("CommandAll1", functionAll(coAll1->currentIndex())); + cg.writeEntry("CommandAll2", functionAll(coAll2->currentIndex())); + cg.writeEntry("CommandAll3", functionAll(coAll3->currentIndex())); + cg.writeEntry("CommandAllWheel", functionAllW(coAllW->currentIndex())); + + if (standAlone) { + config->sync(); + // Send signal to all kwin instances + QDBusMessage message = + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); + } } void KWindowActionsConfig::defaults() { - setComboText(coWin1,"Activate, raise and pass click"); - setComboText(coWin2,"Activate and pass click"); - setComboText(coWin3,"Activate and pass click"); - setComboText(coWinWheel, "Scroll"); - setComboText(coAllKey,"Alt"); - setComboText (coAll1,"Move"); - setComboText(coAll2,"Toggle raise and lower"); - setComboText(coAll3,"Resize"); - setComboText(coAllW,"Nothing"); + setComboText(coWin1, "Activate, raise and pass click"); + setComboText(coWin2, "Activate and pass click"); + setComboText(coWin3, "Activate and pass click"); + setComboText(coWinWheel, "Scroll"); + setComboText(coAllKey, "Alt"); + setComboText(coAll1, "Move"); + setComboText(coAll2, "Toggle raise and lower"); + setComboText(coAll3, "Resize"); + setComboText(coAllW, "Nothing"); } diff --git a/kcmkwin/kwinoptions/mouse.h b/kcmkwin/kwinoptions/mouse.h index e8ef5d96e..f633db2e2 100644 --- a/kcmkwin/kwinoptions/mouse.h +++ b/kcmkwin/kwinoptions/mouse.h @@ -31,113 +31,119 @@ class KConfig; class ToolTipComboBox: public KComboBox { - Q_OBJECT - + Q_OBJECT + public: - ToolTipComboBox(QWidget * owner, char const * const * toolTips_) - : KComboBox(owner) - , toolTips(toolTips_) {} + ToolTipComboBox(QWidget * owner, char const * const * toolTips_) + : KComboBox(owner) + , toolTips(toolTips_) {} public slots: - void changed() {this->setToolTip( i18n(toolTips[currentIndex()]) );} + void changed() { + this->setToolTip(i18n(toolTips[currentIndex()])); + } protected: - char const * const * toolTips; + char const * const * toolTips; }; class KTitleBarActionsConfig : public KCModule { - Q_OBJECT + Q_OBJECT public: - KTitleBarActionsConfig( bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent ); - ~KTitleBarActionsConfig( ); + KTitleBarActionsConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent); + ~KTitleBarActionsConfig(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected: - void showEvent( QShowEvent *ev ); + void showEvent(QShowEvent *ev); public slots: - void changed() { emit KCModule::changed(true); } + void changed() { + emit KCModule::changed(true); + } private: - KComboBox* coTiDbl; + KComboBox* coTiDbl; - KComboBox* coTiAct1; - KComboBox* coTiAct2; - KComboBox* coTiAct3; - KComboBox* coTiAct4; - KComboBox* coTiInAct1; - KComboBox* coTiInAct2; - KComboBox* coTiInAct3; + KComboBox* coTiAct1; + KComboBox* coTiAct2; + KComboBox* coTiAct3; + KComboBox* coTiAct4; + KComboBox* coTiInAct1; + KComboBox* coTiInAct2; + KComboBox* coTiInAct3; - ToolTipComboBox * coMax[3]; + ToolTipComboBox * coMax[3]; - KConfig *config; - bool standAlone; + KConfig *config; + bool standAlone; - const char* functionTiDbl(int); - const char* functionTiAc(int); - const char* functionTiWAc(int); - const char* functionTiInAc(int); - const char* functionMax(int); + const char* functionTiDbl(int); + const char* functionTiAc(int); + const char* functionTiWAc(int); + const char* functionTiInAc(int); + const char* functionMax(int); - void setComboText(KComboBox* combo, const char* text); - const char* fixup( const char* s ); + void setComboText(KComboBox* combo, const char* text); + const char* fixup(const char* s); private slots: - void paletteChanged(); + void paletteChanged(); }; class KWindowActionsConfig : public KCModule { - Q_OBJECT + Q_OBJECT public: - KWindowActionsConfig( bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent ); - ~KWindowActionsConfig( ); + KWindowActionsConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent); + ~KWindowActionsConfig(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected: - void showEvent( QShowEvent *ev ); + void showEvent(QShowEvent *ev); public slots: - void changed() { emit KCModule::changed(true); } + void changed() { + emit KCModule::changed(true); + } private: - KComboBox* coWin1; - KComboBox* coWin2; - KComboBox* coWin3; - KComboBox* coWinWheel; + KComboBox* coWin1; + KComboBox* coWin2; + KComboBox* coWin3; + KComboBox* coWinWheel; - KComboBox* coAllKey; - KComboBox* coAll1; - KComboBox* coAll2; - KComboBox* coAll3; - KComboBox* coAllW; + KComboBox* coAllKey; + KComboBox* coAll1; + KComboBox* coAll2; + KComboBox* coAll3; + KComboBox* coAllW; - KConfig *config; - bool standAlone; + KConfig *config; + bool standAlone; - const char* functionWin(int); - const char* functionWinWheel(int); - const char* functionAllKey(int); - const char* functionAll(int); - const char* functionAllW(int); + const char* functionWin(int); + const char* functionWinWheel(int); + const char* functionAllKey(int); + const char* functionAll(int); + const char* functionAllW(int); - void setComboText(KComboBox* combo, const char* text); - const char* fixup( const char* s ); + void setComboText(KComboBox* combo, const char* text); + const char* fixup(const char* s); }; #endif diff --git a/kcmkwin/kwinoptions/windows.cpp b/kcmkwin/kwinoptions/windows.cpp index 178a552e7..10b7579cd 100644 --- a/kcmkwin/kwinoptions/windows.cpp +++ b/kcmkwin/kwinoptions/windows.cpp @@ -84,14 +84,14 @@ #define MAX_EDGE_RES 1000 -KFocusConfig::~KFocusConfig () +KFocusConfig::~KFocusConfig() { if (standAlone) delete config; } // removed the LCD display over the slider - this is not good GUI design :) RNolden 051701 -KFocusConfig::KFocusConfig (bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) +KFocusConfig::KFocusConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget * parent) : KCModule(inst, parent), config(_config), standAlone(_standAlone) { QString wtstr; @@ -117,51 +117,51 @@ KFocusConfig::KFocusConfig (bool _standAlone, KConfig *_config, const KComponent QGridLayout *gLay = new QGridLayout(); - fcsBox->setLayout( gLay ); + fcsBox->setLayout(gLay); - focusStealing = new KComboBox( this ); - focusStealing->addItem( i18nc( "Focus Stealing Prevention Level", "None" )); - focusStealing->addItem( i18nc( "Focus Stealing Prevention Level", "Low" )); - focusStealing->addItem( i18nc( "Focus Stealing Prevention Level", "Medium" )); - focusStealing->addItem( i18nc( "Focus Stealing Prevention Level", "High" )); - focusStealing->addItem( i18nc( "Focus Stealing Prevention Level", "Extreme" )); - wtstr = i18n( "

This option specifies how much KWin will try to prevent unwanted focus stealing " - "caused by unexpected activation of new windows. (Note: This feature does not " - "work with the Focus Under Mouse or Focus Strictly Under Mouse focus policies.)" - "

    " - "
  • None: Prevention is turned off " - "and new windows always become activated.
  • " - "
  • Low: Prevention is enabled; when some window does not have support " - "for the underlying mechanism and KWin cannot reliably decide whether to " - "activate the window or not, it will be activated. This setting may have both " - "worse and better results than the medium level, depending on the applications.
  • " - "
  • Medium: Prevention is enabled.
  • " - "
  • High: New windows get activated only if no window is currently active " - "or if they belong to the currently active application. This setting is probably " - "not really usable when not using mouse focus policy.
  • " - "
  • Extreme: All windows must be explicitly activated by the user.
  • " - "

" - "

Windows that are prevented from stealing focus are marked as demanding attention, " - "which by default means their taskbar entry will be highlighted. This can be changed " - "in the Notifications control module.

" ); - focusStealing->setWhatsThis( wtstr ); + focusStealing = new KComboBox(this); + focusStealing->addItem(i18nc("Focus Stealing Prevention Level", "None")); + focusStealing->addItem(i18nc("Focus Stealing Prevention Level", "Low")); + focusStealing->addItem(i18nc("Focus Stealing Prevention Level", "Medium")); + focusStealing->addItem(i18nc("Focus Stealing Prevention Level", "High")); + focusStealing->addItem(i18nc("Focus Stealing Prevention Level", "Extreme")); + wtstr = i18n("

This option specifies how much KWin will try to prevent unwanted focus stealing " + "caused by unexpected activation of new windows. (Note: This feature does not " + "work with the Focus Under Mouse or Focus Strictly Under Mouse focus policies.)" + "

    " + "
  • None: Prevention is turned off " + "and new windows always become activated.
  • " + "
  • Low: Prevention is enabled; when some window does not have support " + "for the underlying mechanism and KWin cannot reliably decide whether to " + "activate the window or not, it will be activated. This setting may have both " + "worse and better results than the medium level, depending on the applications.
  • " + "
  • Medium: Prevention is enabled.
  • " + "
  • High: New windows get activated only if no window is currently active " + "or if they belong to the currently active application. This setting is probably " + "not really usable when not using mouse focus policy.
  • " + "
  • Extreme: All windows must be explicitly activated by the user.
  • " + "

" + "

Windows that are prevented from stealing focus are marked as demanding attention, " + "which by default means their taskbar entry will be highlighted. This can be changed " + "in the Notifications control module.

"); + focusStealing->setWhatsThis(wtstr); connect(focusStealing, SIGNAL(activated(int)), SLOT(changed())); focusStealing->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); label = new QLabel(i18n("Focus stealing prevention level:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); label->setBuddy(focusStealing); gLay->addWidget(label, 0, 0, 1, 2); gLay->addWidget(focusStealing, 0, 2); focusCombo = new KComboBox(fcsBox); - focusCombo->setEditable( false ); + focusCombo->setEditable(false); focusCombo->addItem(i18n("Click to Focus"), CLICK_TO_FOCUS); focusCombo->addItem(i18n("Focus Follows Mouse"), FOCUS_FOLLOWS_MOUSE); focusCombo->addItem(i18n("Focus Under Mouse"), FOCUS_UNDER_MOUSE); focusCombo->addItem(i18n("Focus Strictly Under Mouse"), FOCUS_STRICTLY_UNDER_MOUSE); focusCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); label = new QLabel(i18n("&Policy:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); label->setBuddy(focusCombo); gLay->addWidget(label, 1, 0, 1, 2); gLay->addWidget(focusCombo, 1, 2); @@ -169,95 +169,94 @@ KFocusConfig::KFocusConfig (bool _standAlone, KConfig *_config, const KComponent // FIXME, when more policies have been added to KWin wtstr = i18n("The focus policy is used to determine the active window, i.e." - " the window you can work in.
    " - "
  • Click to focus: A window becomes active when you click into it." - " This is the behavior you might know from other operating systems.
  • " - "
  • Focus follows mouse: Moving the mouse pointer actively on to a" - " normal window activates it. New windows will receive the focus," - " without you having to point the mouse at them explicitly." - " Very practical if you are using the mouse a lot.
  • " - "
  • Focus under mouse: The window that happens to be under the" - " mouse pointer is active. If the mouse points nowhere, the last window" - " that was under the mouse has focus." - " New windows will not automatically receive the focus.
  • " - "
  • Focus strictly under mouse: Only the window under the mouse pointer is" - " active. If the mouse points nowhere, nothing has focus.
  • " - "
" - "Note that 'Focus under mouse' and 'Focus strictly under mouse' prevent certain" - " features such as the Alt+Tab walk through windows dialog in the KDE mode" - " from working properly." - ); - focusCombo->setWhatsThis( wtstr); + " the window you can work in.
    " + "
  • Click to focus: A window becomes active when you click into it." + " This is the behavior you might know from other operating systems.
  • " + "
  • Focus follows mouse: Moving the mouse pointer actively on to a" + " normal window activates it. New windows will receive the focus," + " without you having to point the mouse at them explicitly." + " Very practical if you are using the mouse a lot.
  • " + "
  • Focus under mouse: The window that happens to be under the" + " mouse pointer is active. If the mouse points nowhere, the last window" + " that was under the mouse has focus." + " New windows will not automatically receive the focus.
  • " + "
  • Focus strictly under mouse: Only the window under the mouse pointer is" + " active. If the mouse points nowhere, nothing has focus.
  • " + "
" + "Note that 'Focus under mouse' and 'Focus strictly under mouse' prevent certain" + " features such as the Alt+Tab walk through windows dialog in the KDE mode" + " from working properly." + ); + focusCombo->setWhatsThis(wtstr); - connect(focusCombo, SIGNAL(activated(int)), this, SLOT(focusPolicyChanged()) ); + connect(focusCombo, SIGNAL(activated(int)), this, SLOT(focusPolicyChanged())); // autoraise delay autoRaiseOn = new QCheckBox(fcsBox); - connect(autoRaiseOn,SIGNAL(toggled(bool)), this, SLOT(autoRaiseOnTog(bool))); + connect(autoRaiseOn, SIGNAL(toggled(bool)), this, SLOT(autoRaiseOnTog(bool))); autoRaise = new KIntNumInput(500, fcsBox); autoRaise->setRange(0, 3000, 100); - autoRaise->setSteps(100,100); + autoRaise->setSteps(100, 100); autoRaise->setSuffix(i18n(" ms")); autoRaise->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); autoRaiseOnLabel = new QLabel(i18n("&Raise, with the following delay:"), this); - autoRaiseOnLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + autoRaiseOnLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); autoRaiseOnLabel->setBuddy(autoRaise); gLay->addWidget(autoRaiseOn, 2, 0); gLay->addWidget(autoRaiseOnLabel, 2, 1); gLay->addWidget(autoRaise, 2, 2); - connect(focusCombo, SIGNAL(activated(int)), this, SLOT(setDelayFocusEnabled()) ); + connect(focusCombo, SIGNAL(activated(int)), this, SLOT(setDelayFocusEnabled())); delayFocusOn = new QCheckBox(fcsBox); - connect(delayFocusOn,SIGNAL(toggled(bool)), this, SLOT(delayFocusOnTog(bool))); + connect(delayFocusOn, SIGNAL(toggled(bool)), this, SLOT(delayFocusOnTog(bool))); delayFocus = new KIntNumInput(500, fcsBox); delayFocus->setRange(0, 3000, 100); - delayFocus->setSteps(100,100); + delayFocus->setSteps(100, 100); delayFocus->setSuffix(i18n(" ms")); delayFocus->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); delayFocusOnLabel = new QLabel(i18n("Delay focus by:"), this); - delayFocusOnLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + delayFocusOnLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); delayFocusOnLabel->setBuddy(delayFocus); gLay->addWidget(delayFocusOn, 3, 0); gLay->addWidget(delayFocusOnLabel, 3, 1); gLay->addWidget(delayFocus, 3, 2); clickRaiseOn = new QCheckBox(i18n("C&lick raises active window"), fcsBox); - connect(clickRaiseOn,SIGNAL(toggled(bool)), this, SLOT(clickRaiseOnTog(bool))); + connect(clickRaiseOn, SIGNAL(toggled(bool)), this, SLOT(clickRaiseOnTog(bool))); gLay->addWidget(clickRaiseOn, 4, 0, 1, 3); - autoRaiseOn->setWhatsThis( i18n("When this option is enabled, a window in the background will automatically" - " come to the front when the mouse pointer has been over it for some time.") ); + autoRaiseOn->setWhatsThis(i18n("When this option is enabled, a window in the background will automatically" + " come to the front when the mouse pointer has been over it for some time.")); wtstr = i18n("This is the delay after which the window that the mouse pointer is over will automatically" " come to the front."); - autoRaise->setWhatsThis( wtstr ); + autoRaise->setWhatsThis(wtstr); - clickRaiseOn->setWhatsThis( i18n("When this option is enabled, the active window will be brought to the" - " front when you click somewhere into the window contents. To change" - " it for inactive windows, you need to change the settings" - " in the Actions tab.") ); + clickRaiseOn->setWhatsThis(i18n("When this option is enabled, the active window will be brought to the" + " front when you click somewhere into the window contents. To change" + " it for inactive windows, you need to change the settings" + " in the Actions tab.")); - delayFocusOn->setWhatsThis( i18n("When this option is enabled, there will be a delay after which the" - " window the mouse pointer is over will become active (receive focus).") ); - delayFocus->setWhatsThis( i18n("This is the delay after which the window the mouse pointer is over" - " will automatically receive focus.") ); + delayFocusOn->setWhatsThis(i18n("When this option is enabled, there will be a delay after which the" + " window the mouse pointer is over will become active (receive focus).")); + delayFocus->setWhatsThis(i18n("This is the delay after which the window the mouse pointer is over" + " will automatically receive focus.")); - separateScreenFocus = new QCheckBox( i18n( "S&eparate screen focus" ), fcsBox ); + separateScreenFocus = new QCheckBox(i18n("S&eparate screen focus"), fcsBox); gLay->addWidget(separateScreenFocus, 5, 0, 1, 3); - wtstr = i18n( "When this option is enabled, focus operations are limited only to the active Xinerama screen" ); - separateScreenFocus->setWhatsThis( wtstr ); + wtstr = i18n("When this option is enabled, focus operations are limited only to the active Xinerama screen"); + separateScreenFocus->setWhatsThis(wtstr); - activeMouseScreen = new QCheckBox( i18n( "Active screen follows &mouse" ), fcsBox ); + activeMouseScreen = new QCheckBox(i18n("Active screen follows &mouse"), fcsBox); gLay->addWidget(activeMouseScreen, 6, 0, 1, 3); - wtstr = i18n( "When this option is enabled, the active Xinerama screen (where new windows appear, for example)" - " is the screen containing the mouse pointer. When disabled, the active Xinerama screen is the " - " screen containing the focused window. By default this option is disabled for Click to focus and" - " enabled for other focus policies." ); - activeMouseScreen->setWhatsThis( wtstr ); + wtstr = i18n("When this option is enabled, the active Xinerama screen (where new windows appear, for example)" + " is the screen containing the mouse pointer. When disabled, the active Xinerama screen is the " + " screen containing the focused window. By default this option is disabled for Click to focus and" + " enabled for other focus policies."); + activeMouseScreen->setWhatsThis(wtstr); connect(focusCombo, SIGNAL(activated(int)), this, SLOT(updateActiveMouseScreen())); - if (Kephal::ScreenUtils::numScreens() == 1) // No Ximerama - { + if (Kephal::ScreenUtils::numScreens() == 1) { // No Ximerama separateScreenFocus->hide(); activeMouseScreen->hide(); } @@ -268,7 +267,7 @@ KFocusConfig::KFocusConfig (bool _standAlone, KConfig *_config, const KComponent // Any changes goes to slotChanged() connect(focusCombo, SIGNAL(activated(int)), SLOT(changed())); - connect(autoRaiseOn,SIGNAL(clicked()), SLOT(changed())); + connect(autoRaiseOn, SIGNAL(clicked()), SLOT(changed())); connect(delayFocusOn, SIGNAL(clicked()), SLOT(changed())); connect(clickRaiseOn, SIGNAL(clicked()), SLOT(changed())); connect(autoRaise, SIGNAL(valueChanged(int)), SLOT(changed())); @@ -330,7 +329,7 @@ void KFocusConfig::setClickRaise(bool on) void KFocusConfig::focusPolicyChanged() { - int policyIndex=focusCombo->currentIndex(); + int policyIndex = focusCombo->currentIndex(); // the auto raise related widgets are: autoRaise autoRaiseOn->setEnabled(policyIndex != CLICK_TO_FOCUS); @@ -343,7 +342,7 @@ void KFocusConfig::focusPolicyChanged() void KFocusConfig::setDelayFocusEnabled() { - int policyIndex=focusCombo->currentIndex(); + int policyIndex = focusCombo->currentIndex(); // the delayed focus related widgets are: delayFocus delayFocusOn->setEnabled(policyIndex != CLICK_TO_FOCUS); @@ -351,88 +350,94 @@ void KFocusConfig::setDelayFocusEnabled() delayFocusOnTog(policyIndex != CLICK_TO_FOCUS && delayFocusOn->isChecked()); } -void KFocusConfig::autoRaiseOnTog(bool a) { +void KFocusConfig::autoRaiseOnTog(bool a) +{ autoRaise->setEnabled(a); - clickRaiseOn->setEnabled( !a ); + clickRaiseOn->setEnabled(!a); } -void KFocusConfig::delayFocusOnTog(bool a) { +void KFocusConfig::delayFocusOnTog(bool a) +{ delayFocus->setEnabled(a); } -void KFocusConfig::clickRaiseOnTog(bool ) { +void KFocusConfig::clickRaiseOnTog(bool) +{ } -void KFocusConfig::setFocusStealing(int l) { - l = qMax( 0, qMin( 4, l )); +void KFocusConfig::setFocusStealing(int l) +{ + l = qMax(0, qMin(4, l)); focusStealing->setCurrentIndex(l); } -void KFocusConfig::setSeparateScreenFocus(bool s) { +void KFocusConfig::setSeparateScreenFocus(bool s) +{ separateScreenFocus->setChecked(s); } -void KFocusConfig::setActiveMouseScreen(bool a) { +void KFocusConfig::setActiveMouseScreen(bool a) +{ activeMouseScreen->setChecked(a); } void KFocusConfig::updateActiveMouseScreen() { // on by default for non click to focus policies - KConfigGroup cfg( config, "Windows" ); - if( !cfg.hasKey( KWIN_ACTIVE_MOUSE_SCREEN )) - setActiveMouseScreen( focusCombo->currentIndex() != 0 ); + KConfigGroup cfg(config, "Windows"); + if (!cfg.hasKey(KWIN_ACTIVE_MOUSE_SCREEN)) + setActiveMouseScreen(focusCombo->currentIndex() != 0); } -void KFocusConfig::showEvent( QShowEvent *ev ) +void KFocusConfig::showEvent(QShowEvent *ev) { - if ( !standAlone ) { - QWidget::showEvent( ev ); + if (!standAlone) { + QWidget::showEvent(ev); return; } - KCModule::showEvent( ev ); + KCModule::showEvent(ev); } -void KFocusConfig::load( void ) +void KFocusConfig::load(void) { QString key; KConfigGroup cg(config, "Windows"); key = cg.readEntry(KWIN_FOCUS); - if( key == "ClickToFocus") + if (key == "ClickToFocus") setFocus(CLICK_TO_FOCUS); - else if( key == "FocusFollowsMouse") + else if (key == "FocusFollowsMouse") setFocus(FOCUS_FOLLOWS_MOUSE); - else if(key == "FocusUnderMouse") + else if (key == "FocusUnderMouse") setFocus(FOCUS_UNDER_MOUSE); - else if(key == "FocusStrictlyUnderMouse") + else if (key == "FocusStrictlyUnderMouse") setFocus(FOCUS_STRICTLY_UNDER_MOUSE); - int k = cg.readEntry(KWIN_AUTORAISE_INTERVAL,750); + int k = cg.readEntry(KWIN_AUTORAISE_INTERVAL, 750); setAutoRaiseInterval(k); - k = cg.readEntry(KWIN_DELAYFOCUS_INTERVAL,750); + k = cg.readEntry(KWIN_DELAYFOCUS_INTERVAL, 750); setDelayFocusInterval(k); - setAutoRaise( cg.readEntry(KWIN_AUTORAISE, false)); - setDelayFocus( cg.readEntry(KWIN_DELAYFOCUS, false)); - setClickRaise( cg.readEntry(KWIN_CLICKRAISE, true)); + setAutoRaise(cg.readEntry(KWIN_AUTORAISE, false)); + setDelayFocus(cg.readEntry(KWIN_DELAYFOCUS, false)); + setClickRaise(cg.readEntry(KWIN_CLICKRAISE, true)); focusPolicyChanged(); // this will disable/hide the auto raise delay widget if focus==click setDelayFocusEnabled(); - setSeparateScreenFocus( cg.readEntry(KWIN_SEPARATE_SCREEN_FOCUS, false)); + setSeparateScreenFocus(cg.readEntry(KWIN_SEPARATE_SCREEN_FOCUS, false)); // on by default for non click to focus policies - setActiveMouseScreen( cg.readEntry(KWIN_ACTIVE_MOUSE_SCREEN, focusCombo->currentIndex() != 0 )); + setActiveMouseScreen(cg.readEntry(KWIN_ACTIVE_MOUSE_SCREEN, focusCombo->currentIndex() != 0)); // setFocusStealing( cg.readEntry(KWIN_FOCUS_STEALING, 2 )); // TODO default to low for now - setFocusStealing( cg.readEntry(KWIN_FOCUS_STEALING, 1 )); + setFocusStealing(cg.readEntry(KWIN_FOCUS_STEALING, 1)); emit KCModule::changed(false); } -void KFocusConfig::save( void ) +void KFocusConfig::save(void) { int v; @@ -440,21 +445,21 @@ void KFocusConfig::save( void ) v = getFocus(); if (v == CLICK_TO_FOCUS) - cg.writeEntry(KWIN_FOCUS,"ClickToFocus"); + cg.writeEntry(KWIN_FOCUS, "ClickToFocus"); else if (v == FOCUS_UNDER_MOUSE) - cg.writeEntry(KWIN_FOCUS,"FocusUnderMouse"); + cg.writeEntry(KWIN_FOCUS, "FocusUnderMouse"); else if (v == FOCUS_STRICTLY_UNDER_MOUSE) - cg.writeEntry(KWIN_FOCUS,"FocusStrictlyUnderMouse"); + cg.writeEntry(KWIN_FOCUS, "FocusStrictlyUnderMouse"); else - cg.writeEntry(KWIN_FOCUS,"FocusFollowsMouse"); + cg.writeEntry(KWIN_FOCUS, "FocusFollowsMouse"); v = getAutoRaiseInterval(); - if (v <0) v = 0; - cg.writeEntry(KWIN_AUTORAISE_INTERVAL,v); + if (v < 0) v = 0; + cg.writeEntry(KWIN_AUTORAISE_INTERVAL, v); v = getDelayFocusInterval(); - if (v <0) v = 0; - cg.writeEntry(KWIN_DELAYFOCUS_INTERVAL,v); + if (v < 0) v = 0; + cg.writeEntry(KWIN_DELAYFOCUS_INTERVAL, v); cg.writeEntry(KWIN_AUTORAISE, autoRaiseOn->isChecked()); @@ -468,13 +473,12 @@ void KFocusConfig::save( void ) cg.writeEntry(KWIN_FOCUS_STEALING, focusStealing->currentIndex()); - if (standAlone) - { + if (standAlone) { config->sync(); - // Send signal to all kwin instances - QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + // Send signal to all kwin instances + QDBusMessage message = + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); } emit KCModule::changed(false); } @@ -487,30 +491,30 @@ void KFocusConfig::defaults() setAutoRaise(false); setDelayFocus(false); setClickRaise(true); - setSeparateScreenFocus( false ); + setSeparateScreenFocus(false); // setFocusStealing(2); // TODO default to low for now setFocusStealing(1); // on by default for non click to focus policies - setActiveMouseScreen( focusCombo->currentIndex() != 0 ); + setActiveMouseScreen(focusCombo->currentIndex() != 0); setDelayFocusEnabled(); emit KCModule::changed(true); } -KAdvancedConfig::~KAdvancedConfig () +KAdvancedConfig::~KAdvancedConfig() { if (standAlone) delete config; } -KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent) +KAdvancedConfig::KAdvancedConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent) : KCModule(inst, parent), config(_config), standAlone(_standAlone) { QString wtstr; QLabel *label; - QVBoxLayout *lay = new QVBoxLayout (this); + QVBoxLayout *lay = new QVBoxLayout(this); //iTLabel = new QLabel(i18n(" Allowed overlap:\n" // "(% of desktop space)"), @@ -539,15 +543,15 @@ KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KCom shadeHover->setSteps(100, 100); shadeHover->setSuffix(i18n(" ms")); - shadeHoverOn->setWhatsThis( i18n("If Shade Hover is enabled, a shaded window will un-shade automatically " - "when the mouse pointer has been over the title bar for some time.")); + shadeHoverOn->setWhatsThis(i18n("If Shade Hover is enabled, a shaded window will un-shade automatically " + "when the mouse pointer has been over the title bar for some time.")); wtstr = i18n("Sets the time in milliseconds before the window unshades " - "when the mouse pointer goes over the shaded window."); - shadeHover->setWhatsThis( wtstr); + "when the mouse pointer goes over the shaded window."); + shadeHover->setWhatsThis(wtstr); shadeHover->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); shadeHoverLabel = new QLabel(i18n("Dela&y:"), this); - shadeHoverLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + shadeHoverLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); shadeHoverLabel->setBuddy(shadeHover); kLay->addWidget(shadeHoverLabel, 1, 0); kLay->addWidget(shadeHover, 1, 1); @@ -561,26 +565,26 @@ KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KCom wtBox->setTitle(i18n("Window Tabbing")); QVBoxLayout *wtLay = new QVBoxLayout(wtBox); - inactiveTabsSkipTaskbar = new QCheckBox( i18n( "Hide inactive window tabs from the taskbar" ), this ); - inactiveTabsSkipTaskbar->setVisible( false ); // TODO: We want translations in case this is fixed... + inactiveTabsSkipTaskbar = new QCheckBox(i18n("Hide inactive window tabs from the taskbar"), this); + inactiveTabsSkipTaskbar->setVisible(false); // TODO: We want translations in case this is fixed... inactiveTabsSkipTaskbar->setWhatsThis( - i18n( "When turned on hide all tabs that are not active from the taskbar." )); + i18n("When turned on hide all tabs that are not active from the taskbar.")); connect(inactiveTabsSkipTaskbar, SIGNAL(toggled(bool)), SLOT(changed())); - wtLay->addWidget( inactiveTabsSkipTaskbar ); + wtLay->addWidget(inactiveTabsSkipTaskbar); - autogroupSimilarWindows = new QCheckBox( i18n( "Automatically group similar windows" ), this ); + autogroupSimilarWindows = new QCheckBox(i18n("Automatically group similar windows"), this); autogroupSimilarWindows->setWhatsThis( - i18n( "When turned on attempt to automatically detect when a newly opened window is related" - " to an existing one and place them in the same window group." )); + i18n("When turned on attempt to automatically detect when a newly opened window is related" + " to an existing one and place them in the same window group.")); connect(autogroupSimilarWindows, SIGNAL(toggled(bool)), SLOT(changed())); - wtLay->addWidget( autogroupSimilarWindows ); + wtLay->addWidget(autogroupSimilarWindows); - autogroupInForeground = new QCheckBox( i18n( "Switch to automatically grouped windows immediately" ), this ); + autogroupInForeground = new QCheckBox(i18n("Switch to automatically grouped windows immediately"), this); autogroupInForeground->setWhatsThis( - i18n( "When turned on immediately switch to any new window tabs that were automatically added" - " to the current group." )); + i18n("When turned on immediately switch to any new window tabs that were automatically added" + " to the current group.")); connect(autogroupInForeground, SIGNAL(toggled(bool)), SLOT(changed())); - wtLay->addWidget( autogroupInForeground ); + wtLay->addWidget(autogroupInForeground); lay->addWidget(wtBox); @@ -591,10 +595,10 @@ KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KCom connect(shadeHover, SIGNAL(valueChanged(int)), SLOT(changed())); QGridLayout *vLay = new QGridLayout(); - lay->addLayout( vLay ); + lay->addLayout(vLay); placementCombo = new KComboBox(this); - placementCombo->setEditable( false ); + placementCombo->setEditable(false); placementCombo->addItem(i18n("Smart"), SMART_PLACEMENT); placementCombo->addItem(i18n("Maximizing"), MAXIMIZING_PLACEMENT); placementCombo->addItem(i18n("Cascade"), CASCADE_PLACEMENT); @@ -620,62 +624,62 @@ KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KCom "
  • Zero-Cornered will place the window in the top-left corner
  • " "") ; - placementCombo->setWhatsThis( wtstr); + placementCombo->setWhatsThis(wtstr); placementCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); label = new QLabel(i18n("&Placement:"), this); - label->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + label->setAlignment(Qt::AlignVCenter | Qt::AlignRight); label->setBuddy(placementCombo); vLay->addWidget(label, 0, 0); vLay->addWidget(placementCombo, 0, 1); - connect( placementCombo, SIGNAL(activated(int)), SLOT(changed())); + connect(placementCombo, SIGNAL(activated(int)), SLOT(changed())); - hideUtilityWindowsForInactive = new QCheckBox( i18n( "Hide utility windows for inactive applications" ), this ); + hideUtilityWindowsForInactive = new QCheckBox(i18n("Hide utility windows for inactive applications"), this); hideUtilityWindowsForInactive->setWhatsThis( - i18n( "When turned on, utility windows (tool windows, torn-off menus,...) of inactive applications will be" - " hidden and will be shown only when the application becomes active. Note that applications" - " have to mark the windows with the proper window type for this feature to work." )); + i18n("When turned on, utility windows (tool windows, torn-off menus,...) of inactive applications will be" + " hidden and will be shown only when the application becomes active. Note that applications" + " have to mark the windows with the proper window type for this feature to work.")); connect(hideUtilityWindowsForInactive, SIGNAL(toggled(bool)), SLOT(changed())); - vLay->addWidget( hideUtilityWindowsForInactive, 1, 0, 1, 2 ); + vLay->addWidget(hideUtilityWindowsForInactive, 1, 0, 1, 2); tilBox = new KButtonGroup(this); tilBox->setTitle(i18n("Tiling")); QGridLayout *tilBoxLay = new QGridLayout(tilBox); - tilingOn = new QCheckBox( i18n( "Enable Tiling" ), tilBox ); + tilingOn = new QCheckBox(i18n("Enable Tiling"), tilBox); tilingOn->setWhatsThis( - i18n( "A tiling window manager lays out all the windows in a non-overlapping manner." - " This way all windows are always visible.") ); - tilBoxLay->addWidget( tilingOn ); - connect( tilingOn, SIGNAL( toggled(bool) ), SLOT( tilingOnChanged(bool) ) ); - connect( tilingOn, SIGNAL( toggled(bool) ), SLOT( changed() ) ); + i18n("A tiling window manager lays out all the windows in a non-overlapping manner." + " This way all windows are always visible.")); + tilBoxLay->addWidget(tilingOn); + connect(tilingOn, SIGNAL(toggled(bool)), SLOT(tilingOnChanged(bool))); + connect(tilingOn, SIGNAL(toggled(bool)), SLOT(changed())); - tilingLayoutLabel = new QLabel( i18n("Default Tiling &Layout"), tilBox ); - tilBoxLay->addWidget( tilingLayoutLabel, 1, 0 ); + tilingLayoutLabel = new QLabel(i18n("Default Tiling &Layout"), tilBox); + tilBoxLay->addWidget(tilingLayoutLabel, 1, 0); - tilingLayoutCombo = new KComboBox( tilBox ); + tilingLayoutCombo = new KComboBox(tilBox); // NOTE: add your layout to the bottom of this list - tilingLayoutCombo->addItem( i18nc("Spiral tiling layout", "Spiral") ); - tilingLayoutCombo->addItem( i18nc("Two-column horizontal tiling layout", "Columns") ); - tilingLayoutCombo->addItem( i18nc("Floating layout, windows aren't tiled at all", "Floating") ); + tilingLayoutCombo->addItem(i18nc("Spiral tiling layout", "Spiral")); + tilingLayoutCombo->addItem(i18nc("Two-column horizontal tiling layout", "Columns")); + tilingLayoutCombo->addItem(i18nc("Floating layout, windows aren't tiled at all", "Floating")); - tilingLayoutLabel->setBuddy( tilingLayoutCombo ); - connect( tilingLayoutCombo, SIGNAL( activated(int) ), SLOT( changed() ) ); - tilBoxLay->addWidget( tilingLayoutCombo, 1, 1 ); + tilingLayoutLabel->setBuddy(tilingLayoutCombo); + connect(tilingLayoutCombo, SIGNAL(activated(int)), SLOT(changed())); + tilBoxLay->addWidget(tilingLayoutCombo, 1, 1); - tilingRaiseLabel = new QLabel( i18n("Floating &Windows Raising"), tilBox ); - tilBoxLay->addWidget( tilingRaiseLabel, 2, 0 ); + tilingRaiseLabel = new QLabel(i18n("Floating &Windows Raising"), tilBox); + tilBoxLay->addWidget(tilingRaiseLabel, 2, 0); - tilingRaiseCombo = new KComboBox( tilBox ); + tilingRaiseCombo = new KComboBox(tilBox); // when a floating window is activated, all other floating // windows are also brought to the front, above the tiled windows // when a tiled window is focused, all floating windows go to the back. // NOTE: If the user has explicitly set a client to "keep above others", that will be respected. - tilingRaiseCombo->addItem( i18nc( "Window Raising Policy", "Raise/Lower all floating windows" ) ); - tilingRaiseCombo->addItem( i18nc( "Window Raising Policy", "Raise/Lower current window only") ); - tilingRaiseCombo->addItem( i18nc( "Window Raising Policy", "Floating windows are always on top" ) ); + tilingRaiseCombo->addItem(i18nc("Window Raising Policy", "Raise/Lower all floating windows")); + tilingRaiseCombo->addItem(i18nc("Window Raising Policy", "Raise/Lower current window only")); + tilingRaiseCombo->addItem(i18nc("Window Raising Policy", "Floating windows are always on top")); wtstr = i18n("The window raising policy determines how floating windows are stacked" "
      " "
    • Raise/Lower all will raise all floating windows when a" @@ -684,71 +688,79 @@ KAdvancedConfig::KAdvancedConfig (bool _standAlone, KConfig *_config, const KCom "
    • Floating windows on top will always keep floating windows on top, even" " when a tiled window is activated." "
    ") ; - tilingRaiseCombo->setWhatsThis( wtstr ); - connect( tilingRaiseCombo, SIGNAL( activated(int) ), SLOT( changed() ) ); - tilingRaiseLabel->setBuddy( tilingRaiseCombo ); - tilBoxLay->addWidget( tilingRaiseCombo, 2, 1 ); + tilingRaiseCombo->setWhatsThis(wtstr); + connect(tilingRaiseCombo, SIGNAL(activated(int)), SLOT(changed())); + tilingRaiseLabel->setBuddy(tilingRaiseCombo); + tilBoxLay->addWidget(tilingRaiseCombo, 2, 1); - lay->addWidget( tilBox ); + lay->addWidget(tilBox); lay->addStretch(); load(); } -void KAdvancedConfig::setShadeHover(bool on) { +void KAdvancedConfig::setShadeHover(bool on) +{ shadeHoverOn->setChecked(on); shadeHoverLabel->setEnabled(on); shadeHover->setEnabled(on); } -void KAdvancedConfig::setShadeHoverInterval(int k) { +void KAdvancedConfig::setShadeHoverInterval(int k) +{ shadeHover->setValue(k); } -int KAdvancedConfig::getShadeHoverInterval() { +int KAdvancedConfig::getShadeHoverInterval() +{ return shadeHover->value(); } -void KAdvancedConfig::shadeHoverChanged(bool a) { +void KAdvancedConfig::shadeHoverChanged(bool a) +{ shadeHoverLabel->setEnabled(a); shadeHover->setEnabled(a); } -void KAdvancedConfig::setTilingOn( bool on ) { - tilingOn->setChecked( on ); - tilingLayoutLabel->setEnabled( on ); - tilingLayoutCombo->setEnabled( on ); - tilingRaiseLabel->setEnabled( on ); - tilingRaiseCombo->setEnabled( on ); -} - -void KAdvancedConfig::setTilingLayout( int l ) { - tilingLayoutCombo->setCurrentIndex( l ); -} - -void KAdvancedConfig::setTilingRaisePolicy( int l ) { - tilingRaiseCombo->setCurrentIndex( l ); -} - -void KAdvancedConfig::tilingOnChanged( bool a ) { - tilingLayoutLabel->setEnabled( a ); - tilingLayoutCombo->setEnabled( a ); - tilingRaiseLabel->setEnabled( a ); - tilingRaiseCombo->setEnabled( a ); -} - -void KAdvancedConfig::showEvent( QShowEvent *ev ) +void KAdvancedConfig::setTilingOn(bool on) { - if ( !standAlone ) { - QWidget::showEvent( ev ); + tilingOn->setChecked(on); + tilingLayoutLabel->setEnabled(on); + tilingLayoutCombo->setEnabled(on); + tilingRaiseLabel->setEnabled(on); + tilingRaiseCombo->setEnabled(on); +} + +void KAdvancedConfig::setTilingLayout(int l) +{ + tilingLayoutCombo->setCurrentIndex(l); +} + +void KAdvancedConfig::setTilingRaisePolicy(int l) +{ + tilingRaiseCombo->setCurrentIndex(l); +} + +void KAdvancedConfig::tilingOnChanged(bool a) +{ + tilingLayoutLabel->setEnabled(a); + tilingLayoutCombo->setEnabled(a); + tilingRaiseLabel->setEnabled(a); + tilingRaiseCombo->setEnabled(a); +} + +void KAdvancedConfig::showEvent(QShowEvent *ev) +{ + if (!standAlone) { + QWidget::showEvent(ev); return; } - KCModule::showEvent( ev ); + KCModule::showEvent(ev); } -void KAdvancedConfig::load( void ) +void KAdvancedConfig::load(void) { KConfigGroup cg(config, "Windows"); @@ -759,7 +771,7 @@ void KAdvancedConfig::load( void ) // placement policy --- CT 19jan98 --- key = cg.readEntry(KWIN_PLACEMENT); //CT 13mar98 interactive placement -// if( key.left(11) == "interactive") { +// if ( key.left(11) == "interactive") { // setPlacement(INTERACTIVE_PLACEMENT); // int comma_pos = key.find(','); // if (comma_pos < 0) @@ -774,36 +786,36 @@ void KAdvancedConfig::load( void ) // interactiveTrigger->setValue(0); // iTLabel->setEnabled(false); // interactiveTrigger->hide(); - if( key == "Random") + if (key == "Random") setPlacement(RANDOM_PLACEMENT); - else if( key == "Cascade") + else if (key == "Cascade") setPlacement(CASCADE_PLACEMENT); //CT 31jan98 //CT 31mar98 manual placement - else if( key == "manual") + else if (key == "manual") setPlacement(MANUAL_PLACEMENT); - else if( key == "Centered") + else if (key == "Centered") setPlacement(CENTERED_PLACEMENT); - else if( key == "ZeroCornered") + else if (key == "ZeroCornered") setPlacement(ZEROCORNERED_PLACEMENT); - else if( key == "Maximizing") + else if (key == "Maximizing") setPlacement(MAXIMIZING_PLACEMENT); else setPlacement(SMART_PLACEMENT); // } - setHideUtilityWindowsForInactive( cg.readEntry( KWIN_HIDE_UTILITY, true)); - setInactiveTabsSkipTaskbar( cg.readEntry( KWIN_INACTIVE_SKIP_TASKBAR, false)); - setAutogroupSimilarWindows( cg.readEntry( KWIN_AUTOGROUP_SIMILAR, false)); - setAutogroupInForeground( cg.readEntry( KWIN_AUTOGROUP_FOREGROUND, true)); + setHideUtilityWindowsForInactive(cg.readEntry(KWIN_HIDE_UTILITY, true)); + setInactiveTabsSkipTaskbar(cg.readEntry(KWIN_INACTIVE_SKIP_TASKBAR, false)); + setAutogroupSimilarWindows(cg.readEntry(KWIN_AUTOGROUP_SIMILAR, false)); + setAutogroupInForeground(cg.readEntry(KWIN_AUTOGROUP_FOREGROUND, true)); - setTilingOn( cg.readEntry( KWIN_TILINGON, false ) ); - setTilingLayout( cg.readEntry( KWIN_TILING_DEFAULT_LAYOUT, 0 ) ); - setTilingRaisePolicy( cg.readEntry( KWIN_TILING_RAISE_POLICY, 0 ) ); + setTilingOn(cg.readEntry(KWIN_TILINGON, false)); + setTilingLayout(cg.readEntry(KWIN_TILING_DEFAULT_LAYOUT, 0)); + setTilingRaisePolicy(cg.readEntry(KWIN_TILING_RAISE_POLICY, 0)); emit KCModule::changed(false); } -void KAdvancedConfig::save( void ) +void KAdvancedConfig::save(void) { int v; @@ -811,11 +823,11 @@ void KAdvancedConfig::save( void ) cg.writeEntry(KWIN_SHADEHOVER, shadeHoverOn->isChecked()); v = getShadeHoverInterval(); - if (v<0) v = 0; + if (v < 0) v = 0; cg.writeEntry(KWIN_SHADEHOVER_INTERVAL, v); // placement policy --- CT 31jan98 --- - v =getPlacement(); + v = getPlacement(); if (v == RANDOM_PLACEMENT) cg.writeEntry(KWIN_PLACEMENT, "Random"); else if (v == CASCADE_PLACEMENT) @@ -841,19 +853,18 @@ void KAdvancedConfig::save( void ) cg.writeEntry(KWIN_AUTOGROUP_SIMILAR, autogroupSimilarWindows->isChecked()); cg.writeEntry(KWIN_AUTOGROUP_FOREGROUND, autogroupInForeground->isChecked()); - if (standAlone) - { + if (standAlone) { config->sync(); - // Send signal to all kwin instances - QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); - QDBusConnection::sessionBus().send(message); + // Send signal to all kwin instances + QDBusMessage message = + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); } - cg.writeEntry( KWIN_TILINGON, tilingOn->isChecked() ); - cg.writeEntry( KWIN_TILING_DEFAULT_LAYOUT, tilingLayoutCombo->currentIndex() ); - cg.writeEntry( KWIN_TILING_RAISE_POLICY, tilingRaiseCombo->currentIndex() ); + cg.writeEntry(KWIN_TILINGON, tilingOn->isChecked()); + cg.writeEntry(KWIN_TILING_DEFAULT_LAYOUT, tilingLayoutCombo->currentIndex()); + cg.writeEntry(KWIN_TILING_RAISE_POLICY, tilingRaiseCombo->currentIndex()); emit KCModule::changed(false); } @@ -862,13 +873,13 @@ void KAdvancedConfig::defaults() setShadeHover(false); setShadeHoverInterval(250); setPlacement(SMART_PLACEMENT); - setHideUtilityWindowsForInactive( true ); - setTilingOn( false ); - setTilingLayout( 0 ); - setTilingRaisePolicy( 0 ); - setInactiveTabsSkipTaskbar( false ); - setAutogroupSimilarWindows( false ); - setAutogroupInForeground( true ); + setHideUtilityWindowsForInactive(true); + setTilingOn(false); + setTilingLayout(0); + setTilingRaisePolicy(0); + setInactiveTabsSkipTaskbar(false); + setAutogroupSimilarWindows(false); + setAutogroupInForeground(true); emit KCModule::changed(true); } @@ -884,66 +895,70 @@ void KAdvancedConfig::setPlacement(int plac) } -void KAdvancedConfig::setHideUtilityWindowsForInactive(bool s) { - hideUtilityWindowsForInactive->setChecked( s ); +void KAdvancedConfig::setHideUtilityWindowsForInactive(bool s) +{ + hideUtilityWindowsForInactive->setChecked(s); } -void KAdvancedConfig::setInactiveTabsSkipTaskbar(bool s) { - inactiveTabsSkipTaskbar->setChecked( s ); +void KAdvancedConfig::setInactiveTabsSkipTaskbar(bool s) +{ + inactiveTabsSkipTaskbar->setChecked(s); } -void KAdvancedConfig::setAutogroupSimilarWindows(bool s) { - autogroupSimilarWindows->setChecked( s ); +void KAdvancedConfig::setAutogroupSimilarWindows(bool s) +{ + autogroupSimilarWindows->setChecked(s); } -void KAdvancedConfig::setAutogroupInForeground(bool s) { - autogroupInForeground->setChecked( s ); +void KAdvancedConfig::setAutogroupInForeground(bool s) +{ + autogroupInForeground->setChecked(s); } -KMovingConfig::~KMovingConfig () +KMovingConfig::~KMovingConfig() { if (standAlone) delete config; } -KMovingConfig::KMovingConfig (bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent) +KMovingConfig::KMovingConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent) : KCModule(inst, parent), config(_config), standAlone(_standAlone) { QString wtstr; - QBoxLayout *lay = new QVBoxLayout (this); + QBoxLayout *lay = new QVBoxLayout(this); windowsBox = new KButtonGroup(this); windowsBox->setTitle(i18n("Windows")); - QBoxLayout *wLay = new QVBoxLayout (windowsBox); + QBoxLayout *wLay = new QVBoxLayout(windowsBox); QBoxLayout *bLay = new QVBoxLayout; wLay->addLayout(bLay); opaque = new QCheckBox(i18n("Di&splay content in moving windows"), windowsBox); bLay->addWidget(opaque); - opaque->setWhatsThis( i18n("Enable this option if you want a window's content to be fully shown" - " while moving it, instead of just showing a window 'skeleton'. The result may not be satisfying" - " on slow machines without graphic acceleration.") ); + opaque->setWhatsThis(i18n("Enable this option if you want a window's content to be fully shown" + " while moving it, instead of just showing a window 'skeleton'. The result may not be satisfying" + " on slow machines without graphic acceleration.")); resizeOpaqueOn = new QCheckBox(i18n("Display content in &resizing windows"), windowsBox); bLay->addWidget(resizeOpaqueOn); - resizeOpaqueOn->setWhatsThis( i18n("Enable this option if you want a window's content to be shown" - " while resizing it, instead of just showing a window 'skeleton'. The result may not be satisfying" - " on slow machines.") ); + resizeOpaqueOn->setWhatsThis(i18n("Enable this option if you want a window's content to be shown" + " while resizing it, instead of just showing a window 'skeleton'. The result may not be satisfying" + " on slow machines.")); geometryTipOn = new QCheckBox(i18n("Display window &geometry when moving or resizing"), windowsBox); bLay->addWidget(geometryTipOn); - geometryTipOn->setWhatsThis( i18n("Enable this option if you want a window's geometry to be displayed" - " while it is being moved or resized. The window position relative" - " to the top-left corner of the screen is displayed together with" - " its size.")); + geometryTipOn->setWhatsThis(i18n("Enable this option if you want a window's geometry to be displayed" + " while it is being moved or resized. The window position relative" + " to the top-left corner of the screen is displayed together with" + " its size.")); - moveResizeMaximized = new QCheckBox( i18n("Display borders on &maximized windows"), windowsBox); + moveResizeMaximized = new QCheckBox(i18n("Display borders on &maximized windows"), windowsBox); bLay->addWidget(moveResizeMaximized); - moveResizeMaximized->setWhatsThis( i18n("When enabled, this feature activates the border of maximized windows" - " and allows you to move or resize them," - " just like for normal windows")); + moveResizeMaximized->setWhatsThis(i18n("When enabled, this feature activates the border of maximized windows" + " and allows you to move or resize them," + " just like for normal windows")); lay->addWidget(windowsBox); @@ -971,51 +986,51 @@ KMovingConfig::KMovingConfig (bool _standAlone, KConfig *_config, const KCompone QGridLayout *kLay = new QGridLayout(MagicBox); BrdrSnap = new KIntNumInput(10, MagicBox); - BrdrSnap->setSpecialValueText( i18nc("no border snap zone", "none") ); - BrdrSnap->setRange( 0, MAX_BRDR_SNAP); - BrdrSnap->setSteps(1,10); - BrdrSnap->setWhatsThis( i18n("Here you can set the snap zone for screen borders, i.e." - " the 'strength' of the magnetic field which will make windows snap to the border when" - " moved near it.") ); + BrdrSnap->setSpecialValueText(i18nc("no border snap zone", "none")); + BrdrSnap->setRange(0, MAX_BRDR_SNAP); + BrdrSnap->setSteps(1, 10); + BrdrSnap->setWhatsThis(i18n("Here you can set the snap zone for screen borders, i.e." + " the 'strength' of the magnetic field which will make windows snap to the border when" + " moved near it.")); BrdrSnap->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); BrdrSnapLabel = new QLabel(i18n("&Border snap zone:"), this); - BrdrSnapLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + BrdrSnapLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); BrdrSnapLabel->setBuddy(BrdrSnap); kLay->addWidget(BrdrSnapLabel, 0, 0); kLay->addWidget(BrdrSnap, 0, 1); WndwSnap = new KIntNumInput(10, MagicBox); - WndwSnap->setSpecialValueText( i18nc("no window snap zone", "none") ); - WndwSnap->setRange( 0, MAX_WNDW_SNAP); - WndwSnap->setSteps(1,10); - WndwSnap->setWhatsThis( i18n("Here you can set the snap zone for windows, i.e." - " the 'strength' of the magnetic field which will make windows snap to each other when" - " they are moved near another window.") ); + WndwSnap->setSpecialValueText(i18nc("no window snap zone", "none")); + WndwSnap->setRange(0, MAX_WNDW_SNAP); + WndwSnap->setSteps(1, 10); + WndwSnap->setWhatsThis(i18n("Here you can set the snap zone for windows, i.e." + " the 'strength' of the magnetic field which will make windows snap to each other when" + " they are moved near another window.")); BrdrSnap->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); WndwSnapLabel = new QLabel(i18n("&Window snap zone:"), this); - WndwSnapLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + WndwSnapLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); WndwSnapLabel->setBuddy(WndwSnap); kLay->addWidget(WndwSnapLabel, 1, 0); kLay->addWidget(WndwSnap, 1, 1); CntrSnap = new KIntNumInput(10, MagicBox); - CntrSnap->setSpecialValueText( i18nc("no center snap zone", "none") ); - CntrSnap->setRange( 0, MAX_CNTR_SNAP); - CntrSnap->setSteps(1,10); - CntrSnap->setWhatsThis( i18n("Here you can set the snap zone for the screen center, i.e." - " the 'strength' of the magnetic field which will make windows snap to the center of" - " the screen when moved near it.") ); + CntrSnap->setSpecialValueText(i18nc("no center snap zone", "none")); + CntrSnap->setRange(0, MAX_CNTR_SNAP); + CntrSnap->setSteps(1, 10); + CntrSnap->setWhatsThis(i18n("Here you can set the snap zone for the screen center, i.e." + " the 'strength' of the magnetic field which will make windows snap to the center of" + " the screen when moved near it.")); BrdrSnap->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); CntrSnapLabel = new QLabel(i18n("&Center snap zone:"), this); - CntrSnapLabel->setAlignment(Qt::AlignVCenter|Qt::AlignRight); + CntrSnapLabel->setAlignment(Qt::AlignVCenter | Qt::AlignRight); CntrSnapLabel->setBuddy(CntrSnap); kLay->addWidget(CntrSnapLabel, 2, 0); kLay->addWidget(CntrSnap, 2, 1); - OverlapSnap=new QCheckBox(i18n("Snap windows onl&y when overlapping"),MagicBox); - OverlapSnap->setWhatsThis( i18n("Here you can set that windows will be only" - " snapped if you try to overlap them, i.e. they will not be snapped if the windows" - " comes only near another window or border.") ); + OverlapSnap = new QCheckBox(i18n("Snap windows onl&y when overlapping"), MagicBox); + OverlapSnap->setWhatsThis(i18n("Here you can set that windows will be only" + " snapped if you try to overlap them, i.e. they will not be snapped if the windows" + " comes only near another window or border.")); kLay->addWidget(OverlapSnap, 3, 0, 1, 2); lay->addWidget(MagicBox); @@ -1024,17 +1039,17 @@ KMovingConfig::KMovingConfig (bool _standAlone, KConfig *_config, const KCompone load(); // Any changes goes to slotChanged() - connect( opaque, SIGNAL(clicked()), SLOT(changed())); - connect( resizeOpaqueOn, SIGNAL(clicked()), SLOT(changed())); - connect( geometryTipOn, SIGNAL(clicked()), SLOT(changed())); - connect( moveResizeMaximized, SIGNAL(toggled(bool)), SLOT(changed())); - connect( BrdrSnap, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( BrdrSnap, SIGNAL(valueChanged(int)), SLOT(slotBrdrSnapChanged(int))); - connect( WndwSnap, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( WndwSnap, SIGNAL(valueChanged(int)), SLOT(slotWndwSnapChanged(int))); - connect( CntrSnap, SIGNAL(valueChanged(int)), SLOT(changed())); - connect( CntrSnap, SIGNAL(valueChanged(int)), SLOT(slotCntrSnapChanged(int))); - connect( OverlapSnap, SIGNAL(clicked()), SLOT(changed())); + connect(opaque, SIGNAL(clicked()), SLOT(changed())); + connect(resizeOpaqueOn, SIGNAL(clicked()), SLOT(changed())); + connect(geometryTipOn, SIGNAL(clicked()), SLOT(changed())); + connect(moveResizeMaximized, SIGNAL(toggled(bool)), SLOT(changed())); + connect(BrdrSnap, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(BrdrSnap, SIGNAL(valueChanged(int)), SLOT(slotBrdrSnapChanged(int))); + connect(WndwSnap, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(WndwSnap, SIGNAL(valueChanged(int)), SLOT(slotWndwSnapChanged(int))); + connect(CntrSnap, SIGNAL(valueChanged(int)), SLOT(changed())); + connect(CntrSnap, SIGNAL(valueChanged(int)), SLOT(slotCntrSnapChanged(int))); + connect(OverlapSnap, SIGNAL(clicked()), SLOT(changed())); // To get suffix to BrdrSnap, WndwSnap and CntrSnap inputs with default values. slotBrdrSnapChanged(BrdrSnap->value()); @@ -1044,7 +1059,7 @@ KMovingConfig::KMovingConfig (bool _standAlone, KConfig *_config, const KCompone int KMovingConfig::getMove() { - return (opaque->isChecked())? OPAQUE : TRANSPARENT; + return (opaque->isChecked()) ? OPAQUE : TRANSPARENT; } void KMovingConfig::setMove(int trans) @@ -1064,7 +1079,7 @@ bool KMovingConfig::getGeometryTip() int KMovingConfig::getResizeOpaque() { - return (resizeOpaqueOn->isChecked())? RESIZE_OPAQUE : RESIZE_TRANSPARENT; + return (resizeOpaqueOn->isChecked()) ? RESIZE_OPAQUE : RESIZE_TRANSPARENT; } void KMovingConfig::setResizeOpaque(int opaque) @@ -1072,53 +1087,57 @@ void KMovingConfig::setResizeOpaque(int opaque) resizeOpaqueOn->setChecked(opaque == RESIZE_OPAQUE); } -void KMovingConfig::setMoveResizeMaximized(bool a) { +void KMovingConfig::setMoveResizeMaximized(bool a) +{ moveResizeMaximized->setChecked(a); } -void KMovingConfig::slotBrdrSnapChanged(int value) { +void KMovingConfig::slotBrdrSnapChanged(int value) +{ BrdrSnap->setSuffix(i18np(" pixel", " pixels", value)); } -void KMovingConfig::slotWndwSnapChanged(int value) { +void KMovingConfig::slotWndwSnapChanged(int value) +{ WndwSnap->setSuffix(i18np(" pixel", " pixels", value)); } -void KMovingConfig::slotCntrSnapChanged(int value) { +void KMovingConfig::slotCntrSnapChanged(int value) +{ CntrSnap->setSuffix(i18np(" pixel", " pixels", value)); } -void KMovingConfig::showEvent( QShowEvent *ev ) +void KMovingConfig::showEvent(QShowEvent *ev) { - if ( !standAlone ) { - QWidget::showEvent( ev ); + if (!standAlone) { + QWidget::showEvent(ev); return; } - KCModule::showEvent( ev ); + KCModule::showEvent(ev); } -void KMovingConfig::load( void ) +void KMovingConfig::load(void) { QString key; KConfigGroup cg(config, "Windows"); key = cg.readEntry(KWIN_MOVE, "Opaque"); - if( key == "Transparent") + if (key == "Transparent") setMove(TRANSPARENT); - else if( key == "Opaque") + else if (key == "Opaque") setMove(OPAQUE); // DF: please keep the default consistent with kwin (options.cpp line 145) key = cg.readEntry(KWIN_RESIZE_OPAQUE, "Opaque"); - if( key == "Opaque") + if (key == "Opaque") setResizeOpaque(RESIZE_OPAQUE); - else if ( key == "Transparent") + else if (key == "Transparent") setResizeOpaque(RESIZE_TRANSPARENT); //KS 10Jan2003 - Geometry Tip during window move/resize bool showGeomTip = cg.readEntry(KWIN_GEOMETRY, false); - setGeometryTip( showGeomTip ); + setGeometryTip(showGeomTip); setMoveResizeMaximized(cg.readEntry(KWIN_MOVE_RESIZE_MAXIMIZED, false)); @@ -1127,24 +1146,24 @@ void KMovingConfig::load( void ) v = cg.readEntry(KWM_BRDR_SNAP_ZONE, KWM_BRDR_SNAP_ZONE_DEFAULT); if (v > MAX_BRDR_SNAP) setBorderSnapZone(MAX_BRDR_SNAP); - else if (v < 0) setBorderSnapZone (0); + else if (v < 0) setBorderSnapZone(0); else setBorderSnapZone(v); v = cg.readEntry(KWM_WNDW_SNAP_ZONE, KWM_WNDW_SNAP_ZONE_DEFAULT); if (v > MAX_WNDW_SNAP) setWindowSnapZone(MAX_WNDW_SNAP); - else if (v < 0) setWindowSnapZone (0); + else if (v < 0) setWindowSnapZone(0); else setWindowSnapZone(v); v = cg.readEntry(KWM_CNTR_SNAP_ZONE, KWM_CNTR_SNAP_ZONE_DEFAULT); if (v > MAX_CNTR_SNAP) setCenterSnapZone(MAX_CNTR_SNAP); - else if (v < 0) setCenterSnapZone (0); + else if (v < 0) setCenterSnapZone(0); else setCenterSnapZone(v); OverlapSnap->setChecked(cg.readEntry("SnapOnlyWhenOverlapping", false)); emit KCModule::changed(false); } -void KMovingConfig::save( void ) +void KMovingConfig::save(void) { int v; @@ -1152,9 +1171,9 @@ void KMovingConfig::save( void ) v = getMove(); if (v == TRANSPARENT) - cg.writeEntry(KWIN_MOVE,"Transparent"); + cg.writeEntry(KWIN_MOVE, "Transparent"); else - cg.writeEntry(KWIN_MOVE,"Opaque"); + cg.writeEntry(KWIN_MOVE, "Opaque"); cg.writeEntry(KWIN_GEOMETRY, getGeometryTip()); @@ -1167,19 +1186,18 @@ void KMovingConfig::save( void ) cg.writeEntry(KWIN_MOVE_RESIZE_MAXIMIZED, moveResizeMaximized->isChecked()); - cg.writeEntry(KWM_BRDR_SNAP_ZONE,getBorderSnapZone()); - cg.writeEntry(KWM_WNDW_SNAP_ZONE,getWindowSnapZone()); - cg.writeEntry(KWM_CNTR_SNAP_ZONE,getCenterSnapZone()); - cg.writeEntry("SnapOnlyWhenOverlapping",OverlapSnap->isChecked()); + cg.writeEntry(KWM_BRDR_SNAP_ZONE, getBorderSnapZone()); + cg.writeEntry(KWM_WNDW_SNAP_ZONE, getWindowSnapZone()); + cg.writeEntry(KWM_CNTR_SNAP_ZONE, getCenterSnapZone()); + cg.writeEntry("SnapOnlyWhenOverlapping", OverlapSnap->isChecked()); - KConfigGroup( config, "Plugins" ).writeEntry("kwin4_effect_windowgeometryEnabled", getGeometryTip()); + KConfigGroup(config, "Plugins").writeEntry("kwin4_effect_windowgeometryEnabled", getGeometryTip()); - if (standAlone) - { + if (standAlone) { config->sync(); // Send signal to all kwin instances QDBusMessage message = - QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); } emit KCModule::changed(false); @@ -1201,28 +1219,34 @@ void KMovingConfig::defaults() emit KCModule::changed(true); } -int KMovingConfig::getBorderSnapZone() { - return BrdrSnap->value(); +int KMovingConfig::getBorderSnapZone() +{ + return BrdrSnap->value(); } -void KMovingConfig::setBorderSnapZone(int pxls) { - BrdrSnap->setValue(pxls); +void KMovingConfig::setBorderSnapZone(int pxls) +{ + BrdrSnap->setValue(pxls); } -int KMovingConfig::getWindowSnapZone() { - return WndwSnap->value(); +int KMovingConfig::getWindowSnapZone() +{ + return WndwSnap->value(); } -void KMovingConfig::setWindowSnapZone(int pxls) { - WndwSnap->setValue(pxls); +void KMovingConfig::setWindowSnapZone(int pxls) +{ + WndwSnap->setValue(pxls); } -int KMovingConfig::getCenterSnapZone() { - return CntrSnap->value(); +int KMovingConfig::getCenterSnapZone() +{ + return CntrSnap->value(); } -void KMovingConfig::setCenterSnapZone(int pxls) { - CntrSnap->setValue(pxls); +void KMovingConfig::setCenterSnapZone(int pxls) +{ + CntrSnap->setValue(pxls); } #include "windows.moc" diff --git a/kcmkwin/kwinoptions/windows.h b/kcmkwin/kwinoptions/windows.h index 7bce38e6b..dd2b619d3 100644 --- a/kcmkwin/kwinoptions/windows.h +++ b/kcmkwin/kwinoptions/windows.h @@ -67,180 +67,186 @@ class KIntNumInput; class KFocusConfig : public KCModule { - Q_OBJECT + Q_OBJECT public: - KFocusConfig( bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent ); - ~KFocusConfig(); + KFocusConfig(bool _standAlone, KConfig *_config, const KComponentData &inst, QWidget *parent); + ~KFocusConfig(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected: - void showEvent( QShowEvent *ev ); + void showEvent(QShowEvent *ev); private slots: - void setDelayFocusEnabled(); - void focusPolicyChanged(); - void autoRaiseOnTog(bool);//CT 23Oct1998 - void delayFocusOnTog(bool); - void clickRaiseOnTog(bool); - void updateActiveMouseScreen(); - void changed() { emit KCModule::changed(true); } + void setDelayFocusEnabled(); + void focusPolicyChanged(); + void autoRaiseOnTog(bool);//CT 23Oct1998 + void delayFocusOnTog(bool); + void clickRaiseOnTog(bool); + void updateActiveMouseScreen(); + void changed() { + emit KCModule::changed(true); + } private: - int getFocus( void ); - int getAutoRaiseInterval( void ); - int getDelayFocusInterval( void ); + int getFocus(void); + int getAutoRaiseInterval(void); + int getDelayFocusInterval(void); - void setFocus(int); - void setAutoRaiseInterval(int); - void setAutoRaise(bool); - void setDelayFocusInterval(int); - void setDelayFocus(bool); - void setClickRaise(bool); - void setSeparateScreenFocus(bool); - void setActiveMouseScreen(bool); + void setFocus(int); + void setAutoRaiseInterval(int); + void setAutoRaise(bool); + void setDelayFocusInterval(int); + void setDelayFocus(bool); + void setClickRaise(bool); + void setSeparateScreenFocus(bool); + void setActiveMouseScreen(bool); - void setFocusStealing( int ); - KComboBox* focusStealing; + void setFocusStealing(int); + KComboBox* focusStealing; - //QGroupBox *fcsBox; - QWidget* fcsBox; - KComboBox *focusCombo; - QLabel *autoRaiseOnLabel; - QCheckBox *autoRaiseOn; - QLabel *delayFocusOnLabel; - QCheckBox *delayFocusOn; - QCheckBox *clickRaiseOn; - KIntNumInput *autoRaise; - KIntNumInput *delayFocus; - QCheckBox *separateScreenFocus; - QCheckBox *activeMouseScreen; + //QGroupBox *fcsBox; + QWidget* fcsBox; + KComboBox *focusCombo; + QLabel *autoRaiseOnLabel; + QCheckBox *autoRaiseOn; + QLabel *delayFocusOnLabel; + QCheckBox *delayFocusOn; + QCheckBox *clickRaiseOn; + KIntNumInput *autoRaise; + KIntNumInput *delayFocus; + QCheckBox *separateScreenFocus; + QCheckBox *activeMouseScreen; - KConfig *config; - bool standAlone; + KConfig *config; + bool standAlone; }; class KMovingConfig : public KCModule { - Q_OBJECT + Q_OBJECT public: - KMovingConfig( bool _standAlone, KConfig *config, const KComponentData &inst, QWidget *parent ); - ~KMovingConfig(); + KMovingConfig(bool _standAlone, KConfig *config, const KComponentData &inst, QWidget *parent); + ~KMovingConfig(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected: - void showEvent( QShowEvent *ev ); + void showEvent(QShowEvent *ev); private slots: - void changed() { emit KCModule::changed(true); } - void slotBrdrSnapChanged( int ); - void slotWndwSnapChanged( int ); - void slotCntrSnapChanged( int ); + void changed() { + emit KCModule::changed(true); + } + void slotBrdrSnapChanged(int); + void slotWndwSnapChanged(int); + void slotCntrSnapChanged(int); private: - int getMove( void ); - int getResizeOpaque ( void ); - bool getGeometryTip( void ); //KS + int getMove(void); + int getResizeOpaque(void); + bool getGeometryTip(void); //KS - void setMove(int); - void setResizeOpaque(int); - void setGeometryTip(bool); //KS - void setMoveResizeMaximized(bool); + void setMove(int); + void setResizeOpaque(int); + void setGeometryTip(bool); //KS + void setMoveResizeMaximized(bool); - KButtonGroup *windowsBox; - QCheckBox *opaque; - QCheckBox *resizeOpaqueOn; - QCheckBox *geometryTipOn; - QCheckBox *moveResizeMaximized; + KButtonGroup *windowsBox; + QCheckBox *opaque; + QCheckBox *resizeOpaqueOn; + QCheckBox *geometryTipOn; + QCheckBox *moveResizeMaximized; - KConfig *config; - bool standAlone; + KConfig *config; + bool standAlone; - int getBorderSnapZone(); - void setBorderSnapZone( int ); - int getWindowSnapZone(); - void setWindowSnapZone( int ); - int getCenterSnapZone(); - void setCenterSnapZone( int ); + int getBorderSnapZone(); + void setBorderSnapZone(int); + int getWindowSnapZone(); + void setWindowSnapZone(int); + int getCenterSnapZone(); + void setCenterSnapZone(int); - KButtonGroup *MagicBox; - QLabel *BrdrSnapLabel, *WndwSnapLabel, *CntrSnapLabel; - KIntNumInput *BrdrSnap, *WndwSnap, *CntrSnap; - QCheckBox *OverlapSnap; + KButtonGroup *MagicBox; + QLabel *BrdrSnapLabel, *WndwSnapLabel, *CntrSnapLabel; + KIntNumInput *BrdrSnap, *WndwSnap, *CntrSnap; + QCheckBox *OverlapSnap; }; class KAdvancedConfig : public KCModule { - Q_OBJECT + Q_OBJECT public: - KAdvancedConfig( bool _standAlone, KConfig *config, const KComponentData &inst, QWidget *parent ); - ~KAdvancedConfig(); + KAdvancedConfig(bool _standAlone, KConfig *config, const KComponentData &inst, QWidget *parent); + ~KAdvancedConfig(); - void load(); - void save(); - void defaults(); + void load(); + void save(); + void defaults(); protected: - void showEvent( QShowEvent *ev ); + void showEvent(QShowEvent *ev); private slots: - void shadeHoverChanged(bool); + void shadeHoverChanged(bool); - void changed() { emit KCModule::changed(true); } + void changed() { + emit KCModule::changed(true); + } - void tilingOnChanged( bool a ); + void tilingOnChanged(bool a); private: - int getShadeHoverInterval (void ); - void setShadeHover(bool); - void setShadeHoverInterval(int); + int getShadeHoverInterval(void); + void setShadeHover(bool); + void setShadeHoverInterval(int); - KButtonGroup *shBox; - KButtonGroup *wtBox; - QCheckBox *shadeHoverOn; - QLabel *shadeHoverLabel; - KIntNumInput *shadeHover; + KButtonGroup *shBox; + KButtonGroup *wtBox; + QCheckBox *shadeHoverOn; + QLabel *shadeHoverLabel; + KIntNumInput *shadeHover; - KConfig *config; - bool standAlone; + KConfig *config; + bool standAlone; - void setHideUtilityWindowsForInactive( bool ); - QCheckBox* hideUtilityWindowsForInactive; + void setHideUtilityWindowsForInactive(bool); + QCheckBox* hideUtilityWindowsForInactive; - void setInactiveTabsSkipTaskbar( bool ); - QCheckBox* inactiveTabsSkipTaskbar; + void setInactiveTabsSkipTaskbar(bool); + QCheckBox* inactiveTabsSkipTaskbar; - void setAutogroupSimilarWindows( bool ); - QCheckBox* autogroupSimilarWindows; + void setAutogroupSimilarWindows(bool); + QCheckBox* autogroupSimilarWindows; - void setAutogroupInForeground( bool ); - QCheckBox* autogroupInForeground; + void setAutogroupInForeground(bool); + QCheckBox* autogroupInForeground; - int getPlacement( void ); //CT - void setPlacement(int); //CT + int getPlacement(void); //CT + void setPlacement(int); //CT - KComboBox *placementCombo; + KComboBox *placementCombo; - // ------------------------------ - // Tiling related widgets/methods - // ------------------------------ - KButtonGroup *tilBox; - QCheckBox *tilingOn; - QLabel *tilingLayoutLabel; - QLabel *tilingRaiseLabel; - KComboBox *tilingLayoutCombo; - KComboBox *tilingRaiseCombo; - void setTilingOn( bool ); - void setTilingLayout( int ); - void setTilingRaisePolicy( int ); + // ------------------------------ + // Tiling related widgets/methods + // ------------------------------ + KButtonGroup *tilBox; + QCheckBox *tilingOn; + QLabel *tilingLayoutLabel; + QLabel *tilingRaiseLabel; + KComboBox *tilingLayoutCombo; + KComboBox *tilingRaiseCombo; + void setTilingOn(bool); + void setTilingLayout(int); + void setTilingRaisePolicy(int); }; #endif // KKWMWINDOWS_H diff --git a/kcmkwin/kwinrules/detectwidget.cpp b/kcmkwin/kwinrules/detectwidget.cpp index c117308ba..9ba3f0550 100644 --- a/kcmkwin/kwinrules/detectwidget.cpp +++ b/kcmkwin/kwinrules/detectwidget.cpp @@ -40,195 +40,189 @@ namespace KWin { -DetectWidget::DetectWidget( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +DetectWidget::DetectWidget(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -DetectDialog::DetectDialog( QWidget* parent, const char* name ) - : KDialog( parent ), - grabber( NULL ) - { - setObjectName( name ); - setModal( true ); - setButtons( Ok | Cancel ); +DetectDialog::DetectDialog(QWidget* parent, const char* name) + : KDialog(parent), + grabber(NULL) +{ + setObjectName(name); + setModal(true); + setButtons(Ok | Cancel); - widget = new DetectWidget( this ); - setMainWidget( widget ); - } + widget = new DetectWidget(this); + setMainWidget(widget); +} -void DetectDialog::detect( WId window ) - { - if( window == 0 ) +void DetectDialog::detect(WId window) +{ + if (window == 0) selectWindow(); else - readWindow( window ); - } + readWindow(window); +} -void DetectDialog::readWindow( WId w ) - { - if( w == 0 ) - { - emit detectionDone( false ); +void DetectDialog::readWindow(WId w) +{ + if (w == 0) { + emit detectionDone(false); return; - } - info = KWindowSystem::windowInfo( w, -1U, -1U ); // read everything - if( !info.valid()) - { - emit detectionDone( false ); + } + info = KWindowSystem::windowInfo(w, -1U, -1U); // read everything + if (!info.valid()) { + emit detectionDone(false); return; - } + } wmclass_class = info.windowClassClass(); wmclass_name = info.windowClassName(); role = info.windowRole(); - type = info.windowType( NET::NormalMask | NET::DesktopMask | NET::DockMask - | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask - | NET::UtilityMask | NET::SplashMask ); + type = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask + | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask + | NET::UtilityMask | NET::SplashMask); title = info.name(); extrarole = ""; // TODO machine = info.clientMachine(); executeDialog(); - } +} void DetectDialog::executeDialog() - { - static const char* const types[] = - { - I18N_NOOP( "Normal Window" ), - I18N_NOOP( "Desktop" ), - I18N_NOOP( "Dock (panel)" ), - I18N_NOOP( "Toolbar" ), - I18N_NOOP( "Torn-Off Menu" ), - I18N_NOOP( "Dialog Window" ), - I18N_NOOP( "Override Type" ), - I18N_NOOP( "Standalone Menubar" ), - I18N_NOOP( "Utility Window" ), - I18N_NOOP( "Splash Screen" ) - }; - widget->class_label->setText( wmclass_class + " (" + wmclass_name + ' ' + wmclass_class + ')' ); - widget->role_label->setText( role ); - widget->use_role->setEnabled( !role.isEmpty()); - if( widget->use_role->isEnabled()) - widget->use_role->setChecked( true ); +{ + static const char* const types[] = { + I18N_NOOP("Normal Window"), + I18N_NOOP("Desktop"), + I18N_NOOP("Dock (panel)"), + I18N_NOOP("Toolbar"), + I18N_NOOP("Torn-Off Menu"), + I18N_NOOP("Dialog Window"), + I18N_NOOP("Override Type"), + I18N_NOOP("Standalone Menubar"), + I18N_NOOP("Utility Window"), + I18N_NOOP("Splash Screen") + }; + widget->class_label->setText(wmclass_class + " (" + wmclass_name + ' ' + wmclass_class + ')'); + widget->role_label->setText(role); + widget->use_role->setEnabled(!role.isEmpty()); + if (widget->use_role->isEnabled()) + widget->use_role->setChecked(true); else - widget->use_whole_class->setChecked( true ); - if( type == NET::Unknown ) - widget->type_label->setText( i18n( "Unknown - will be treated as Normal Window" )); + widget->use_whole_class->setChecked(true); + if (type == NET::Unknown) + widget->type_label->setText(i18n("Unknown - will be treated as Normal Window")); else - widget->type_label->setText( i18n( types[ type ] )); - widget->title_label->setText( title ); - widget->extrarole_label->setText( extrarole ); - widget->machine_label->setText( machine ); - emit detectionDone( exec() == KDialog::Accepted ); - } + widget->type_label->setText(i18n(types[ type ])); + widget->title_label->setText(title); + widget->extrarole_label->setText(extrarole); + widget->machine_label->setText(machine); + emit detectionDone(exec() == KDialog::Accepted); +} QByteArray DetectDialog::selectedClass() const - { - if( widget->use_class->isChecked() || widget->use_role->isChecked()) +{ + if (widget->use_class->isChecked() || widget->use_role->isChecked()) return wmclass_class; return wmclass_name + ' ' + wmclass_class; - } +} bool DetectDialog::selectedWholeClass() const - { +{ return widget->use_whole_class->isChecked(); - } +} QByteArray DetectDialog::selectedRole() const - { - if( widget->use_role->isChecked()) +{ + if (widget->use_role->isChecked()) return role; return ""; - } +} QString DetectDialog::selectedTitle() const - { +{ return title; - } +} Rules::StringMatch DetectDialog::titleMatch() const - { +{ return widget->match_title->isChecked() ? Rules::ExactMatch : Rules::UnimportantMatch; - } +} bool DetectDialog::selectedWholeApp() const - { +{ return widget->use_class->isChecked(); - } +} NET::WindowType DetectDialog::selectedType() const - { +{ return type; - } +} QByteArray DetectDialog::selectedMachine() const - { +{ return machine; - } +} void DetectDialog::selectWindow() - { +{ // use a dialog, so that all user input is blocked // use WX11BypassWM and moving away so that it's not actually visible // grab only mouse, so that keyboard can be used e.g. for switching windows - grabber = new KDialog( 0, Qt::X11BypassWindowManagerHint ); - grabber->move( -1000, -1000 ); - grabber->setModal( true ); + grabber = new KDialog(0, Qt::X11BypassWindowManagerHint); + grabber->move(-1000, -1000); + grabber->setModal(true); grabber->show(); - grabber->grabMouse( Qt::CrossCursor ); - grabber->installEventFilter( this ); - } + grabber->grabMouse(Qt::CrossCursor); + grabber->installEventFilter(this); +} -bool DetectDialog::eventFilter( QObject* o, QEvent* e ) - { - if( o != grabber ) +bool DetectDialog::eventFilter(QObject* o, QEvent* e) +{ + if (o != grabber) return false; - if( e->type() != QEvent::MouseButtonRelease ) + if (e->type() != QEvent::MouseButtonRelease) return false; delete grabber; grabber = NULL; - if( static_cast< QMouseEvent* >( e )->button() != Qt::LeftButton ) - { - emit detectionDone( false ); + if (static_cast< QMouseEvent* >(e)->button() != Qt::LeftButton) { + emit detectionDone(false); return true; - } - readWindow( findWindow()); - return true; } + readWindow(findWindow()); + return true; +} WId DetectDialog::findWindow() - { +{ Window root; Window child; uint mask; int rootX, rootY, x, y; Window parent = QX11Info::appRootWindow(); - Atom wm_state = XInternAtom( QX11Info::display(), "WM_STATE", False ); - for( int i = 0; - i < 10; - ++i ) - { - XQueryPointer( QX11Info::display(), parent, &root, &child, - &rootX, &rootY, &x, &y, &mask ); - if( child == None ) + Atom wm_state = XInternAtom(QX11Info::display(), "WM_STATE", False); + for (int i = 0; + i < 10; + ++i) { + XQueryPointer(QX11Info::display(), parent, &root, &child, + &rootX, &rootY, &x, &y, &mask); + if (child == None) return 0; Atom type; int format; unsigned long nitems, after; unsigned char* prop; - if( XGetWindowProperty( QX11Info::display(), child, wm_state, 0, 0, False, AnyPropertyType, - &type, &format, &nitems, &after, &prop ) == Success ) - { - if( prop != NULL ) - XFree( prop ); - if( type != None ) - return child; - } - parent = child; + if (XGetWindowProperty(QX11Info::display(), child, wm_state, 0, 0, False, AnyPropertyType, + &type, &format, &nitems, &after, &prop) == Success) { + if (prop != NULL) + XFree(prop); + if (type != None) + return child; } - return 0; + parent = child; } + return 0; +} } // namespace diff --git a/kcmkwin/kwinrules/detectwidget.h b/kcmkwin/kwinrules/detectwidget.h index f8d65c070..62a96ef1c 100644 --- a/kcmkwin/kwinrules/detectwidget.h +++ b/kcmkwin/kwinrules/detectwidget.h @@ -35,54 +35,54 @@ namespace KWin class DetectWidget : public QWidget, public Ui_DetectWidget - { +{ Q_OBJECT - public: - explicit DetectWidget( QWidget* parent = NULL ); - }; +public: + explicit DetectWidget(QWidget* parent = NULL); +}; class DetectDialog : public KDialog - { +{ Q_OBJECT - public: - explicit DetectDialog( QWidget* parent = NULL, const char* name = NULL ); - void detect( WId window ); - QByteArray selectedClass() const; - bool selectedWholeClass() const; - QByteArray selectedRole() const; - bool selectedWholeApp() const; - NET::WindowType selectedType() const; - QString selectedTitle() const; - Rules::StringMatch titleMatch() const; - QByteArray selectedMachine() const; - const KWindowInfo& windowInfo() const; - signals: - void detectionDone( bool ); - protected: - virtual bool eventFilter( QObject* o, QEvent* e ); - private: - void selectWindow(); - void readWindow( WId window ); - void executeDialog(); - WId findWindow(); - QByteArray wmclass_class; - QByteArray wmclass_name; - QByteArray role; - NET::WindowType type; - QString title; - QByteArray extrarole; - QByteArray machine; - DetectWidget* widget; - KDialog* grabber; - KWindowInfo info; - }; +public: + explicit DetectDialog(QWidget* parent = NULL, const char* name = NULL); + void detect(WId window); + QByteArray selectedClass() const; + bool selectedWholeClass() const; + QByteArray selectedRole() const; + bool selectedWholeApp() const; + NET::WindowType selectedType() const; + QString selectedTitle() const; + Rules::StringMatch titleMatch() const; + QByteArray selectedMachine() const; + const KWindowInfo& windowInfo() const; +signals: + void detectionDone(bool); +protected: + virtual bool eventFilter(QObject* o, QEvent* e); +private: + void selectWindow(); + void readWindow(WId window); + void executeDialog(); + WId findWindow(); + QByteArray wmclass_class; + QByteArray wmclass_name; + QByteArray role; + NET::WindowType type; + QString title; + QByteArray extrarole; + QByteArray machine; + DetectWidget* widget; + KDialog* grabber; + KWindowInfo info; +}; inline const KWindowInfo& DetectDialog::windowInfo() const - { +{ return info; - } +} } // namespace diff --git a/kcmkwin/kwinrules/kcm.cpp b/kcmkwin/kwinrules/kcm.cpp index 832f1cb5a..d4ea0a170 100644 --- a/kcmkwin/kwinrules/kcm.cpp +++ b/kcmkwin/kwinrules/kcm.cpp @@ -32,41 +32,41 @@ #include K_PLUGIN_FACTORY(KCMRulesFactory, - registerPlugin(); - ) + registerPlugin(); + ) K_EXPORT_PLUGIN(KCMRulesFactory("kcmkwinrules")) namespace KWin { -KCMRules::KCMRules( QWidget *parent, const QVariantList & ) -: KCModule( KCMRulesFactory::componentData(), parent ) -, config( "kwinrulesrc" ) - { - QVBoxLayout *layout = new QVBoxLayout( this ); +KCMRules::KCMRules(QWidget *parent, const QVariantList &) + : KCModule(KCMRulesFactory::componentData(), parent) + , config("kwinrulesrc") +{ + QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); - widget = new KCMRulesList( this ); - layout->addWidget( widget ); - connect( widget, SIGNAL( changed( bool )), SLOT( moduleChanged( bool ))); - KAboutData *about = new KAboutData(I18N_NOOP( "kcmkwinrules" ), 0, - ki18n( "Window-Specific Settings Configuration Module" ), - 0, KLocalizedString(), KAboutData::License_GPL, ki18n( "(c) 2004 KWin and KControl Authors" )); - about->addAuthor(ki18n("Lubos Lunak"),KLocalizedString(),"l.lunak@kde.org"); + widget = new KCMRulesList(this); + layout->addWidget(widget); + connect(widget, SIGNAL(changed(bool)), SLOT(moduleChanged(bool))); + KAboutData *about = new KAboutData(I18N_NOOP("kcmkwinrules"), 0, + ki18n("Window-Specific Settings Configuration Module"), + 0, KLocalizedString(), KAboutData::License_GPL, ki18n("(c) 2004 KWin and KControl Authors")); + about->addAuthor(ki18n("Lubos Lunak"), KLocalizedString(), "l.lunak@kde.org"); setAboutData(about); - } +} void KCMRules::load() - { +{ config.reparseConfiguration(); widget->load(); - emit KCModule::changed( false ); - } + emit KCModule::changed(false); +} void KCMRules::save() - { +{ widget->save(); - emit KCModule::changed( false ); + emit KCModule::changed(false); // Send signal to kwin config.sync(); // Send signal to all kwin instances @@ -74,26 +74,26 @@ void KCMRules::save() QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); - } +} void KCMRules::defaults() - { +{ widget->defaults(); - } +} QString KCMRules::quickHelp() const - { +{ return i18n("

    Window-specific Settings

    Here you can customize window settings specifically only" - " for some windows.

    " - "

    Please note that this configuration will not take effect if you do not use" - " KWin as your window manager. If you do use a different window manager, please refer to its documentation" - " for how to customize window behavior.

    "); - } + " for some windows.

    " + "

    Please note that this configuration will not take effect if you do not use" + " KWin as your window manager. If you do use a different window manager, please refer to its documentation" + " for how to customize window behavior.

    "); +} -void KCMRules::moduleChanged( bool state ) - { - emit KCModule::changed( state ); - } +void KCMRules::moduleChanged(bool state) +{ + emit KCModule::changed(state); +} } diff --git a/kcmkwin/kwinrules/kcm.h b/kcmkwin/kwinrules/kcm.h index 24a1d2687..d6d2569c2 100644 --- a/kcmkwin/kwinrules/kcm.h +++ b/kcmkwin/kwinrules/kcm.h @@ -32,20 +32,20 @@ class KCMRulesList; class KCMRules : public KCModule - { +{ Q_OBJECT - public: - KCMRules( QWidget *parent, const QVariantList &args ); - virtual void load(); - virtual void save(); - virtual void defaults(); - virtual QString quickHelp() const; - protected slots: - void moduleChanged( bool state ); - private: - KCMRulesList* widget; - KConfig config; - }; +public: + KCMRules(QWidget *parent, const QVariantList &args); + virtual void load(); + virtual void save(); + virtual void defaults(); + virtual QString quickHelp() const; +protected slots: + void moduleChanged(bool state); +private: + KCMRulesList* widget; + KConfig config; +}; } // namespace diff --git a/kcmkwin/kwinrules/main.cpp b/kcmkwin/kwinrules/main.cpp index 31e60b417..4f41b51f1 100644 --- a/kcmkwin/kwinrules/main.cpp +++ b/kcmkwin/kwinrules/main.cpp @@ -32,125 +32,113 @@ namespace KWin { -static void loadRules( QList< Rules* >& rules ) - { - KConfig _cfg( "kwinrulesrc" ); - KConfigGroup cfg(&_cfg, "General" ); - int count = cfg.readEntry( "count",0 ); - for( int i = 1; - i <= count; - ++i ) - { - cfg = KConfigGroup(&_cfg,QString::number( i )); - Rules* rule = new Rules( cfg ); - rules.append( rule ); - } +static void loadRules(QList< Rules* >& rules) +{ + KConfig _cfg("kwinrulesrc"); + KConfigGroup cfg(&_cfg, "General"); + int count = cfg.readEntry("count", 0); + for (int i = 1; + i <= count; + ++i) { + cfg = KConfigGroup(&_cfg, QString::number(i)); + Rules* rule = new Rules(cfg); + rules.append(rule); } +} -static void saveRules( const QList< Rules* >& rules ) - { - KConfig cfg( "kwinrulesrc" ); +static void saveRules(const QList< Rules* >& rules) +{ + KConfig cfg("kwinrulesrc"); QStringList groups = cfg.groupList(); - for( QStringList::ConstIterator it = groups.constBegin(); - it != groups.constEnd(); - ++it ) - cfg.deleteGroup( *it ); - cfg.group("General").writeEntry( "count", rules.count()); + for (QStringList::ConstIterator it = groups.constBegin(); + it != groups.constEnd(); + ++it) + cfg.deleteGroup(*it); + cfg.group("General").writeEntry("count", rules.count()); int i = 1; - for( QList< Rules* >::ConstIterator it = rules.constBegin(); - it != rules.constEnd(); - ++it ) - { - KConfigGroup cg( &cfg, QString::number( i )); - (*it)->write( cg ); + for (QList< Rules* >::ConstIterator it = rules.constBegin(); + it != rules.constEnd(); + ++it) { + KConfigGroup cg(&cfg, QString::number(i)); + (*it)->write(cg); ++i; - } } +} -static Rules* findRule( const QList< Rules* >& rules, Window wid, bool whole_app ) - { - KWindowInfo info = KWindowSystem::windowInfo( wid, - NET::WMName | NET::WMWindowType, - NET::WM2WindowClass | NET::WM2WindowRole | NET::WM2ClientMachine ); - if( !info.valid()) // shouldn't really happen +static Rules* findRule(const QList< Rules* >& rules, Window wid, bool whole_app) +{ + KWindowInfo info = KWindowSystem::windowInfo(wid, + NET::WMName | NET::WMWindowType, + NET::WM2WindowClass | NET::WM2WindowRole | NET::WM2ClientMachine); + if (!info.valid()) // shouldn't really happen return NULL; QByteArray wmclass_class = info.windowClassClass().toLower(); QByteArray wmclass_name = info.windowClassName().toLower(); QByteArray role = info.windowRole().toLower(); - NET::WindowType type = info.windowType( NET::NormalMask | NET::DesktopMask | NET::DockMask - | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask - | NET::UtilityMask | NET::SplashMask ); + NET::WindowType type = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask + | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask + | NET::UtilityMask | NET::SplashMask); QString title = info.name(); // QCString extrarole = ""; // TODO QByteArray machine = info.clientMachine().toLower(); Rules* best_match = NULL; int match_quality = 0; - for( QList< Rules* >::ConstIterator it = rules.constBegin(); - it != rules.constEnd(); - ++it ) - { + for (QList< Rules* >::ConstIterator it = rules.constBegin(); + it != rules.constEnd(); + ++it) { // try to find an exact match, i.e. not a generic rule Rules* rule = *it; int quality = 0; bool generic = true; - if( rule->wmclassmatch != Rules::ExactMatch ) + if (rule->wmclassmatch != Rules::ExactMatch) continue; // too generic - if( !rule->matchWMClass( wmclass_class, wmclass_name )) + if (!rule->matchWMClass(wmclass_class, wmclass_name)) continue; // from now on, it matches the app - now try to match for a specific window - if( rule->wmclasscomplete ) - { + if (rule->wmclasscomplete) { quality += 1; generic = false; // this can be considered specific enough (old X apps) - } - if( !whole_app ) - { - if( rule->windowrolematch != Rules::UnimportantMatch ) - { + } + if (!whole_app) { + if (rule->windowrolematch != Rules::UnimportantMatch) { quality += rule->windowrolematch == Rules::ExactMatch ? 5 : 1; generic = false; - } - if( rule->titlematch != Rules::UnimportantMatch ) - { + } + if (rule->titlematch != Rules::UnimportantMatch) { quality += rule->titlematch == Rules::ExactMatch ? 3 : 1; generic = false; - } - if( rule->types != NET::AllTypesMask ) - { + } + if (rule->types != NET::AllTypesMask) { int bits = 0; - for( unsigned int bit = 1; - bit < 1U << 31; - bit <<= 1 ) - if( rule->types & bit ) + for (unsigned int bit = 1; + bit < 1U << 31; + bit <<= 1) + if (rule->types & bit) ++bits; - if( bits == 1 ) + if (bits == 1) quality += 2; - } - if( generic ) // ignore generic rules, use only the ones that are for this window + } + if (generic) // ignore generic rules, use only the ones that are for this window continue; - } - else - { - if( rule->types == NET::AllTypesMask ) + } else { + if (rule->types == NET::AllTypesMask) quality += 2; - } - if( !rule->matchType( type ) - || !rule->matchRole( role ) - || !rule->matchTitle( title ) - || !rule->matchClientMachine( machine )) + } + if (!rule->matchType(type) + || !rule->matchRole(role) + || !rule->matchTitle(title) + || !rule->matchClientMachine(machine)) continue; - if( quality > match_quality ) - { + if (quality > match_quality) { best_match = rule; match_quality = quality; - } } - if( best_match != NULL ) + } + if (best_match != NULL) return best_match; Rules* ret = new Rules; - if( whole_app ) - { - ret->description = i18n( "Application settings for %1", QString::fromLatin1( wmclass_class )); + if (whole_app) { + ret->description = i18n("Application settings for %1", QString::fromLatin1(wmclass_class)); // TODO maybe exclude some types? If yes, then also exclude them above // when searching. ret->types = NET::AllTypesMask; @@ -159,23 +147,20 @@ static Rules* findRule( const QList< Rules* >& rules, Window wid, bool whole_app ret->clientmachinematch = Rules::UnimportantMatch; ret->extrarolematch = Rules::UnimportantMatch; ret->windowrolematch = Rules::UnimportantMatch; - if( wmclass_name == wmclass_class ) - { + if (wmclass_name == wmclass_class) { ret->wmclasscomplete = false; ret->wmclass = wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } - else - { + } else { // WM_CLASS components differ - perhaps the app got -name argument ret->wmclasscomplete = true; ret->wmclass = wmclass_name + ' ' + wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } - return ret; } - ret->description = i18n( "Window settings for %1", QString::fromLatin1( wmclass_class )); - if( type == NET::Unknown ) + return ret; + } + ret->description = i18n("Window settings for %1", QString::fromLatin1(wmclass_class)); + if (type == NET::Unknown) ret->types = NET::NormalMask; else ret->types = 1 << type; // convert type to its mask @@ -185,35 +170,26 @@ static Rules* findRule( const QList< Rules* >& rules, Window wid, bool whole_app ret->clientmachinematch = Rules::UnimportantMatch; // ret->extrarole = extra; TODO ret->extrarolematch = Rules::UnimportantMatch; - if( !role.isEmpty() - && role != "unknown" && role != "unnamed" ) // Qt sets this if not specified - { + if (!role.isEmpty() + && role != "unknown" && role != "unnamed") { // Qt sets this if not specified ret->windowrole = role; ret->windowrolematch = Rules::ExactMatch; - if( wmclass_name == wmclass_class ) - { + if (wmclass_name == wmclass_class) { ret->wmclasscomplete = false; ret->wmclass = wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } - else - { + } else { // WM_CLASS components differ - perhaps the app got -name argument ret->wmclasscomplete = true; ret->wmclass = wmclass_name + ' ' + wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } } - else // no role set - { - if( wmclass_name != wmclass_class ) - { + } else { // no role set + if (wmclass_name != wmclass_class) { ret->wmclasscomplete = true; ret->wmclass = wmclass_name + ' ' + wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } - else - { + } else { // This is a window that has no role set, and both components of WM_CLASS // match (possibly only differing in case), which most likely means either // the application doesn't give a damn about distinguishing its various @@ -225,65 +201,61 @@ static Rules* findRule( const QList< Rules* >& rules, Window wid, bool whole_app ret->wmclasscomplete = false; ret->wmclass = wmclass_class; ret->wmclassmatch = Rules::ExactMatch; - } } - return ret; } + return ret; +} -static int edit( Window wid, bool whole_app ) - { +static int edit(Window wid, bool whole_app) +{ QList< Rules* > rules; - loadRules( rules ); - Rules* orig_rule = findRule( rules, wid, whole_app ); + loadRules(rules); + Rules* orig_rule = findRule(rules, wid, whole_app); RulesDialog dlg; // dlg.edit() creates new Rules instance if edited - Rules* edited_rule = dlg.edit( orig_rule, wid, true ); - if( edited_rule == NULL || edited_rule->isEmpty()) - { - rules.removeAll( orig_rule ); + Rules* edited_rule = dlg.edit(orig_rule, wid, true); + if (edited_rule == NULL || edited_rule->isEmpty()) { + rules.removeAll(orig_rule); delete orig_rule; - if( orig_rule != edited_rule ) + if (orig_rule != edited_rule) delete edited_rule; - } - else if( edited_rule != orig_rule ) - { - int pos = rules.indexOf( orig_rule ); - if( pos != -1) + } else if (edited_rule != orig_rule) { + int pos = rules.indexOf(orig_rule); + if (pos != -1) rules[ pos ] = edited_rule; else - rules.prepend( edited_rule ); + rules.prepend(edited_rule); delete orig_rule; - } - saveRules( rules ); + } + saveRules(rules); // Send signal to all kwin instances QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); QDBusConnection::sessionBus().send(message); return 0; - } +} } // namespace extern "C" -KDE_EXPORT int kdemain( int argc, char* argv[] ) - { - KCmdLineArgs::init( argc, argv, "kwin_rules_dialog", "kcmkwinrules", ki18n( "KWin" ), "1.0" , - ki18n( "KWin helper utility" )); +KDE_EXPORT int kdemain(int argc, char* argv[]) +{ + KCmdLineArgs::init(argc, argv, "kwin_rules_dialog", "kcmkwinrules", ki18n("KWin"), "1.0" , + ki18n("KWin helper utility")); KCmdLineOptions options; options.add("wid ", ki18n("WId of the window for special window settings.")); options.add("whole-app", ki18n("Whether the settings should affect all windows of the application.")); - KCmdLineArgs::addCmdLineOptions( options ); + KCmdLineArgs::addCmdLineOptions(options); KApplication app; KCmdLineArgs* args = KCmdLineArgs::parsedArgs(); bool id_ok = false; - Window id = args->getOption( "wid" ).toULongLong( &id_ok ); - bool whole_app = args->isSet( "whole-app" ); + Window id = args->getOption("wid").toULongLong(&id_ok); + bool whole_app = args->isSet("whole-app"); args->clear(); - if( !id_ok || id == None ) - { - KCmdLineArgs::usageError( i18n( "This helper utility is not supposed to be called directly." )); - return 1; - } - return KWin::edit( id, whole_app ); + if (!id_ok || id == None) { + KCmdLineArgs::usageError(i18n("This helper utility is not supposed to be called directly.")); + return 1; } + return KWin::edit(id, whole_app); +} diff --git a/kcmkwin/kwinrules/ruleslist.cpp b/kcmkwin/kwinrules/ruleslist.cpp index 9ce7ba3cc..c0f3b1b62 100644 --- a/kcmkwin/kwinrules/ruleslist.cpp +++ b/kcmkwin/kwinrules/ruleslist.cpp @@ -29,173 +29,169 @@ namespace KWin { -KCMRulesList::KCMRulesList( QWidget* parent) - : QWidget( parent) - { - setupUi( this ); +KCMRulesList::KCMRulesList(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); // connect both current/selected, so that current==selected (stupid QListBox :( ) - connect( rules_listbox, SIGNAL(itemChanged(QListWidgetItem*)), - SLOT(activeChanged())); - connect( rules_listbox, SIGNAL(itemSelectionChanged()), - SLOT( activeChanged())); - connect( new_button, SIGNAL( clicked()), - SLOT( newClicked())); - connect( modify_button, SIGNAL( clicked()), - SLOT( modifyClicked())); - connect( delete_button, SIGNAL( clicked()), - SLOT( deleteClicked())); - connect( moveup_button, SIGNAL( clicked()), - SLOT( moveupClicked())); - connect( movedown_button, SIGNAL( clicked()), - SLOT( movedownClicked())); - connect( rules_listbox, SIGNAL(itemDoubleClicked(QListWidgetItem*) ), - SLOT( modifyClicked())); + connect(rules_listbox, SIGNAL(itemChanged(QListWidgetItem*)), + SLOT(activeChanged())); + connect(rules_listbox, SIGNAL(itemSelectionChanged()), + SLOT(activeChanged())); + connect(new_button, SIGNAL(clicked()), + SLOT(newClicked())); + connect(modify_button, SIGNAL(clicked()), + SLOT(modifyClicked())); + connect(delete_button, SIGNAL(clicked()), + SLOT(deleteClicked())); + connect(moveup_button, SIGNAL(clicked()), + SLOT(moveupClicked())); + connect(movedown_button, SIGNAL(clicked()), + SLOT(movedownClicked())); + connect(rules_listbox, SIGNAL(itemDoubleClicked(QListWidgetItem*)), + SLOT(modifyClicked())); load(); - } +} KCMRulesList::~KCMRulesList() - { - for( QVector< Rules* >::Iterator it = rules.begin(); - it != rules.end(); - ++it ) +{ + for (QVector< Rules* >::Iterator it = rules.begin(); + it != rules.end(); + ++it) delete *it; rules.clear(); - } +} void KCMRulesList::activeChanged() - { +{ QListWidgetItem *item = rules_listbox->currentItem(); int itemRow = rules_listbox->row(item); - if( item != NULL ) // make current==selected - rules_listbox->setCurrentItem( item, QItemSelectionModel::ClearAndSelect ); - modify_button->setEnabled( item != NULL ); - delete_button->setEnabled( item != NULL ); - moveup_button->setEnabled( item != NULL && itemRow > 0 ); - movedown_button->setEnabled( item != NULL && itemRow < (rules_listbox->count()-1) ); - } + if (item != NULL) // make current==selected + rules_listbox->setCurrentItem(item, QItemSelectionModel::ClearAndSelect); + modify_button->setEnabled(item != NULL); + delete_button->setEnabled(item != NULL); + moveup_button->setEnabled(item != NULL && itemRow > 0); + movedown_button->setEnabled(item != NULL && itemRow < (rules_listbox->count() - 1)); +} void KCMRulesList::newClicked() - { +{ RulesDialog dlg(this); - Rules* rule = dlg.edit( NULL, 0, false ); - if( rule == NULL ) + Rules* rule = dlg.edit(NULL, 0, false); + if (rule == NULL) return; int pos = rules_listbox->currentRow() + 1; - rules_listbox->insertItem( pos , rule->description ); - rules_listbox->setCurrentRow( pos, QItemSelectionModel::ClearAndSelect ); - rules.insert( rules.begin() + pos, rule ); - emit changed( true ); - } + rules_listbox->insertItem(pos , rule->description); + rules_listbox->setCurrentRow(pos, QItemSelectionModel::ClearAndSelect); + rules.insert(rules.begin() + pos, rule); + emit changed(true); +} void KCMRulesList::modifyClicked() - { +{ int pos = rules_listbox->currentRow(); - if ( pos == -1 ) + if (pos == -1) return; RulesDialog dlg(this); - Rules* rule = dlg.edit( rules[ pos ], 0, false ); - if( rule == rules[ pos ] ) + Rules* rule = dlg.edit(rules[ pos ], 0, false); + if (rule == rules[ pos ]) return; delete rules[ pos ]; rules[ pos ] = rule; - rules_listbox->item(pos)->setText( rule->description ); - emit changed( true ); - } + rules_listbox->item(pos)->setText(rule->description); + emit changed(true); +} void KCMRulesList::deleteClicked() - { +{ int pos = rules_listbox->currentRow(); - assert( pos != -1 ); - delete rules_listbox->takeItem( pos ); - rules.erase( rules.begin() + pos ); - emit changed( true ); - } + assert(pos != -1); + delete rules_listbox->takeItem(pos); + rules.erase(rules.begin() + pos); + emit changed(true); +} void KCMRulesList::moveupClicked() - { +{ int pos = rules_listbox->currentRow(); - assert( pos != -1 ); - if( pos > 0 ) - { - QListWidgetItem * item = rules_listbox->takeItem( pos ); - rules_listbox->insertItem( pos - 1 , item ); - rules_listbox->setCurrentItem( item, QItemSelectionModel::ClearAndSelect ); + assert(pos != -1); + if (pos > 0) { + QListWidgetItem * item = rules_listbox->takeItem(pos); + rules_listbox->insertItem(pos - 1 , item); + rules_listbox->setCurrentItem(item, QItemSelectionModel::ClearAndSelect); Rules* rule = rules[ pos ]; rules[ pos ] = rules[ pos - 1 ]; rules[ pos - 1 ] = rule; - } - emit changed( true ); } + emit changed(true); +} void KCMRulesList::movedownClicked() - { +{ int pos = rules_listbox->currentRow(); - assert( pos != -1 ); - if( pos < int( rules_listbox->count()) - 1 ) - { - QListWidgetItem * item = rules_listbox->takeItem( pos ); - rules_listbox->insertItem( pos + 1 , item ); - rules_listbox->setCurrentItem( item, QItemSelectionModel::ClearAndSelect ); + assert(pos != -1); + if (pos < int(rules_listbox->count()) - 1) { + QListWidgetItem * item = rules_listbox->takeItem(pos); + rules_listbox->insertItem(pos + 1 , item); + rules_listbox->setCurrentItem(item, QItemSelectionModel::ClearAndSelect); Rules* rule = rules[ pos ]; rules[ pos ] = rules[ pos + 1 ]; rules[ pos + 1 ] = rule; - } - emit changed( true ); } + emit changed(true); +} void KCMRulesList::load() - { +{ rules_listbox->clear(); - for( QVector< Rules* >::Iterator it = rules.begin(); - it != rules.end(); - ++it ) + for (QVector< Rules* >::Iterator it = rules.begin(); + it != rules.end(); + ++it) delete *it; rules.clear(); - KConfig _cfg( "kwinrulesrc" ); - KConfigGroup cfg(&_cfg, "General" ); - int count = cfg.readEntry( "count",0 ); - rules.reserve( count ); - for( int i = 1; - i <= count; - ++i ) - { - cfg = KConfigGroup(&_cfg,QString::number( i )); - Rules* rule = new Rules( cfg ); - rules.append( rule ); - rules_listbox->addItem( rule->description ); - } - if( rules.count() > 0 ) - rules_listbox->setCurrentItem( rules_listbox->item( 0 )); - else - rules_listbox->setCurrentItem( NULL ); - activeChanged(); + KConfig _cfg("kwinrulesrc"); + KConfigGroup cfg(&_cfg, "General"); + int count = cfg.readEntry("count", 0); + rules.reserve(count); + for (int i = 1; + i <= count; + ++i) { + cfg = KConfigGroup(&_cfg, QString::number(i)); + Rules* rule = new Rules(cfg); + rules.append(rule); + rules_listbox->addItem(rule->description); } + if (rules.count() > 0) + rules_listbox->setCurrentItem(rules_listbox->item(0)); + else + rules_listbox->setCurrentItem(NULL); + activeChanged(); +} void KCMRulesList::save() - { - KConfig cfg( QLatin1String("kwinrulesrc") ); +{ + KConfig cfg(QLatin1String("kwinrulesrc")); QStringList groups = cfg.groupList(); - for( QStringList::ConstIterator it = groups.constBegin(); - it != groups.constEnd(); - ++it ) - cfg.deleteGroup( *it ); - cfg.group("General").writeEntry( "count", rules.count()); + for (QStringList::ConstIterator it = groups.constBegin(); + it != groups.constEnd(); + ++it) + cfg.deleteGroup(*it); + cfg.group("General").writeEntry("count", rules.count()); int i = 1; - for( QVector< Rules* >::ConstIterator it = rules.constBegin(); - it != rules.constEnd(); - ++it ) - { - KConfigGroup cg( &cfg, QString::number( i )); - (*it)->write( cg ); + for (QVector< Rules* >::ConstIterator it = rules.constBegin(); + it != rules.constEnd(); + ++it) { + KConfigGroup cg(&cfg, QString::number(i)); + (*it)->write(cg); ++i; - } } +} void KCMRulesList::defaults() - { +{ load(); - } +} } // namespace diff --git a/kcmkwin/kwinrules/ruleslist.h b/kcmkwin/kwinrules/ruleslist.h index 53c1155b0..4eb0752bc 100644 --- a/kcmkwin/kwinrules/ruleslist.h +++ b/kcmkwin/kwinrules/ruleslist.h @@ -29,26 +29,26 @@ namespace KWin class KCMRulesList : public QWidget, Ui_KCMRulesList - { +{ Q_OBJECT - public: - KCMRulesList( QWidget* parent = NULL ); - virtual ~KCMRulesList(); - void load(); - void save(); - void defaults(); - signals: - void changed( bool ); - private slots: - void newClicked(); - void modifyClicked(); - void deleteClicked(); - void moveupClicked(); - void movedownClicked(); - void activeChanged(); - private: - QVector< Rules* > rules; - }; +public: + KCMRulesList(QWidget* parent = NULL); + virtual ~KCMRulesList(); + void load(); + void save(); + void defaults(); +signals: + void changed(bool); +private slots: + void newClicked(); + void modifyClicked(); + void deleteClicked(); + void moveupClicked(); + void movedownClicked(); + void activeChanged(); +private: + QVector< Rules* > rules; +}; } // namespace diff --git a/kcmkwin/kwinrules/ruleswidget.cpp b/kcmkwin/kwinrules/ruleswidget.cpp index 5efcea8ce..f9fc4076e 100644 --- a/kcmkwin/kwinrules/ruleswidget.cpp +++ b/kcmkwin/kwinrules/ruleswidget.cpp @@ -47,135 +47,134 @@ namespace KWin enable_##var->setWhatsThis( enableDesc ); \ rule_##var->setWhatsThis( type##RuleDesc ); -RulesWidget::RulesWidget( QWidget* parent ) - : detect_dlg( NULL ) - { - Q_UNUSED( parent ); +RulesWidget::RulesWidget(QWidget* parent) + : detect_dlg(NULL) +{ + Q_UNUSED(parent); setupUi(this); QString enableDesc = - i18n( "Enable this checkbox to alter this window property for the specified window(s)." ); + i18n("Enable this checkbox to alter this window property for the specified window(s)."); QString setRuleDesc = - i18n( "Specify how the window property should be affected:
      " - "
    • Do Not Affect: The window property will not be affected and therefore" - " the default handling for it will be used. Specifying this will block more generic" - " window settings from taking effect.
    • " - "
    • Apply Initially: The window property will be only set to the given value" - " after the window is created. No further changes will be affected.
    • " - "
    • Remember: The value of the window property will be remembered and every time" - " time the window is created, the last remembered value will be applied.
    • " - "
    • Force: The window property will be always forced to the given value.
    • " - "
    • Apply Now: The window property will be set to the given value immediately" - " and will not be affected later (this action will be deleted afterwards).
    • " - "
    • Force temporarily: The window property will be forced to the given value" - " until it is hidden (this action will be deleted after the window is hidden).
    • " - "
    " ); + i18n("Specify how the window property should be affected:
      " + "
    • Do Not Affect: The window property will not be affected and therefore" + " the default handling for it will be used. Specifying this will block more generic" + " window settings from taking effect.
    • " + "
    • Apply Initially: The window property will be only set to the given value" + " after the window is created. No further changes will be affected.
    • " + "
    • Remember: The value of the window property will be remembered and every time" + " time the window is created, the last remembered value will be applied.
    • " + "
    • Force: The window property will be always forced to the given value.
    • " + "
    • Apply Now: The window property will be set to the given value immediately" + " and will not be affected later (this action will be deleted afterwards).
    • " + "
    • Force temporarily: The window property will be forced to the given value" + " until it is hidden (this action will be deleted after the window is hidden).
    • " + "
    "); QString forceRuleDesc = - i18n( "Specify how the window property should be affected:
      " - "
    • Do Not Affect: The window property will not be affected and therefore" - " the default handling for it will be used. Specifying this will block more generic" - " window settings from taking effect.
    • " - "
    • Force: The window property will be always forced to the given value.
    • " - "
    • Force temporarily: The window property will be forced to the given value" - " until it is hidden (this action will be deleted after the window is hidden).
    • " - "
    " ); + i18n("Specify how the window property should be affected:
      " + "
    • Do Not Affect: The window property will not be affected and therefore" + " the default handling for it will be used. Specifying this will block more generic" + " window settings from taking effect.
    • " + "
    • Force: The window property will be always forced to the given value.
    • " + "
    • Force temporarily: The window property will be forced to the given value" + " until it is hidden (this action will be deleted after the window is hidden).
    • " + "
    "); // window tabs have enable signals done in designer // geometry tab - SETUP( position, set ); - SETUP( size, set ); - SETUP( desktop, set ); - SETUP( maximizehoriz, set ); - SETUP( maximizevert, set ); - SETUP( minimize, set ); - SETUP( shade, set ); - SETUP( fullscreen, set ); - SETUP( placement, force ); + SETUP(position, set); + SETUP(size, set); + SETUP(desktop, set); + SETUP(maximizehoriz, set); + SETUP(maximizevert, set); + SETUP(minimize, set); + SETUP(shade, set); + SETUP(fullscreen, set); + SETUP(placement, force); // preferences tab - SETUP( above, set ); - SETUP( below, set ); - SETUP( noborder, set ); - SETUP( skiptaskbar, set ); - SETUP( skippager, set ); - SETUP( skipswitcher, set ); - SETUP( acceptfocus, force ); - SETUP( closeable, force ); - SETUP( autogroup, force ); - SETUP( autogroupfg, force ); - SETUP( autogroupid, force ); - SETUP( opacityactive, force ); - SETUP( opacityinactive, force ); - SETUP( tilingoption, force ); - SETUP( shortcut, force ); + SETUP(above, set); + SETUP(below, set); + SETUP(noborder, set); + SETUP(skiptaskbar, set); + SETUP(skippager, set); + SETUP(skipswitcher, set); + SETUP(acceptfocus, force); + SETUP(closeable, force); + SETUP(autogroup, force); + SETUP(autogroupfg, force); + SETUP(autogroupid, force); + SETUP(opacityactive, force); + SETUP(opacityinactive, force); + SETUP(tilingoption, force); + SETUP(shortcut, force); // workarounds tab - SETUP( fsplevel, force ); - SETUP( moveresizemode, force ); - SETUP( type, force ); - SETUP( ignoreposition, force ); - SETUP( minsize, force ); - SETUP( maxsize, force ); - SETUP( strictgeometry, force ); - SETUP( disableglobalshortcuts, force ); + SETUP(fsplevel, force); + SETUP(moveresizemode, force); + SETUP(type, force); + SETUP(ignoreposition, force); + SETUP(minsize, force); + SETUP(maxsize, force); + SETUP(strictgeometry, force); + SETUP(disableglobalshortcuts, force); int i; - for( i = 1; - i <= KWindowSystem::numberOfDesktops(); - ++i ) - desktop->addItem( QString::number( i ).rightJustified( 2 ) + ':' + KWindowSystem::desktopName( i )); - desktop->addItem( i18n( "All Desktops" )); - } + for (i = 1; + i <= KWindowSystem::numberOfDesktops(); + ++i) + desktop->addItem(QString::number(i).rightJustified(2) + ':' + KWindowSystem::desktopName(i)); + desktop->addItem(i18n("All Desktops")); +} #undef SETUP #define UPDATE_ENABLE_SLOT( var ) \ -void RulesWidget::updateEnable##var() \ + void RulesWidget::updateEnable##var() \ { \ - /* leave the label readable label_##var->setEnabled( enable_##var->isChecked() && rule_##var->currentIndex() != 0 );*/ \ - Ui::RulesWidgetBase::var->setEnabled( enable_##var->isChecked() && rule_##var->currentIndex() != 0 ); \ + /* leave the label readable label_##var->setEnabled( enable_##var->isChecked() && rule_##var->currentIndex() != 0 );*/ \ + Ui::RulesWidgetBase::var->setEnabled( enable_##var->isChecked() && rule_##var->currentIndex() != 0 ); \ } // geometry tab -UPDATE_ENABLE_SLOT( position ) -UPDATE_ENABLE_SLOT( size ) -UPDATE_ENABLE_SLOT( desktop ) -UPDATE_ENABLE_SLOT( maximizehoriz ) -UPDATE_ENABLE_SLOT( maximizevert ) -UPDATE_ENABLE_SLOT( minimize ) -UPDATE_ENABLE_SLOT( shade ) -UPDATE_ENABLE_SLOT( fullscreen ) -UPDATE_ENABLE_SLOT( placement ) +UPDATE_ENABLE_SLOT(position) +UPDATE_ENABLE_SLOT(size) +UPDATE_ENABLE_SLOT(desktop) +UPDATE_ENABLE_SLOT(maximizehoriz) +UPDATE_ENABLE_SLOT(maximizevert) +UPDATE_ENABLE_SLOT(minimize) +UPDATE_ENABLE_SLOT(shade) +UPDATE_ENABLE_SLOT(fullscreen) +UPDATE_ENABLE_SLOT(placement) // preferences tab -UPDATE_ENABLE_SLOT( above ) -UPDATE_ENABLE_SLOT( below ) -UPDATE_ENABLE_SLOT( noborder ) -UPDATE_ENABLE_SLOT( skiptaskbar ) -UPDATE_ENABLE_SLOT( skippager ) -UPDATE_ENABLE_SLOT( skipswitcher ) -UPDATE_ENABLE_SLOT( acceptfocus ) -UPDATE_ENABLE_SLOT( closeable ) -UPDATE_ENABLE_SLOT( autogroup ) -UPDATE_ENABLE_SLOT( autogroupfg ) -UPDATE_ENABLE_SLOT( autogroupid ) -UPDATE_ENABLE_SLOT( opacityactive ) -UPDATE_ENABLE_SLOT( opacityinactive ) -UPDATE_ENABLE_SLOT( tilingoption ) +UPDATE_ENABLE_SLOT(above) +UPDATE_ENABLE_SLOT(below) +UPDATE_ENABLE_SLOT(noborder) +UPDATE_ENABLE_SLOT(skiptaskbar) +UPDATE_ENABLE_SLOT(skippager) +UPDATE_ENABLE_SLOT(skipswitcher) +UPDATE_ENABLE_SLOT(acceptfocus) +UPDATE_ENABLE_SLOT(closeable) +UPDATE_ENABLE_SLOT(autogroup) +UPDATE_ENABLE_SLOT(autogroupfg) +UPDATE_ENABLE_SLOT(autogroupid) +UPDATE_ENABLE_SLOT(opacityactive) +UPDATE_ENABLE_SLOT(opacityinactive) +UPDATE_ENABLE_SLOT(tilingoption) void RulesWidget::updateEnableshortcut() - { - shortcut->setEnabled( enable_shortcut->isChecked() && rule_shortcut->currentIndex() != 0 ); - shortcut_edit->setEnabled( enable_shortcut->isChecked() && rule_shortcut->currentIndex() != 0 ); - } +{ + shortcut->setEnabled(enable_shortcut->isChecked() && rule_shortcut->currentIndex() != 0); + shortcut_edit->setEnabled(enable_shortcut->isChecked() && rule_shortcut->currentIndex() != 0); +} // workarounds tab -UPDATE_ENABLE_SLOT( fsplevel ) -UPDATE_ENABLE_SLOT( moveresizemode ) -UPDATE_ENABLE_SLOT( type ) -UPDATE_ENABLE_SLOT( ignoreposition ) -UPDATE_ENABLE_SLOT( minsize ) -UPDATE_ENABLE_SLOT( maxsize ) -UPDATE_ENABLE_SLOT( strictgeometry ) -UPDATE_ENABLE_SLOT( disableglobalshortcuts ) +UPDATE_ENABLE_SLOT(fsplevel) +UPDATE_ENABLE_SLOT(moveresizemode) +UPDATE_ENABLE_SLOT(type) +UPDATE_ENABLE_SLOT(ignoreposition) +UPDATE_ENABLE_SLOT(minsize) +UPDATE_ENABLE_SLOT(maxsize) +UPDATE_ENABLE_SLOT(strictgeometry) +UPDATE_ENABLE_SLOT(disableglobalshortcuts) #undef UPDATE_ENABLE_SLOT -static const int set_rule_to_combo[] = - { +static const int set_rule_to_combo[] = { 0, // Unused 0, // Don't Affect 3, // Force @@ -183,20 +182,18 @@ static const int set_rule_to_combo[] = 2, // Remember 4, // ApplyNow 5 // ForceTemporarily - }; +}; -static const Rules::SetRule combo_to_set_rule[] = - { - ( Rules::SetRule )Rules::DontAffect, - ( Rules::SetRule )Rules::Apply, - ( Rules::SetRule )Rules::Remember, - ( Rules::SetRule )Rules::Force, - ( Rules::SetRule )Rules::ApplyNow, - ( Rules::SetRule )Rules::ForceTemporarily - }; +static const Rules::SetRule combo_to_set_rule[] = { + (Rules::SetRule)Rules::DontAffect, + (Rules::SetRule)Rules::Apply, + (Rules::SetRule)Rules::Remember, + (Rules::SetRule)Rules::Force, + (Rules::SetRule)Rules::ApplyNow, + (Rules::SetRule)Rules::ForceTemporarily +}; -static const int force_rule_to_combo[] = - { +static const int force_rule_to_combo[] = { 0, // Unused 0, // Don't Affect 1, // Force @@ -204,89 +201,89 @@ static const int force_rule_to_combo[] = 0, // Remember 0, // ApplyNow 2 // ForceTemporarily - }; +}; -static const Rules::ForceRule combo_to_force_rule[] = - { - ( Rules::ForceRule )Rules::DontAffect, - ( Rules::ForceRule )Rules::Force, - ( Rules::ForceRule )Rules::ForceTemporarily - }; +static const Rules::ForceRule combo_to_force_rule[] = { + (Rules::ForceRule)Rules::DontAffect, + (Rules::ForceRule)Rules::Force, + (Rules::ForceRule)Rules::ForceTemporarily +}; -static QString positionToStr( const QPoint& p ) - { - if( p == invalidPoint ) +static QString positionToStr(const QPoint& p) +{ + if (p == invalidPoint) return QString(); - return QString::number( p.x()) + ',' + QString::number( p.y()); - } + return QString::number(p.x()) + ',' + QString::number(p.y()); +} -static QPoint strToPosition( const QString& str ) - { // two numbers, with + or -, separated by any of , x X : - QRegExp reg( "\\s*([+-]?[0-9]*)\\s*[,xX:]\\s*([+-]?[0-9]*)\\s*" ); - if( !reg.exactMatch( str )) +static QPoint strToPosition(const QString& str) +{ + // two numbers, with + or -, separated by any of , x X : + QRegExp reg("\\s*([+-]?[0-9]*)\\s*[,xX:]\\s*([+-]?[0-9]*)\\s*"); + if (!reg.exactMatch(str)) return invalidPoint; - return QPoint( reg.cap( 1 ).toInt(), reg.cap( 2 ).toInt()); - } + return QPoint(reg.cap(1).toInt(), reg.cap(2).toInt()); +} -static QString sizeToStr( const QSize& s ) - { - if( !s.isValid()) +static QString sizeToStr(const QSize& s) +{ + if (!s.isValid()) return QString(); - return QString::number( s.width()) + ',' + QString::number( s.height()); - } + return QString::number(s.width()) + ',' + QString::number(s.height()); +} -static QSize strToSize( const QString& str ) - { // two numbers, with + or -, separated by any of , x X : - QRegExp reg( "\\s*([+-]?[0-9]*)\\s*[,xX:]\\s*([+-]?[0-9]*)\\s*" ); - if( !reg.exactMatch( str )) +static QSize strToSize(const QString& str) +{ + // two numbers, with + or -, separated by any of , x X : + QRegExp reg("\\s*([+-]?[0-9]*)\\s*[,xX:]\\s*([+-]?[0-9]*)\\s*"); + if (!reg.exactMatch(str)) return QSize(); - return QSize( reg.cap( 1 ).toInt(), reg.cap( 2 ).toInt()); - } + return QSize(reg.cap(1).toInt(), reg.cap(2).toInt()); +} //used for opacity settings -static QString intToStr( const int& s ) - { - if( s < 1 || s > 100 ) +static QString intToStr(const int& s) +{ + if (s < 1 || s > 100) return QString(); return QString::number(s); - } - -static int strToInt( const QString& str ) - { +} + +static int strToInt(const QString& str) +{ int tmp = str.toInt(); - if( tmp < 1 || tmp > 100 ) + if (tmp < 1 || tmp > 100) return 100; return tmp; - } - -int RulesWidget::desktopToCombo( int d ) const - { - if( d >= 1 && d < desktop->count()) +} + +int RulesWidget::desktopToCombo(int d) const +{ + if (d >= 1 && d < desktop->count()) return d - 1; return desktop->count() - 1; // on all desktops - } +} -int RulesWidget::comboToDesktop( int val ) const - { - if( val == desktop->count() - 1 ) +int RulesWidget::comboToDesktop(int val) const +{ + if (val == desktop->count() - 1) return NET::OnAllDesktops; return val + 1; - } +} -int RulesWidget::tilingToCombo( int t ) const - { +int RulesWidget::tilingToCombo(int t) const +{ return qBound(0, t, 1); - } +} -int RulesWidget::comboToTiling( int val ) const - { +int RulesWidget::comboToTiling(int val) const +{ return val; // 0 is tiling, 1 is floating - } +} -static int placementToCombo( Placement::Policy placement ) - { - static const int conv[] = - { +static int placementToCombo(Placement::Policy placement) +{ + static const int conv[] = { 1, // NoPlacement 0, // Default 0, // Unknown @@ -298,14 +295,13 @@ static int placementToCombo( Placement::Policy placement ) 8, // UnderMouse 9, // OnMainWindow 3 // Maximizing - }; + }; return conv[ placement ]; - } +} -static Placement::Policy comboToPlacement( int val ) - { - static const Placement::Policy conv[] = - { +static Placement::Policy comboToPlacement(int val) +{ + static const Placement::Policy conv[] = { Placement::Default, Placement::NoPlacement, Placement::Smart, @@ -317,44 +313,42 @@ static Placement::Policy comboToPlacement( int val ) Placement::UnderMouse, Placement::OnMainWindow // no Placement::Unknown - }; + }; return conv[ val ]; - } +} -static int moveresizeToCombo( Options::MoveResizeMode mode ) - { +static int moveresizeToCombo(Options::MoveResizeMode mode) +{ return mode == Options::Opaque ? 0 : 1; - } +} -static Options::MoveResizeMode comboToMoveResize( int val ) - { +static Options::MoveResizeMode comboToMoveResize(int val) +{ return val == 0 ? Options::Opaque : Options::Transparent; - } +} -static int typeToCombo( NET::WindowType type ) - { - if( type < NET::Normal || type > NET::Splash ) +static int typeToCombo(NET::WindowType type) +{ + if (type < NET::Normal || type > NET::Splash) return 0; // Normal - static const int conv[] = - { + static const int conv[] = { 0, // Normal 7, // Desktop - 3, // Dock - 4, // Toolbar - 5, // Menu - 1, // Dialog - 8, // Override + 3, // Dock + 4, // Toolbar + 5, // Menu + 1, // Dialog + 8, // Override 9, // TopMenu - 2, // Utility - 6 // Splash - }; + 2, // Utility + 6 // Splash + }; return conv[ type ]; - } +} -static NET::WindowType comboToType( int val ) - { - static const NET::WindowType conv[] = - { +static NET::WindowType comboToType(int val) +{ + static const NET::WindowType conv[] = { NET::Normal, NET::Dialog, NET::Utility, @@ -365,25 +359,25 @@ static NET::WindowType comboToType( int val ) NET::Desktop, NET::Override, NET::TopMenu - }; + }; return conv[ val ]; - } +} #define GENERIC_RULE( var, func, Type, type, uimethod, uimethod0 ) \ - if( rules->var##rule == Rules::Unused##Type##Rule ) \ - { \ + if ( rules->var##rule == Rules::Unused##Type##Rule ) \ + { \ enable_##var->setChecked( false ); \ rule_##var->setCurrentIndex( 0 ); \ Ui::RulesWidgetBase::var->uimethod0; \ updateEnable##var(); \ - } \ + } \ else \ - { \ + { \ enable_##var->setChecked( true ); \ rule_##var->setCurrentIndex( type##_rule_to_combo[ rules->var##rule ] ); \ Ui::RulesWidgetBase::var->uimethod( func( rules->var )); \ updateEnable##var(); \ - } + } #define CHECKBOX_SET_RULE( var, func ) GENERIC_RULE( var, func, Set, set, setChecked, setChecked( false )) #define LINEEDIT_SET_RULE( var, func ) GENERIC_RULE( var, func, Set, set, setText, setText( "" )) @@ -392,71 +386,71 @@ static NET::WindowType comboToType( int val ) #define LINEEDIT_FORCE_RULE( var, func ) GENERIC_RULE( var, func, Force, force, setText, setText( "" )) #define COMBOBOX_FORCE_RULE( var, func ) GENERIC_RULE( var, func, Force, force, setCurrentIndex, setCurrentIndex( 0 )) -void RulesWidget::setRules( Rules* rules ) - { +void RulesWidget::setRules(Rules* rules) +{ Rules tmp; - if( rules == NULL ) + if (rules == NULL) rules = &tmp; // empty - description->setText( rules->description ); - wmclass->setText( rules->wmclass ); - whole_wmclass->setChecked( rules->wmclasscomplete ); - wmclass_match->setCurrentIndex( rules->wmclassmatch ); + description->setText(rules->description); + wmclass->setText(rules->wmclass); + whole_wmclass->setChecked(rules->wmclasscomplete); + wmclass_match->setCurrentIndex(rules->wmclassmatch); wmclassMatchChanged(); - role->setText( rules->windowrole ); - role_match->setCurrentIndex( rules->windowrolematch ); + role->setText(rules->windowrole); + role_match->setCurrentIndex(rules->windowrolematch); roleMatchChanged(); - types->item(0)->setSelected( rules->types & NET::NormalMask ); - types->item(1)->setSelected( rules->types & NET::DialogMask ); - types->item(2)->setSelected( rules->types & NET::UtilityMask ); - types->item(3)->setSelected( rules->types & NET::DockMask ); - types->item(4)->setSelected( rules->types & NET::ToolbarMask ); - types->item(5)->setSelected( rules->types & NET::MenuMask ); - types->item(6)->setSelected( rules->types & NET::SplashMask ); - types->item(7)->setSelected( rules->types & NET::DesktopMask ); - types->item(8)->setSelected( rules->types & NET::OverrideMask ); - types->item(9)->setSelected( rules->types & NET::TopMenuMask ); - title->setText( rules->title ); - title_match->setCurrentIndex( rules->titlematch ); + types->item(0)->setSelected(rules->types & NET::NormalMask); + types->item(1)->setSelected(rules->types & NET::DialogMask); + types->item(2)->setSelected(rules->types & NET::UtilityMask); + types->item(3)->setSelected(rules->types & NET::DockMask); + types->item(4)->setSelected(rules->types & NET::ToolbarMask); + types->item(5)->setSelected(rules->types & NET::MenuMask); + types->item(6)->setSelected(rules->types & NET::SplashMask); + types->item(7)->setSelected(rules->types & NET::DesktopMask); + types->item(8)->setSelected(rules->types & NET::OverrideMask); + types->item(9)->setSelected(rules->types & NET::TopMenuMask); + title->setText(rules->title); + title_match->setCurrentIndex(rules->titlematch); titleMatchChanged(); - extra->setText( rules->extrarole ); - extra_match->setCurrentIndex( rules->extrarolematch ); + extra->setText(rules->extrarole); + extra_match->setCurrentIndex(rules->extrarolematch); extraMatchChanged(); - machine->setText( rules->clientmachine ); - machine_match->setCurrentIndex( rules->clientmachinematch ); + machine->setText(rules->clientmachine); + machine_match->setCurrentIndex(rules->clientmachinematch); machineMatchChanged(); - LINEEDIT_SET_RULE( position, positionToStr ); - LINEEDIT_SET_RULE( size, sizeToStr ); - COMBOBOX_SET_RULE( desktop, desktopToCombo ); - CHECKBOX_SET_RULE( maximizehoriz, ); - CHECKBOX_SET_RULE( maximizevert, ); - CHECKBOX_SET_RULE( minimize, ); - CHECKBOX_SET_RULE( shade, ); - CHECKBOX_SET_RULE( fullscreen, ); - COMBOBOX_FORCE_RULE( placement, placementToCombo ); - CHECKBOX_SET_RULE( above, ); - CHECKBOX_SET_RULE( below, ); - CHECKBOX_SET_RULE( noborder, ); - CHECKBOX_SET_RULE( skiptaskbar, ); - CHECKBOX_SET_RULE( skippager, ); - CHECKBOX_SET_RULE( skipswitcher, ); - CHECKBOX_FORCE_RULE( acceptfocus, ); - CHECKBOX_FORCE_RULE( closeable, ); - CHECKBOX_FORCE_RULE( autogroup, ); - CHECKBOX_FORCE_RULE( autogroupfg, ); - LINEEDIT_FORCE_RULE( autogroupid, ); - LINEEDIT_FORCE_RULE( opacityactive, intToStr ); - LINEEDIT_FORCE_RULE( opacityinactive, intToStr ); - COMBOBOX_FORCE_RULE( tilingoption, tilingToCombo ); - LINEEDIT_SET_RULE( shortcut, ); - COMBOBOX_FORCE_RULE( fsplevel, ); - COMBOBOX_FORCE_RULE( moveresizemode, moveresizeToCombo ); - COMBOBOX_FORCE_RULE( type, typeToCombo ); - CHECKBOX_FORCE_RULE( ignoreposition, ); - LINEEDIT_FORCE_RULE( minsize, sizeToStr ); - LINEEDIT_FORCE_RULE( maxsize, sizeToStr ); - CHECKBOX_FORCE_RULE( strictgeometry, ); - CHECKBOX_FORCE_RULE( disableglobalshortcuts, ); - } + LINEEDIT_SET_RULE(position, positionToStr); + LINEEDIT_SET_RULE(size, sizeToStr); + COMBOBOX_SET_RULE(desktop, desktopToCombo); + CHECKBOX_SET_RULE(maximizehoriz,); + CHECKBOX_SET_RULE(maximizevert,); + CHECKBOX_SET_RULE(minimize,); + CHECKBOX_SET_RULE(shade,); + CHECKBOX_SET_RULE(fullscreen,); + COMBOBOX_FORCE_RULE(placement, placementToCombo); + CHECKBOX_SET_RULE(above,); + CHECKBOX_SET_RULE(below,); + CHECKBOX_SET_RULE(noborder,); + CHECKBOX_SET_RULE(skiptaskbar,); + CHECKBOX_SET_RULE(skippager,); + CHECKBOX_SET_RULE(skipswitcher,); + CHECKBOX_FORCE_RULE(acceptfocus,); + CHECKBOX_FORCE_RULE(closeable,); + CHECKBOX_FORCE_RULE(autogroup,); + CHECKBOX_FORCE_RULE(autogroupfg,); + LINEEDIT_FORCE_RULE(autogroupid,); + LINEEDIT_FORCE_RULE(opacityactive, intToStr); + LINEEDIT_FORCE_RULE(opacityinactive, intToStr); + COMBOBOX_FORCE_RULE(tilingoption, tilingToCombo); + LINEEDIT_SET_RULE(shortcut,); + COMBOBOX_FORCE_RULE(fsplevel,); + COMBOBOX_FORCE_RULE(moveresizemode, moveresizeToCombo); + COMBOBOX_FORCE_RULE(type, typeToCombo); + CHECKBOX_FORCE_RULE(ignoreposition,); + LINEEDIT_FORCE_RULE(minsize, sizeToStr); + LINEEDIT_FORCE_RULE(maxsize, sizeToStr); + CHECKBOX_FORCE_RULE(strictgeometry,); + CHECKBOX_FORCE_RULE(disableglobalshortcuts,); +} #undef GENERIC_RULE #undef CHECKBOX_SET_RULE @@ -467,11 +461,11 @@ void RulesWidget::setRules( Rules* rules ) #undef COMBOBOX_FORCE_RULE #define GENERIC_RULE( var, func, Type, type, uimethod ) \ - if( enable_##var->isChecked() && rule_##var->currentIndex() >= 0) \ - { \ + if ( enable_##var->isChecked() && rule_##var->currentIndex() >= 0) \ + { \ rules->var##rule = combo_to_##type##_rule[ rule_##var->currentIndex() ]; \ rules->var = func( Ui::RulesWidgetBase::var->uimethod()); \ - } \ + } \ else \ rules->var##rule = Rules::Unused##Type##Rule; @@ -483,25 +477,24 @@ void RulesWidget::setRules( Rules* rules ) #define COMBOBOX_FORCE_RULE( var, func ) GENERIC_RULE( var, func, Force, force, currentIndex ) Rules* RulesWidget::rules() const - { +{ Rules* rules = new Rules(); rules->description = description->text(); rules->wmclass = wmclass->text().toUtf8(); rules->wmclasscomplete = whole_wmclass->isChecked(); - rules->wmclassmatch = static_cast< Rules::StringMatch >( wmclass_match->currentIndex()); + rules->wmclassmatch = static_cast< Rules::StringMatch >(wmclass_match->currentIndex()); rules->windowrole = role->text().toUtf8(); - rules->windowrolematch = static_cast< Rules::StringMatch >( role_match->currentIndex()); + rules->windowrolematch = static_cast< Rules::StringMatch >(role_match->currentIndex()); rules->types = 0; bool all_types = true; - for( int i = 0; - i < types->count(); - ++i ) - if( !types->item(i)->isSelected()) + for (int i = 0; + i < types->count(); + ++i) + if (!types->item(i)->isSelected()) all_types = false; - if( all_types ) // if all types are selected, use AllTypesMask (for future expansion) + if (all_types) // if all types are selected, use AllTypesMask (for future expansion) rules->types = NET::AllTypesMask; - else - { + else { rules->types |= types->item(0)->isSelected() ? NET::NormalMask : 0U; rules->types |= types->item(1)->isSelected() ? NET::DialogMask : 0U; rules->types |= types->item(2)->isSelected() ? NET::UtilityMask : 0U; @@ -512,47 +505,47 @@ Rules* RulesWidget::rules() const rules->types |= types->item(7)->isSelected() ? NET::DesktopMask : 0U; rules->types |= types->item(8)->isSelected() ? NET::OverrideMask : 0U; rules->types |= types->item(9)->isSelected() ? NET::TopMenuMask : 0U; - } - rules->title = title->text(); - rules->titlematch = static_cast< Rules::StringMatch >( title_match->currentIndex()); - rules->extrarole = extra->text().toUtf8(); - rules->extrarolematch = static_cast< Rules::StringMatch >( extra_match->currentIndex()); - rules->clientmachine = machine->text().toUtf8(); - rules->clientmachinematch = static_cast< Rules::StringMatch >( machine_match->currentIndex()); - LINEEDIT_SET_RULE( position, strToPosition ); - LINEEDIT_SET_RULE( size, strToSize ); - COMBOBOX_SET_RULE( desktop, comboToDesktop ); - CHECKBOX_SET_RULE( maximizehoriz, ); - CHECKBOX_SET_RULE( maximizevert, ); - CHECKBOX_SET_RULE( minimize, ); - CHECKBOX_SET_RULE( shade, ); - CHECKBOX_SET_RULE( fullscreen, ); - COMBOBOX_FORCE_RULE( placement, comboToPlacement ); - CHECKBOX_SET_RULE( above, ); - CHECKBOX_SET_RULE( below, ); - CHECKBOX_SET_RULE( noborder, ); - CHECKBOX_SET_RULE( skiptaskbar, ); - CHECKBOX_SET_RULE( skippager, ); - CHECKBOX_SET_RULE( skipswitcher, ); - CHECKBOX_FORCE_RULE( acceptfocus, ); - CHECKBOX_FORCE_RULE( closeable, ); - CHECKBOX_FORCE_RULE( autogroup, ); - CHECKBOX_FORCE_RULE( autogroupfg, ); - LINEEDIT_FORCE_RULE( autogroupid, ); - LINEEDIT_FORCE_RULE( opacityactive, strToInt ); - LINEEDIT_FORCE_RULE( opacityinactive, strToInt ); - COMBOBOX_FORCE_RULE( tilingoption, comboToTiling ); - LINEEDIT_SET_RULE( shortcut, ); - COMBOBOX_FORCE_RULE( fsplevel, ); - COMBOBOX_FORCE_RULE( moveresizemode, comboToMoveResize ); - COMBOBOX_FORCE_RULE( type, comboToType ); - CHECKBOX_FORCE_RULE( ignoreposition, ); - LINEEDIT_FORCE_RULE( minsize, strToSize ); - LINEEDIT_FORCE_RULE( maxsize, strToSize ); - CHECKBOX_FORCE_RULE( strictgeometry, ); - CHECKBOX_FORCE_RULE( disableglobalshortcuts, ); - return rules; } + rules->title = title->text(); + rules->titlematch = static_cast< Rules::StringMatch >(title_match->currentIndex()); + rules->extrarole = extra->text().toUtf8(); + rules->extrarolematch = static_cast< Rules::StringMatch >(extra_match->currentIndex()); + rules->clientmachine = machine->text().toUtf8(); + rules->clientmachinematch = static_cast< Rules::StringMatch >(machine_match->currentIndex()); + LINEEDIT_SET_RULE(position, strToPosition); + LINEEDIT_SET_RULE(size, strToSize); + COMBOBOX_SET_RULE(desktop, comboToDesktop); + CHECKBOX_SET_RULE(maximizehoriz,); + CHECKBOX_SET_RULE(maximizevert,); + CHECKBOX_SET_RULE(minimize,); + CHECKBOX_SET_RULE(shade,); + CHECKBOX_SET_RULE(fullscreen,); + COMBOBOX_FORCE_RULE(placement, comboToPlacement); + CHECKBOX_SET_RULE(above,); + CHECKBOX_SET_RULE(below,); + CHECKBOX_SET_RULE(noborder,); + CHECKBOX_SET_RULE(skiptaskbar,); + CHECKBOX_SET_RULE(skippager,); + CHECKBOX_SET_RULE(skipswitcher,); + CHECKBOX_FORCE_RULE(acceptfocus,); + CHECKBOX_FORCE_RULE(closeable,); + CHECKBOX_FORCE_RULE(autogroup,); + CHECKBOX_FORCE_RULE(autogroupfg,); + LINEEDIT_FORCE_RULE(autogroupid,); + LINEEDIT_FORCE_RULE(opacityactive, strToInt); + LINEEDIT_FORCE_RULE(opacityinactive, strToInt); + COMBOBOX_FORCE_RULE(tilingoption, comboToTiling); + LINEEDIT_SET_RULE(shortcut,); + COMBOBOX_FORCE_RULE(fsplevel,); + COMBOBOX_FORCE_RULE(moveresizemode, comboToMoveResize); + COMBOBOX_FORCE_RULE(type, comboToType); + CHECKBOX_FORCE_RULE(ignoreposition,); + LINEEDIT_FORCE_RULE(minsize, strToSize); + LINEEDIT_FORCE_RULE(maxsize, strToSize); + CHECKBOX_FORCE_RULE(strictgeometry,); + CHECKBOX_FORCE_RULE(disableglobalshortcuts,); + return rules; +} #undef GENERIC_RULE #undef CHECKBOX_SET_RULE @@ -563,117 +556,113 @@ Rules* RulesWidget::rules() const #undef COMBOBOX_FORCE_RULE #define STRING_MATCH_COMBO( type ) \ -void RulesWidget::type##MatchChanged() \ + void RulesWidget::type##MatchChanged() \ { \ - edit_reg_##type->setEnabled( type##_match->currentIndex() == Rules::RegExpMatch ); \ - type->setEnabled( type##_match->currentIndex() != Rules::UnimportantMatch ); \ + edit_reg_##type->setEnabled( type##_match->currentIndex() == Rules::RegExpMatch ); \ + type->setEnabled( type##_match->currentIndex() != Rules::UnimportantMatch ); \ } -STRING_MATCH_COMBO( wmclass ) -STRING_MATCH_COMBO( role ) -STRING_MATCH_COMBO( title ) -STRING_MATCH_COMBO( extra ) -STRING_MATCH_COMBO( machine ) +STRING_MATCH_COMBO(wmclass) +STRING_MATCH_COMBO(role) +STRING_MATCH_COMBO(title) +STRING_MATCH_COMBO(extra) +STRING_MATCH_COMBO(machine) #undef STRING_MATCH_COMBO void RulesWidget::detectClicked() - { - assert( detect_dlg == NULL ); +{ + assert(detect_dlg == NULL); detect_dlg = new DetectDialog; - connect( detect_dlg, SIGNAL( detectionDone( bool )), this, SLOT( detected( bool ))); - detect_dlg->detect( 0 ); - } + connect(detect_dlg, SIGNAL(detectionDone(bool)), this, SLOT(detected(bool))); + detect_dlg->detect(0); +} -void RulesWidget::detected( bool ok ) - { - if( ok ) - { - wmclass->setText( detect_dlg->selectedClass()); - wmclass_match->setCurrentIndex( Rules::ExactMatch ); +void RulesWidget::detected(bool ok) +{ + if (ok) { + wmclass->setText(detect_dlg->selectedClass()); + wmclass_match->setCurrentIndex(Rules::ExactMatch); wmclassMatchChanged(); // grrr - whole_wmclass->setChecked( detect_dlg->selectedWholeClass()); - role->setText( detect_dlg->selectedRole()); - role_match->setCurrentIndex( detect_dlg->selectedRole().isEmpty() - ? Rules::UnimportantMatch : Rules::ExactMatch ); + whole_wmclass->setChecked(detect_dlg->selectedWholeClass()); + role->setText(detect_dlg->selectedRole()); + role_match->setCurrentIndex(detect_dlg->selectedRole().isEmpty() + ? Rules::UnimportantMatch : Rules::ExactMatch); roleMatchChanged(); - if( detect_dlg->selectedWholeApp()) - { - for( int i = 0; - i < types->count(); - ++i ) - types->item(i)->setSelected( true ); - } - else - { + if (detect_dlg->selectedWholeApp()) { + for (int i = 0; + i < types->count(); + ++i) + types->item(i)->setSelected(true); + } else { NET::WindowType type = detect_dlg->selectedType(); - for( int i = 0; - i < types->count(); - ++i ) - types->item(i)->setSelected( false ); - types->item( typeToCombo(type) )->setSelected( true ); - } - title->setText( detect_dlg->selectedTitle()); - title_match->setCurrentIndex( detect_dlg->titleMatch()); + for (int i = 0; + i < types->count(); + ++i) + types->item(i)->setSelected(false); + types->item(typeToCombo(type))->setSelected(true); + } + title->setText(detect_dlg->selectedTitle()); + title_match->setCurrentIndex(detect_dlg->titleMatch()); titleMatchChanged(); - machine->setText( detect_dlg->selectedMachine()); - machine_match->setCurrentIndex( Rules::UnimportantMatch ); + machine->setText(detect_dlg->selectedMachine()); + machine_match->setCurrentIndex(Rules::UnimportantMatch); machineMatchChanged(); // prefill values from to window to settings which already set const KWindowInfo& info = detect_dlg->windowInfo(); - prefillUnusedValues( info ); - } + prefillUnusedValues(info); + } delete detect_dlg; detect_dlg = NULL; detect_dlg_ok = ok; - } +} #define GENERIC_PREFILL( var, func, info, uimethod ) \ - if( !enable_##var->isChecked()) \ - { \ + if ( !enable_##var->isChecked()) \ + { \ Ui::RulesWidgetBase::var->uimethod( func( info )); \ - } + } #define CHECKBOX_PREFILL( var, func, info ) GENERIC_PREFILL( var, func, info, setChecked ) #define LINEEDIT_PREFILL( var, func, info ) GENERIC_PREFILL( var, func, info, setText ) #define COMBOBOX_PREFILL( var, func, info ) GENERIC_PREFILL( var, func, info, setCurrentIndex ) -void RulesWidget::prefillUnusedValues( const KWindowInfo& info ) - { - LINEEDIT_PREFILL( position, positionToStr, info.frameGeometry().topLeft() ); - LINEEDIT_PREFILL( size, sizeToStr, info.frameGeometry().size() ); - COMBOBOX_PREFILL( desktop, desktopToCombo, info.desktop() ); - CHECKBOX_PREFILL( maximizehoriz,, info.state() & NET::MaxHoriz ); - CHECKBOX_PREFILL( maximizevert,, info.state() & NET::MaxVert ); - CHECKBOX_PREFILL( minimize,, info.isMinimized() ); - CHECKBOX_PREFILL( shade,, info.state() & NET::Shaded ); - CHECKBOX_PREFILL( fullscreen,, info.state() & NET::FullScreen ); +void RulesWidget::prefillUnusedValues(const KWindowInfo& info) +{ + LINEEDIT_PREFILL(position, positionToStr, info.frameGeometry().topLeft()); + LINEEDIT_PREFILL(size, sizeToStr, info.frameGeometry().size()); + COMBOBOX_PREFILL(desktop, desktopToCombo, info.desktop()); + CHECKBOX_PREFILL(maximizehoriz, , info.state() & NET::MaxHoriz); + CHECKBOX_PREFILL(maximizevert, , info.state() & NET::MaxVert); + CHECKBOX_PREFILL(minimize, , info.isMinimized()); + CHECKBOX_PREFILL(shade, , info.state() & NET::Shaded); + CHECKBOX_PREFILL(fullscreen, , info.state() & NET::FullScreen); //COMBOBOX_PREFILL( placement, placementToCombo ); - CHECKBOX_PREFILL( above,, info.state() & NET::KeepAbove ); - CHECKBOX_PREFILL( below,, info.state() & NET::KeepBelow ); + CHECKBOX_PREFILL(above, , info.state() & NET::KeepAbove); + CHECKBOX_PREFILL(below, , info.state() & NET::KeepBelow); // noborder is only internal KWin information, so let's guess - CHECKBOX_PREFILL( noborder,, info.frameGeometry() == info.geometry() ); - CHECKBOX_PREFILL( skiptaskbar,, info.state() & NET::SkipTaskbar ); - CHECKBOX_PREFILL( skippager,, info.state() & NET::SkipPager ); - CHECKBOX_PREFILL( skipswitcher,, false ); + CHECKBOX_PREFILL(noborder, , info.frameGeometry() == info.geometry()); + CHECKBOX_PREFILL(skiptaskbar, , info.state() & NET::SkipTaskbar); + CHECKBOX_PREFILL(skippager, , info.state() & NET::SkipPager); + CHECKBOX_PREFILL(skipswitcher, , false); //CHECKBOX_PREFILL( acceptfocus, ); //CHECKBOX_PREFILL( closeable, ); //CHECKBOX_PREFILL( autogroup, ); //CHECKBOX_PREFILL( autogroupfg, ); //LINEEDIT_PREFILL( autogroupid, ); - LINEEDIT_PREFILL( opacityactive, intToStr, 100 /*get the actual opacity somehow*/); - LINEEDIT_PREFILL( opacityinactive, intToStr, 100 /*get the actual opacity somehow*/); - COMBOBOX_PREFILL( tilingoption, tilingToCombo, 0 ); + LINEEDIT_PREFILL(opacityactive, intToStr, 100 /*get the actual opacity somehow*/); + LINEEDIT_PREFILL(opacityinactive, intToStr, 100 /*get the actual opacity somehow*/); + COMBOBOX_PREFILL(tilingoption, tilingToCombo, 0); //LINEEDIT_PREFILL( shortcut, ); //COMBOBOX_PREFILL( fsplevel, ); //COMBOBOX_PREFILL( moveresizemode, moveresizeToCombo ); - COMBOBOX_PREFILL( type, typeToCombo, info.windowType( SUPPORTED_MANAGED_WINDOW_TYPES_MASK ) ); + COMBOBOX_PREFILL(type, typeToCombo, info.windowType(SUPPORTED_MANAGED_WINDOW_TYPES_MASK)); //CHECKBOX_PREFILL( ignoreposition, ); - LINEEDIT_PREFILL( minsize, sizeToStr, info.frameGeometry().size() ); - LINEEDIT_PREFILL( maxsize, sizeToStr, info.frameGeometry().size() ); + LINEEDIT_PREFILL(minsize, sizeToStr, info.frameGeometry().size()); + LINEEDIT_PREFILL(maxsize, sizeToStr, info.frameGeometry().size()); //CHECKBOX_PREFILL( strictgeometry, ); //CHECKBOX_PREFILL( disableglobalshortcuts, ); - } +} #undef GENERIC_PREFILL #undef CHECKBOX_PREFILL @@ -681,172 +670,168 @@ void RulesWidget::prefillUnusedValues( const KWindowInfo& info ) #undef COMBOBOX_PREFILL bool RulesWidget::finalCheck() - { - if( description->text().isEmpty()) - { - if( !wmclass->text().isEmpty()) - description->setText( i18n( "Settings for %1", wmclass->text())); +{ + if (description->text().isEmpty()) { + if (!wmclass->text().isEmpty()) + description->setText(i18n("Settings for %1", wmclass->text())); else - description->setText( i18n( "Unnamed entry" )); - } + description->setText(i18n("Unnamed entry")); + } bool all_types = true; - for( int i = 0; - i < types->count(); - ++i ) - if( !types->item(i)->isSelected()) + for (int i = 0; + i < types->count(); + ++i) + if (!types->item(i)->isSelected()) all_types = false; - if( wmclass_match->currentIndex() == Rules::UnimportantMatch && all_types ) - { - if( KMessageBox::warningContinueCancel( window(), - i18n( "You have specified the window class as unimportant.\n" - "This means the settings will possibly apply to windows from all applications. " - "If you really want to create a generic setting, it is recommended you at least " - "limit the window types to avoid special window types." )) != KMessageBox::Continue ) + if (wmclass_match->currentIndex() == Rules::UnimportantMatch && all_types) { + if (KMessageBox::warningContinueCancel(window(), + i18n("You have specified the window class as unimportant.\n" + "This means the settings will possibly apply to windows from all applications. " + "If you really want to create a generic setting, it is recommended you at least " + "limit the window types to avoid special window types.")) != KMessageBox::Continue) return false; - } + } return true; - } +} -void RulesWidget::prepareWindowSpecific( WId window ) - { - tabs->setCurrentIndex( 2 ); // geometry tab, skip tabs for window identification - KWindowInfo info( window, -1U, -1U ); // read everything - prefillUnusedValues( info ); - } +void RulesWidget::prepareWindowSpecific(WId window) +{ + tabs->setCurrentIndex(2); // geometry tab, skip tabs for window identification + KWindowInfo info(window, -1U, -1U); // read everything + prefillUnusedValues(info); +} void RulesWidget::shortcutEditClicked() - { - QPointer dlg = new EditShortcutDialog( window()); - dlg->setShortcut( shortcut->text()); - if( dlg->exec() == QDialog::Accepted ) - shortcut->setText( dlg->shortcut()); +{ + QPointer dlg = new EditShortcutDialog(window()); + dlg->setShortcut(shortcut->text()); + if (dlg->exec() == QDialog::Accepted) + shortcut->setText(dlg->shortcut()); delete dlg; - } +} -RulesDialog::RulesDialog( QWidget* parent, const char* name ) - : KDialog( parent ) - { - setObjectName( name ); - setModal( true ); - setCaption( i18n( "Edit Window-Specific Settings" ) ); - setButtons( Ok | Cancel ); - setWindowIcon(KIcon("preferences-system-windows-actions")); +RulesDialog::RulesDialog(QWidget* parent, const char* name) + : KDialog(parent) +{ + setObjectName(name); + setModal(true); + setCaption(i18n("Edit Window-Specific Settings")); + setButtons(Ok | Cancel); + setWindowIcon(KIcon("preferences-system-windows-actions")); - widget = new RulesWidget( this ); - setMainWidget( widget ); - } + widget = new RulesWidget(this); + setMainWidget(widget); +} // window is set only for Alt+F3/Window-specific settings, because the dialog // is then related to one specific window -Rules* RulesDialog::edit( Rules* r, WId window, bool show_hints ) - { +Rules* RulesDialog::edit(Rules* r, WId window, bool show_hints) +{ rules = r; - widget->setRules( rules ); - if( window != 0 ) - widget->prepareWindowSpecific( window ); - if( show_hints ) - QTimer::singleShot( 0, this, SLOT( displayHints())); + widget->setRules(rules); + if (window != 0) + widget->prepareWindowSpecific(window); + if (show_hints) + QTimer::singleShot(0, this, SLOT(displayHints())); exec(); return rules; - } +} void RulesDialog::displayHints() - { +{ QString str = "

    "; - str += i18n( "This configuration dialog allows altering settings only for the selected window" - " or application. Find the setting you want to affect, enable the setting using the checkbox," - " select in what way the setting should be affected and to which value." ); + str += i18n("This configuration dialog allows altering settings only for the selected window" + " or application. Find the setting you want to affect, enable the setting using the checkbox," + " select in what way the setting should be affected and to which value."); #if 0 // maybe later - str += "

    " + i18n( "Consult the documentation for more details." ); + str += "

    " + i18n("Consult the documentation for more details."); #endif str += "

    "; - KMessageBox::information( this, str, QString(), "displayhints" ); - } + KMessageBox::information(this, str, QString(), "displayhints"); +} void RulesDialog::accept() - { - if( !widget->finalCheck()) +{ + if (!widget->finalCheck()) return; rules = widget->rules(); KDialog::accept(); - } +} -EditShortcut::EditShortcut( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +EditShortcut::EditShortcut(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} void EditShortcut::editShortcut() - { - QPointer< ShortcutDialog > dlg = new ShortcutDialog( QKeySequence( shortcut->text()), window()); - if( dlg->exec() == QDialog::Accepted ) - shortcut->setText( dlg->shortcut().toString()); +{ + QPointer< ShortcutDialog > dlg = new ShortcutDialog(QKeySequence(shortcut->text()), window()); + if (dlg->exec() == QDialog::Accepted) + shortcut->setText(dlg->shortcut().toString()); delete dlg; - } +} void EditShortcut::clearShortcut() - { - shortcut->setText( QLatin1String("") ); - } +{ + shortcut->setText(QLatin1String("")); +} -EditShortcutDialog::EditShortcutDialog( QWidget* parent, const char* name ) -: KDialog( parent ) - { - setObjectName( name ); - setModal( true ); - setCaption( i18n( "Edit Shortcut" ) ); - setButtons( Ok | Cancel ); +EditShortcutDialog::EditShortcutDialog(QWidget* parent, const char* name) + : KDialog(parent) +{ + setObjectName(name); + setModal(true); + setCaption(i18n("Edit Shortcut")); + setButtons(Ok | Cancel); - widget = new EditShortcut( this ); - setMainWidget( widget ); - } + widget = new EditShortcut(this); + setMainWidget(widget); +} -void EditShortcutDialog::setShortcut( const QString& cut ) - { - widget->shortcut->setText( cut ); - } +void EditShortcutDialog::setShortcut(const QString& cut) +{ + widget->shortcut->setText(cut); +} QString EditShortcutDialog::shortcut() const - { +{ return widget->shortcut->text(); - } +} -ShortcutDialog::ShortcutDialog( const QKeySequence& cut, QWidget* parent ) - : KDialog( parent ) - , widget( new KKeySequenceWidget( this )) - { - widget->setKeySequence( cut ); +ShortcutDialog::ShortcutDialog(const QKeySequence& cut, QWidget* parent) + : KDialog(parent) + , widget(new KKeySequenceWidget(this)) +{ + widget->setKeySequence(cut); // It's a global shortcut so don't allow multikey shortcuts widget->setMultiKeyShortcutsAllowed(false); - setMainWidget( widget ); - } + setMainWidget(widget); +} void ShortcutDialog::accept() - { +{ QKeySequence seq = shortcut(); - if( !seq.isEmpty()) - { - if( seq[0] == Qt::Key_Escape ) - { + if (!seq.isEmpty()) { + if (seq[0] == Qt::Key_Escape) { reject(); return; - } - if( seq[0] == Qt::Key_Space - || (seq[0] & Qt::KeyboardModifierMask) == 0 ) - { // clear + } + if (seq[0] == Qt::Key_Space + || (seq[0] & Qt::KeyboardModifierMask) == 0) { + // clear widget->clearKeySequence(); KDialog::accept(); return; - } } - KDialog::accept(); } + KDialog::accept(); +} QKeySequence ShortcutDialog::shortcut() const - { +{ return widget->keySequence(); - } +} } // namespace diff --git a/kcmkwin/kwinrules/ruleswidget.h b/kcmkwin/kwinrules/ruleswidget.h index f51a73970..ca44bf2c7 100644 --- a/kcmkwin/kwinrules/ruleswidget.h +++ b/kcmkwin/kwinrules/ruleswidget.h @@ -35,123 +35,123 @@ class DetectDialog; class RulesWidget : public QWidget, public Ui::RulesWidgetBase - { +{ Q_OBJECT - public: - RulesWidget( QWidget* parent = NULL ); - void setRules( Rules* r ); - Rules* rules() const; - bool finalCheck(); - void prepareWindowSpecific( WId window ); - signals: - void changed( bool state ); - protected slots: - void detectClicked(); - void wmclassMatchChanged(); - void roleMatchChanged(); - void titleMatchChanged(); - void extraMatchChanged(); - void machineMatchChanged(); - void shortcutEditClicked(); - private slots: - // geometry tab - void updateEnableposition(); - void updateEnablesize(); - void updateEnabledesktop(); - void updateEnablemaximizehoriz(); - void updateEnablemaximizevert(); - void updateEnableminimize(); - void updateEnableshade(); - void updateEnablefullscreen(); - void updateEnableplacement(); - // preferences tab - void updateEnableabove(); - void updateEnablebelow(); - void updateEnablenoborder(); - void updateEnableskiptaskbar(); - void updateEnableskippager(); - void updateEnableskipswitcher(); - void updateEnableacceptfocus(); - void updateEnablecloseable(); - void updateEnableautogroup(); - void updateEnableautogroupfg(); - void updateEnableautogroupid(); - void updateEnableopacityactive(); - void updateEnableopacityinactive(); - void updateEnabletilingoption(); - // workarounds tab - void updateEnablefsplevel(); - void updateEnablemoveresizemode(); - void updateEnabletype(); - void updateEnableignoreposition(); - void updateEnableminsize(); - void updateEnablemaxsize(); - void updateEnablestrictgeometry(); - void updateEnableshortcut(); - void updateEnabledisableglobalshortcuts(); - // internal - void detected( bool ); - private: - int desktopToCombo( int d ) const; - int comboToDesktop( int val ) const; - int tilingToCombo( int t ) const; - int comboToTiling( int val ) const; - void prefillUnusedValues( const KWindowInfo& info ); - DetectDialog* detect_dlg; - bool detect_dlg_ok; - }; +public: + RulesWidget(QWidget* parent = NULL); + void setRules(Rules* r); + Rules* rules() const; + bool finalCheck(); + void prepareWindowSpecific(WId window); +signals: + void changed(bool state); +protected slots: + void detectClicked(); + void wmclassMatchChanged(); + void roleMatchChanged(); + void titleMatchChanged(); + void extraMatchChanged(); + void machineMatchChanged(); + void shortcutEditClicked(); +private slots: + // geometry tab + void updateEnableposition(); + void updateEnablesize(); + void updateEnabledesktop(); + void updateEnablemaximizehoriz(); + void updateEnablemaximizevert(); + void updateEnableminimize(); + void updateEnableshade(); + void updateEnablefullscreen(); + void updateEnableplacement(); + // preferences tab + void updateEnableabove(); + void updateEnablebelow(); + void updateEnablenoborder(); + void updateEnableskiptaskbar(); + void updateEnableskippager(); + void updateEnableskipswitcher(); + void updateEnableacceptfocus(); + void updateEnablecloseable(); + void updateEnableautogroup(); + void updateEnableautogroupfg(); + void updateEnableautogroupid(); + void updateEnableopacityactive(); + void updateEnableopacityinactive(); + void updateEnabletilingoption(); + // workarounds tab + void updateEnablefsplevel(); + void updateEnablemoveresizemode(); + void updateEnabletype(); + void updateEnableignoreposition(); + void updateEnableminsize(); + void updateEnablemaxsize(); + void updateEnablestrictgeometry(); + void updateEnableshortcut(); + void updateEnabledisableglobalshortcuts(); + // internal + void detected(bool); +private: + int desktopToCombo(int d) const; + int comboToDesktop(int val) const; + int tilingToCombo(int t) const; + int comboToTiling(int val) const; + void prefillUnusedValues(const KWindowInfo& info); + DetectDialog* detect_dlg; + bool detect_dlg_ok; +}; class RulesDialog : public KDialog - { +{ Q_OBJECT - public: - explicit RulesDialog( QWidget* parent = NULL, const char* name = NULL ); - Rules* edit( Rules* r, WId window, bool show_hints ); - protected: - virtual void accept(); - private slots: - void displayHints(); - private: - RulesWidget* widget; - Rules* rules; - }; +public: + explicit RulesDialog(QWidget* parent = NULL, const char* name = NULL); + Rules* edit(Rules* r, WId window, bool show_hints); +protected: + virtual void accept(); +private slots: + void displayHints(); +private: + RulesWidget* widget; + Rules* rules; +}; class EditShortcut : public QWidget, public Ui_EditShortcut - { +{ Q_OBJECT - public: - EditShortcut( QWidget* parent = NULL ); - protected slots: - void editShortcut(); - void clearShortcut(); - }; +public: + EditShortcut(QWidget* parent = NULL); +protected slots: + void editShortcut(); + void clearShortcut(); +}; class EditShortcutDialog : public KDialog - { +{ Q_OBJECT - public: - explicit EditShortcutDialog( QWidget* parent = NULL, const char* name = NULL ); - void setShortcut( const QString& cut ); - QString shortcut() const; - private: - EditShortcut* widget; - }; +public: + explicit EditShortcutDialog(QWidget* parent = NULL, const char* name = NULL); + void setShortcut(const QString& cut); + QString shortcut() const; +private: + EditShortcut* widget; +}; // slightly duped from utils.cpp class ShortcutDialog : public KDialog - { +{ Q_OBJECT - public: - explicit ShortcutDialog( const QKeySequence& cut, QWidget* parent = NULL ); - virtual void accept(); - QKeySequence shortcut() const; - private: - KKeySequenceWidget* widget; - }; +public: + explicit ShortcutDialog(const QKeySequence& cut, QWidget* parent = NULL); + virtual void accept(); + QKeySequence shortcut() const; +private: + KKeySequenceWidget* widget; +}; } // namespace diff --git a/kcmkwin/kwinscreenedges/main.cpp b/kcmkwin/kwinscreenedges/main.cpp index 19a96e9ff..1cbbef1cf 100644 --- a/kcmkwin/kwinscreenedges/main.cpp +++ b/kcmkwin/kwinscreenedges/main.cpp @@ -29,537 +29,511 @@ along with this program. If not, see . #include #include -K_PLUGIN_FACTORY( KWinScreenEdgesConfigFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( KWinScreenEdgesConfigFactory( "kcmkwinscreenedges" )) +K_PLUGIN_FACTORY(KWinScreenEdgesConfigFactory, registerPlugin();) +K_EXPORT_PLUGIN(KWinScreenEdgesConfigFactory("kcmkwinscreenedges")) namespace KWin { -KWinScreenEdgesConfigForm::KWinScreenEdgesConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinScreenEdgesConfigForm::KWinScreenEdgesConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinScreenEdgesConfig::KWinScreenEdgesConfig( QWidget* parent, const QVariantList& args ) - : KCModule( KWinScreenEdgesConfigFactory::componentData(), parent, args ) - , m_config( KSharedConfig::openConfig( "kwinrc" )) - { - m_ui = new KWinScreenEdgesConfigForm( this ); - QVBoxLayout* layout = new QVBoxLayout( this ); - layout->addWidget( m_ui ); +KWinScreenEdgesConfig::KWinScreenEdgesConfig(QWidget* parent, const QVariantList& args) + : KCModule(KWinScreenEdgesConfigFactory::componentData(), parent, args) + , m_config(KSharedConfig::openConfig("kwinrc")) +{ + m_ui = new KWinScreenEdgesConfigForm(this); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_ui); monitorInit(); - connect( m_ui->monitor, SIGNAL( changed() ), this, SLOT( changed() )); + connect(m_ui->monitor, SIGNAL(changed()), this, SLOT(changed())); - connect( m_ui->desktopSwitchCombo, SIGNAL( currentIndexChanged(int) ), this, SLOT( changed() )); - connect( m_ui->activationDelaySpin, SIGNAL( valueChanged(int) ), this, SLOT( changed() )); - connect( m_ui->triggerCooldownSpin, SIGNAL( valueChanged(int) ), this, SLOT( changed() )); - connect( m_ui->quickMaximizeBox, SIGNAL( stateChanged(int) ), this, SLOT( changed() )); - connect( m_ui->quickTileBox, SIGNAL( stateChanged(int) ), this, SLOT( changed() )); + connect(m_ui->desktopSwitchCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_ui->activationDelaySpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->triggerCooldownSpin, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(m_ui->quickMaximizeBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_ui->quickTileBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); // Visual feedback of action group conflicts - connect( m_ui->desktopSwitchCombo, SIGNAL( currentIndexChanged(int) ), this, SLOT( groupChanged() )); - connect( m_ui->quickMaximizeBox, SIGNAL( stateChanged(int) ), this, SLOT( groupChanged() )); - connect( m_ui->quickTileBox, SIGNAL( stateChanged(int) ), this, SLOT( groupChanged() )); + connect(m_ui->desktopSwitchCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(groupChanged())); + connect(m_ui->quickMaximizeBox, SIGNAL(stateChanged(int)), this, SLOT(groupChanged())); + connect(m_ui->quickTileBox, SIGNAL(stateChanged(int)), this, SLOT(groupChanged())); // NOTICE: this is intended to workaround broken GL implementations that successfully segfault on glXQuery :-( KConfigGroup gl_workaround_config(m_config, "Compositing"); const bool checkIsSafe = gl_workaround_config.readEntry("CheckIsSafe", true); - if( checkIsSafe && CompositingPrefs::compositingPossible() ) - { + if (checkIsSafe && CompositingPrefs::compositingPossible()) { gl_workaround_config.writeEntry("CheckIsSafe", false); gl_workaround_config.sync(); m_defaultPrefs.detect(); // Driver-specific config detection gl_workaround_config.writeEntry("CheckIsSafe", true); gl_workaround_config.sync(); - } - load(); } + load(); +} KWinScreenEdgesConfig::~KWinScreenEdgesConfig() - { - } +{ +} void KWinScreenEdgesConfig::groupChanged() - { +{ // Monitor conflicts bool hide = false; - if( m_ui->desktopSwitchCombo->currentIndex() == 2 ) + if (m_ui->desktopSwitchCombo->currentIndex() == 2) hide = true; - monitorHideEdge( ElectricTop, hide ); - monitorHideEdge( ElectricRight, hide ); - monitorHideEdge( ElectricBottom, hide ); - monitorHideEdge( ElectricLeft, hide ); - } + monitorHideEdge(ElectricTop, hide); + monitorHideEdge(ElectricRight, hide); + monitorHideEdge(ElectricBottom, hide); + monitorHideEdge(ElectricLeft, hide); +} void KWinScreenEdgesConfig::load() - { +{ KCModule::load(); monitorLoad(); - KConfigGroup config( m_config, "Windows" ); + KConfigGroup config(m_config, "Windows"); - m_ui->desktopSwitchCombo->setCurrentIndex( config.readEntry( "ElectricBorders", 0 )); - m_ui->activationDelaySpin->setValue( config.readEntry( "ElectricBorderDelay", 150 )); - m_ui->triggerCooldownSpin->setValue( config.readEntry( "ElectricBorderCooldown", 350 )); - m_ui->quickMaximizeBox->setChecked( config.readEntry( "ElectricBorderMaximize", true )); - m_ui->quickTileBox->setChecked( config.readEntry( "ElectricBorderTiling", true )); + m_ui->desktopSwitchCombo->setCurrentIndex(config.readEntry("ElectricBorders", 0)); + m_ui->activationDelaySpin->setValue(config.readEntry("ElectricBorderDelay", 150)); + m_ui->triggerCooldownSpin->setValue(config.readEntry("ElectricBorderCooldown", 350)); + m_ui->quickMaximizeBox->setChecked(config.readEntry("ElectricBorderMaximize", true)); + m_ui->quickTileBox->setChecked(config.readEntry("ElectricBorderTiling", true)); - emit changed( false ); - } + emit changed(false); +} void KWinScreenEdgesConfig::save() - { +{ KCModule::save(); monitorSave(); - KConfigGroup config( m_config, "Windows" ); + KConfigGroup config(m_config, "Windows"); - config.writeEntry( "ElectricBorders", m_ui->desktopSwitchCombo->currentIndex() ); - config.writeEntry( "ElectricBorderDelay", m_ui->activationDelaySpin->value() ); - config.writeEntry( "ElectricBorderCooldown", m_ui->triggerCooldownSpin->value() ); - config.writeEntry( "ElectricBorderMaximize", m_ui->quickMaximizeBox->isChecked() ); - config.writeEntry( "ElectricBorderTiling", m_ui->quickTileBox->isChecked() ); + config.writeEntry("ElectricBorders", m_ui->desktopSwitchCombo->currentIndex()); + config.writeEntry("ElectricBorderDelay", m_ui->activationDelaySpin->value()); + config.writeEntry("ElectricBorderCooldown", m_ui->triggerCooldownSpin->value()); + config.writeEntry("ElectricBorderMaximize", m_ui->quickMaximizeBox->isChecked()); + config.writeEntry("ElectricBorderTiling", m_ui->quickTileBox->isChecked()); config.sync(); // Reload KWin. - QDBusMessage message = QDBusMessage::createSignal( "/KWin", "org.kde.KWin", "reloadConfig" ); - QDBusConnection::sessionBus().send( message ); + QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); - emit changed( false ); - } + emit changed(false); +} void KWinScreenEdgesConfig::defaults() - { +{ monitorDefaults(); - m_ui->desktopSwitchCombo->setCurrentIndex( 0 ); - m_ui->activationDelaySpin->setValue( 150 ); - m_ui->triggerCooldownSpin->setValue( 350 ); - m_ui->quickMaximizeBox->setChecked( true ); - m_ui->quickTileBox->setChecked( true ); + m_ui->desktopSwitchCombo->setCurrentIndex(0); + m_ui->activationDelaySpin->setValue(150); + m_ui->triggerCooldownSpin->setValue(350); + m_ui->quickMaximizeBox->setChecked(true); + m_ui->quickTileBox->setChecked(true); - emit changed( true ); - } + emit changed(true); +} -void KWinScreenEdgesConfig::showEvent( QShowEvent* e ) - { - KCModule::showEvent( e ); +void KWinScreenEdgesConfig::showEvent(QShowEvent* e) +{ + KCModule::showEvent(e); monitorShowEvent(); - } +} // Copied from kcmkwin/kwincompositing/main.cpp -bool KWinScreenEdgesConfig::effectEnabled( const QString& effect, const KConfigGroup& cfg ) const - { +bool KWinScreenEdgesConfig::effectEnabled(const QString& effect, const KConfigGroup& cfg) const +{ KService::List services = KServiceTypeTrader::self()->query( - "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); - if( services.isEmpty()) + "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) return false; QVariant v = services.first()->property("X-KDE-PluginInfo-EnabledByDefault"); return cfg.readEntry("kwin4_effect_" + effect + "Enabled", v.toBool()); - } +} //----------------------------------------------------------------------------- // Monitor -void KWinScreenEdgesConfig::monitorAddItem( const QString& item ) - { - for( int i = 0; i < 8; i++ ) - m_ui->monitor->addEdgeItem( i, item ); - } +void KWinScreenEdgesConfig::monitorAddItem(const QString& item) +{ + for (int i = 0; i < 8; i++) + m_ui->monitor->addEdgeItem(i, item); +} -void KWinScreenEdgesConfig::monitorItemSetEnabled( int index, bool enabled ) - { - for( int i = 0; i < 8; i++ ) - m_ui->monitor->setEdgeItemEnabled( i, index, enabled ); - } +void KWinScreenEdgesConfig::monitorItemSetEnabled(int index, bool enabled) +{ + for (int i = 0; i < 8; i++) + m_ui->monitor->setEdgeItemEnabled(i, index, enabled); +} void KWinScreenEdgesConfig::monitorInit() - { - monitorAddItem( i18n( "No Action" )); - monitorAddItem( i18n( "Show Dashboard" )); - monitorAddItem( i18n( "Show Desktop" )); - monitorAddItem( i18n( "Lock Screen" )); - monitorAddItem( i18n( "Prevent Screen Locking" )); +{ + monitorAddItem(i18n("No Action")); + monitorAddItem(i18n("Show Dashboard")); + monitorAddItem(i18n("Show Desktop")); + monitorAddItem(i18n("Lock Screen")); + monitorAddItem(i18n("Prevent Screen Locking")); //Prevent Screen Locking is not supported on some edges - m_ui->monitor->setEdgeItemEnabled( int( Monitor::Top ), 4, false ); - m_ui->monitor->setEdgeItemEnabled( int( Monitor::Left ), 4, false ); - m_ui->monitor->setEdgeItemEnabled( int( Monitor::Right ), 4, false ); - m_ui->monitor->setEdgeItemEnabled( int( Monitor::Bottom ), 4, false ); - + m_ui->monitor->setEdgeItemEnabled(int(Monitor::Top), 4, false); + m_ui->monitor->setEdgeItemEnabled(int(Monitor::Left), 4, false); + m_ui->monitor->setEdgeItemEnabled(int(Monitor::Right), 4, false); + m_ui->monitor->setEdgeItemEnabled(int(Monitor::Bottom), 4, false); + // Search the effect names KServiceTypeTrader* trader = KServiceTypeTrader::self(); KService::List services; - services = trader->query( "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_presentwindows'" ); - if( services.isEmpty() ) - { + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_presentwindows'"); + if (services.isEmpty()) { // adding empty strings in case the effect is not found // TODO: after string freeze add a info that the effect is missing - monitorAddItem( QString() ); - monitorAddItem( QString() ); - } - else - { - monitorAddItem( services.first()->name() + " - " + i18n( "All Desktops" )); - monitorAddItem( services.first()->name() + " - " + i18n( "Current Desktop" )); - } - services = trader->query( "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_desktopgrid'" ); - if( services.isEmpty() ) - { + monitorAddItem(QString()); + monitorAddItem(QString()); + } else { + monitorAddItem(services.first()->name() + " - " + i18n("All Desktops")); + monitorAddItem(services.first()->name() + " - " + i18n("Current Desktop")); + } + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_desktopgrid'"); + if (services.isEmpty()) { // adding empty strings in case the effect is not found // TODO: after string freeze add a info that the effect is missing - monitorAddItem( QString() ); - } - else - { - monitorAddItem( services.first()->name()); - } - services = trader->query( "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_cube'" ); - if( services.isEmpty() ) - { + monitorAddItem(QString()); + } else { + monitorAddItem(services.first()->name()); + } + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_cube'"); + if (services.isEmpty()) { // adding empty strings in case the effect is not found // TODO: after string freeze add a info that the effect is missing - monitorAddItem( QString() ); - monitorAddItem( QString() ); - monitorAddItem( QString() ); - } - else - { - monitorAddItem( services.first()->name() + " - " + i18n( "Cube" )); - monitorAddItem( services.first()->name() + " - " + i18n( "Cylinder" )); - monitorAddItem( services.first()->name() + " - " + i18n( "Sphere" )); - } - services = trader->query( "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_flipswitch'" ); - if( services.isEmpty() ) - { + monitorAddItem(QString()); + monitorAddItem(QString()); + monitorAddItem(QString()); + } else { + monitorAddItem(services.first()->name() + " - " + i18n("Cube")); + monitorAddItem(services.first()->name() + " - " + i18n("Cylinder")); + monitorAddItem(services.first()->name() + " - " + i18n("Sphere")); + } + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_flipswitch'"); + if (services.isEmpty()) { // adding empty strings in case the effect is not found // TODO: after string freeze add a info that the effect is missing - monitorAddItem( QString() ); - monitorAddItem( QString() ); - } - else - { - monitorAddItem( services.first()->name() + " - " + i18n( "All Desktops" )); - monitorAddItem( services.first()->name() + " - " + i18n( "Current Desktop" )); - } + monitorAddItem(QString()); + monitorAddItem(QString()); + } else { + monitorAddItem(services.first()->name() + " - " + i18n("All Desktops")); + monitorAddItem(services.first()->name() + " - " + i18n("Current Desktop")); + } monitorShowEvent(); - } +} -void KWinScreenEdgesConfig::monitorLoadAction( ElectricBorder edge, const QString& configName ) - { - KConfigGroup config( m_config, "ElectricBorders" ); - QString lowerName = config.readEntry( configName, "None" ).toLower(); - if( lowerName == "dashboard" ) monitorChangeEdge( edge, int( ElectricActionDashboard )); - else if( lowerName == "showdesktop" ) monitorChangeEdge( edge, int( ElectricActionShowDesktop )); - else if( lowerName == "lockscreen" ) monitorChangeEdge( edge, int( ElectricActionLockScreen )); - else if( lowerName == "preventscreenlocking" ) monitorChangeEdge( edge, int( ElectricActionPreventScreenLocking )); - } +void KWinScreenEdgesConfig::monitorLoadAction(ElectricBorder edge, const QString& configName) +{ + KConfigGroup config(m_config, "ElectricBorders"); + QString lowerName = config.readEntry(configName, "None").toLower(); + if (lowerName == "dashboard") monitorChangeEdge(edge, int(ElectricActionDashboard)); + else if (lowerName == "showdesktop") monitorChangeEdge(edge, int(ElectricActionShowDesktop)); + else if (lowerName == "lockscreen") monitorChangeEdge(edge, int(ElectricActionLockScreen)); + else if (lowerName == "preventscreenlocking") monitorChangeEdge(edge, int(ElectricActionPreventScreenLocking)); +} void KWinScreenEdgesConfig::monitorLoad() - { +{ // Load ElectricBorderActions - monitorLoadAction( ElectricTop, "Top" ); - monitorLoadAction( ElectricTopRight, "TopRight" ); - monitorLoadAction( ElectricRight, "Right" ); - monitorLoadAction( ElectricBottomRight, "BottomRight" ); - monitorLoadAction( ElectricBottom, "Bottom" ); - monitorLoadAction( ElectricBottomLeft, "BottomLeft" ); - monitorLoadAction( ElectricLeft, "Left" ); - monitorLoadAction( ElectricTopLeft, "TopLeft" ); + monitorLoadAction(ElectricTop, "Top"); + monitorLoadAction(ElectricTopRight, "TopRight"); + monitorLoadAction(ElectricRight, "Right"); + monitorLoadAction(ElectricBottomRight, "BottomRight"); + monitorLoadAction(ElectricBottom, "Bottom"); + monitorLoadAction(ElectricBottomLeft, "BottomLeft"); + monitorLoadAction(ElectricLeft, "Left"); + monitorLoadAction(ElectricTopLeft, "TopLeft"); // Load effect-specific actions: // Present Windows - KConfigGroup presentWindowsConfig( m_config, "Effect-PresentWindows" ); + KConfigGroup presentWindowsConfig(m_config, "Effect-PresentWindows"); QList list = QList(); // PresentWindows BorderActivateAll - list.append( int( ElectricTopLeft ) ); - list = presentWindowsConfig.readEntry( "BorderActivateAll", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( PresentWindowsAll ) ); - } + list.append(int(ElectricTopLeft)); + list = presentWindowsConfig.readEntry("BorderActivateAll", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(PresentWindowsAll)); + } // PresentWindows BorderActivate list.clear(); - list.append( int( ElectricNone ) ); - list = presentWindowsConfig.readEntry( "BorderActivate", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( PresentWindowsCurrent ) ); - } + list.append(int(ElectricNone)); + list = presentWindowsConfig.readEntry("BorderActivate", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(PresentWindowsCurrent)); + } // Desktop Grid - KConfigGroup gridConfig( m_config, "Effect-DesktopGrid" ); + KConfigGroup gridConfig(m_config, "Effect-DesktopGrid"); list.clear(); - list.append( int( ElectricNone ) ); - list = gridConfig.readEntry( "BorderActivate", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( DesktopGrid ) ); - } + list.append(int(ElectricNone)); + list = gridConfig.readEntry("BorderActivate", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(DesktopGrid)); + } // Desktop Cube - KConfigGroup cubeConfig( m_config, "Effect-Cube" ); + KConfigGroup cubeConfig(m_config, "Effect-Cube"); list.clear(); - list.append( int( ElectricNone ) ); - list = cubeConfig.readEntry( "BorderActivate", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( Cube ) ); - } + list.append(int(ElectricNone)); + list = cubeConfig.readEntry("BorderActivate", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(Cube)); + } list.clear(); - list.append( int( ElectricNone ) ); - list = cubeConfig.readEntry( "BorderActivateCylinder", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( Cylinder ) ); - } + list.append(int(ElectricNone)); + list = cubeConfig.readEntry("BorderActivateCylinder", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(Cylinder)); + } list.clear(); - list.append( int( ElectricNone ) ); - list = cubeConfig.readEntry( "BorderActivateSphere", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( Sphere ) ); - } + list.append(int(ElectricNone)); + list = cubeConfig.readEntry("BorderActivateSphere", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(Sphere)); + } // Flip Switch - KConfigGroup flipSwitchConfig( m_config, "Effect-FlipSwitch" ); + KConfigGroup flipSwitchConfig(m_config, "Effect-FlipSwitch"); list.clear(); // FlipSwitch BorderActivateAll - list.append( int( ElectricNone ) ); - list = flipSwitchConfig.readEntry( "BorderActivateAll", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( FlipSwitchAll ) ); - } + list.append(int(ElectricNone)); + list = flipSwitchConfig.readEntry("BorderActivateAll", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(FlipSwitchAll)); + } // FlipSwitch BorderActivate list.clear(); - list.append( int( ElectricNone ) ); - list = flipSwitchConfig.readEntry( "BorderActivate", list ); - foreach( int i, list ) - { - monitorChangeEdge( ElectricBorder( i ), int( FlipSwitchCurrent ) ); - } + list.append(int(ElectricNone)); + list = flipSwitchConfig.readEntry("BorderActivate", list); + foreach (int i, list) { + monitorChangeEdge(ElectricBorder(i), int(FlipSwitchCurrent)); } +} -void KWinScreenEdgesConfig::monitorSaveAction( int edge, const QString& configName ) - { - KConfigGroup config( m_config, "ElectricBorders" ); - int item = m_ui->monitor->selectedEdgeItem( edge ); - if( item == 1 ) // Plasma dashboard - config.writeEntry( configName, "Dashboard" ); - else if( item == 2 ) - config.writeEntry( configName, "ShowDesktop" ); - else if( item == 3) - config.writeEntry( configName, "LockScreen" ); - else if ( item == 4) - config.writeEntry( configName, "PreventScreenLocking" ); +void KWinScreenEdgesConfig::monitorSaveAction(int edge, const QString& configName) +{ + KConfigGroup config(m_config, "ElectricBorders"); + int item = m_ui->monitor->selectedEdgeItem(edge); + if (item == 1) // Plasma dashboard + config.writeEntry(configName, "Dashboard"); + else if (item == 2) + config.writeEntry(configName, "ShowDesktop"); + else if (item == 3) + config.writeEntry(configName, "LockScreen"); + else if (item == 4) + config.writeEntry(configName, "PreventScreenLocking"); else // Anything else - config.writeEntry( configName, "None" ); + config.writeEntry(configName, "None"); - if ((edge == int( Monitor::TopRight )) || - (edge == int( Monitor::BottomRight )) || - (edge == int( Monitor::BottomLeft )) || - (edge == int( Monitor::TopLeft ))) - { - KConfig scrnConfig("kscreensaverrc"); - KConfigGroup scrnGroup = scrnConfig.group("ScreenSaver"); - scrnGroup.writeEntry("Action" + configName, (item == 4) ? 2 /* Prevent Screen Locking */ : 0 /* None */); - scrnGroup.sync(); - } + if ((edge == int(Monitor::TopRight)) || + (edge == int(Monitor::BottomRight)) || + (edge == int(Monitor::BottomLeft)) || + (edge == int(Monitor::TopLeft))) { + KConfig scrnConfig("kscreensaverrc"); + KConfigGroup scrnGroup = scrnConfig.group("ScreenSaver"); + scrnGroup.writeEntry("Action" + configName, (item == 4) ? 2 /* Prevent Screen Locking */ : 0 /* None */); + scrnGroup.sync(); } +} void KWinScreenEdgesConfig::monitorSave() - { +{ // Save ElectricBorderActions - monitorSaveAction( int( Monitor::Top ), "Top" ); - monitorSaveAction( int( Monitor::TopRight ), "TopRight" ); - monitorSaveAction( int( Monitor::Right ), "Right" ); - monitorSaveAction( int( Monitor::BottomRight ), "BottomRight" ); - monitorSaveAction( int( Monitor::Bottom ), "Bottom" ); - monitorSaveAction( int( Monitor::BottomLeft ), "BottomLeft" ); - monitorSaveAction( int( Monitor::Left ), "Left" ); - monitorSaveAction( int( Monitor::TopLeft ), "TopLeft" ); + monitorSaveAction(int(Monitor::Top), "Top"); + monitorSaveAction(int(Monitor::TopRight), "TopRight"); + monitorSaveAction(int(Monitor::Right), "Right"); + monitorSaveAction(int(Monitor::BottomRight), "BottomRight"); + monitorSaveAction(int(Monitor::Bottom), "Bottom"); + monitorSaveAction(int(Monitor::BottomLeft), "BottomLeft"); + monitorSaveAction(int(Monitor::Left), "Left"); + monitorSaveAction(int(Monitor::TopLeft), "TopLeft"); // Save effect-specific actions: // Present Windows - KConfigGroup presentWindowsConfig( m_config, "Effect-PresentWindows" ); - presentWindowsConfig.writeEntry( "BorderActivateAll", - monitorCheckEffectHasEdge( int( PresentWindowsAll ))); - presentWindowsConfig.writeEntry( "BorderActivate", - monitorCheckEffectHasEdge( int( PresentWindowsCurrent ))); + KConfigGroup presentWindowsConfig(m_config, "Effect-PresentWindows"); + presentWindowsConfig.writeEntry("BorderActivateAll", + monitorCheckEffectHasEdge(int(PresentWindowsAll))); + presentWindowsConfig.writeEntry("BorderActivate", + monitorCheckEffectHasEdge(int(PresentWindowsCurrent))); // Desktop Grid - KConfigGroup gridConfig( m_config, "Effect-DesktopGrid" ); - gridConfig.writeEntry( "BorderActivate", - monitorCheckEffectHasEdge( int( DesktopGrid ))); + KConfigGroup gridConfig(m_config, "Effect-DesktopGrid"); + gridConfig.writeEntry("BorderActivate", + monitorCheckEffectHasEdge(int(DesktopGrid))); // Desktop Cube - KConfigGroup cubeConfig( m_config, "Effect-Cube" ); - cubeConfig.writeEntry( "BorderActivate", - monitorCheckEffectHasEdge( int( Cube ))); - cubeConfig.writeEntry( "BorderActivateCylinder", - monitorCheckEffectHasEdge( int( Cylinder ))); - cubeConfig.writeEntry( "BorderActivateSphere", - monitorCheckEffectHasEdge( int( Sphere ))); + KConfigGroup cubeConfig(m_config, "Effect-Cube"); + cubeConfig.writeEntry("BorderActivate", + monitorCheckEffectHasEdge(int(Cube))); + cubeConfig.writeEntry("BorderActivateCylinder", + monitorCheckEffectHasEdge(int(Cylinder))); + cubeConfig.writeEntry("BorderActivateSphere", + monitorCheckEffectHasEdge(int(Sphere))); // Flip Switch - KConfigGroup flipSwitchConfig( m_config, "Effect-FlipSwitch" ); - flipSwitchConfig.writeEntry( "BorderActivateAll", - monitorCheckEffectHasEdge( int( FlipSwitchAll ))); - flipSwitchConfig.writeEntry( "BorderActivate", - monitorCheckEffectHasEdge( int( FlipSwitchCurrent ))); - } + KConfigGroup flipSwitchConfig(m_config, "Effect-FlipSwitch"); + flipSwitchConfig.writeEntry("BorderActivateAll", + monitorCheckEffectHasEdge(int(FlipSwitchAll))); + flipSwitchConfig.writeEntry("BorderActivate", + monitorCheckEffectHasEdge(int(FlipSwitchCurrent))); +} void KWinScreenEdgesConfig::monitorDefaults() - { +{ // Clear all edges - for( int i = 0; i < 8; i++ ) - m_ui->monitor->selectEdgeItem( i, 0 ); + for (int i = 0; i < 8; i++) + m_ui->monitor->selectEdgeItem(i, 0); // Present windows = Top-left - m_ui->monitor->selectEdgeItem( int( Monitor::TopLeft ), int( PresentWindowsAll )); - } + m_ui->monitor->selectEdgeItem(int(Monitor::TopLeft), int(PresentWindowsAll)); +} void KWinScreenEdgesConfig::monitorShowEvent() - { +{ // Check if they are enabled - KConfigGroup config( m_config, "Compositing" ); - if( config.readEntry( "Enabled", m_defaultPrefs.recommendCompositing() )) - { // Compositing enabled - config = KConfigGroup( m_config, "Plugins" ); + KConfigGroup config(m_config, "Compositing"); + if (config.readEntry("Enabled", m_defaultPrefs.recommendCompositing())) { + // Compositing enabled + config = KConfigGroup(m_config, "Plugins"); // Present Windows - bool enabled = effectEnabled( "presentwindows", config ); - monitorItemSetEnabled( int( PresentWindowsCurrent ), enabled ); - monitorItemSetEnabled( int( PresentWindowsAll ), enabled ); + bool enabled = effectEnabled("presentwindows", config); + monitorItemSetEnabled(int(PresentWindowsCurrent), enabled); + monitorItemSetEnabled(int(PresentWindowsAll), enabled); // Desktop Grid - enabled = effectEnabled( "desktopgrid", config ); - monitorItemSetEnabled( int( DesktopGrid ), enabled ); + enabled = effectEnabled("desktopgrid", config); + monitorItemSetEnabled(int(DesktopGrid), enabled); // Desktop Cube - enabled = effectEnabled( "cube", config ); - monitorItemSetEnabled( int( Cube ), enabled ); - monitorItemSetEnabled( int( Cylinder ), enabled ); - monitorItemSetEnabled( int( Sphere ), enabled ); + enabled = effectEnabled("cube", config); + monitorItemSetEnabled(int(Cube), enabled); + monitorItemSetEnabled(int(Cylinder), enabled); + monitorItemSetEnabled(int(Sphere), enabled); // Flip Switch - enabled = effectEnabled( "flipswitch", config ); - monitorItemSetEnabled( int( FlipSwitchAll ), enabled ); - monitorItemSetEnabled( int( FlipSwitchCurrent ), enabled ); - } - else // Compositing disabled - { - monitorItemSetEnabled( int( PresentWindowsCurrent ), false ); - monitorItemSetEnabled( int( PresentWindowsAll ), false ); - monitorItemSetEnabled( int( DesktopGrid ), false ); - monitorItemSetEnabled( int( Cube ), false ); - monitorItemSetEnabled( int( Cylinder ), false ); - monitorItemSetEnabled( int( Sphere ), false ); - monitorItemSetEnabled( int( FlipSwitchAll ), false ); - monitorItemSetEnabled( int( FlipSwitchCurrent ), false ); - } + enabled = effectEnabled("flipswitch", config); + monitorItemSetEnabled(int(FlipSwitchAll), enabled); + monitorItemSetEnabled(int(FlipSwitchCurrent), enabled); + } else { // Compositing disabled + monitorItemSetEnabled(int(PresentWindowsCurrent), false); + monitorItemSetEnabled(int(PresentWindowsAll), false); + monitorItemSetEnabled(int(DesktopGrid), false); + monitorItemSetEnabled(int(Cube), false); + monitorItemSetEnabled(int(Cylinder), false); + monitorItemSetEnabled(int(Sphere), false); + monitorItemSetEnabled(int(FlipSwitchAll), false); + monitorItemSetEnabled(int(FlipSwitchCurrent), false); } +} -void KWinScreenEdgesConfig::monitorChangeEdge( ElectricBorder border, int index ) - { - switch( border ) - { - case ElectricTop: - m_ui->monitor->selectEdgeItem( int( Monitor::Top ), index ); - break; - case ElectricTopRight: - m_ui->monitor->selectEdgeItem( int( Monitor::TopRight ), index ); - break; - case ElectricRight: - m_ui->monitor->selectEdgeItem( int( Monitor::Right ), index ); - break; - case ElectricBottomRight: - m_ui->monitor->selectEdgeItem( int( Monitor::BottomRight ), index ); - break; - case ElectricBottom: - m_ui->monitor->selectEdgeItem( int( Monitor::Bottom ), index ); - break; - case ElectricBottomLeft: - m_ui->monitor->selectEdgeItem( int( Monitor::BottomLeft ), index ); - break; - case ElectricLeft: - m_ui->monitor->selectEdgeItem( int( Monitor::Left ), index ); - break; - case ElectricTopLeft: - m_ui->monitor->selectEdgeItem( int( Monitor::TopLeft ), index ); - break; - default: // Nothing - break; - } +void KWinScreenEdgesConfig::monitorChangeEdge(ElectricBorder border, int index) +{ + switch(border) { + case ElectricTop: + m_ui->monitor->selectEdgeItem(int(Monitor::Top), index); + break; + case ElectricTopRight: + m_ui->monitor->selectEdgeItem(int(Monitor::TopRight), index); + break; + case ElectricRight: + m_ui->monitor->selectEdgeItem(int(Monitor::Right), index); + break; + case ElectricBottomRight: + m_ui->monitor->selectEdgeItem(int(Monitor::BottomRight), index); + break; + case ElectricBottom: + m_ui->monitor->selectEdgeItem(int(Monitor::Bottom), index); + break; + case ElectricBottomLeft: + m_ui->monitor->selectEdgeItem(int(Monitor::BottomLeft), index); + break; + case ElectricLeft: + m_ui->monitor->selectEdgeItem(int(Monitor::Left), index); + break; + case ElectricTopLeft: + m_ui->monitor->selectEdgeItem(int(Monitor::TopLeft), index); + break; + default: // Nothing + break; } +} -void KWinScreenEdgesConfig::monitorHideEdge( ElectricBorder border, bool hidden ) - { - switch( border ) - { - case ElectricTop: - m_ui->monitor->setEdgeHidden( int( Monitor::Top ), hidden ); - break; - case ElectricTopRight: - m_ui->monitor->setEdgeHidden( int( Monitor::TopRight ), hidden ); - break; - case ElectricRight: - m_ui->monitor->setEdgeHidden( int( Monitor::Right ), hidden ); - break; - case ElectricBottomRight: - m_ui->monitor->setEdgeHidden( int( Monitor::BottomRight ), hidden ); - break; - case ElectricBottom: - m_ui->monitor->setEdgeHidden( int( Monitor::Bottom ), hidden ); - break; - case ElectricBottomLeft: - m_ui->monitor->setEdgeHidden( int( Monitor::BottomLeft ), hidden ); - break; - case ElectricLeft: - m_ui->monitor->setEdgeHidden( int( Monitor::Left ), hidden ); - break; - case ElectricTopLeft: - m_ui->monitor->setEdgeHidden( int( Monitor::TopLeft ), hidden ); - break; - default: // Nothing - break; - } +void KWinScreenEdgesConfig::monitorHideEdge(ElectricBorder border, bool hidden) +{ + switch(border) { + case ElectricTop: + m_ui->monitor->setEdgeHidden(int(Monitor::Top), hidden); + break; + case ElectricTopRight: + m_ui->monitor->setEdgeHidden(int(Monitor::TopRight), hidden); + break; + case ElectricRight: + m_ui->monitor->setEdgeHidden(int(Monitor::Right), hidden); + break; + case ElectricBottomRight: + m_ui->monitor->setEdgeHidden(int(Monitor::BottomRight), hidden); + break; + case ElectricBottom: + m_ui->monitor->setEdgeHidden(int(Monitor::Bottom), hidden); + break; + case ElectricBottomLeft: + m_ui->monitor->setEdgeHidden(int(Monitor::BottomLeft), hidden); + break; + case ElectricLeft: + m_ui->monitor->setEdgeHidden(int(Monitor::Left), hidden); + break; + case ElectricTopLeft: + m_ui->monitor->setEdgeHidden(int(Monitor::TopLeft), hidden); + break; + default: // Nothing + break; } +} -QList KWinScreenEdgesConfig::monitorCheckEffectHasEdge( int index ) const - { +QList KWinScreenEdgesConfig::monitorCheckEffectHasEdge(int index) const +{ QList list = QList(); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::Top )) == index ) - list.append( int( ElectricTop ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::TopRight )) == index ) - list.append( int( ElectricTopRight ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::Right )) == index ) - list.append( int( ElectricRight ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::BottomRight )) == index ) - list.append( int( ElectricBottomRight ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::Bottom )) == index ) - list.append( int( ElectricBottom ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::BottomLeft )) == index ) - list.append( int( ElectricBottomLeft ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::Left )) == index ) - list.append( int( ElectricLeft ) ); - if( m_ui->monitor->selectedEdgeItem( int( Monitor::TopLeft )) == index ) - list.append( int( ElectricTopLeft ) ); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::Top)) == index) + list.append(int(ElectricTop)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::TopRight)) == index) + list.append(int(ElectricTopRight)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::Right)) == index) + list.append(int(ElectricRight)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::BottomRight)) == index) + list.append(int(ElectricBottomRight)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::Bottom)) == index) + list.append(int(ElectricBottom)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::BottomLeft)) == index) + list.append(int(ElectricBottomLeft)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::Left)) == index) + list.append(int(ElectricLeft)); + if (m_ui->monitor->selectedEdgeItem(int(Monitor::TopLeft)) == index) + list.append(int(ElectricTopLeft)); - if( list.isEmpty() ) - list.append( int( ElectricNone ) ); + if (list.isEmpty()) + list.append(int(ElectricNone)); return list; - } +} } // namespace diff --git a/kcmkwin/kwinscreenedges/main.h b/kcmkwin/kwinscreenedges/main.h index 146f6e8ce..63e0a621b 100644 --- a/kcmkwin/kwinscreenedges/main.h +++ b/kcmkwin/kwinscreenedges/main.h @@ -35,62 +35,61 @@ namespace KWin { class KWinScreenEdgesConfigForm : public QWidget, public Ui::KWinScreenEdgesConfigForm - { +{ Q_OBJECT - public: - explicit KWinScreenEdgesConfigForm( QWidget* parent ); - }; +public: + explicit KWinScreenEdgesConfigForm(QWidget* parent); +}; class KWinScreenEdgesConfig : public KCModule - { +{ Q_OBJECT - public: - explicit KWinScreenEdgesConfig( QWidget* parent, const QVariantList& args ); - ~KWinScreenEdgesConfig(); +public: + explicit KWinScreenEdgesConfig(QWidget* parent, const QVariantList& args); + ~KWinScreenEdgesConfig(); - public slots: - virtual void groupChanged(); - virtual void save(); - virtual void load(); - virtual void defaults(); - protected: - virtual void showEvent( QShowEvent* e ); +public slots: + virtual void groupChanged(); + virtual void save(); + virtual void load(); + virtual void defaults(); +protected: + virtual void showEvent(QShowEvent* e); - private: - KWinScreenEdgesConfigForm* m_ui; - KSharedConfigPtr m_config; - CompositingPrefs m_defaultPrefs; +private: + KWinScreenEdgesConfigForm* m_ui; + KSharedConfigPtr m_config; + CompositingPrefs m_defaultPrefs; - enum EffectActions - { - PresentWindowsAll = ELECTRIC_ACTION_COUNT, // Start at the end of built in actions - PresentWindowsCurrent, - DesktopGrid, - Cube, - Cylinder, - Sphere, - FlipSwitchAll, - FlipSwitchCurrent - }; - - bool effectEnabled( const QString& effect, const KConfigGroup& cfg ) const; - - void monitorAddItem( const QString& item ); - void monitorItemSetEnabled( int index, bool enabled ); - void monitorInit(); - void monitorLoadAction( ElectricBorder edge, const QString& configName ); - void monitorLoad(); - void monitorSaveAction( int edge, const QString& configName ); - void monitorSave(); - void monitorDefaults(); - void monitorShowEvent(); - void monitorChangeEdge( ElectricBorder border, int index ); - void monitorHideEdge( ElectricBorder border, bool hidden ); - QList monitorCheckEffectHasEdge( int index ) const; + enum EffectActions { + PresentWindowsAll = ELECTRIC_ACTION_COUNT, // Start at the end of built in actions + PresentWindowsCurrent, + DesktopGrid, + Cube, + Cylinder, + Sphere, + FlipSwitchAll, + FlipSwitchCurrent }; + bool effectEnabled(const QString& effect, const KConfigGroup& cfg) const; + + void monitorAddItem(const QString& item); + void monitorItemSetEnabled(int index, bool enabled); + void monitorInit(); + void monitorLoadAction(ElectricBorder edge, const QString& configName); + void monitorLoad(); + void monitorSaveAction(int edge, const QString& configName); + void monitorSave(); + void monitorDefaults(); + void monitorShowEvent(); + void monitorChangeEdge(ElectricBorder border, int index); + void monitorHideEdge(ElectricBorder border, bool hidden); + QList monitorCheckEffectHasEdge(int index) const; +}; + } // namespace #endif diff --git a/kcmkwin/kwinscreenedges/monitor.cpp b/kcmkwin/kwinscreenedges/monitor.cpp index 7f234d08f..e28c414b8 100644 --- a/kcmkwin/kwinscreenedges/monitor.cpp +++ b/kcmkwin/kwinscreenedges/monitor.cpp @@ -36,215 +36,206 @@ along with this program. If not, see . namespace KWin { -Monitor::Monitor( QWidget* parent ) - : ScreenPreviewWidget( parent ) - { +Monitor::Monitor(QWidget* parent) + : ScreenPreviewWidget(parent) +{ QDesktopWidget *desktop = QApplication::desktop(); QRect avail = desktop->availableGeometry(desktop->screenNumber(this)); - setRatio((qreal)avail.width()/(qreal)avail.height()); - for( int i = 0; - i < 8; - ++i ) - popups[ i ] = new QMenu( this ); - scene = new QGraphicsScene( this ); - view = new QGraphicsView( scene, this ); - view->setBackgroundBrush( Qt::black ); - view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - view->setFocusPolicy( Qt::NoFocus ); - view->setFrameShape( QFrame::NoFrame ); - for( int i = 0; - i < 8; - ++i ) - { - items[ i ] = new Corner( this ); - scene->addItem( items[ i ] ); + setRatio((qreal)avail.width() / (qreal)avail.height()); + for (int i = 0; + i < 8; + ++i) + popups[ i ] = new QMenu(this); + scene = new QGraphicsScene(this); + view = new QGraphicsView(scene, this); + view->setBackgroundBrush(Qt::black); + view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view->setFocusPolicy(Qt::NoFocus); + view->setFrameShape(QFrame::NoFrame); + for (int i = 0; + i < 8; + ++i) { + items[ i ] = new Corner(this); + scene->addItem(items[ i ]); hidden[ i ] = false; - grp[ i ] = new QActionGroup( this ); - } - checkSize(); + grp[ i ] = new QActionGroup(this); } + checkSize(); +} void Monitor::clear() - { - for( int i = 0; - i < 8; - ++i ) - { +{ + for (int i = 0; + i < 8; + ++i) { popups[ i ]->clear(); - setEdge( i, false ); - setEdgeHidden( i, false ); + setEdge(i, false); + setEdgeHidden(i, false); delete grp[ i ]; - grp[ i ] = new QActionGroup( this ); - } + grp[ i ] = new QActionGroup(this); } +} -void Monitor::resizeEvent( QResizeEvent* e ) - { - ScreenPreviewWidget::resizeEvent( e ); +void Monitor::resizeEvent(QResizeEvent* e) +{ + ScreenPreviewWidget::resizeEvent(e); checkSize(); - } - +} + void Monitor::checkSize() - { +{ QRect contentsRect = previewRect(); //int w = 151; //int h = 115; view->setGeometry(contentsRect); - scene->setSceneRect(QRect(QPoint(0,0), contentsRect.size())); - int x2 = ( contentsRect.width() - 20 ) / 2; + scene->setSceneRect(QRect(QPoint(0, 0), contentsRect.size())); + int x2 = (contentsRect.width() - 20) / 2; int x3 = contentsRect.width() - 20; - int y2 = ( contentsRect.height() - 20 ) / 2; + int y2 = (contentsRect.height() - 20) / 2; int y3 = contentsRect.height() - 20; - items[ 0 ]->setRect( 0, y2, 20, 20 ); - items[ 1 ]->setRect( x3, y2, 20, 20 ); - items[ 2 ]->setRect( x2, 0, 20, 20 ); - items[ 3 ]->setRect( x2, y3, 20, 20 ); - items[ 4 ]->setRect( 0, 0, 20, 20 ); - items[ 5 ]->setRect( x3, 0, 20, 20 ); - items[ 6 ]->setRect( 0, y3, 20, 20 ); - items[ 7 ]->setRect( x3, y3, 20, 20 ); - } + items[ 0 ]->setRect(0, y2, 20, 20); + items[ 1 ]->setRect(x3, y2, 20, 20); + items[ 2 ]->setRect(x2, 0, 20, 20); + items[ 3 ]->setRect(x2, y3, 20, 20); + items[ 4 ]->setRect(0, 0, 20, 20); + items[ 5 ]->setRect(x3, 0, 20, 20); + items[ 6 ]->setRect(0, y3, 20, 20); + items[ 7 ]->setRect(x3, y3, 20, 20); +} -void Monitor::setEdge( int edge, bool set ) - { - items[ edge ]->setActive( set ); - } +void Monitor::setEdge(int edge, bool set) +{ + items[ edge ]->setActive(set); +} -bool Monitor::edge( int edge ) const - { +bool Monitor::edge(int edge) const +{ return items[ edge ]->brush() == Qt::green; - } +} -void Monitor::setEdgeHidden( int edge, bool set ) - { +void Monitor::setEdgeHidden(int edge, bool set) +{ hidden[ edge ] = set; - if( set ) + if (set) items[ edge ]->hide(); else items[ edge ]->show(); - } +} -bool Monitor::edgeHidden( int edge ) const - { +bool Monitor::edgeHidden(int edge) const +{ return hidden[ edge ]; - } +} -void Monitor::addEdgeItem( int edge, const QString& item ) - { - QAction* act = popups[ edge ]->addAction( item ); - act->setCheckable( true ); - popup_actions[ edge ].append( act ); - grp[ edge ]->addAction( act ); - if( popup_actions[ edge ].count() == 1 ) - { - act->setChecked( true ); - items[ edge ]->setToolTip( item ); - } - setEdge( edge, !popup_actions[ edge ][ 0 ]->isChecked()); +void Monitor::addEdgeItem(int edge, const QString& item) +{ + QAction* act = popups[ edge ]->addAction(item); + act->setCheckable(true); + popup_actions[ edge ].append(act); + grp[ edge ]->addAction(act); + if (popup_actions[ edge ].count() == 1) { + act->setChecked(true); + items[ edge ]->setToolTip(item); } + setEdge(edge, !popup_actions[ edge ][ 0 ]->isChecked()); +} -void Monitor::setEdgeItemEnabled( int edge, int index, bool enabled ) - { - popup_actions[ edge ][ index ]->setEnabled( enabled ); - } +void Monitor::setEdgeItemEnabled(int edge, int index, bool enabled) +{ + popup_actions[ edge ][ index ]->setEnabled(enabled); +} -bool Monitor::edgeItemEnabled( int edge, int index ) const - { +bool Monitor::edgeItemEnabled(int edge, int index) const +{ return popup_actions[ edge ][ index ]->isEnabled(); - } +} -void Monitor::selectEdgeItem( int edge, int index ) - { - popup_actions[ edge ][ index ]->setChecked( true ); - setEdge( edge, !popup_actions[ edge ][ 0 ]->isChecked()); +void Monitor::selectEdgeItem(int edge, int index) +{ + popup_actions[ edge ][ index ]->setChecked(true); + setEdge(edge, !popup_actions[ edge ][ 0 ]->isChecked()); QString actionText = popup_actions[ edge ][ index ]->text(); // remove accelerators added by KAcceleratorManager - actionText = KGlobal::locale()->removeAcceleratorMarker( actionText ); - items[ edge ]->setToolTip( actionText ); - } + actionText = KGlobal::locale()->removeAcceleratorMarker(actionText); + items[ edge ]->setToolTip(actionText); +} -int Monitor::selectedEdgeItem( int edge ) const - { - foreach( QAction* act, popup_actions[ edge ] ) - if( act->isChecked()) - return popup_actions[ edge ].indexOf( act ); +int Monitor::selectedEdgeItem(int edge) const +{ + foreach (QAction * act, popup_actions[ edge ]) + if (act->isChecked()) + return popup_actions[ edge ].indexOf(act); abort(); - } +} -void Monitor::popup( Corner* c, QPoint pos ) - { - for( int i = 0; - i < 8; - ++i ) - { - if( items[ i ] == c ) - { - if( popup_actions[ i ].count() == 0 ) +void Monitor::popup(Corner* c, QPoint pos) +{ + for (int i = 0; + i < 8; + ++i) { + if (items[ i ] == c) { + if (popup_actions[ i ].count() == 0) return; - if( QAction* a = popups[ i ]->exec( pos )) - { - selectEdgeItem( i, popup_actions[ i ].indexOf( a )); + if (QAction* a = popups[ i ]->exec(pos)) { + selectEdgeItem(i, popup_actions[ i ].indexOf(a)); emit changed(); - emit edgeSelectionChanged( i, popup_actions[ i ].indexOf( a )); - c->setToolTip( KGlobal::locale()->removeAcceleratorMarker( a->text() )); - } - return; + emit edgeSelectionChanged(i, popup_actions[ i ].indexOf(a)); + c->setToolTip(KGlobal::locale()->removeAcceleratorMarker(a->text())); } + return; } - abort(); } + abort(); +} -void Monitor::flip( Corner* c, QPoint pos ) - { - for( int i = 0; - i < 8; - ++i ) - { - if( items[ i ] == c ) - { - if( popup_actions[ i ].count() == 0 ) - setEdge( i, !edge( i )); +void Monitor::flip(Corner* c, QPoint pos) +{ + for (int i = 0; + i < 8; + ++i) { + if (items[ i ] == c) { + if (popup_actions[ i ].count() == 0) + setEdge(i, !edge(i)); else - popup( c, pos ); + popup(c, pos); return; - } } - abort(); } + abort(); +} -Monitor::Corner::Corner( Monitor* m ) - : monitor( m ), - m_active( false ), - m_hover( false ) - { +Monitor::Corner::Corner(Monitor* m) + : monitor(m), + m_active(false), + m_hover(false) +{ button = new Plasma::FrameSvg(); button->setImagePath("widgets/button"); setAcceptHoverEvents(true); - } +} -Monitor::Corner::~Corner( ) - { +Monitor::Corner::~Corner() +{ delete button; - } +} -void Monitor::Corner::contextMenuEvent( QGraphicsSceneContextMenuEvent* e ) - { - monitor->popup( this, e->screenPos()); - } +void Monitor::Corner::contextMenuEvent(QGraphicsSceneContextMenuEvent* e) +{ + monitor->popup(this, e->screenPos()); +} -void Monitor::Corner::mousePressEvent( QGraphicsSceneMouseEvent* e ) - { - monitor->flip( this, e->screenPos()); - } +void Monitor::Corner::mousePressEvent(QGraphicsSceneMouseEvent* e) +{ + monitor->flip(this, e->screenPos()); +} -void Monitor::Corner::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget ) - { +void Monitor::Corner::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +{ Q_UNUSED(option) Q_UNUSED(widget) - if (m_hover) - { + if (m_hover) { button->setElementPrefix("normal"); qreal left, top, right, bottom; @@ -256,51 +247,48 @@ void Monitor::Corner::paint( QPainter* painter, const QStyleOptionGraphicsItem* QRectF activeRect = QRectF(QPointF(0, 0), rect().size()); activeRect.adjust(left - activeLeft, top - activeTop, - -(right - activeRight), -(bottom - activeBottom)); + -(right - activeRight), -(bottom - activeBottom)); button->setElementPrefix("active"); button->resizeFrame(activeRect.size()); - button->paintFrame(painter, rect().topLeft()+activeRect.topLeft()); - } - else - { - button->setElementPrefix(m_active?"pressed":"normal"); + button->paintFrame(painter, rect().topLeft() + activeRect.topLeft()); + } else { + button->setElementPrefix(m_active ? "pressed" : "normal"); button->resizeFrame(rect().size()); button->paintFrame(painter, rect().topLeft()); - } - - if (m_active) - { - QPainterPath roundedRect; - painter->setRenderHint(QPainter::Antialiasing); - roundedRect.addRoundedRect(rect().adjusted(5,5,-5,-5), 2, 2); - painter->fillPath(roundedRect, QApplication::palette().text()); - } } -void Monitor::Corner::hoverEnterEvent( QGraphicsSceneHoverEvent * e) + if (m_active) { + QPainterPath roundedRect; + painter->setRenderHint(QPainter::Antialiasing); + roundedRect.addRoundedRect(rect().adjusted(5, 5, -5, -5), 2, 2); + painter->fillPath(roundedRect, QApplication::palette().text()); + } +} + +void Monitor::Corner::hoverEnterEvent(QGraphicsSceneHoverEvent * e) { - Q_UNUSED( e ); + Q_UNUSED(e); m_hover = true; update(); } -void Monitor::Corner::hoverLeaveEvent( QGraphicsSceneHoverEvent * e) +void Monitor::Corner::hoverLeaveEvent(QGraphicsSceneHoverEvent * e) { - Q_UNUSED( e ); + Q_UNUSED(e); m_hover = false; update(); } -void Monitor::Corner::setActive( bool active ) - { +void Monitor::Corner::setActive(bool active) +{ m_active = active; update(); - } +} bool Monitor::Corner::active() const - { +{ return m_active; - } +} } // namespace #include "monitor.moc" diff --git a/kcmkwin/kwinscreenedges/monitor.h b/kcmkwin/kwinscreenedges/monitor.h index 3c5e65246..bf0392eff 100644 --- a/kcmkwin/kwinscreenedges/monitor.h +++ b/kcmkwin/kwinscreenedges/monitor.h @@ -35,7 +35,7 @@ class QMenu; namespace Plasma { - class FrameSvg; +class FrameSvg; } namespace KWin @@ -43,71 +43,70 @@ namespace KWin class Monitor : public ScreenPreviewWidget - { +{ Q_OBJECT - public: - Monitor( QWidget* parent ); - void setEdge( int edge, bool set ); - bool edge( int edge ) const; - void setEdgeHidden( int edge, bool set ); - bool edgeHidden( int edge ) const; - void clear(); - void addEdgeItem( int edge, const QString& item ); - void setEdgeItemEnabled( int edge, int index, bool enabled ); - bool edgeItemEnabled( int edge, int index ) const; - void selectEdgeItem( int edge, int index ); - int selectedEdgeItem( int edge ) const; +public: + Monitor(QWidget* parent); + void setEdge(int edge, bool set); + bool edge(int edge) const; + void setEdgeHidden(int edge, bool set); + bool edgeHidden(int edge) const; + void clear(); + void addEdgeItem(int edge, const QString& item); + void setEdgeItemEnabled(int edge, int index, bool enabled); + bool edgeItemEnabled(int edge, int index) const; + void selectEdgeItem(int edge, int index); + int selectedEdgeItem(int edge) const; - enum Edges - { - Left, - Right, - Top, - Bottom, - TopLeft, - TopRight, - BottomLeft, - BottomRight - }; - signals: - void changed(); - void edgeSelectionChanged( int edge, int index ); - protected: - virtual void resizeEvent( QResizeEvent* e ); - private: - class Corner; - void popup( Corner* c, QPoint pos ); - void flip( Corner* c, QPoint pos ); - void checkSize(); - QGraphicsView* view; - QGraphicsScene* scene; - Corner* items[ 8 ]; - bool hidden[ 8 ]; - QMenu* popups[ 8 ]; - QVector< QAction* > popup_actions[ 8 ]; - QActionGroup* grp[ 8 ]; + enum Edges { + Left, + Right, + Top, + Bottom, + TopLeft, + TopRight, + BottomLeft, + BottomRight }; +signals: + void changed(); + void edgeSelectionChanged(int edge, int index); +protected: + virtual void resizeEvent(QResizeEvent* e); +private: + class Corner; + void popup(Corner* c, QPoint pos); + void flip(Corner* c, QPoint pos); + void checkSize(); + QGraphicsView* view; + QGraphicsScene* scene; + Corner* items[ 8 ]; + bool hidden[ 8 ]; + QMenu* popups[ 8 ]; + QVector< QAction* > popup_actions[ 8 ]; + QActionGroup* grp[ 8 ]; +}; class Monitor::Corner : public QGraphicsRectItem - { - public: - Corner( Monitor* m ); - ~Corner( ); - void setActive(bool active); - bool active() const; - protected: - virtual void contextMenuEvent( QGraphicsSceneContextMenuEvent* e ); - virtual void mousePressEvent( QGraphicsSceneMouseEvent* e ); - virtual void hoverEnterEvent( QGraphicsSceneHoverEvent * e); - virtual void hoverLeaveEvent( QGraphicsSceneHoverEvent * e); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); - private: - Monitor* monitor; - Plasma::FrameSvg *button; - bool m_active; - bool m_hover; - }; +{ +public: + Corner(Monitor* m); + ~Corner(); + void setActive(bool active); + bool active() const; +protected: + virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent* e); + virtual void mousePressEvent(QGraphicsSceneMouseEvent* e); + virtual void hoverEnterEvent(QGraphicsSceneHoverEvent * e); + virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent * e); + virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); +private: + Monitor* monitor; + Plasma::FrameSvg *button; + bool m_active; + bool m_hover; +}; } // namespace diff --git a/kcmkwin/kwintabbox/layoutconfig.cpp b/kcmkwin/kwintabbox/layoutconfig.cpp index cce16288a..058f398c6 100644 --- a/kcmkwin/kwintabbox/layoutconfig.cpp +++ b/kcmkwin/kwintabbox/layoutconfig.cpp @@ -32,191 +32,164 @@ namespace TabBox * LayoutConfigPrivate ***************************************************/ class LayoutConfigPrivate - { - public: - LayoutConfigPrivate(); - ~LayoutConfigPrivate() { } +{ +public: + LayoutConfigPrivate(); + ~LayoutConfigPrivate() { } TabBoxConfig config; Ui::LayoutConfigForm ui; - }; +}; LayoutConfigPrivate::LayoutConfigPrivate() - { - } +{ +} /*************************************************** * LayoutConfig ***************************************************/ LayoutConfig::LayoutConfig(QWidget* parent) : QWidget(parent) - { +{ d = new LayoutConfigPrivate; - d->ui.setupUi( this ); + d->ui.setupUi(this); // init the item layout combo box - d->ui.itemLayoutCombo->addItem( i18n("Informative") ); - d->ui.itemLayoutCombo->addItem( i18n("Compact") ); - d->ui.itemLayoutCombo->addItem( i18n("Small Icons") ); - d->ui.itemLayoutCombo->addItem( i18n("Large Icons") ); - d->ui.itemLayoutCombo->addItem( i18n("Text Only") ); + d->ui.itemLayoutCombo->addItem(i18n("Informative")); + d->ui.itemLayoutCombo->addItem(i18n("Compact")); + d->ui.itemLayoutCombo->addItem(i18n("Small Icons")); + d->ui.itemLayoutCombo->addItem(i18n("Large Icons")); + d->ui.itemLayoutCombo->addItem(i18n("Text Only")); // TODO: user defined layouts // init the selected item layout combo box - d->ui.selectedItemLayoutCombo->addItem( i18n("Informative") ); - d->ui.selectedItemLayoutCombo->addItem( i18n("Compact") ); - d->ui.selectedItemLayoutCombo->addItem( i18n("Small Icons") ); - d->ui.selectedItemLayoutCombo->addItem( i18n("Large Icons") ); - d->ui.selectedItemLayoutCombo->addItem( i18n("Text Only") ); + d->ui.selectedItemLayoutCombo->addItem(i18n("Informative")); + d->ui.selectedItemLayoutCombo->addItem(i18n("Compact")); + d->ui.selectedItemLayoutCombo->addItem(i18n("Small Icons")); + d->ui.selectedItemLayoutCombo->addItem(i18n("Large Icons")); + d->ui.selectedItemLayoutCombo->addItem(i18n("Text Only")); - connect( d->ui.minWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changed()) ); - connect( d->ui.minHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changed()) ); - connect( d->ui.itemLayoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed()) ); - connect( d->ui.layoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed()) ); - connect( d->ui.selectedItemCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed()) ); - connect( d->ui.selectedItemLayoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed()) ); - connect( d->ui.selectedItemBox, SIGNAL(clicked(bool)), this, SLOT(changed()) ); + connect(d->ui.minWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(d->ui.minHeightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changed())); + connect(d->ui.itemLayoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(d->ui.layoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(d->ui.selectedItemCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(d->ui.selectedItemLayoutCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(d->ui.selectedItemBox, SIGNAL(clicked(bool)), this, SLOT(changed())); - } +} LayoutConfig::~LayoutConfig() - { +{ delete d; - } +} TabBoxConfig& LayoutConfig::config() const - { +{ return d->config; - } +} -void LayoutConfig::setConfig( const KWin::TabBox::TabBoxConfig& config ) - { +void LayoutConfig::setConfig(const KWin::TabBox::TabBoxConfig& config) +{ d->config = config; - d->ui.selectedItemBox->setChecked( config.selectedItemViewPosition() != TabBoxConfig::NonePosition ); + d->ui.selectedItemBox->setChecked(config.selectedItemViewPosition() != TabBoxConfig::NonePosition); - d->ui.layoutCombo->setCurrentIndex( config.layout() ); - d->ui.selectedItemCombo->setCurrentIndex( config.selectedItemViewPosition() - 1 ); + d->ui.layoutCombo->setCurrentIndex(config.layout()); + d->ui.selectedItemCombo->setCurrentIndex(config.selectedItemViewPosition() - 1); - d->ui.minWidthSpinBox->setValue( config.minWidth() ); - d->ui.minHeightSpinBox->setValue( config.minHeight() ); + d->ui.minWidthSpinBox->setValue(config.minWidth()); + d->ui.minHeightSpinBox->setValue(config.minHeight()); // item layouts - if( config.layoutName().compare( "Default", Qt::CaseInsensitive ) == 0 ) - { - d->ui.itemLayoutCombo->setCurrentIndex( 0 ); - } - else if( config.layoutName().compare( "Compact", Qt::CaseInsensitive ) == 0 ) - { - d->ui.itemLayoutCombo->setCurrentIndex( 1 ); - } - else if( config.layoutName().compare( "Small Icons", Qt::CaseInsensitive ) == 0 ) - { - d->ui.itemLayoutCombo->setCurrentIndex( 2 ); - } - else if( config.layoutName().compare( "Big Icons", Qt::CaseInsensitive ) == 0 ) - { - d->ui.itemLayoutCombo->setCurrentIndex( 3 ); - } - else if( config.layoutName().compare( "Text", Qt::CaseInsensitive ) == 0 ) - { - d->ui.itemLayoutCombo->setCurrentIndex( 4 ); - } - else - { + if (config.layoutName().compare("Default", Qt::CaseInsensitive) == 0) { + d->ui.itemLayoutCombo->setCurrentIndex(0); + } else if (config.layoutName().compare("Compact", Qt::CaseInsensitive) == 0) { + d->ui.itemLayoutCombo->setCurrentIndex(1); + } else if (config.layoutName().compare("Small Icons", Qt::CaseInsensitive) == 0) { + d->ui.itemLayoutCombo->setCurrentIndex(2); + } else if (config.layoutName().compare("Big Icons", Qt::CaseInsensitive) == 0) { + d->ui.itemLayoutCombo->setCurrentIndex(3); + } else if (config.layoutName().compare("Text", Qt::CaseInsensitive) == 0) { + d->ui.itemLayoutCombo->setCurrentIndex(4); + } else { // TODO: user defined layouts - } - - if( config.selectedItemLayoutName().compare( "Default", Qt::CaseInsensitive ) == 0 ) - { - d->ui.selectedItemLayoutCombo->setCurrentIndex( 0 ); - } - else if( config.selectedItemLayoutName().compare( "Compact", Qt::CaseInsensitive ) == 0 ) - { - d->ui.selectedItemLayoutCombo->setCurrentIndex( 1 ); - } - else if( config.selectedItemLayoutName().compare( "Small Icons", Qt::CaseInsensitive ) == 0 ) - { - d->ui.selectedItemLayoutCombo->setCurrentIndex( 2 ); - } - else if( config.selectedItemLayoutName().compare( "Big Icons", Qt::CaseInsensitive ) == 0 ) - { - d->ui.selectedItemLayoutCombo->setCurrentIndex( 3 ); - } - else if( config.selectedItemLayoutName().compare( "Text", Qt::CaseInsensitive ) == 0 ) - { - d->ui.selectedItemLayoutCombo->setCurrentIndex( 4 ); - } - else - { - // TODO: user defined layouts - } - } + if (config.selectedItemLayoutName().compare("Default", Qt::CaseInsensitive) == 0) { + d->ui.selectedItemLayoutCombo->setCurrentIndex(0); + } else if (config.selectedItemLayoutName().compare("Compact", Qt::CaseInsensitive) == 0) { + d->ui.selectedItemLayoutCombo->setCurrentIndex(1); + } else if (config.selectedItemLayoutName().compare("Small Icons", Qt::CaseInsensitive) == 0) { + d->ui.selectedItemLayoutCombo->setCurrentIndex(2); + } else if (config.selectedItemLayoutName().compare("Big Icons", Qt::CaseInsensitive) == 0) { + d->ui.selectedItemLayoutCombo->setCurrentIndex(3); + } else if (config.selectedItemLayoutName().compare("Text", Qt::CaseInsensitive) == 0) { + d->ui.selectedItemLayoutCombo->setCurrentIndex(4); + } else { + // TODO: user defined layouts + } + +} + void LayoutConfig::changed() - { +{ // it's actually overkill but we just sync all options - d->config.setMinWidth( d->ui.minWidthSpinBox->value() ); - d->config.setMinHeight( d->ui.minHeightSpinBox->value() ); - d->config.setLayout( TabBoxConfig::LayoutMode( d->ui.layoutCombo->currentIndex() ) ); + d->config.setMinWidth(d->ui.minWidthSpinBox->value()); + d->config.setMinHeight(d->ui.minHeightSpinBox->value()); + d->config.setLayout(TabBoxConfig::LayoutMode(d->ui.layoutCombo->currentIndex())); QString layout; - switch( d->ui.itemLayoutCombo->currentIndex() ) - { + switch(d->ui.itemLayoutCombo->currentIndex()) { + case 0: + layout = "Default"; + break; + case 1: + layout = "Compact"; + break; + case 2: + layout = "Small Icons"; + break; + case 3: + layout = "Big Icons"; + break; + case 4: + layout = "Text"; + break; + default: + // TODO: user defined layouts + break; + } + d->config.setLayoutName(layout); + + if (d->ui.selectedItemBox->isChecked()) { + d->config.setSelectedItemViewPosition(TabBoxConfig::SelectedItemViewPosition( + d->ui.selectedItemCombo->currentIndex() + 1)); + QString selectedLayout; + switch(d->ui.selectedItemLayoutCombo->currentIndex()) { case 0: - layout = "Default"; + selectedLayout = "Default"; break; case 1: - layout = "Compact"; + selectedLayout = "Compact"; break; case 2: - layout = "Small Icons"; + selectedLayout = "Small Icons"; break; case 3: - layout = "Big Icons"; + selectedLayout = "Big Icons"; break; case 4: - layout = "Text"; + selectedLayout = "Text"; break; default: // TODO: user defined layouts break; } - d->config.setLayoutName( layout ); - - if( d->ui.selectedItemBox->isChecked() ) - { - d->config.setSelectedItemViewPosition( TabBoxConfig::SelectedItemViewPosition( - d->ui.selectedItemCombo->currentIndex() + 1) ); - QString selectedLayout; - switch( d->ui.selectedItemLayoutCombo->currentIndex() ) - { - case 0: - selectedLayout = "Default"; - break; - case 1: - selectedLayout = "Compact"; - break; - case 2: - selectedLayout = "Small Icons"; - break; - case 3: - selectedLayout = "Big Icons"; - break; - case 4: - selectedLayout = "Text"; - break; - default: - // TODO: user defined layouts - break; - } - d->config.setSelectedItemLayoutName( selectedLayout ); - } - else - { - d->config.setSelectedItemViewPosition( TabBoxConfig::NonePosition ); - } + d->config.setSelectedItemLayoutName(selectedLayout); + } else { + d->config.setSelectedItemViewPosition(TabBoxConfig::NonePosition); } +} } // namespace KWin } // namespace TabBox diff --git a/kcmkwin/kwintabbox/layoutconfig.h b/kcmkwin/kwintabbox/layoutconfig.h index b76698d32..3ee887bac 100644 --- a/kcmkwin/kwintabbox/layoutconfig.h +++ b/kcmkwin/kwintabbox/layoutconfig.h @@ -32,22 +32,22 @@ class TabBoxConfig; class LayoutConfigPrivate; class LayoutConfig : public QWidget - { +{ Q_OBJECT - public: - LayoutConfig( QWidget* parent = NULL ); - ~LayoutConfig(); +public: + LayoutConfig(QWidget* parent = NULL); + ~LayoutConfig(); - void setConfig( const TabBoxConfig& config ); - TabBoxConfig& config() const; + void setConfig(const TabBoxConfig& config); + TabBoxConfig& config() const; - private slots: - void changed(); +private slots: + void changed(); - private: - LayoutConfigPrivate* d; - }; +private: + LayoutConfigPrivate* d; +}; } // namespace TabBox } // namespace KWin diff --git a/kcmkwin/kwintabbox/main.cpp b/kcmkwin/kwintabbox/main.cpp index cf1917322..51b9b4fb9 100644 --- a/kcmkwin/kwintabbox/main.cpp +++ b/kcmkwin/kwintabbox/main.cpp @@ -40,62 +40,62 @@ along with this program. If not, see . #include "tabboxconfig.h" #include "layoutconfig.h" -K_PLUGIN_FACTORY( KWinTabBoxConfigFactory, registerPlugin(); ) -K_EXPORT_PLUGIN( KWinTabBoxConfigFactory( "kcm_kwintabbox" )) +K_PLUGIN_FACTORY(KWinTabBoxConfigFactory, registerPlugin();) +K_EXPORT_PLUGIN(KWinTabBoxConfigFactory("kcm_kwintabbox")) namespace KWin { -KWinTabBoxConfigForm::KWinTabBoxConfigForm( QWidget* parent ) - : QWidget( parent ) - { - setupUi( this ); - } +KWinTabBoxConfigForm::KWinTabBoxConfigForm(QWidget* parent) + : QWidget(parent) +{ + setupUi(this); +} -KWinTabBoxConfig::KWinTabBoxConfig( QWidget* parent, const QVariantList& args ) - : KCModule( KWinTabBoxConfigFactory::componentData(), parent, args ) - , m_config( KSharedConfig::openConfig( "kwinrc" )) - { - KGlobal::locale()->insertCatalog( "kwin_effects" ); - KTabWidget* tabWidget = new KTabWidget( this ); - m_primaryTabBoxUi = new KWinTabBoxConfigForm( tabWidget ); - m_alternativeTabBoxUi = new KWinTabBoxConfigForm( tabWidget ); +KWinTabBoxConfig::KWinTabBoxConfig(QWidget* parent, const QVariantList& args) + : KCModule(KWinTabBoxConfigFactory::componentData(), parent, args) + , m_config(KSharedConfig::openConfig("kwinrc")) +{ + KGlobal::locale()->insertCatalog("kwin_effects"); + KTabWidget* tabWidget = new KTabWidget(this); + m_primaryTabBoxUi = new KWinTabBoxConfigForm(tabWidget); + m_alternativeTabBoxUi = new KWinTabBoxConfigForm(tabWidget); m_alternativeTabBoxUi->description->setText( - i18n( "These settings are used by the \"Walk Through Windows Alternative\" actions." )); - tabWidget->addTab( m_primaryTabBoxUi, i18n("Main") ); - tabWidget->addTab( m_alternativeTabBoxUi, i18n("Alternative") ); - QVBoxLayout* layout = new QVBoxLayout( this ); - KTitleWidget* infoLabel = new KTitleWidget( tabWidget ); - infoLabel->setText( i18n("Focus policy settings limit the functionality of navigating through windows."), - KTitleWidget::InfoMessage ); - infoLabel->setPixmap( KTitleWidget::InfoMessage, KTitleWidget::ImageLeft ); - layout->addWidget( infoLabel ); - layout->addWidget( tabWidget ); + i18n("These settings are used by the \"Walk Through Windows Alternative\" actions.")); + tabWidget->addTab(m_primaryTabBoxUi, i18n("Main")); + tabWidget->addTab(m_alternativeTabBoxUi, i18n("Alternative")); + QVBoxLayout* layout = new QVBoxLayout(this); + KTitleWidget* infoLabel = new KTitleWidget(tabWidget); + infoLabel->setText(i18n("Focus policy settings limit the functionality of navigating through windows."), + KTitleWidget::InfoMessage); + infoLabel->setPixmap(KTitleWidget::InfoMessage, KTitleWidget::ImageLeft); + layout->addWidget(infoLabel); + layout->addWidget(tabWidget); - m_editor = new KShortcutsEditor( m_primaryTabBoxUi, KShortcutsEditor::GlobalAction ); + m_editor = new KShortcutsEditor(m_primaryTabBoxUi, KShortcutsEditor::GlobalAction); // Shortcut config. The shortcut belongs to the component "kwin"! - m_actionCollection = new KActionCollection( this, KComponentData("kwin") ); - m_actionCollection->setConfigGroup( "Navigation" ); - m_actionCollection->setConfigGlobal( true ); - KAction* a = qobject_cast(m_actionCollection->addAction( "Walk Through Windows" )); + m_actionCollection = new KActionCollection(this, KComponentData("kwin")); + m_actionCollection->setConfigGroup("Navigation"); + m_actionCollection->setConfigGlobal(true); + KAction* a = qobject_cast(m_actionCollection->addAction("Walk Through Windows")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Walk Through Windows" )); - a->setGlobalShortcut( KShortcut( Qt::ALT+Qt::Key_Tab ) ); - a = qobject_cast(m_actionCollection->addAction( "Walk Through Windows (Reverse)" )); + a->setText(i18n("Walk Through Windows")); + a->setGlobalShortcut(KShortcut(Qt::ALT + Qt::Key_Tab)); + a = qobject_cast(m_actionCollection->addAction("Walk Through Windows (Reverse)")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Walk Through Windows (Reverse)" )); - a->setGlobalShortcut( KShortcut( Qt::ALT+Qt::SHIFT+Qt::Key_Backtab ) ); - a = qobject_cast(m_actionCollection->addAction( "Walk Through Windows Alternative" )); + a->setText(i18n("Walk Through Windows (Reverse)")); + a->setGlobalShortcut(KShortcut(Qt::ALT + Qt::SHIFT + Qt::Key_Backtab)); + a = qobject_cast(m_actionCollection->addAction("Walk Through Windows Alternative")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Walk Through Windows Alternative" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); - a = qobject_cast(m_actionCollection->addAction( "Walk Through Windows Alternative (Reverse)" )); + a->setText(i18n("Walk Through Windows Alternative")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); + a = qobject_cast(m_actionCollection->addAction("Walk Through Windows Alternative (Reverse)")); a->setProperty("isConfigurationAction", true); - a->setText( i18n( "Walk Through Windows Alternative (Reverse)" )); - a->setGlobalShortcut( KShortcut(), KAction::ActiveShortcut ); - m_editor->addCollection( m_actionCollection, i18n( "Navigation" ) ); - layout->addWidget( m_editor ); - setLayout( layout ); + a->setText(i18n("Walk Through Windows Alternative (Reverse)")); + a->setGlobalShortcut(KShortcut(), KAction::ActiveShortcut); + m_editor->addCollection(m_actionCollection, i18n("Navigation")); + layout->addWidget(m_editor); + setLayout(layout); // search the effect names // TODO: way to recognize if a effect is not found @@ -106,203 +106,197 @@ KWinTabBoxConfig::KWinTabBoxConfig( QWidget* parent, const QVariantList& args ) QString coverswitch; QString flipswitch; services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_boxswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) boxswitch = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_presentwindows'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) presentwindows = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_coverswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) coverswitch = services.first()->name(); services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_flipswitch'"); - if( !services.isEmpty() ) + if (!services.isEmpty()) flipswitch = services.first()->name(); - m_primaryTabBoxUi->effectCombo->addItem( i18n("No Effect") ); - m_primaryTabBoxUi->effectCombo->addItem( boxswitch ); - m_primaryTabBoxUi->effectCombo->addItem( presentwindows ); - m_primaryTabBoxUi->effectCombo->addItem( coverswitch ); - m_primaryTabBoxUi->effectCombo->addItem( flipswitch ); + m_primaryTabBoxUi->effectCombo->addItem(i18n("No Effect")); + m_primaryTabBoxUi->effectCombo->addItem(boxswitch); + m_primaryTabBoxUi->effectCombo->addItem(presentwindows); + m_primaryTabBoxUi->effectCombo->addItem(coverswitch); + m_primaryTabBoxUi->effectCombo->addItem(flipswitch); - m_alternativeTabBoxUi->effectCombo->addItem( i18n("No Effect") ); - m_alternativeTabBoxUi->effectCombo->addItem( boxswitch ); - m_alternativeTabBoxUi->effectCombo->addItem( presentwindows ); - m_alternativeTabBoxUi->effectCombo->addItem( coverswitch ); - m_alternativeTabBoxUi->effectCombo->addItem( flipswitch ); + m_alternativeTabBoxUi->effectCombo->addItem(i18n("No Effect")); + m_alternativeTabBoxUi->effectCombo->addItem(boxswitch); + m_alternativeTabBoxUi->effectCombo->addItem(presentwindows); + m_alternativeTabBoxUi->effectCombo->addItem(coverswitch); + m_alternativeTabBoxUi->effectCombo->addItem(flipswitch); // effect config and info button - m_primaryTabBoxUi->effectInfoButton->setIcon( KIcon( "dialog-information" )); - m_primaryTabBoxUi->effectConfigButton->setIcon( KIcon( "configure" )); - m_alternativeTabBoxUi->effectInfoButton->setIcon( KIcon( "dialog-information" )); - m_alternativeTabBoxUi->effectConfigButton->setIcon( KIcon( "configure" )); + m_primaryTabBoxUi->effectInfoButton->setIcon(KIcon("dialog-information")); + m_primaryTabBoxUi->effectConfigButton->setIcon(KIcon("configure")); + m_alternativeTabBoxUi->effectInfoButton->setIcon(KIcon("dialog-information")); + m_alternativeTabBoxUi->effectConfigButton->setIcon(KIcon("configure")); // combo boxes - connect( m_primaryTabBoxUi->listModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); - connect( m_primaryTabBoxUi->switchingModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); - connect( m_primaryTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->listModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->switchingModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); // check boxes - connect( m_primaryTabBoxUi->showOutlineCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( m_primaryTabBoxUi->showTabBox, SIGNAL(toggled(bool)), this, SLOT(changed())); - connect( m_primaryTabBoxUi->highlightWindowCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( m_primaryTabBoxUi->showDesktopBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->showOutlineCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->showTabBox, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->highlightWindowCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_primaryTabBoxUi->showDesktopBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); // combo boxes alternative - connect( m_alternativeTabBoxUi->listModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); - connect( m_alternativeTabBoxUi->switchingModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); - connect( m_alternativeTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->listModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->switchingModeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changed())); // check boxes alternative - connect( m_alternativeTabBoxUi->showOutlineCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( m_alternativeTabBoxUi->showTabBox, SIGNAL(toggled(bool)), this, SLOT(changed())); - connect( m_alternativeTabBoxUi->highlightWindowCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); - connect( m_alternativeTabBoxUi->showDesktopBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->showOutlineCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->showTabBox, SIGNAL(toggled(bool)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->highlightWindowCheck, SIGNAL(stateChanged(int)), this, SLOT(changed())); + connect(m_alternativeTabBoxUi->showDesktopBox, SIGNAL(stateChanged(int)), this, SLOT(changed())); // effects - connect( m_primaryTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotEffectSelectionChanged(int))); - connect( m_primaryTabBoxUi->effectInfoButton, SIGNAL(clicked(bool)), this, SLOT(slotAboutEffectClicked())); - connect( m_primaryTabBoxUi->effectConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureEffectClicked())); + connect(m_primaryTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotEffectSelectionChanged(int))); + connect(m_primaryTabBoxUi->effectInfoButton, SIGNAL(clicked(bool)), this, SLOT(slotAboutEffectClicked())); + connect(m_primaryTabBoxUi->effectConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureEffectClicked())); - connect( m_primaryTabBoxUi->layoutConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureLayoutClicked())); + connect(m_primaryTabBoxUi->layoutConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureLayoutClicked())); // effects alternative - connect( m_alternativeTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotEffectSelectionChangedAlternative(int))); - connect( m_alternativeTabBoxUi->effectInfoButton, SIGNAL(clicked(bool)), this, SLOT(slotAboutEffectClickedAlternative())); - connect( m_alternativeTabBoxUi->effectConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureEffectClickedAlternative())); + connect(m_alternativeTabBoxUi->effectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(slotEffectSelectionChangedAlternative(int))); + connect(m_alternativeTabBoxUi->effectInfoButton, SIGNAL(clicked(bool)), this, SLOT(slotAboutEffectClickedAlternative())); + connect(m_alternativeTabBoxUi->effectConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureEffectClickedAlternative())); - connect( m_alternativeTabBoxUi->layoutConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureLayoutClickedAlternative())); + connect(m_alternativeTabBoxUi->layoutConfigButton, SIGNAL(clicked(bool)), this, SLOT(slotConfigureLayoutClickedAlternative())); // check focus policy - we don't offer configs for unreasonable focus policies - KConfigGroup config( m_config, "Windows" ); - QString policy = config.readEntry ("FocusPolicy", "ClickToFocus"); - if( (policy == "FocusUnderMouse") || (policy == "FocusStrictlyUnderMouse" ) ) - { - tabWidget->setEnabled( false ); + KConfigGroup config(m_config, "Windows"); + QString policy = config.readEntry("FocusPolicy", "ClickToFocus"); + if ((policy == "FocusUnderMouse") || (policy == "FocusStrictlyUnderMouse")) { + tabWidget->setEnabled(false); infoLabel->show(); - } - else + } else infoLabel->hide(); - } +} KWinTabBoxConfig::~KWinTabBoxConfig() - { - } +{ +} void KWinTabBoxConfig::load() - { +{ KCModule::load(); - KConfigGroup config( m_config, "TabBox" ); - KConfigGroup alternativeConfig( m_config, "TabBoxAlternative" ); - loadConfig( config, m_tabBoxConfig ); - loadConfig( alternativeConfig, m_tabBoxAlternativeConfig ); + KConfigGroup config(m_config, "TabBox"); + KConfigGroup alternativeConfig(m_config, "TabBoxAlternative"); + loadConfig(config, m_tabBoxConfig); + loadConfig(alternativeConfig, m_tabBoxAlternativeConfig); // sync to ui - updateUiFromConfig( m_primaryTabBoxUi, m_tabBoxConfig ); - updateUiFromConfig( m_alternativeTabBoxUi, m_tabBoxAlternativeConfig ); + updateUiFromConfig(m_primaryTabBoxUi, m_tabBoxConfig); + updateUiFromConfig(m_alternativeTabBoxUi, m_tabBoxAlternativeConfig); // effects // Set current option to "none" if no plugin is activated. - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 0 ); - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 0 ); - KConfigGroup effectconfig( m_config, "Plugins" ); - KConfigGroup boxswitchconfig( m_config, "Effect-BoxSwitch" ); - if( effectEnabled( "boxswitch", effectconfig ) ) - { - if( boxswitchconfig.readEntry( "TabBox", true) ) - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 1 ); - if( boxswitchconfig.readEntry( "TabBoxAlternative", false) ) - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 1 ); - } - KConfigGroup presentwindowsconfig( m_config, "Effect-PresentWindows"); - if( effectEnabled( "presentwindows", effectconfig ) ) - { - if( presentwindowsconfig.readEntry("TabBox", false) ) - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 2 ); - if( presentwindowsconfig.readEntry("TabBoxAlternative", false) ) - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 2 ); - } - KConfigGroup coverswitchconfig( m_config, "Effect-CoverSwitch" ); - if( effectEnabled( "coverswitch", effectconfig ) ) - { - if( coverswitchconfig.readEntry("TabBox", false) ) - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 3 ); - if( coverswitchconfig.readEntry("TabBoxAlternative", false) ) - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 3 ); - } - KConfigGroup flipswitchconfig( m_config, "Effect-FlipSwitch" ); - if( effectEnabled( "flipswitch", effectconfig ) ) - { - if( flipswitchconfig.readEntry("TabBox", false) ) - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 4 ); - if( flipswitchconfig.readEntry("TabBoxAlternative", false) ) - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 4 ); - } - slotEffectSelectionChanged( m_primaryTabBoxUi->effectCombo->currentIndex() ); - slotEffectSelectionChangedAlternative( m_alternativeTabBoxUi->effectCombo->currentIndex() ); - - emit changed( false ); + m_primaryTabBoxUi->effectCombo->setCurrentIndex(0); + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(0); + KConfigGroup effectconfig(m_config, "Plugins"); + KConfigGroup boxswitchconfig(m_config, "Effect-BoxSwitch"); + if (effectEnabled("boxswitch", effectconfig)) { + if (boxswitchconfig.readEntry("TabBox", true)) + m_primaryTabBoxUi->effectCombo->setCurrentIndex(1); + if (boxswitchconfig.readEntry("TabBoxAlternative", false)) + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(1); } - -void KWinTabBoxConfig::loadConfig( const KConfigGroup& config, KWin::TabBox::TabBoxConfig& tabBoxConfig ) - { - tabBoxConfig.setClientListMode( TabBox::TabBoxConfig::ClientListMode( - config.readEntry( "ListMode", TabBox::TabBoxConfig::defaultListMode() ))); - tabBoxConfig.setClientSwitchingMode( TabBox::TabBoxConfig::ClientSwitchingMode( - config.readEntry( "SwitchingMode", TabBox::TabBoxConfig::defaultSwitchingMode() ))); - tabBoxConfig.setLayout( TabBox::TabBoxConfig::LayoutMode( - config.readEntry( "LayoutMode", TabBox::TabBoxConfig::defaultLayoutMode() ))); - tabBoxConfig.setSelectedItemViewPosition( TabBox::TabBoxConfig::SelectedItemViewPosition( - config.readEntry( "SelectedItem", TabBox::TabBoxConfig::defaultSelectedItemViewPosition()))); - tabBoxConfig.setShowDesktop( config.readEntry( "ShowDesktop", - TabBox::TabBoxConfig::defaultShowDesktop())); - - tabBoxConfig.setShowOutline( config.readEntry( "ShowOutline", - TabBox::TabBoxConfig::defaultShowOutline())); - tabBoxConfig.setShowTabBox( config.readEntry( "ShowTabBox", - TabBox::TabBoxConfig::defaultShowTabBox())); - tabBoxConfig.setHighlightWindows( config.readEntry( "HighlightWindows", - TabBox::TabBoxConfig::defaultHighlightWindow())); - - tabBoxConfig.setMinWidth( config.readEntry( "MinWidth", - TabBox::TabBoxConfig::defaultMinWidth())); - tabBoxConfig.setMinHeight( config.readEntry( "MinHeight", - TabBox::TabBoxConfig::defaultMinHeight())); - - tabBoxConfig.setLayoutName( config.readEntry( "LayoutName", TabBox::TabBoxConfig::defaultLayoutName())); - tabBoxConfig.setSelectedItemLayoutName( config.readEntry( "SelectedLayoutName", TabBox::TabBoxConfig::defaultSelectedItemLayoutName())); + KConfigGroup presentwindowsconfig(m_config, "Effect-PresentWindows"); + if (effectEnabled("presentwindows", effectconfig)) { + if (presentwindowsconfig.readEntry("TabBox", false)) + m_primaryTabBoxUi->effectCombo->setCurrentIndex(2); + if (presentwindowsconfig.readEntry("TabBoxAlternative", false)) + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(2); } + KConfigGroup coverswitchconfig(m_config, "Effect-CoverSwitch"); + if (effectEnabled("coverswitch", effectconfig)) { + if (coverswitchconfig.readEntry("TabBox", false)) + m_primaryTabBoxUi->effectCombo->setCurrentIndex(3); + if (coverswitchconfig.readEntry("TabBoxAlternative", false)) + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(3); + } + KConfigGroup flipswitchconfig(m_config, "Effect-FlipSwitch"); + if (effectEnabled("flipswitch", effectconfig)) { + if (flipswitchconfig.readEntry("TabBox", false)) + m_primaryTabBoxUi->effectCombo->setCurrentIndex(4); + if (flipswitchconfig.readEntry("TabBoxAlternative", false)) + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(4); + } + slotEffectSelectionChanged(m_primaryTabBoxUi->effectCombo->currentIndex()); + slotEffectSelectionChangedAlternative(m_alternativeTabBoxUi->effectCombo->currentIndex()); -void KWinTabBoxConfig::saveConfig( KConfigGroup& config, const KWin::TabBox::TabBoxConfig& tabBoxConfig ) - { + emit changed(false); +} + +void KWinTabBoxConfig::loadConfig(const KConfigGroup& config, KWin::TabBox::TabBoxConfig& tabBoxConfig) +{ + tabBoxConfig.setClientListMode(TabBox::TabBoxConfig::ClientListMode( + config.readEntry("ListMode", TabBox::TabBoxConfig::defaultListMode()))); + tabBoxConfig.setClientSwitchingMode(TabBox::TabBoxConfig::ClientSwitchingMode( + config.readEntry("SwitchingMode", TabBox::TabBoxConfig::defaultSwitchingMode()))); + tabBoxConfig.setLayout(TabBox::TabBoxConfig::LayoutMode( + config.readEntry("LayoutMode", TabBox::TabBoxConfig::defaultLayoutMode()))); + tabBoxConfig.setSelectedItemViewPosition(TabBox::TabBoxConfig::SelectedItemViewPosition( + config.readEntry("SelectedItem", TabBox::TabBoxConfig::defaultSelectedItemViewPosition()))); + tabBoxConfig.setShowDesktop(config.readEntry("ShowDesktop", + TabBox::TabBoxConfig::defaultShowDesktop())); + + tabBoxConfig.setShowOutline(config.readEntry("ShowOutline", + TabBox::TabBoxConfig::defaultShowOutline())); + tabBoxConfig.setShowTabBox(config.readEntry("ShowTabBox", + TabBox::TabBoxConfig::defaultShowTabBox())); + tabBoxConfig.setHighlightWindows(config.readEntry("HighlightWindows", + TabBox::TabBoxConfig::defaultHighlightWindow())); + + tabBoxConfig.setMinWidth(config.readEntry("MinWidth", + TabBox::TabBoxConfig::defaultMinWidth())); + tabBoxConfig.setMinHeight(config.readEntry("MinHeight", + TabBox::TabBoxConfig::defaultMinHeight())); + + tabBoxConfig.setLayoutName(config.readEntry("LayoutName", TabBox::TabBoxConfig::defaultLayoutName())); + tabBoxConfig.setSelectedItemLayoutName(config.readEntry("SelectedLayoutName", TabBox::TabBoxConfig::defaultSelectedItemLayoutName())); +} + +void KWinTabBoxConfig::saveConfig(KConfigGroup& config, const KWin::TabBox::TabBoxConfig& tabBoxConfig) +{ // combo boxes - config.writeEntry( "ListMode", int(tabBoxConfig.clientListMode()) ); - config.writeEntry( "SwitchingMode", int(tabBoxConfig.clientSwitchingMode()) ); - config.writeEntry( "LayoutMode", int(tabBoxConfig.layout()) ); - config.writeEntry( "SelectedItem", int(tabBoxConfig.selectedItemViewPosition()) ); - config.writeEntry( "LayoutName", tabBoxConfig.layoutName() ); - config.writeEntry( "SelectedLayoutName", tabBoxConfig.selectedItemLayoutName() ); - config.writeEntry( "ShowDesktop", tabBoxConfig.isShowDesktop() ); + config.writeEntry("ListMode", int(tabBoxConfig.clientListMode())); + config.writeEntry("SwitchingMode", int(tabBoxConfig.clientSwitchingMode())); + config.writeEntry("LayoutMode", int(tabBoxConfig.layout())); + config.writeEntry("SelectedItem", int(tabBoxConfig.selectedItemViewPosition())); + config.writeEntry("LayoutName", tabBoxConfig.layoutName()); + config.writeEntry("SelectedLayoutName", tabBoxConfig.selectedItemLayoutName()); + config.writeEntry("ShowDesktop", tabBoxConfig.isShowDesktop()); // check boxes - config.writeEntry( "ShowOutline", tabBoxConfig.isShowOutline() ); - config.writeEntry( "ShowTabBox", tabBoxConfig.isShowTabBox() ); - config.writeEntry( "HighlightWindows", tabBoxConfig.isHighlightWindows() ); + config.writeEntry("ShowOutline", tabBoxConfig.isShowOutline()); + config.writeEntry("ShowTabBox", tabBoxConfig.isShowTabBox()); + config.writeEntry("HighlightWindows", tabBoxConfig.isHighlightWindows()); // spin boxes - config.writeEntry( "MinWidth", tabBoxConfig.minWidth() ); - config.writeEntry( "MinHeight", tabBoxConfig.minHeight() ); + config.writeEntry("MinWidth", tabBoxConfig.minWidth()); + config.writeEntry("MinHeight", tabBoxConfig.minHeight()); config.sync(); - } +} void KWinTabBoxConfig::save() - { +{ KCModule::save(); - KConfigGroup config( m_config, "TabBox" ); + KConfigGroup config(m_config, "TabBox"); // sync ui to config - updateConfigFromUi( m_primaryTabBoxUi, m_tabBoxConfig ); - updateConfigFromUi( m_alternativeTabBoxUi, m_tabBoxAlternativeConfig ); - saveConfig( config, m_tabBoxConfig ); - config = KConfigGroup( m_config, "TabBoxAlternative" ); - saveConfig( config, m_tabBoxAlternativeConfig ); + updateConfigFromUi(m_primaryTabBoxUi, m_tabBoxConfig); + updateConfigFromUi(m_alternativeTabBoxUi, m_tabBoxAlternativeConfig); + saveConfig(config, m_tabBoxConfig); + config = KConfigGroup(m_config, "TabBoxAlternative"); + saveConfig(config, m_tabBoxAlternativeConfig); // effects bool boxSwitch = false; @@ -313,200 +307,197 @@ void KWinTabBoxConfig::save() bool presentWindowSwitchingAlternative = false; bool coverSwitchAlternative = false; bool flipSwitchAlternative = false; - switch( m_primaryTabBoxUi->effectCombo->currentIndex() ) - { - case 1: - boxSwitch = true; - break; - case 2: - presentWindowSwitching = true; - break; - case 3: - coverSwitch = true; - break; - case 4: - flipSwitch = true; - break; - default: - break; // nothing - } - switch( m_alternativeTabBoxUi->effectCombo->currentIndex() ) - { - case 1: - boxSwitchAlternative = true; - break; - case 2: - presentWindowSwitchingAlternative = true; - break; - case 3: - coverSwitchAlternative = true; - break; - case 4: - flipSwitchAlternative = true; - break; - default: - break; // nothing - } + switch(m_primaryTabBoxUi->effectCombo->currentIndex()) { + case 1: + boxSwitch = true; + break; + case 2: + presentWindowSwitching = true; + break; + case 3: + coverSwitch = true; + break; + case 4: + flipSwitch = true; + break; + default: + break; // nothing + } + switch(m_alternativeTabBoxUi->effectCombo->currentIndex()) { + case 1: + boxSwitchAlternative = true; + break; + case 2: + presentWindowSwitchingAlternative = true; + break; + case 3: + coverSwitchAlternative = true; + break; + case 4: + flipSwitchAlternative = true; + break; + default: + break; // nothing + } // activate effects if not active - KConfigGroup effectconfig( m_config, "Plugins" ); - if( boxSwitch || boxSwitchAlternative ) + KConfigGroup effectconfig(m_config, "Plugins"); + if (boxSwitch || boxSwitchAlternative) effectconfig.writeEntry("kwin4_effect_boxswitchEnabled", true); - if( presentWindowSwitching || presentWindowSwitchingAlternative ) + if (presentWindowSwitching || presentWindowSwitchingAlternative) effectconfig.writeEntry("kwin4_effect_presentwindowsEnabled", true); - if( coverSwitch || coverSwitchAlternative ) + if (coverSwitch || coverSwitchAlternative) effectconfig.writeEntry("kwin4_effect_coverswitchEnabled", true); - if( flipSwitch || flipSwitchAlternative ) + if (flipSwitch || flipSwitchAlternative) effectconfig.writeEntry("kwin4_effect_flipswitchEnabled", true); effectconfig.sync(); - KConfigGroup boxswitchconfig( m_config, "Effect-BoxSwitch" ); - boxswitchconfig.writeEntry( "TabBox", boxSwitch ); - boxswitchconfig.writeEntry( "TabBoxAlternative", boxSwitchAlternative ); + KConfigGroup boxswitchconfig(m_config, "Effect-BoxSwitch"); + boxswitchconfig.writeEntry("TabBox", boxSwitch); + boxswitchconfig.writeEntry("TabBoxAlternative", boxSwitchAlternative); boxswitchconfig.sync(); - KConfigGroup presentwindowsconfig( m_config, "Effect-PresentWindows" ); - presentwindowsconfig.writeEntry( "TabBox", presentWindowSwitching ); - presentwindowsconfig.writeEntry( "TabBoxAlternative", presentWindowSwitchingAlternative ); + KConfigGroup presentwindowsconfig(m_config, "Effect-PresentWindows"); + presentwindowsconfig.writeEntry("TabBox", presentWindowSwitching); + presentwindowsconfig.writeEntry("TabBoxAlternative", presentWindowSwitchingAlternative); presentwindowsconfig.sync(); - KConfigGroup coverswitchconfig( m_config, "Effect-CoverSwitch" ); - coverswitchconfig.writeEntry( "TabBox", coverSwitch ); - coverswitchconfig.writeEntry( "TabBoxAlternative", coverSwitchAlternative ); + KConfigGroup coverswitchconfig(m_config, "Effect-CoverSwitch"); + coverswitchconfig.writeEntry("TabBox", coverSwitch); + coverswitchconfig.writeEntry("TabBoxAlternative", coverSwitchAlternative); coverswitchconfig.sync(); - KConfigGroup flipswitchconfig( m_config, "Effect-FlipSwitch" ); - flipswitchconfig.writeEntry( "TabBox", flipSwitch ); - flipswitchconfig.writeEntry( "TabBoxAlternative", flipSwitchAlternative ); + KConfigGroup flipswitchconfig(m_config, "Effect-FlipSwitch"); + flipswitchconfig.writeEntry("TabBox", flipSwitch); + flipswitchconfig.writeEntry("TabBoxAlternative", flipSwitchAlternative); flipswitchconfig.sync(); m_editor->save(); // Reload KWin. - QDBusMessage message = QDBusMessage::createSignal( "/KWin", "org.kde.KWin", "reloadConfig" ); - QDBusConnection::sessionBus().send( message ); + QDBusMessage message = QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"); + QDBusConnection::sessionBus().send(message); - emit changed( false ); - } + emit changed(false); +} void KWinTabBoxConfig::defaults() - { +{ // combo boxes - m_primaryTabBoxUi->listModeCombo->setCurrentIndex( TabBox::TabBoxConfig::defaultListMode() ); - m_primaryTabBoxUi->switchingModeCombo->setCurrentIndex( TabBox::TabBoxConfig::defaultSwitchingMode() ); + m_primaryTabBoxUi->listModeCombo->setCurrentIndex(TabBox::TabBoxConfig::defaultListMode()); + m_primaryTabBoxUi->switchingModeCombo->setCurrentIndex(TabBox::TabBoxConfig::defaultSwitchingMode()); // checkboxes - m_primaryTabBoxUi->showOutlineCheck->setChecked( TabBox::TabBoxConfig::defaultShowOutline() ); - m_primaryTabBoxUi->showTabBox->setChecked( TabBox::TabBoxConfig::defaultShowTabBox() ); - m_primaryTabBoxUi->highlightWindowCheck->setChecked( TabBox::TabBoxConfig::defaultHighlightWindow() ); - m_primaryTabBoxUi->showDesktopBox->setChecked( TabBox::TabBoxConfig::defaultShowDesktop() ); + m_primaryTabBoxUi->showOutlineCheck->setChecked(TabBox::TabBoxConfig::defaultShowOutline()); + m_primaryTabBoxUi->showTabBox->setChecked(TabBox::TabBoxConfig::defaultShowTabBox()); + m_primaryTabBoxUi->highlightWindowCheck->setChecked(TabBox::TabBoxConfig::defaultHighlightWindow()); + m_primaryTabBoxUi->showDesktopBox->setChecked(TabBox::TabBoxConfig::defaultShowDesktop()); // effects - m_primaryTabBoxUi->effectCombo->setCurrentIndex( 1 ); + m_primaryTabBoxUi->effectCombo->setCurrentIndex(1); // alternative // combo boxes - m_alternativeTabBoxUi->listModeCombo->setCurrentIndex( TabBox::TabBoxConfig::defaultListMode() ); - m_alternativeTabBoxUi->switchingModeCombo->setCurrentIndex( TabBox::TabBoxConfig::defaultSwitchingMode() ); + m_alternativeTabBoxUi->listModeCombo->setCurrentIndex(TabBox::TabBoxConfig::defaultListMode()); + m_alternativeTabBoxUi->switchingModeCombo->setCurrentIndex(TabBox::TabBoxConfig::defaultSwitchingMode()); // checkboxes - m_alternativeTabBoxUi->showOutlineCheck->setChecked( TabBox::TabBoxConfig::defaultShowOutline() ); - m_alternativeTabBoxUi->showTabBox->setChecked( TabBox::TabBoxConfig::defaultShowTabBox() ); - m_alternativeTabBoxUi->highlightWindowCheck->setChecked( TabBox::TabBoxConfig::defaultHighlightWindow() ); - m_alternativeTabBoxUi->showDesktopBox->setChecked( TabBox::TabBoxConfig::defaultShowDesktop() ); + m_alternativeTabBoxUi->showOutlineCheck->setChecked(TabBox::TabBoxConfig::defaultShowOutline()); + m_alternativeTabBoxUi->showTabBox->setChecked(TabBox::TabBoxConfig::defaultShowTabBox()); + m_alternativeTabBoxUi->highlightWindowCheck->setChecked(TabBox::TabBoxConfig::defaultHighlightWindow()); + m_alternativeTabBoxUi->showDesktopBox->setChecked(TabBox::TabBoxConfig::defaultShowDesktop()); // effects - m_alternativeTabBoxUi->effectCombo->setCurrentIndex( 0 ); + m_alternativeTabBoxUi->effectCombo->setCurrentIndex(0); m_editor->allDefault(); - emit changed( true ); - } + emit changed(true); +} bool KWinTabBoxConfig::effectEnabled(const QString& effect, const KConfigGroup& cfg) const - { +{ KService::List services = KServiceTypeTrader::self()->query( - "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\'' ); - if( services.isEmpty()) + "KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) return false; - QVariant v = services.first()->property( "X-KDE-PluginInfo-EnabledByDefault" ); - return cfg.readEntry( "kwin4_effect_" + effect + "Enabled", v.toBool() ); - } + QVariant v = services.first()->property("X-KDE-PluginInfo-EnabledByDefault"); + return cfg.readEntry("kwin4_effect_" + effect + "Enabled", v.toBool()); +} -void KWinTabBoxConfig::updateUiFromConfig( KWinTabBoxConfigForm* ui, const KWin::TabBox::TabBoxConfig& config ) - { +void KWinTabBoxConfig::updateUiFromConfig(KWinTabBoxConfigForm* ui, const KWin::TabBox::TabBoxConfig& config) +{ // combo boxes - ui->listModeCombo->setCurrentIndex( config.clientListMode() ); - ui->switchingModeCombo->setCurrentIndex( config.clientSwitchingMode() ); + ui->listModeCombo->setCurrentIndex(config.clientListMode()); + ui->switchingModeCombo->setCurrentIndex(config.clientSwitchingMode()); // check boxes - ui->showOutlineCheck->setChecked( config.isShowOutline() ); - ui->showTabBox->setChecked( config.isShowTabBox()); - ui->highlightWindowCheck->setChecked( config.isHighlightWindows() ); - ui->showDesktopBox->setChecked( config.isShowDesktop() ); - } + ui->showOutlineCheck->setChecked(config.isShowOutline()); + ui->showTabBox->setChecked(config.isShowTabBox()); + ui->highlightWindowCheck->setChecked(config.isHighlightWindows()); + ui->showDesktopBox->setChecked(config.isShowDesktop()); +} -void KWinTabBoxConfig::updateConfigFromUi( const KWin::KWinTabBoxConfigForm* ui, TabBox::TabBoxConfig& config ) - { - config.setClientListMode( TabBox::TabBoxConfig::ClientListMode(ui->listModeCombo->currentIndex()) ); - config.setClientSwitchingMode( TabBox::TabBoxConfig::ClientSwitchingMode(ui->switchingModeCombo->currentIndex()) ); +void KWinTabBoxConfig::updateConfigFromUi(const KWin::KWinTabBoxConfigForm* ui, TabBox::TabBoxConfig& config) +{ + config.setClientListMode(TabBox::TabBoxConfig::ClientListMode(ui->listModeCombo->currentIndex())); + config.setClientSwitchingMode(TabBox::TabBoxConfig::ClientSwitchingMode(ui->switchingModeCombo->currentIndex())); - config.setShowOutline( ui->showOutlineCheck->isChecked() ); - config.setShowTabBox( ui->showTabBox->isChecked() ); - config.setHighlightWindows( ui->highlightWindowCheck->isChecked() ); - config.setShowDesktop( ui->showDesktopBox->isChecked() ); - } + config.setShowOutline(ui->showOutlineCheck->isChecked()); + config.setShowTabBox(ui->showTabBox->isChecked()); + config.setHighlightWindows(ui->highlightWindowCheck->isChecked()); + config.setShowDesktop(ui->showDesktopBox->isChecked()); +} -void KWinTabBoxConfig::slotEffectSelectionChanged( int index ) - { - effectSelectionChanged( m_primaryTabBoxUi, index ); - } +void KWinTabBoxConfig::slotEffectSelectionChanged(int index) +{ + effectSelectionChanged(m_primaryTabBoxUi, index); +} -void KWinTabBoxConfig::slotEffectSelectionChangedAlternative( int index ) - { - effectSelectionChanged( m_alternativeTabBoxUi, index ); - } +void KWinTabBoxConfig::slotEffectSelectionChangedAlternative(int index) +{ + effectSelectionChanged(m_alternativeTabBoxUi, index); +} -void KWinTabBoxConfig::effectSelectionChanged( KWinTabBoxConfigForm* ui, int index ) - { +void KWinTabBoxConfig::effectSelectionChanged(KWinTabBoxConfigForm* ui, int index) +{ bool enabled = false; - if( index > 0 ) + if (index > 0) enabled = true; - ui->effectInfoButton->setEnabled( enabled ); - ui->effectConfigButton->setEnabled( enabled ); - } + ui->effectInfoButton->setEnabled(enabled); + ui->effectConfigButton->setEnabled(enabled); +} void KWinTabBoxConfig::slotAboutEffectClicked() - { - aboutEffectClicked( m_primaryTabBoxUi ); - } +{ + aboutEffectClicked(m_primaryTabBoxUi); +} void KWinTabBoxConfig::slotAboutEffectClickedAlternative() - { - aboutEffectClicked( m_alternativeTabBoxUi ); - } +{ + aboutEffectClicked(m_alternativeTabBoxUi); +} -void KWinTabBoxConfig::aboutEffectClicked( KWinTabBoxConfigForm* ui ) - { +void KWinTabBoxConfig::aboutEffectClicked(KWinTabBoxConfigForm* ui) +{ KServiceTypeTrader* trader = KServiceTypeTrader::self(); KService::List services; QString effect; - switch( ui->effectCombo->currentIndex() ) - { - case 1: - effect = "boxswitch"; - break; - case 2: - effect = "presentwindows"; - break; - case 3: - effect = "coverswitch"; - break; - case 4: - effect = "flipswitch"; - break; - default: - return; - } - services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); - if( services.isEmpty() ) + switch(ui->effectCombo->currentIndex()) { + case 1: + effect = "boxswitch"; + break; + case 2: + effect = "presentwindows"; + break; + case 3: + effect = "coverswitch"; + break; + case 4: + effect = "flipswitch"; + break; + default: return; - KPluginInfo pluginInfo( services.first() ); + } + services = trader->query("KWin/Effect", "[X-KDE-PluginInfo-Name] == 'kwin4_effect_" + effect + '\''); + if (services.isEmpty()) + return; + KPluginInfo pluginInfo(services.first()); const QString name = pluginInfo.name(); const QString comment = pluginInfo.comment(); @@ -518,120 +509,113 @@ void KWinTabBoxConfig::aboutEffectClicked( KWinTabBoxConfigForm* ui ) const QString icon = pluginInfo.icon(); KAboutData aboutData(name.toUtf8(), name.toUtf8(), ki18n(name.toUtf8()), version.toUtf8(), ki18n(comment.toUtf8()), KAboutLicense::byKeyword(license).key(), ki18n(QByteArray()), ki18n(QByteArray()), website.toLatin1()); - aboutData.setProgramIconName( icon ); + aboutData.setProgramIconName(icon); const QStringList authors = author.split(','); const QStringList emails = email.split(','); int i = 0; - if( authors.count() == emails.count() ) - { - foreach( const QString &author, authors ) - { - if( !author.isEmpty() ) - { + if (authors.count() == emails.count()) { + foreach (const QString & author, authors) { + if (!author.isEmpty()) { aboutData.addAuthor(ki18n(author.toUtf8()), ki18n(QByteArray()), emails[i].toUtf8(), 0); - } - i++; } + i++; } - QPointer< KAboutApplicationDialog > aboutPlugin = new KAboutApplicationDialog( &aboutData, this ); + } + QPointer< KAboutApplicationDialog > aboutPlugin = new KAboutApplicationDialog(&aboutData, this); aboutPlugin->exec(); delete aboutPlugin; - } +} void KWinTabBoxConfig::slotConfigureEffectClicked() - { - configureEffectClicked( m_primaryTabBoxUi ); - } +{ + configureEffectClicked(m_primaryTabBoxUi); +} void KWinTabBoxConfig::slotConfigureEffectClickedAlternative() - { - configureEffectClicked( m_alternativeTabBoxUi ); - } +{ + configureEffectClicked(m_alternativeTabBoxUi); +} -void KWinTabBoxConfig::configureEffectClicked( KWinTabBoxConfigForm* ui ) - { +void KWinTabBoxConfig::configureEffectClicked(KWinTabBoxConfigForm* ui) +{ QString effect; - switch( ui->effectCombo->currentIndex() ) - { - case 1: - effect = "boxswitch_config"; - break; - case 2: - effect = "presentwindows_config"; - break; - case 3: - effect = "coverswitch_config"; - break; - case 4: - effect = "flipswitch_config"; - break; - default: - return; - } - KCModuleProxy* proxy = new KCModuleProxy( effect ); - QPointer< KDialog > configDialog = new KDialog( this ); - configDialog->setWindowTitle( ui->effectCombo->currentText() ); - configDialog->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default ); + switch(ui->effectCombo->currentIndex()) { + case 1: + effect = "boxswitch_config"; + break; + case 2: + effect = "presentwindows_config"; + break; + case 3: + effect = "coverswitch_config"; + break; + case 4: + effect = "flipswitch_config"; + break; + default: + return; + } + KCModuleProxy* proxy = new KCModuleProxy(effect); + QPointer< KDialog > configDialog = new KDialog(this); + configDialog->setWindowTitle(ui->effectCombo->currentText()); + configDialog->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default); connect(configDialog, SIGNAL(defaultClicked()), proxy, SLOT(defaults())); - QWidget *showWidget = new QWidget( configDialog ); + QWidget *showWidget = new QWidget(configDialog); QVBoxLayout *layout = new QVBoxLayout; - showWidget->setLayout( layout ); - layout->addWidget( proxy ); - layout->insertSpacing( -1, KDialog::marginHint() ); - configDialog->setMainWidget( showWidget ); + showWidget->setLayout(layout); + layout->addWidget(proxy); + layout->insertSpacing(-1, KDialog::marginHint()); + configDialog->setMainWidget(showWidget); - if( configDialog->exec() == QDialog::Accepted ) - { + if (configDialog->exec() == QDialog::Accepted) { proxy->save(); - } - else - { + } else { proxy->load(); - } - delete configDialog; } + delete configDialog; +} void KWinTabBoxConfig::slotConfigureLayoutClicked() - { - QPointer dialog = new KDialog( this ); - dialog->setCaption( i18n("Configure Layout") ); - dialog->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default ); - connect( dialog, SIGNAL(okClicked()), this, SLOT(slotLayoutChanged())); +{ + QPointer dialog = new KDialog(this); + dialog->setCaption(i18n("Configure Layout")); + dialog->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default); + connect(dialog, SIGNAL(okClicked()), this, SLOT(slotLayoutChanged())); - m_configForm = new TabBox::LayoutConfig( dialog ); - m_configForm->setConfig( m_tabBoxConfig ); - dialog->setMainWidget( m_configForm ); + m_configForm = new TabBox::LayoutConfig(dialog); + m_configForm->setConfig(m_tabBoxConfig); + dialog->setMainWidget(m_configForm); dialog->exec(); delete dialog; - } +} void KWinTabBoxConfig::slotLayoutChanged() - { +{ m_tabBoxConfig = m_configForm->config(); - emit changed( true ); - } + emit changed(true); +} void KWinTabBoxConfig::slotConfigureLayoutClickedAlternative() - { - QPointer dialog = new KDialog( this ); - dialog->setCaption( i18n("Configure Layout") ); - dialog->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Default ); - connect( dialog, SIGNAL(okClicked()), this, SLOT(slotLayoutChangedAlternative())); +{ + QPointer dialog = new KDialog(this); + dialog->setCaption(i18n("Configure Layout")); + dialog->setButtons(KDialog::Ok | KDialog::Cancel | KDialog::Default); + connect(dialog, SIGNAL(okClicked()), this, SLOT(slotLayoutChangedAlternative())); - m_configForm = new TabBox::LayoutConfig( dialog ); - m_configForm->setConfig( m_tabBoxAlternativeConfig ); - dialog->setMainWidget( m_configForm ); + m_configForm = new TabBox::LayoutConfig(dialog); + m_configForm->setConfig(m_tabBoxAlternativeConfig); + dialog->setMainWidget(m_configForm); dialog->exec(); delete dialog; - } +} void KWinTabBoxConfig::slotLayoutChangedAlternative() - { +{ m_tabBoxAlternativeConfig = m_configForm->config(); - emit changed( true ); - } + emit changed(true); +} } // namespace diff --git a/kcmkwin/kwintabbox/main.h b/kcmkwin/kwintabbox/main.h index 249ccae39..5c1af8ab2 100644 --- a/kcmkwin/kwintabbox/main.h +++ b/kcmkwin/kwintabbox/main.h @@ -32,7 +32,8 @@ class KActionCollection; namespace KWin { -namespace TabBox { +namespace TabBox +{ class LayoutConfig; } @@ -40,59 +41,59 @@ class LayoutConfig; class KWinTabBoxConfigForm : public QWidget, public Ui::KWinTabBoxConfigForm - { +{ Q_OBJECT - public: - explicit KWinTabBoxConfigForm( QWidget* parent ); - }; +public: + explicit KWinTabBoxConfigForm(QWidget* parent); +}; class KWinTabBoxConfig : public KCModule - { +{ Q_OBJECT - public: - explicit KWinTabBoxConfig( QWidget* parent, const QVariantList& args ); - ~KWinTabBoxConfig(); +public: + explicit KWinTabBoxConfig(QWidget* parent, const QVariantList& args); + ~KWinTabBoxConfig(); - public slots: - virtual void save(); - virtual void load(); - virtual void defaults(); +public slots: + virtual void save(); + virtual void load(); + virtual void defaults(); - private slots: - void slotEffectSelectionChanged( int index ); - void slotAboutEffectClicked(); - void slotConfigureEffectClicked(); - void slotConfigureLayoutClicked(); - void slotLayoutChanged(); - void slotEffectSelectionChangedAlternative( int index ); - void slotAboutEffectClickedAlternative(); - void slotConfigureEffectClickedAlternative(); - void slotConfigureLayoutClickedAlternative(); - void slotLayoutChangedAlternative(); +private slots: + void slotEffectSelectionChanged(int index); + void slotAboutEffectClicked(); + void slotConfigureEffectClicked(); + void slotConfigureLayoutClicked(); + void slotLayoutChanged(); + void slotEffectSelectionChangedAlternative(int index); + void slotAboutEffectClickedAlternative(); + void slotConfigureEffectClickedAlternative(); + void slotConfigureLayoutClickedAlternative(); + void slotLayoutChangedAlternative(); - private: - void updateUiFromConfig( KWinTabBoxConfigForm* ui, const TabBox::TabBoxConfig& config ); - void updateConfigFromUi( const KWinTabBoxConfigForm* ui, TabBox::TabBoxConfig& config ); - void loadConfig( const KConfigGroup& config, KWin::TabBox::TabBoxConfig& tabBoxConfig ); - void saveConfig( KConfigGroup& config, const KWin::TabBox::TabBoxConfig& tabBoxConfig ); - void effectSelectionChanged( KWinTabBoxConfigForm* ui, int index ); - void aboutEffectClicked( KWinTabBoxConfigForm* ui ); - void configureEffectClicked( KWinTabBoxConfigForm* ui ); +private: + void updateUiFromConfig(KWinTabBoxConfigForm* ui, const TabBox::TabBoxConfig& config); + void updateConfigFromUi(const KWinTabBoxConfigForm* ui, TabBox::TabBoxConfig& config); + void loadConfig(const KConfigGroup& config, KWin::TabBox::TabBoxConfig& tabBoxConfig); + void saveConfig(KConfigGroup& config, const KWin::TabBox::TabBoxConfig& tabBoxConfig); + void effectSelectionChanged(KWinTabBoxConfigForm* ui, int index); + void aboutEffectClicked(KWinTabBoxConfigForm* ui); + void configureEffectClicked(KWinTabBoxConfigForm* ui); - private: - KWinTabBoxConfigForm* m_primaryTabBoxUi; - KWinTabBoxConfigForm* m_alternativeTabBoxUi; - KSharedConfigPtr m_config; - KActionCollection* m_actionCollection; - KShortcutsEditor* m_editor; - TabBox::TabBoxConfig m_tabBoxConfig; - TabBox::TabBoxConfig m_tabBoxAlternativeConfig; - TabBox::LayoutConfig* m_configForm; +private: + KWinTabBoxConfigForm* m_primaryTabBoxUi; + KWinTabBoxConfigForm* m_alternativeTabBoxUi; + KSharedConfigPtr m_config; + KActionCollection* m_actionCollection; + KShortcutsEditor* m_editor; + TabBox::TabBoxConfig m_tabBoxConfig; + TabBox::TabBoxConfig m_tabBoxAlternativeConfig; + TabBox::LayoutConfig* m_configForm; - bool effectEnabled( const QString& effect, const KConfigGroup& cfg ) const; - }; + bool effectEnabled(const QString& effect, const KConfigGroup& cfg) const; +}; } // namespace diff --git a/kcmkwin/kwintabbox/previewhandlerimpl.cpp b/kcmkwin/kwintabbox/previewhandlerimpl.cpp index c437f29d9..cbe2a38be 100644 --- a/kcmkwin/kwintabbox/previewhandlerimpl.cpp +++ b/kcmkwin/kwintabbox/previewhandlerimpl.cpp @@ -30,155 +30,153 @@ namespace TabBox { PreviewClientImpl::PreviewClientImpl(WId id) - : m_id( id ) - { - } + : m_id(id) +{ +} PreviewClientImpl::~PreviewClientImpl() - { - } +{ +} QString PreviewClientImpl::caption() const - { - KWindowInfo info = KWindowSystem::windowInfo( m_id, NET::WMVisibleName ); +{ + KWindowInfo info = KWindowSystem::windowInfo(m_id, NET::WMVisibleName); return info.visibleName(); - } +} -QPixmap PreviewClientImpl::icon( const QSize& size ) const - { - return KWindowSystem::icon( m_id, size.width(), size.height(), true ); - } +QPixmap PreviewClientImpl::icon(const QSize& size) const +{ + return KWindowSystem::icon(m_id, size.width(), size.height(), true); +} bool PreviewClientImpl::isMinimized() const - { - KWindowInfo info = KWindowSystem::windowInfo( m_id, NET::WMState | NET::XAWMState ); +{ + KWindowInfo info = KWindowSystem::windowInfo(m_id, NET::WMState | NET::XAWMState); return info.isMinimized(); - } +} int PreviewClientImpl::width() const - { +{ return 0; // only needed for the outline - not needed in preview - } +} int PreviewClientImpl::height() const - { +{ return 0; // only needed for the outline - not needed in preview - } +} WId PreviewClientImpl::window() const - { +{ return m_id; - } +} int PreviewClientImpl::x() const - { +{ return 0; // only needed for the outline - not needed in preview - } +} int PreviewClientImpl::y() const - { +{ return 0; // only needed for the outline - not needed in preview - } +} /******************************************************* * PreviewHandlerImpl *******************************************************/ PreviewHandlerImpl::PreviewHandlerImpl() - { +{ QList< WId > windows = KWindowSystem::stackingOrder(); - foreach( WId w, windows ) - { - m_stackingOrder.append( new PreviewClientImpl( w ) ); - kDebug( 1212 ) << "Window " << w; - } + foreach (WId w, windows) { + m_stackingOrder.append(new PreviewClientImpl(w)); + kDebug(1212) << "Window " << w; } +} PreviewHandlerImpl::~PreviewHandlerImpl() - { - qDeleteAll( m_stackingOrder.begin(), m_stackingOrder.end() ); +{ + qDeleteAll(m_stackingOrder.begin(), m_stackingOrder.end()); m_stackingOrder.clear(); - } +} -TabBoxClient* PreviewHandlerImpl::clientToAddToList( TabBoxClient* client, int desktop, bool allDesktops ) const - { - Q_UNUSED( desktop ) - Q_UNUSED( allDesktops ) +TabBoxClient* PreviewHandlerImpl::clientToAddToList(TabBoxClient* client, int desktop, bool allDesktops) const +{ + Q_UNUSED(desktop) + Q_UNUSED(allDesktops) // don't include desktops and panels - KWindowInfo info = KWindowSystem::windowInfo( client->window(), NET::WMWindowType ); + KWindowInfo info = KWindowSystem::windowInfo(client->window(), NET::WMWindowType); NET::WindowType wType = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask); if (wType != NET::Normal && wType != NET::Override && wType != NET::Unknown && - wType != NET::Dialog && wType != NET::Utility) - { + wType != NET::Dialog && wType != NET::Utility) { return NULL; - } - return client; } + return client; +} TabBoxClientList PreviewHandlerImpl::stackingOrder() const - { +{ return m_stackingOrder; - } +} -int PreviewHandlerImpl::nextDesktopFocusChain( int desktop ) const - { +int PreviewHandlerImpl::nextDesktopFocusChain(int desktop) const +{ int ret = desktop + 1; - if( ret > numberOfDesktops() ) + if (ret > numberOfDesktops()) ret = 1; return ret; - } +} int PreviewHandlerImpl::numberOfDesktops() const - { +{ return KWindowSystem::numberOfDesktops(); - } +} int PreviewHandlerImpl::currentDesktop() const - { +{ return KWindowSystem::currentDesktop(); - } +} -QString PreviewHandlerImpl::desktopName( int desktop ) const - { - return KWindowSystem::desktopName( desktop ); - } +QString PreviewHandlerImpl::desktopName(int desktop) const +{ + return KWindowSystem::desktopName(desktop); +} -QString PreviewHandlerImpl::desktopName( TabBoxClient* client ) const - { - Q_UNUSED( client ) - return desktopName( 1 ); - } +QString PreviewHandlerImpl::desktopName(TabBoxClient* client) const +{ + Q_UNUSED(client) + return desktopName(1); +} -TabBoxClient* PreviewHandlerImpl::nextClientFocusChain( TabBoxClient* client ) const - { - if( m_stackingOrder.isEmpty() ) +TabBoxClient* PreviewHandlerImpl::nextClientFocusChain(TabBoxClient* client) const +{ + if (m_stackingOrder.isEmpty()) return NULL; - int index = m_stackingOrder.indexOf( client ); + int index = m_stackingOrder.indexOf(client); index++; - if( index >= m_stackingOrder.count() ) + if (index >= m_stackingOrder.count()) index = 0; return m_stackingOrder[ index ]; - } +} KWin::TabBox::TabBoxClient* PreviewHandlerImpl::activeClient() const - { - if( m_stackingOrder.isEmpty() ) +{ + if (m_stackingOrder.isEmpty()) return NULL; return m_stackingOrder[ 0 ]; - } +} int PreviewHandlerImpl::activeScreen() const - { +{ return 0; - } +} TabBoxClient* PreviewHandlerImpl::desktopClient() const - { +{ return 0; - } +} } // namespace TabBox diff --git a/kcmkwin/kwintabbox/previewhandlerimpl.h b/kcmkwin/kwintabbox/previewhandlerimpl.h index 2f906f34a..6d2656204 100644 --- a/kcmkwin/kwintabbox/previewhandlerimpl.h +++ b/kcmkwin/kwintabbox/previewhandlerimpl.h @@ -31,45 +31,45 @@ namespace TabBox class PreviewClientImpl : public KWin::TabBox::TabBoxClient - { - public: - PreviewClientImpl( WId id ); - ~PreviewClientImpl(); +{ +public: + PreviewClientImpl(WId id); + ~PreviewClientImpl(); - virtual QString caption() const; - virtual int height() const; - virtual QPixmap icon( const QSize& size = QSize( 32, 32 ) ) const; - virtual bool isMinimized() const; - virtual int width() const; - virtual WId window() const; - virtual int x() const; - virtual int y() const; + virtual QString caption() const; + virtual int height() const; + virtual QPixmap icon(const QSize& size = QSize(32, 32)) const; + virtual bool isMinimized() const; + virtual int width() const; + virtual WId window() const; + virtual int x() const; + virtual int y() const; - private: - WId m_id; - }; +private: + WId m_id; +}; class PreviewHandlerImpl : public KWin::TabBox::TabBoxHandler - { - public: - PreviewHandlerImpl(); - ~PreviewHandlerImpl(); - virtual KWin::TabBox::TabBoxClient* clientToAddToList(KWin::TabBox::TabBoxClient* client, int desktop, bool allDesktops) const; - virtual KWin::TabBox::TabBoxClientList stackingOrder() const; - virtual int nextDesktopFocusChain(int desktop) const; - virtual int numberOfDesktops() const; - virtual int currentDesktop() const; - virtual QString desktopName(int desktop) const; - virtual QString desktopName(KWin::TabBox::TabBoxClient* client) const; - virtual KWin::TabBox::TabBoxClient* nextClientFocusChain(KWin::TabBox::TabBoxClient* client) const; - virtual KWin::TabBox::TabBoxClient* activeClient() const; - virtual int activeScreen() const; - virtual TabBoxClient* desktopClient() const; +{ +public: + PreviewHandlerImpl(); + ~PreviewHandlerImpl(); + virtual KWin::TabBox::TabBoxClient* clientToAddToList(KWin::TabBox::TabBoxClient* client, int desktop, bool allDesktops) const; + virtual KWin::TabBox::TabBoxClientList stackingOrder() const; + virtual int nextDesktopFocusChain(int desktop) const; + virtual int numberOfDesktops() const; + virtual int currentDesktop() const; + virtual QString desktopName(int desktop) const; + virtual QString desktopName(KWin::TabBox::TabBoxClient* client) const; + virtual KWin::TabBox::TabBoxClient* nextClientFocusChain(KWin::TabBox::TabBoxClient* client) const; + virtual KWin::TabBox::TabBoxClient* activeClient() const; + virtual int activeScreen() const; + virtual TabBoxClient* desktopClient() const; - private: - TabBoxClientList m_stackingOrder; - }; +private: + TabBoxClientList m_stackingOrder; +}; } // namespace TabBox } // namespace KWin diff --git a/killer/killer.cpp b/killer/killer.cpp index 725026600..581c60c60 100644 --- a/killer/killer.cpp +++ b/killer/killer.cpp @@ -32,10 +32,10 @@ DEALINGS IN THE SOFTWARE. #include #include -int main( int argc, char* argv[] ) - { - KCmdLineArgs::init( argc, argv, "kwin_killer_helper", "kwin", ki18n( "KWin" ), "1.0" , - ki18n( "KWin helper utility" )); +int main(int argc, char* argv[]) +{ + KCmdLineArgs::init(argc, argv, "kwin_killer_helper", "kwin", ki18n("KWin"), "1.0" , + ki18n("KWin helper utility")); KCmdLineOptions options; options.add("pid ", ki18n("PID of the application to terminate")); @@ -44,43 +44,39 @@ int main( int argc, char* argv[] ) options.add("applicationname ", ki18n("Name of the application to be terminated")); options.add("wid ", ki18n("ID of resource belonging to the application")); options.add("timestamp