events.cpp

00001 /*****************************************************************
00002  KWin - the KDE window manager
00003  This file is part of the KDE project.
00004 
00005 Copyright (C) 1999, 2000 Matthias Ettrich <ettrich@kde.org>
00006 Copyright (C) 2003 Lubos Lunak <l.lunak@kde.org>
00007 
00008 You can Freely distribute this program under the GNU General Public
00009 License. See the file "COPYING" for the exact licensing terms.
00010 ******************************************************************/
00011 
00012 /*
00013 
00014  This file contains things relevant to handling incoming events.
00015 
00016 */
00017 
00018 #include "client.h"
00019 #include "workspace.h"
00020 #include "atoms.h"
00021 #include "tabbox.h"
00022 #include "group.h"
00023 #include "rules.h"
00024 
00025 #include <qwhatsthis.h>
00026 #include <kkeynative.h>
00027 #include <qapplication.h>
00028 
00029 #include <X11/extensions/shape.h>
00030 #include <X11/Xatom.h>
00031 
00032 extern Time qt_x_time;
00033 extern Atom qt_window_role;
00034 
00035 namespace KWinInternal
00036 {
00037 
00038 // ****************************************
00039 // WinInfo
00040 // ****************************************
00041 
00042 WinInfo::WinInfo( Client * c, Display * display, Window window,
00043     Window rwin, const unsigned long pr[], int pr_size )
00044     : NETWinInfo( display, window, rwin, pr, pr_size, NET::WindowManager ), m_client( c )
00045     {
00046     }
00047 
00048 void WinInfo::changeDesktop(int desktop)
00049     {
00050     m_client->workspace()->sendClientToDesktop( m_client, desktop, true );
00051     }
00052 
00053 void WinInfo::changeState( unsigned long state, unsigned long mask )
00054     {
00055     mask &= ~NET::Sticky; // KWin doesn't support large desktops, ignore
00056     mask &= ~NET::Hidden; // clients are not allowed to change this directly
00057     state &= mask; // for safety, clear all other bits
00058 
00059     if(( mask & NET::FullScreen ) != 0 && ( state & NET::FullScreen ) == 0 )
00060         m_client->setFullScreen( false, false );
00061     if ( (mask & NET::Max) == NET::Max )
00062         m_client->setMaximize( state & NET::MaxVert, state & NET::MaxHoriz );
00063     else if ( mask & NET::MaxVert )
00064         m_client->setMaximize( state & NET::MaxVert, m_client->maximizeMode() & Client::MaximizeHorizontal );
00065     else if ( mask & NET::MaxHoriz )
00066         m_client->setMaximize( m_client->maximizeMode() & Client::MaximizeVertical, state & NET::MaxHoriz );
00067 
00068     if ( mask & NET::Shaded )
00069         m_client->setShade( state & NET::Shaded ? ShadeNormal : ShadeNone );
00070     if ( mask & NET::KeepAbove)
00071         m_client->setKeepAbove( (state & NET::KeepAbove) != 0 );
00072     if ( mask & NET::KeepBelow)
00073         m_client->setKeepBelow( (state & NET::KeepBelow) != 0 );
00074     if( mask & NET::SkipTaskbar )
00075         m_client->setSkipTaskbar( ( state & NET::SkipTaskbar ) != 0, true );
00076     if( mask & NET::SkipPager )
00077         m_client->setSkipPager( ( state & NET::SkipPager ) != 0 );
00078     if( mask & NET::DemandsAttention )
00079         m_client->demandAttention(( state & NET::DemandsAttention ) != 0 );
00080     if( mask & NET::Modal )
00081         m_client->setModal( ( state & NET::Modal ) != 0 );
00082     // unsetting fullscreen first, setting it last (because e.g. maximize works only for !isFullScreen() )
00083     if(( mask & NET::FullScreen ) != 0 && ( state & NET::FullScreen ) != 0 )
00084         m_client->setFullScreen( true, false );
00085     }
00086 
00087 
00088 // ****************************************
00089 // RootInfo
00090 // ****************************************
00091 
00092 RootInfo::RootInfo( Workspace* ws, Display *dpy, Window w, const char *name, unsigned long pr[], int pr_num, int scr )
00093     : NETRootInfo4( dpy, w, name, pr, pr_num, scr )
00094     {
00095     workspace = ws;
00096     }
00097 
00098 void RootInfo::changeNumberOfDesktops(int n)
00099     {
00100     workspace->setNumberOfDesktops( n );
00101     }
00102 
00103 void RootInfo::changeCurrentDesktop(int d)
00104     {
00105     workspace->setCurrentDesktop( d );
00106     }
00107 
00108 void RootInfo::changeActiveWindow( Window w, NET::RequestSource src, Time timestamp, Window active_window )
00109     {
00110     if( Client* c = workspace->findClient( WindowMatchPredicate( w )))
00111         {
00112         if( timestamp == CurrentTime )
00113             timestamp = c->userTime();
00114         if( src != NET::FromApplication && src != FromTool )
00115             src = NET::FromTool;
00116         if( src == NET::FromTool )
00117             workspace->activateClient( c, true ); // force
00118         else // NET::FromApplication
00119             {
00120             Client* c2;
00121             if( workspace->allowClientActivation( c, timestamp ))
00122                 workspace->activateClient( c );
00123             // if activation of the requestor's window would be allowed, allow activation too
00124             else if( active_window != None
00125                 && ( c2 = workspace->findClient( WindowMatchPredicate( active_window ))) != NULL
00126                 && workspace->allowClientActivation( c2,
00127                     timestampCompare( timestamp, c2->userTime() > 0 ? timestamp : c2->userTime())))
00128                 workspace->activateClient( c );
00129             else
00130                 c->demandAttention();
00131             }
00132         }
00133     }
00134 
00135 void RootInfo::restackWindow( Window w, RequestSource src, Window above, int detail, Time timestamp )
00136     {
00137     if( Client* c = workspace->findClient( WindowMatchPredicate( w )))
00138         {
00139         if( timestamp == CurrentTime )
00140             timestamp = c->userTime();
00141         if( src != NET::FromApplication && src != FromTool )
00142             src = NET::FromTool;
00143         c->restackWindow( above, detail, src, timestamp, true );
00144         }
00145     }
00146 
00147 void RootInfo::gotTakeActivity( Window w, Time timestamp, long flags )
00148     {
00149     if( Client* c = workspace->findClient( WindowMatchPredicate( w )))
00150         workspace->handleTakeActivity( c, timestamp, flags );
00151     }
00152 
00153 void RootInfo::closeWindow(Window w)
00154     {
00155     Client* c = workspace->findClient( WindowMatchPredicate( w ));
00156     if ( c )
00157         c->closeWindow();
00158     }
00159 
00160 void RootInfo::moveResize(Window w, int x_root, int y_root, unsigned long direction)
00161     {
00162     Client* c = workspace->findClient( WindowMatchPredicate( w ));
00163     if ( c )
00164         {
00165         updateXTime(); // otherwise grabbing may have old timestamp - this message should include timestamp
00166         c->NETMoveResize( x_root, y_root, (Direction)direction);
00167         }
00168     }
00169 
00170 void RootInfo::moveResizeWindow(Window w, int flags, int x, int y, int width, int height )
00171     {
00172     Client* c = workspace->findClient( WindowMatchPredicate( w ));
00173     if ( c )
00174         c->NETMoveResizeWindow( flags, x, y, width, height );
00175     }
00176 
00177 void RootInfo::gotPing( Window w, Time timestamp )
00178     {
00179     if( Client* c = workspace->findClient( WindowMatchPredicate( w )))
00180         c->gotPing( timestamp );
00181     }
00182 
00183 void RootInfo::changeShowingDesktop( bool showing )
00184     {
00185     workspace->setShowingDesktop( showing );
00186     }
00187 
00188 // ****************************************
00189 // Workspace
00190 // ****************************************
00191 
00195 bool Workspace::workspaceEvent( XEvent * e )
00196     {
00197     if ( mouse_emulation && (e->type == ButtonPress || e->type == ButtonRelease ) ) 
00198         {
00199         mouse_emulation = FALSE;
00200         XUngrabKeyboard( qt_xdisplay(), qt_x_time );
00201         }
00202 
00203     if ( e->type == PropertyNotify || e->type == ClientMessage ) 
00204         {
00205         if ( netCheck( e ) )
00206             return TRUE;
00207         }
00208 
00209     // events that should be handled before Clients can get them
00210     switch (e->type) 
00211         {
00212         case ButtonPress:
00213         case ButtonRelease:
00214             was_user_interaction = true;
00215         // fallthrough
00216         case MotionNotify:
00217             if ( tab_grab || control_grab )
00218                 {
00219                 tab_box->handleMouseEvent( e );
00220                 return TRUE;
00221                 }
00222             break;
00223         case KeyPress:
00224             {
00225             was_user_interaction = true;
00226             KKeyNative keyX( (XEvent*)e );
00227             uint keyQt = keyX.keyCodeQt();
00228             kdDebug(125) << "Workspace::keyPress( " << keyX.key().toString() << " )" << endl;
00229             if (movingClient)
00230                 {
00231                 movingClient->keyPressEvent(keyQt);
00232                 return true;
00233                 }
00234             if( tab_grab || control_grab )
00235                 {
00236                 tabBoxKeyPress( keyX );
00237                 return true;
00238                 }
00239             break;
00240             }
00241         case KeyRelease:
00242             was_user_interaction = true;
00243             if( tab_grab || control_grab )
00244                 {
00245                 tabBoxKeyRelease( e->xkey );
00246                 return true;
00247                 }
00248             break;
00249         };
00250 
00251     if( Client* c = findClient( WindowMatchPredicate( e->xany.window )))
00252         {
00253         if( c->windowEvent( e ))
00254             return true;
00255         }
00256     else if( Client* c = findClient( WrapperIdMatchPredicate( e->xany.window )))
00257         {
00258         if( c->windowEvent( e ))
00259             return true;
00260         }
00261     else if( Client* c = findClient( FrameIdMatchPredicate( e->xany.window )))
00262         {
00263         if( c->windowEvent( e ))
00264             return true;
00265         }
00266     else
00267         {
00268         Window special = findSpecialEventWindow( e );
00269         if( special != None )
00270             if( Client* c = findClient( WindowMatchPredicate( special )))
00271                 {
00272                 if( c->windowEvent( e ))
00273                     return true;
00274                 }
00275         }
00276     if( movingClient != NULL && movingClient->moveResizeGrabWindow() == e->xany.window
00277         && ( e->type == MotionNotify || e->type == ButtonPress || e->type == ButtonRelease ))
00278         {
00279         if( movingClient->windowEvent( e ))
00280             return true;
00281         }
00282 
00283     switch (e->type) 
00284         {
00285         case CreateNotify:
00286             if ( e->xcreatewindow.parent == root &&
00287                  !QWidget::find( e->xcreatewindow.window) &&
00288                  !e->xcreatewindow.override_redirect )
00289             {
00290         // see comments for allowClientActivation()
00291             XChangeProperty(qt_xdisplay(), e->xcreatewindow.window,
00292                             atoms->kde_net_wm_user_creation_time, XA_CARDINAL,
00293                             32, PropModeReplace, (unsigned char *)&qt_x_time, 1);
00294             }
00295         break;
00296 
00297     case UnmapNotify:
00298             {
00299         // check for system tray windows
00300             if ( removeSystemTrayWin( e->xunmap.window, true ) ) 
00301                 {
00302         // If the system tray gets destroyed, the system tray
00303         // icons automatically get unmapped, reparented and mapped
00304         // again to the closest non-client ancestor due to
00305         // QXEmbed's SaveSet feature. Unfortunatly with kicker
00306         // this closest ancestor is not the root window, but our
00307         // decoration, so we reparent explicitely back to the root
00308         // window.
00309                 XEvent ev;
00310                 WId w = e->xunmap.window;
00311                 if ( XCheckTypedWindowEvent (qt_xdisplay(), w,
00312                                              ReparentNotify, &ev) )
00313                     {
00314                     if ( ev.xreparent.parent != root ) 
00315                         {
00316                         XReparentWindow( qt_xdisplay(), w, root, 0, 0 );
00317                         addSystemTrayWin( w );
00318                         }
00319                     }
00320                 return TRUE;
00321                 }
00322 
00323             return ( e->xunmap.event != e->xunmap.window ); // hide wm typical event from Qt
00324             }
00325         case MapNotify:
00326 
00327             return ( e->xmap.event != e->xmap.window ); // hide wm typical event from Qt
00328 
00329         case ReparentNotify:
00330             {
00331         //do not confuse Qt with these events. After all, _we_ are the
00332         //window manager who does the reparenting.
00333             return TRUE;
00334             }
00335         case DestroyNotify:
00336             {
00337             if ( removeSystemTrayWin( e->xdestroywindow.window, false ) )
00338                 return TRUE;
00339             return false;
00340             }
00341         case MapRequest:
00342             {
00343             updateXTime();
00344 
00345             // e->xmaprequest.window is different from e->xany.window
00346             // TODO this shouldn't be necessary now
00347             Client* c = findClient( WindowMatchPredicate( e->xmaprequest.window ));
00348             if ( !c ) 
00349                 {
00350 // don't check for the parent being the root window, this breaks when some app unmaps
00351 // a window, changes something and immediately maps it back, without giving KWin
00352 // a chance to reparent it back to root
00353 // since KWin can get MapRequest only for root window children and
00354 // children of WindowWrapper (=clients), the check is AFAIK useless anyway
00355 // Note: Now the save-set support in Client::mapRequestEvent() actually requires that
00356 // this code doesn't check the parent to be root.
00357 //            if ( e->xmaprequest.parent == root ) { //###TODO store previously destroyed client ids
00358                 if ( addSystemTrayWin( e->xmaprequest.window ) )
00359                     return TRUE;
00360                 c = createClient( e->xmaprequest.window, false );
00361                 if ( c != NULL && root != qt_xrootwin() ) 
00362                     { // TODO what is this?
00363                     // TODO may use QWidget::create
00364                     XReparentWindow( qt_xdisplay(), c->frameId(), root, 0, 0 );
00365                     }
00366                 if( c == NULL ) // refused to manage, simply map it (most probably override redirect)
00367                     XMapRaised( qt_xdisplay(), e->xmaprequest.window );
00368                 return true;
00369                 }
00370             if( c )
00371                 {
00372                 c->windowEvent( e );
00373                 updateFocusChains( c, FocusChainUpdate );
00374                 return true;
00375                 }
00376             break;
00377             }
00378         case EnterNotify:
00379             {
00380             if ( QWhatsThis::inWhatsThisMode() )
00381                 {
00382                 QWidget* w = QWidget::find( e->xcrossing.window );
00383                 if ( w )
00384                     QWhatsThis::leaveWhatsThisMode();
00385                 }
00386             if( electricBorder(e))
00387                 return true;
00388             break;
00389             }
00390         case LeaveNotify:
00391             {
00392             if ( !QWhatsThis::inWhatsThisMode() )
00393                 break;
00394             // TODO is this cliente ever found, given that client events are searched above?
00395             Client* c = findClient( FrameIdMatchPredicate( e->xcrossing.window ));
00396             if ( c && e->xcrossing.detail != NotifyInferior )
00397                 QWhatsThis::leaveWhatsThisMode();
00398             break;
00399             }
00400         case ConfigureRequest:
00401             {
00402             if ( e->xconfigurerequest.parent == root ) 
00403                 {
00404                 XWindowChanges wc;
00405                 wc.border_width = e->xconfigurerequest.border_width;
00406                 wc.x = e->xconfigurerequest.x;
00407                 wc.y = e->xconfigurerequest.y;
00408                 wc.width = e->xconfigurerequest.width;
00409                 wc.height = e->xconfigurerequest.height;
00410                 wc.sibling = None;
00411                 wc.stack_mode = Above;
00412                 unsigned int value_mask = e->xconfigurerequest.value_mask
00413                     & ( CWX | CWY | CWWidth | CWHeight | CWBorderWidth );
00414                 XConfigureWindow( qt_xdisplay(), e->xconfigurerequest.window, value_mask, &wc );
00415                 return true;
00416                 }
00417             break;
00418             }
00419         case KeyPress:
00420             if ( mouse_emulation )
00421                 return keyPressMouseEmulation( e->xkey );
00422             break;
00423         case KeyRelease:
00424             if ( mouse_emulation )
00425                 return FALSE;
00426             break;
00427         case FocusIn:
00428             if( e->xfocus.window == rootWin()
00429                 && ( e->xfocus.detail == NotifyDetailNone || e->xfocus.detail == NotifyPointerRoot ))
00430                 {
00431                 updateXTime(); // focusToNull() uses qt_x_time, which is old now (FocusIn has no timestamp)
00432                 Window focus;
00433                 int revert;
00434                 XGetInputFocus( qt_xdisplay(), &focus, &revert );
00435                 if( focus == None || focus == PointerRoot )
00436                     {
00437                     //kdWarning( 1212 ) << "X focus set to None/PointerRoot, reseting focus" << endl;
00438                     Client *c = mostRecentlyActivatedClient();
00439                     if( c != NULL )
00440                         requestFocus( c, true );
00441                     else if( activateNextClient( NULL ))
00442                         ; // ok, activated
00443                     else
00444                         focusToNull();
00445                     }
00446                 }
00447             // fall through
00448         case FocusOut:
00449             return true; // always eat these, they would tell Qt that KWin is the active app
00450         case ClientMessage:
00451             if( electricBorder( e ))
00452                 return true;
00453             break;
00454         default:
00455             break;
00456         }
00457     return FALSE;
00458     }
00459 
00460 // Some events don't have the actual window which caused the event
00461 // as e->xany.window (e.g. ConfigureRequest), but as some other
00462 // field in the XEvent structure.
00463 Window Workspace::findSpecialEventWindow( XEvent* e )
00464     {
00465     switch( e->type )
00466         {
00467         case CreateNotify:
00468             return e->xcreatewindow.window;
00469         case DestroyNotify:
00470             return e->xdestroywindow.window;
00471         case UnmapNotify:
00472             return e->xunmap.window;
00473         case MapNotify:
00474             return e->xmap.window;
00475         case MapRequest:
00476             return e->xmaprequest.window;
00477         case ReparentNotify:
00478             return e->xreparent.window;
00479         case ConfigureNotify:
00480             return e->xconfigure.window;
00481         case GravityNotify:
00482             return e->xgravity.window;
00483         case ConfigureRequest:
00484             return e->xconfigurerequest.window;
00485         case CirculateNotify:
00486             return e->xcirculate.window;
00487         case CirculateRequest:
00488             return e->xcirculaterequest.window;
00489         default:
00490             return None;
00491         };
00492     }
00493 
00497 bool Workspace::netCheck( XEvent* e )
00498     {
00499     unsigned int dirty = rootInfo->event( e );
00500 
00501     if ( dirty & NET::DesktopNames )
00502         saveDesktopSettings();
00503 
00504     return dirty != 0;
00505     }
00506 
00507 
00508 // ****************************************
00509 // Client
00510 // ****************************************
00511 
00515 bool Client::windowEvent( XEvent* e )
00516     {
00517     if( e->xany.window == window()) // avoid doing stuff on frame or wrapper
00518         {
00519         unsigned long dirty[ 2 ];
00520         info->event( e, dirty, 2 ); // pass through the NET stuff
00521 
00522         if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMName ) != 0 )
00523             fetchName();
00524         if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIconName ) != 0 )
00525             fetchIconicName();
00526         if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMStrut ) != 0
00527             || ( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2ExtendedStrut ) != 0 )
00528             {
00529             if( isTopMenu())  // the fallback mode of KMenuBar may alter the strut
00530                 checkWorkspacePosition();  // restore it
00531             workspace()->updateClientArea();
00532             }
00533         if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0 )
00534             getIcons();
00535         // Note there's a difference between userTime() and info->userTime()
00536         // info->userTime() is the value of the property, userTime() also includes
00537         // updates of the time done by KWin (ButtonPress on windowrapper etc.).
00538         if(( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2UserTime ) != 0 )
00539             {
00540             workspace()->setWasUserInteraction();
00541             updateUserTime( info->userTime());
00542             }
00543         if(( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId ) != 0 )
00544             startupIdChanged();
00545         if( dirty[ WinInfo::PROTOCOLS ] & NET::WMIconGeometry )
00546             {
00547             if( demandAttentionKNotifyTimer != NULL )
00548                 demandAttentionKNotify();
00549             }
00550         }
00551 
00552 // TODO move all focus handling stuff to separate file?
00553     switch (e->type) 
00554         {
00555         case UnmapNotify:
00556             unmapNotifyEvent( &e->xunmap );
00557             break;
00558         case DestroyNotify:
00559             destroyNotifyEvent( &e->xdestroywindow );
00560             break;
00561         case MapRequest:
00562             // this one may pass the event to workspace
00563             return mapRequestEvent( &e->xmaprequest );
00564         case ConfigureRequest:
00565             configureRequestEvent( &e->xconfigurerequest );
00566             break;
00567         case PropertyNotify:
00568             propertyNotifyEvent( &e->xproperty );
00569             break;
00570         case KeyPress:
00571             updateUserTime();
00572             workspace()->setWasUserInteraction();
00573             break;
00574         case ButtonPress:
00575             updateUserTime();
00576             workspace()->setWasUserInteraction();
00577             buttonPressEvent( e->xbutton.window, e->xbutton.button, e->xbutton.state,
00578                 e->xbutton.x, e->xbutton.y, e->xbutton.x_root, e->xbutton.y_root );
00579             break;
00580         case KeyRelease:
00581     // don't update user time on releases
00582     // e.g. if the user presses Alt+F2, the Alt release
00583     // would appear as user input to the currently active window
00584             break;
00585         case ButtonRelease:
00586     // don't update user time on releases
00587     // e.g. if the user presses Alt+F2, the Alt release
00588     // would appear as user input to the currently active window
00589             buttonReleaseEvent( e->xbutton.window, e->xbutton.button, e->xbutton.state,
00590                 e->xbutton.x, e->xbutton.y, e->xbutton.x_root, e->xbutton.y_root );
00591             break;
00592         case MotionNotify:
00593             motionNotifyEvent( e->xmotion.window, e->xmotion.state,
00594                 e->xmotion.x, e->xmotion.y, e->xmotion.x_root, e->xmotion.y_root );
00595             break;
00596         case EnterNotify:
00597             enterNotifyEvent( &e->xcrossing );
00598             // MotionNotify is guaranteed to be generated only if the mouse
00599             // move start and ends in the window; for cases when it only
00600             // starts or only ends there, Enter/LeaveNotify are generated.
00601             // Fake a MotionEvent in such cases to make handle of mouse
00602             // events simpler (Qt does that too).
00603             motionNotifyEvent( e->xcrossing.window, e->xcrossing.state,
00604                 e->xcrossing.x, e->xcrossing.y, e->xcrossing.x_root, e->xcrossing.y_root );
00605             break;
00606         case LeaveNotify:
00607             motionNotifyEvent( e->xcrossing.window, e->xcrossing.state,
00608                 e->xcrossing.x, e->xcrossing.y, e->xcrossing.x_root, e->xcrossing.y_root );
00609             leaveNotifyEvent( &e->xcrossing );
00610             break;
00611         case FocusIn:
00612             focusInEvent( &e->xfocus );
00613             break;
00614         case FocusOut:
00615             focusOutEvent( &e->xfocus );
00616             break;
00617         case ReparentNotify:
00618             break;
00619         case ClientMessage:
00620             clientMessageEvent( &e->xclient );
00621             break;
00622         case ColormapChangeMask:
00623             if( e->xany.window == window())
00624             {
00625             cmap = e->xcolormap.colormap;
00626             if ( isActive() )
00627                 workspace()->updateColormap();
00628             }
00629             break;
00630         case VisibilityNotify:
00631             visibilityNotifyEvent( &e->xvisibility );
00632             break;
00633         default:
00634             if( e->xany.window == window())
00635             {
00636             if( e->type == Shape::shapeEvent() )
00637                 {
00638                 is_shape = Shape::hasShape( window()); // workaround for #19644
00639                 updateShape();
00640                 }
00641             }
00642             break;
00643         }
00644     return true; // eat all events
00645     }
00646 
00650 bool Client::mapRequestEvent( XMapRequestEvent* e )
00651     {
00652     if( e->window != window())
00653         {
00654         // Special support for the save-set feature, which is a bit broken.
00655         // If there's a window from one client embedded in another one,
00656         // e.g. using XEMBED, and the embedder suddenly looses its X connection,
00657         // save-set will reparent the embedded window to its closest ancestor
00658         // that will remains. Unfortunately, with reparenting window managers,
00659         // this is not the root window, but the frame (or in KWin's case,
00660         // it's the wrapper for the client window). In this case,
00661         // the wrapper will get ReparentNotify for a window it won't know,
00662         // which will be ignored, and then it gets MapRequest, as save-set
00663         // always maps. Returning true here means that Workspace::workspaceEvent()
00664         // will handle this MapRequest and manage this window (i.e. act as if
00665         // it was reparented to root window).
00666         if( e->parent == wrapperId())
00667             return false;
00668         return true; // no messing with frame etc.
00669         }
00670     if( isTopMenu() && workspace()->managingTopMenus())
00671         return true; // kwin controls these
00672     switch ( mappingState() )
00673         {
00674         case WithdrawnState:
00675             assert( false ); // WMs are not supposed to manage clients in Withdrawn state,
00676 //        manage();      // after initial mapping manage() is called from createClient()
00677             break;
00678         case IconicState:
00679     // also copied in clientMessage()
00680             if( isMinimized())
00681                 unminimize();
00682             if( isShade())
00683                 setShade( ShadeNone );
00684             if( !isOnCurrentDesktop())
00685                 {
00686                 if( workspace()->allowClientActivation( this ))
00687                     workspace()->activateClient( this );
00688                 else
00689                     demandAttention();
00690                 }
00691             break;
00692         case NormalState:
00693         // TODO fake MapNotify?
00694             break;
00695         }
00696     return true;
00697     }
00698 
00702 void Client::unmapNotifyEvent( XUnmapEvent* e )
00703     {
00704     if( e->window != window())
00705         return;
00706     if( e->event != wrapperId())
00707         { // most probably event from root window when initially reparenting
00708         bool ignore = true;
00709         if( e->event == workspace()->rootWin() && e->send_event )
00710             ignore = false; // XWithdrawWindow()
00711         if( ignore )
00712             return;
00713         }
00714     switch( mappingState())
00715         {
00716         case IconicState:
00717             releaseWindow();
00718           return;
00719         case NormalState:
00720             // maybe we will be destroyed soon. Check this first.
00721             XEvent ev;
00722             if( XCheckTypedWindowEvent (qt_xdisplay(), window(),
00723                 DestroyNotify, &ev) ) // TODO I don't like this much
00724                 {
00725                 destroyClient(); // deletes this
00726                 return;
00727                 }
00728             releaseWindow();
00729           break;
00730     default:
00731         assert( false );
00732         }
00733     }
00734 
00735 void Client::destroyNotifyEvent( XDestroyWindowEvent* e )
00736     {
00737     if( e->window != window())
00738         return;
00739     destroyClient();
00740     }
00741     
00742     
00743 bool         blockAnimation = FALSE;
00744 
00748 void Client::clientMessageEvent( XClientMessageEvent* e )
00749     {
00750     if( e->window != window())
00751         return; // ignore frame/wrapper
00752     // WM_STATE
00753     if ( e->message_type == atoms->kde_wm_change_state )
00754         {
00755         if( isTopMenu() && workspace()->managingTopMenus())
00756             return; // kwin controls these
00757         if( e->data.l[ 1 ] )
00758             blockAnimation = true;
00759         if( e->data.l[ 0 ] == IconicState )
00760             minimize();
00761         else if( e->data.l[ 0 ] == NormalState )
00762             { // copied from mapRequest()
00763             if( isMinimized())
00764                 unminimize();
00765             if( isShade())
00766                 setShade( ShadeNone );
00767             if( !isOnCurrentDesktop())
00768                 {
00769                 if( workspace()->allowClientActivation( this ))
00770                     workspace()->activateClient( this );
00771                 else
00772                     demandAttention();
00773                 }
00774             }
00775         blockAnimation = false;
00776         }
00777     else if ( e->message_type == atoms->wm_change_state)
00778         {
00779         if( isTopMenu() && workspace()->managingTopMenus())
00780             return; // kwin controls these
00781         if ( e->data.l[0] == IconicState )
00782             minimize();
00783         return;
00784         }
00785     }
00786 
00787 
00791 void Client::configureRequestEvent( XConfigureRequestEvent* e )
00792     {
00793     if( e->window != window())
00794         return; // ignore frame/wrapper
00795     if ( isResize() || isMove())
00796         return; // we have better things to do right now
00797 
00798     if( fullscreen_mode == FullScreenNormal ) // refuse resizing of fullscreen windows
00799         { // but allow resizing fullscreen hacks in order to let them cancel fullscreen mode
00800         sendSyntheticConfigureNotify();
00801         return;
00802         }
00803     if( isSplash() // no manipulations with splashscreens either
00804         || isTopMenu()) // topmenus neither
00805         {
00806         sendSyntheticConfigureNotify();
00807         return;
00808         }
00809 
00810     if ( e->value_mask & CWBorderWidth ) 
00811         {
00812         // first, get rid of a window border
00813         XWindowChanges wc;
00814         unsigned int value_mask = 0;
00815 
00816         wc.border_width = 0;
00817         value_mask = CWBorderWidth;
00818         XConfigureWindow( qt_xdisplay(), window(), value_mask, & wc );
00819         }
00820 
00821     if( e->value_mask & ( CWX | CWY | CWHeight | CWWidth ))
00822         configureRequest( e->value_mask, e->x, e->y, e->width, e->height, 0, false );
00823 
00824     if ( e->value_mask & CWStackMode )
00825         restackWindow( e->above, e->detail, NET::FromApplication, userTime(), false );
00826 
00827     // TODO sending a synthetic configure notify always is fine, even in cases where
00828     // the ICCCM doesn't require this - it can be though of as 'the WM decided to move
00829     // the window later'. The client should not cause that many configure request,
00830     // so this should not have any significant impact. With user moving/resizing
00831     // the it should be optimized though (see also Client::setGeometry()/plainResize()/move()).
00832     sendSyntheticConfigureNotify();
00833 
00834     // SELI TODO accept configure requests for isDesktop windows (because kdesktop
00835     // may get XRANDR resize event before kwin), but check it's still at the bottom?
00836     }
00837 
00838 
00842 void Client::propertyNotifyEvent( XPropertyEvent* e )
00843     {
00844     if( e->window != window())
00845         return; // ignore frame/wrapper
00846     switch ( e->atom ) 
00847         {
00848         case XA_WM_NORMAL_HINTS:
00849             getWmNormalHints();
00850             break;
00851         case XA_WM_NAME:
00852             fetchName();
00853             break;
00854         case XA_WM_ICON_NAME:
00855             fetchIconicName();
00856             break;
00857         case XA_WM_TRANSIENT_FOR:
00858             readTransient();
00859             break;
00860         case XA_WM_HINTS:
00861             getWMHints();
00862             getIcons(); // because KWin::icon() uses WMHints as fallback
00863             break;
00864         default:
00865             if ( e->atom == atoms->wm_protocols )
00866                 getWindowProtocols();
00867             else if (e->atom == atoms->wm_client_leader )
00868                 getWmClientLeader();
00869             else if( e->atom == qt_window_role )
00870                 window_role = staticWindowRole( window());
00871             else if( e->atom == atoms->motif_wm_hints )
00872                 getMotifHints();
00873             break;
00874         }
00875     }
00876 
00877 
00878 void Client::enterNotifyEvent( XCrossingEvent* e )
00879     {
00880     if( e->window != frameId())
00881         return; // care only about entering the whole frame
00882     if( e->mode == NotifyNormal ||
00883          ( !options->focusPolicyIsReasonable() &&
00884              e->mode == NotifyUngrab ) ) 
00885         {
00886 
00887         if (options->shadeHover && isShade()) 
00888             {
00889             delete shadeHoverTimer;
00890             shadeHoverTimer = new QTimer( this );
00891             connect( shadeHoverTimer, SIGNAL( timeout() ), this, SLOT( shadeHover() ));
00892             shadeHoverTimer->start( options->shadeHoverInterval, TRUE );
00893             }
00894 
00895         if ( options->focusPolicy == Options::ClickToFocus )
00896             return;
00897 
00898         if ( options->autoRaise && !isDesktop() &&
00899              !isDock() && !isTopMenu() && workspace()->focusChangeEnabled() &&
00900              workspace()->topClientOnDesktop( workspace()->currentDesktop()) != this ) 
00901             {
00902             delete autoRaiseTimer;
00903             autoRaiseTimer = new QTimer( this );
00904             connect( autoRaiseTimer, SIGNAL( timeout() ), this, SLOT( autoRaise() ) );
00905             autoRaiseTimer->start( options->autoRaiseInterval, TRUE  );
00906             }
00907 
00908         if ( options->focusPolicy !=  Options::FocusStrictlyUnderMouse && ( isDesktop() || isDock() || isTopMenu() ) )
00909             return;
00910         if ( options->delayFocus )
00911             workspace()->requestDelayFocus( this );
00912         else
00913             workspace()->requestFocus( this );
00914 
00915         return;
00916         }
00917     }
00918 
00919 void Client::leaveNotifyEvent( XCrossingEvent* e )
00920     {
00921     if( e->window != frameId())
00922         return; // care only about leaving the whole frame
00923     if ( e->mode == NotifyNormal ) 
00924         {
00925         if ( !buttonDown ) 
00926             {
00927             mode = PositionCenter;
00928             setCursor( arrowCursor );
00929             }
00930         bool lostMouse = !rect().contains( QPoint( e->x, e->y ) );
00931         // 'lostMouse' wouldn't work with e.g. B2 or Keramik, which have non-rectangular decorations
00932         // (i.e. the LeaveNotify event comes before leaving the rect and no LeaveNotify event
00933         // comes after leaving the rect) - so lets check if the pointer is really outside the window
00934 
00935         // TODO this still sucks if a window appears above this one - it should lose the mouse
00936         // if this window is another client, but not if it's a popup ... maybe after KDE3.1 :(
00937         // (repeat after me 'AARGHL!')
00938         if ( !lostMouse && e->detail != NotifyInferior ) 
00939             {
00940             int d1, d2, d3, d4;
00941             unsigned int d5;
00942             Window w, child;
00943             if( XQueryPointer( qt_xdisplay(), frameId(), &w, &child, &d1, &d2, &d3, &d4, &d5 ) == False
00944                 || child == None )
00945                 lostMouse = true; // really lost the mouse
00946             }
00947         if ( lostMouse ) 
00948             {
00949             cancelAutoRaise();
00950             workspace()->cancelDelayFocus();
00951             cancelShadeHover();
00952             if ( shade_mode == ShadeHover && !moveResizeMode && !buttonDown )
00953                setShade( ShadeNormal );
00954             }
00955         if ( options->focusPolicy == Options::FocusStrictlyUnderMouse )
00956             if ( isActive() && lostMouse )
00957                 workspace()->requestFocus( 0 ) ;
00958         return;
00959         }
00960     }
00961 
00962 #define XCapL KKeyNative::modXLock()
00963 #define XNumL KKeyNative::modXNumLock()
00964 #define XScrL KKeyNative::modXScrollLock()
00965 void Client::grabButton( int modifier )
00966     {
00967     unsigned int mods[ 8 ] = 
00968         {
00969         0, XCapL, XNumL, XNumL | XCapL,
00970         XScrL, XScrL | XCapL,
00971         XScrL | XNumL, XScrL | XNumL | XCapL
00972         };
00973     for( int i = 0;
00974          i < 8;
00975          ++i )
00976         XGrabButton( qt_xdisplay(), AnyButton,
00977             modifier | mods[ i ],
00978             wrapperId(),  FALSE, ButtonPressMask,
00979             GrabModeSync, GrabModeAsync, None, None );
00980     }
00981 
00982 void Client::ungrabButton( int modifier )
00983     {
00984     unsigned int mods[ 8 ] = 
00985         {
00986         0, XCapL, XNumL, XNumL | XCapL,
00987         XScrL, XScrL | XCapL,
00988         XScrL | XNumL, XScrL | XNumL | XCapL
00989         };
00990     for( int i = 0;
00991          i < 8;
00992          ++i )
00993         XUngrabButton( qt_xdisplay(), AnyButton,
00994             modifier | mods[ i ], wrapperId());
00995     }
00996 #undef XCapL
00997 #undef XNumL
00998 #undef XScrL
00999 
01000 /*
01001   Releases the passive grab for some modifier combinations when a
01002   window becomes active. This helps broken X programs that
01003   missinterpret LeaveNotify events in grab mode to work properly
01004   (Motif, AWT, Tk, ...)
01005  */
01006 void Client::updateMouseGrab()
01007     {
01008     if( workspace()->globalShortcutsDisabled())
01009         {
01010         XUngrabButton( qt_xdisplay(), AnyButton, AnyModifier, wrapperId());
01011         // keep grab for the simple click without modifiers if needed
01012         if( !( !options->clickRaise || not_obscured ))
01013             grabButton( None );
01014         return;
01015         }
01016     if( isActive() && !workspace()->forcedGlobalMouseGrab()) // see Workspace::establishTabBoxGrab()
01017         {
01018         // remove the grab for no modifiers only if the window
01019         // is unobscured or if the user doesn't want click raise
01020         if( !options->clickRaise || not_obscured )
01021             ungrabButton( None );
01022         else
01023             grabButton( None );
01024         ungrabButton( ShiftMask );
01025         ungrabButton( ControlMask );
01026         ungrabButton( ControlMask | ShiftMask );
01027         }
01028     else
01029         {
01030         XUngrabButton( qt_xdisplay(), AnyButton, AnyModifier, wrapperId());
01031         // simply grab all modifier combinations
01032         XGrabButton(qt_xdisplay(), AnyButton, AnyModifier, wrapperId(), FALSE,
01033             ButtonPressMask,
01034             GrabModeSync, GrabModeAsync,
01035             None, None );
01036         }
01037     }
01038 
01039 int qtToX11Button( Qt::ButtonState button )
01040     {
01041     if( button == Qt::LeftButton )
01042         return Button1;
01043     else if( button == Qt::MidButton )
01044         return Button2;
01045     else if( button == Qt::RightButton )
01046         return Button3;
01047     return AnyButton;
01048     }
01049     
01050 int qtToX11State( Qt::ButtonState state )
01051     {
01052     int ret = 0;
01053     if( state & Qt::LeftButton )
01054         ret |= Button1Mask;
01055     if( state & Qt::MidButton )
01056         ret |= Button2Mask;
01057     if( state & Qt::RightButton )
01058         ret |= Button3Mask;
01059     if( state & Qt::ShiftButton )
01060         ret |= ShiftMask;
01061     if( state & Qt::ControlButton )
01062         ret |= ControlMask;
01063     if( state & Qt::AltButton )
01064         ret |= KKeyNative::modX(KKey::ALT);
01065     if( state & Qt::MetaButton )
01066         ret |= KKeyNative::modX(KKey::WIN);
01067     return ret;
01068     }
01069 
01070 // Qt propagates mouse events up the widget hierachy, which means events
01071 // for the decoration window cannot be (easily) intercepted as X11 events
01072 bool Client::eventFilter( QObject* o, QEvent* e )
01073     {
01074     if( decoration == NULL
01075         || o != decoration->widget())
01076         return false;
01077     if( e->type() == QEvent::MouseButtonPress )
01078         {
01079         QMouseEvent* ev = static_cast< QMouseEvent* >( e );
01080         return buttonPressEvent( decorationId(), qtToX11Button( ev->button()), qtToX11State( ev->state()),
01081             ev->x(), ev->y(), ev->globalX(), ev->globalY() );
01082         }
01083     if( e->type() == QEvent::MouseButtonRelease )
01084         {
01085         QMouseEvent* ev = static_cast< QMouseEvent* >( e );
01086         return buttonReleaseEvent( decorationId(), qtToX11Button( ev->button()), qtToX11State( ev->state()),
01087             ev->x(), ev->y(), ev->globalX(), ev->globalY() );
01088         }
01089     if( e->type() == QEvent::MouseMove ) // FRAME i fake z enter/leave?
01090         {
01091         QMouseEvent* ev = static_cast< QMouseEvent* >( e );
01092         return motionNotifyEvent( decorationId(), qtToX11State( ev->state()),
01093             ev->x(), ev->y(), ev->globalX(), ev->globalY() );
01094         }
01095     if( e->type() == QEvent::Wheel )
01096         {
01097         QWheelEvent* ev = static_cast< QWheelEvent* >( e );
01098         bool r = buttonPressEvent( decorationId(), ev->delta() > 0 ? Button4 : Button5, qtToX11State( ev->state()),
01099             ev->x(), ev->y(), ev->globalX(), ev->globalY() );
01100         r = r || buttonReleaseEvent( decorationId(), ev->delta() > 0 ? Button4 : Button5, qtToX11State( ev->state()),
01101             ev->x(), ev->y(), ev->globalX(), ev->globalY() );
01102         return r;
01103         }
01104     if( e->type() == QEvent::Resize )
01105         {
01106         QResizeEvent* ev = static_cast< QResizeEvent* >( e );
01107         // Filter out resize events that inform about size different than frame size.
01108         // This will ensure that decoration->width() etc. and decoration->widget()->width() will be in sync.
01109         // These events only seem to be delayed events from initial resizing before show() was called
01110         // on the decoration widget.
01111         if( ev->size() != size())
01112             return true;
01113         }
01114     return false;
01115     }
01116 
01117 // return value matters only when filtering events before decoration gets them
01118 bool Client::buttonPressEvent( Window w, int button, int state, int x, int y, int x_root, int y_root )
01119     {
01120     if (buttonDown)
01121         {
01122         if( w == wrapperId())
01123             XAllowEvents(qt_xdisplay(), SyncPointer, CurrentTime ); //qt_x_time);
01124         return true;
01125         }
01126 
01127     if( w == wrapperId() || w == frameId() || w == decorationId())
01128         { // FRAME neco s tohohle by se melo zpracovat, nez to dostane dekorace
01129         updateUserTime();
01130         workspace()->setWasUserInteraction();
01131         uint keyModX = (options->keyCmdAllModKey() == Qt::Key_Meta) ?
01132             KKeyNative::modX(KKey::WIN) :
01133             KKeyNative::modX(KKey::ALT);
01134         bool bModKeyHeld = keyModX != 0 && ( state & KKeyNative::accelModMaskX()) == keyModX;
01135 
01136         if( isSplash()
01137             && button == Button1 && !bModKeyHeld )
01138             { // hide splashwindow if the user clicks on it
01139             hideClient( true );
01140             if( w == wrapperId())
01141                     XAllowEvents(qt_xdisplay(), SyncPointer, CurrentTime ); //qt_x_time);
01142             return true;
01143             }
01144 
01145         Options::MouseCommand com = Options::MouseNothing;
01146         bool was_action = false;
01147         bool perform_handled = false;
01148         if ( bModKeyHeld )
01149             {
01150             was_action = true;
01151             switch (button) 
01152                 {
01153                 case Button1:
01154                     com = options->commandAll1();
01155                     break;
01156                 case Button2:
01157                     com = options->commandAll2();
01158                     break;
01159                 case Button3:
01160                     com = options->commandAll3();
01161                     break;
01162                 case Button4:
01163                 case Button5:
01164                     com = options->operationWindowMouseWheel( button == Button4 ? 120 : -120 );
01165                     break;
01166                 }
01167             }
01168         else
01169             { // inactive inner window
01170             if( !isActive() && w == wrapperId())
01171                 {
01172                 was_action = true;
01173                 perform_handled = true;
01174                 switch (button) 
01175                     {
01176                     case Button1:
01177                         com = options->commandWindow1();
01178                         break;
01179                     case Button2:
01180                         com = options->commandWindow2();
01181                         break;
01182                     case Button3:
01183                         com = options->commandWindow3();
01184                         break;
01185                     default:
01186                         com = Options::MouseActivateAndPassClick;
01187                     }
01188                 }
01189             // active inner window
01190             if( isActive() && w == wrapperId()
01191                 && options->clickRaise && button < 4 ) // exclude wheel
01192                 {
01193                 com = Options::MouseActivateRaiseAndPassClick;
01194                 was_action = true;
01195                 perform_handled = true;
01196                 }
01197             }
01198         if( was_action )
01199             {
01200             bool replay = performMouseCommand( com, QPoint( x_root, y_root), perform_handled );
01201 
01202             if ( isSpecialWindow())
01203                 replay = TRUE;
01204 
01205             if( w == wrapperId()) // these can come only from a grab
01206                 XAllowEvents(qt_xdisplay(), replay? ReplayPointer : SyncPointer, CurrentTime ); //qt_x_time);
01207             return true;
01208             }
01209         }
01210 
01211     if( w == wrapperId()) // these can come only from a grab
01212         {
01213         XAllowEvents(qt_xdisplay(), ReplayPointer, CurrentTime ); //qt_x_time);
01214         return true;
01215         }
01216     if( w == decorationId())
01217         return false; // don't eat decoration events
01218     if( w == frameId())
01219         processDecorationButtonPress( button, state, x, y, x_root, y_root );
01220     return true;
01221     }
01222 
01223 
01224 // this function processes button press events only after decoration decides not to handle them,
01225 // unlike buttonPressEvent(), which (when the window is decoration) filters events before decoration gets them
01226 void Client::processDecorationButtonPress( int button, int /*state*/, int x, int y, int x_root, int y_root )
01227     {
01228     Options::MouseCommand com = Options::MouseNothing;
01229     bool active = isActive();
01230     if ( !wantsInput() ) // we cannot be active, use it anyway
01231         active = TRUE;
01232 
01233     if ( button == Button1 )
01234         com = active ? options->commandActiveTitlebar1() : options->commandInactiveTitlebar1();
01235     else if ( button == Button2 )
01236         com = active ? options->commandActiveTitlebar2() : options->commandInactiveTitlebar2();
01237     else if ( button == Button3 )
01238         com = active ? options->commandActiveTitlebar3() : options->commandInactiveTitlebar3();
01239     if( button == Button1
01240         && com != Options::MouseOperationsMenu // actions where it's not possible to get the matching
01241         && com != Options::MouseMinimize )  // mouse release event
01242         {
01243         mode = mousePosition( QPoint( x, y ));
01244         buttonDown = TRUE;
01245         moveOffset = QPoint( x, y );
01246         invertedMoveOffset = rect().bottomRight() - moveOffset;
01247         unrestrictedMoveResize = false;
01248         setCursor( mode ); // update to sizeAllCursor if about to move
01249         }
01250     performMouseCommand( com, QPoint( x_root, y_root ));
01251     }
01252 
01253 // called from decoration
01254 void Client::processMousePressEvent( QMouseEvent* e )
01255     {
01256     if( e->type() != QEvent::MouseButtonPress )
01257         {
01258         kdWarning() << "processMousePressEvent()" << endl;
01259         return;
01260         }
01261     int button;
01262     switch( e->button())
01263         {
01264         case LeftButton:
01265             button = Button1;
01266           break;
01267         case MidButton:
01268             button = Button2;
01269           break;
01270         case RightButton:
01271             button = Button3;
01272           break;
01273         default:
01274             return;
01275         }
01276     processDecorationButtonPress( button, e->state(), e->x(), e->y(), e->globalX(), e->globalY());
01277     }
01278 
01279 // return value matters only when filtering events before decoration gets them
01280 bool Client::buttonReleaseEvent( Window w, int /*button*/, int state, int x, int y, int x_root, int y_root )
01281     {
01282     if( w == decorationId() && !buttonDown)
01283         return false;
01284     if( w == wrapperId())
01285         {
01286         XAllowEvents(qt_xdisplay(), SyncPointer, CurrentTime ); //qt_x_time);
01287         return true;
01288         }
01289     if( w != frameId() && w != decorationId() && w != moveResizeGrabWindow())
01290         return true;
01291     x = this->x(); // translate from grab window to local coords
01292     y = this->y();
01293     if ( (state & ( Button1Mask & Button2Mask & Button3Mask )) == 0 )
01294         {
01295         buttonDown = FALSE;
01296         if ( moveResizeMode ) 
01297             {
01298             finishMoveResize( false );
01299             // mouse position is still relative to old Client position, adjust it
01300             QPoint mousepos( x_root - x, y_root - y );
01301             mode = mousePosition( mousepos );
01302             }
01303         setCursor( mode );
01304         }
01305     return true;
01306     }
01307 
01308 static bool was_motion = false;
01309 static Time next_motion_time = CurrentTime;
01310 // Check whole incoming X queue for MotionNotify events
01311 // checking whole queue is done by always returning False in the predicate.
01312 // If there are more MotionNotify events in the queue, all until the last
01313 // one may be safely discarded (if a ButtonRelease event comes, a MotionNotify
01314 // will be faked from it, so there's no need to check other events).
01315 // This helps avoiding being overloaded by being flooded from many events
01316 // from the XServer.
01317 static Bool motion_predicate( Display*, XEvent* ev, XPointer )
01318 {
01319     if( ev->type == MotionNotify )
01320         {
01321     was_motion = true;
01322         next_motion_time = ev->xmotion.time;  // for setting time
01323         }
01324     return False;
01325 }
01326 
01327 static bool waitingMotionEvent()
01328     {
01329 // The queue doesn't need to be checked until the X timestamp
01330 // of processes events reaches the timestamp of the last suitable
01331 // MotionNotify event in the queue.
01332     if( next_motion_time != CurrentTime
01333         && timestampCompare( qt_x_time, next_motion_time ) < 0 )
01334         return true;
01335     was_motion = false;
01336     XSync( qt_xdisplay(), False ); // this helps to discard more MotionNotify events
01337     XEvent dummy;
01338     XCheckIfEvent( qt_xdisplay(), &dummy, motion_predicate, NULL );
01339     return was_motion;
01340     }
01341 
01342 // return value matters only when filtering events before decoration gets them
01343 bool Client::motionNotifyEvent( Window w, int /*state*/, int x, int y, int x_root, int y_root )
01344     {
01345     if( w != frameId() && w != decorationId() && w != moveResizeGrabWindow())
01346         return true; // care only about the whole frame
01347     if ( !buttonDown ) 
01348         {
01349         Position newmode = mousePosition( QPoint( x, y ));
01350         if( newmode != mode )
01351             setCursor( newmode );
01352         mode = newmode;
01353         // reset the timestamp for the optimization, otherwise with long passivity
01354         // the option in waitingMotionEvent() may be always true
01355         next_motion_time = CurrentTime;
01356         return false;
01357         }
01358     if( w == moveResizeGrabWindow())
01359         {
01360         x = this->x(); // translate from grab window to local coords
01361         y = this->y();
01362         }
01363     if( !waitingMotionEvent())
01364         handleMoveResize( x, y, x_root, y_root );
01365     return true;
01366     }
01367     
01368 void Client::focusInEvent( XFocusInEvent* e )
01369     {
01370     if( e->window != window())
01371         return; // only window gets focus
01372     if ( e->mode == NotifyUngrab )
01373         return; // we don't care
01374     if ( e->detail == NotifyPointer )
01375         return;  // we don't care
01376     if( !isShown( false ) || !isOnCurrentDesktop()) // we unmapped it, but it got focus meanwhile ->
01377         return;            // activateNextClient() already transferred focus elsewhere
01378     // check if this client is in should_get_focus list or if activation is allowed
01379     bool activate =  workspace()->allowClientActivation( this, -1U, true );
01380     workspace()->gotFocusIn( this ); // remove from should_get_focus list
01381     if( activate )
01382         setActive( TRUE );
01383     else
01384         {
01385         workspace()->restoreFocus();
01386         demandAttention();
01387         }
01388     }
01389 
01390 // When a client loses focus, FocusOut events are usually immediatelly
01391 // followed by FocusIn events for another client that gains the focus
01392 // (unless the focus goes to another screen, or to the nofocus widget).
01393 // Without this check, the former focused client would have to be
01394 // deactivated, and after that, the new one would be activated, with
01395 // a short time when there would be no active client. This can cause
01396 // flicker sometimes, e.g. when a fullscreen is shown, and focus is transferred
01397 // from it to its transient, the fullscreen would be kept in the Active layer
01398 // at the beginning and at the end, but not in the middle, when the active
01399 // client would be temporarily none (see Client::belongToLayer() ).
01400 // Therefore, the events queue is checked, whether it contains the matching
01401 // FocusIn event, and if yes, deactivation of the previous client will
01402 // be skipped, as activation of the new one will automatically deactivate
01403 // previously active client.
01404 static bool follows_focusin = false;
01405 static bool follows_focusin_failed = false;
01406 static Bool predicate_follows_focusin( Display*, XEvent* e, XPointer arg )
01407     {
01408     if( follows_focusin || follows_focusin_failed )
01409         return False;
01410     Client* c = ( Client* ) arg;
01411     if( e->type == FocusIn && c->workspace()->findClient( WindowMatchPredicate( e->xfocus.window )))
01412         { // found FocusIn
01413         follows_focusin = true;
01414         return False;
01415         }
01416     // events that may be in the queue before the FocusIn event that's being
01417     // searched for
01418     if( e->type == FocusIn || e->type == FocusOut || e->type == KeymapNotify )
01419         return False;
01420     follows_focusin_failed = true; // a different event - stop search
01421     return False;
01422     }
01423 
01424 static bool check_follows_focusin( Client* c )
01425     {
01426     follows_focusin = follows_focusin_failed = false;
01427     XEvent dummy;
01428     // XCheckIfEvent() is used to make the search non-blocking, the predicate
01429     // always returns False, so nothing is removed from the events queue.
01430     // XPeekIfEvent() would block.
01431     XCheckIfEvent( qt_xdisplay(), &dummy, predicate_follows_focusin, (XPointer)c );
01432     return follows_focusin;
01433     }
01434 
01435 
01436 void Client::focusOutEvent( XFocusOutEvent* e )
01437     {
01438     if( e->window != window())
01439         return; // only window gets focus
01440     if ( e->mode == NotifyGrab )
01441         return; // we don't care
01442     if ( isShade() )
01443         return; // here neither
01444     if ( e->detail != NotifyNonlinear
01445         && e->detail != NotifyNonlinearVirtual )
01446         // SELI check all this
01447         return; // hack for motif apps like netscape
01448     if ( QApplication::activePopupWidget() )
01449         return;
01450     if( !check_follows_focusin( this ))
01451         setActive( FALSE );
01452     }
01453 
01454 void Client::visibilityNotifyEvent( XVisibilityEvent * e)
01455     {
01456     if( e->window != frameId())
01457         return; // care only about the whole frame
01458     bool new_not_obscured = e->state == VisibilityUnobscured;
01459     if( not_obscured == new_not_obscured )
01460         return;
01461     not_obscured = new_not_obscured;
01462     updateMouseGrab();
01463     }
01464 
01465 // performs _NET_WM_MOVERESIZE
01466 void Client::NETMoveResize( int x_root, int y_root, NET::Direction direction )
01467     {
01468     if( direction == NET::Move )
01469         performMouseCommand( Options::MouseMove, QPoint( x_root, y_root ));
01470     else if( moveResizeMode && direction == NET::MoveResizeCancel )
01471     {
01472         finishMoveResize( true );
01473         buttonDown = FALSE;
01474         setCursor( mode );
01475     }
01476     else if( direction >= NET::TopLeft && direction <= NET::Left ) 
01477         {
01478         static const Position convert[] =
01479             {
01480             PositionTopLeft,
01481             PositionTop,
01482             PositionTopRight,
01483             PositionRight,
01484             PositionBottomRight,
01485             PositionBottom,
01486             PositionBottomLeft,
01487             PositionLeft
01488             };
01489         if(!isResizable() || isShade())
01490             return;
01491         if( moveResizeMode )
01492             finishMoveResize( false );
01493         buttonDown = TRUE;
01494         moveOffset = QPoint( x_root - x(), y_root - y()); // map from global
01495         invertedMoveOffset = rect().bottomRight() - moveOffset;
01496         unrestrictedMoveResize = false;
01497         mode = convert[ direction ];
01498         setCursor( mode );
01499         if( !startMoveResize())
01500             {
01501             buttonDown = false;
01502             setCursor( mode );
01503             }
01504         }
01505     else if( direction == NET::KeyboardMove )
01506         { // ignore mouse coordinates given in the message, mouse position is used by the moving algorithm
01507         QCursor::setPos( geometry().center() );
01508         performMouseCommand( Options::MouseUnrestrictedMove, geometry().center());
01509         }
01510     else if( direction == NET::KeyboardSize )
01511         { // ignore mouse coordinates given in the message, mouse position is used by the resizing algorithm
01512         QCursor::setPos( geometry().bottomRight());
01513         performMouseCommand( Options::MouseUnrestrictedResize, geometry().bottomRight());
01514         }
01515     }
01516 
01517 void Client::keyPressEvent( uint key_code )
01518     {
01519     updateUserTime();
01520     if ( !isMove() && !isResize() )
01521         return;
01522     bool is_control = key_code & Qt::CTRL;
01523     bool is_alt = key_code & Qt::ALT;
01524     key_code = key_code & 0xffff;
01525     int delta = is_control?1:is_alt?32:8;
01526     QPoint pos = QCursor::pos();
01527     switch ( key_code ) 
01528         {
01529         case Key_Left:
01530             pos.rx() -= delta;
01531             break;
01532         case Key_Right:
01533             pos.rx() += delta;
01534             break;
01535         case Key_Up:
01536             pos.ry() -= delta;
01537             break;
01538         case Key_Down:
01539             pos.ry() += delta;
01540             break;
01541         case Key_Space:
01542         case Key_Return:
01543         case Key_Enter:
01544             finishMoveResize( false );
01545             buttonDown = FALSE;
01546             setCursor( mode );
01547             break;
01548         case Key_Escape:
01549             finishMoveResize( true );
01550             buttonDown = FALSE;
01551             setCursor( mode );
01552             break;
01553         default:
01554             return;
01555         }
01556     QCursor::setPos( pos );
01557     }
01558 
01559 // ****************************************
01560 // Group
01561 // ****************************************
01562 
01563 bool Group::groupEvent( XEvent* e )
01564     {
01565     unsigned long dirty[ 2 ];
01566     leader_info->event( e, dirty, 2 ); // pass through the NET stuff
01567     if ( ( dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0 )
01568         getIcons();
01569     if(( dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId ) != 0 )
01570         startupIdChanged();
01571     return false;
01572     }
01573 
01574 
01575 } // namespace
KDE Home | KDE Accessibility Home | Description of Access Keys