1 /********************************************************************
2 KWin - the KDE window manager
3 This file is part of the KDE project.
5 Copyright (C) 1999, 2000 Matthias Ettrich <ettrich@kde.org>
6 Copyright (C) 2003 Lubos Lunak <l.lunak@kde.org>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *********************************************************************/
24 //#define QT_CLEAN_NAMESPACE
25 #include <ksharedconfig.h>
30 #include <kcmdlineargs.h>
31 #include <kaboutdata.h>
39 #include <kxerrorhandler.h>
40 #include <QtDBus/QtDBus>
43 #include <kstandarddirs.h>
47 #include <QVBoxLayout>
56 #define INT32 _X11INT32
57 #include <X11/Xproto.h>
68 int screen_number
= -1;
70 static bool initting
= false;
71 // Whether to run Xlib in synchronous mode and print backtraces for X errors.
72 // Note that you most probably need to configure cmake with "-D__KDE_HAVE_GCC_VISIBILITY=0"
73 // and -rdynamic in CXXFLAGS for kBacktrace() to work.
74 static bool kwin_sync
= false;
76 // this is copied from KXErrorHandler and modified to explicitly use known extensions
77 static QByteArray
errorMessage( const XErrorEvent
& event
, Display
* dpy
)
78 { // "Error: <error> (<value>), Request: <request>(<value>), Resource: <value>"
82 if( event
.request_code
< 128 ) // core request
84 XGetErrorText( dpy
, event
.error_code
, tmp
, 255 );
85 if( char* paren
= strchr( tmp
, '(' )) // the explanation in parentheses just makes
86 *paren
= '\0'; // it more verbose and is not really useful
87 // the various casts are to get overloads non-ambiguous :-/
88 ret
= QByteArray( "error: " ) + (const char*)tmp
+ '[' + QByteArray::number( event
.error_code
) + ']';
89 sprintf( num
, "%d", event
.request_code
);
90 XGetErrorDatabaseText( dpy
, "XRequest", num
, "<unknown>", tmp
, 256 );
91 ret
+= QByteArray( ", request: " ) + (const char*)tmp
+ '[' + QByteArray::number( event
.request_code
) + ']';
92 if( event
.resourceid
!= 0 )
93 ret
+= QByteArray( ", resource: 0x" ) + QByteArray::number( (qlonglong
)event
.resourceid
, 16 );
97 // XGetErrorText() currently has a bug that makes it fail to find text
98 // for some errors (when error==error_base), also XGetErrorDatabaseText()
99 // requires the right extension name, so it is needed to get info about
100 // all extensions. However that is almost impossible:
101 // - Xlib itself has it, but in internal data.
102 // - Opening another X connection now can cause deadlock with server grabs.
103 // - Fetching it at startup means a bunch of roundtrips.
105 // KWin here explicitly uses known extensions.
107 const char** extensions
;
110 Extensions::fillExtensionsData( extensions
, nextensions
, majors
, error_bases
);
111 XGetErrorText( dpy
, event
.error_code
, tmp
, 255 );
117 if( error_bases
[ i
] != 0
118 && event
.error_code
>= error_bases
[ i
] && ( index
== -1 || error_bases
[ i
] > base
))
121 base
= error_bases
[ i
];
123 if( tmp
== QString::number( event
.error_code
)) // XGetErrorText() failed,
124 { // or it has a bug that causes not finding all errors, check ourselves
127 snprintf( num
, 255, "%s.%d", extensions
[ index
], event
.error_code
- base
);
128 XGetErrorDatabaseText( dpy
, "XProtoError", num
, "<unknown>", tmp
, 255 );
131 strcpy( tmp
, "<unknown>" );
133 if( char* paren
= strchr( tmp
, '(' ))
136 ret
= QByteArray( "error: " ) + (const char*)tmp
+ '[' + (const char*)extensions
[ index
]
137 + '+' + QByteArray::number( event
.error_code
- base
) + ']';
139 ret
= QByteArray( "error: " ) + (const char*)tmp
+ '[' + QByteArray::number( event
.error_code
) + ']';
144 if( majors
[ i
] == event
.request_code
)
146 snprintf( num
, 255, "%s.%d", extensions
[ i
], event
.minor_code
);
147 XGetErrorDatabaseText( dpy
, "XRequest", num
, "<unknown>", tmp
, 255 );
148 ret
+= QByteArray( ", request: " ) + (const char*)tmp
+ '[' + (const char*)extensions
[ i
] + '+'
149 + QByteArray::number( event
.minor_code
) + ']';
151 if( tmp
[ 0 ] == '\0' ) // not found???
152 ret
+= QByteArray( ", request <unknown> [" ) + QByteArray::number( event
.request_code
) + ':'
153 + QByteArray::number( event
.minor_code
) + ']';
154 if( event
.resourceid
!= 0 )
155 ret
+= QByteArray( ", resource: 0x" ) + QByteArray::number( (qlonglong
)event
.resourceid
, 16 );
161 int x11ErrorHandler(Display
*d
, XErrorEvent
*e
)
163 bool ignore_badwindow
= true; //maybe temporary
167 e
->request_code
== X_ChangeWindowAttributes
168 || e
->request_code
== X_GrabKey
170 && (e
->error_code
== BadAccess
))
172 fputs(i18n("kwin: it looks like there's already a window manager running. kwin not started.\n").toLocal8Bit(), stderr
);
176 if (ignore_badwindow
&& (e
->error_code
== BadWindow
|| e
->error_code
== BadColor
))
179 // fprintf( stderr, "kwin: X Error (%s)\n", KXErrorHandler::errorMessage( *e, d ).data());
180 fprintf( stderr
, "kwin: X Error (%s)\n", errorMessage( *e
, d
).data());
183 kDebug() << kBacktrace();
187 fputs(i18n("kwin: failure during initialization; aborting").toLocal8Bit(), stderr
);
194 class AlternativeWMDialog
: public KDialog
197 AlternativeWMDialog() : KDialog()
199 setButtons( KDialog::Ok
| KDialog::Cancel
);
201 QWidget
* mainWidget
= new QWidget( this );
202 QVBoxLayout
* layout
= new QVBoxLayout( mainWidget
);
203 QString text
= i18n("KWin is unstable.\n"
204 "It seems to have crashed several times in a row.\n"
205 "You can select another window manager to run:");
206 QLabel
* textLabel
= new QLabel( text
, mainWidget
);
207 layout
->addWidget( textLabel
);
208 wmList
= new QComboBox( mainWidget
);
209 wmList
->setEditable( true );
210 layout
->addWidget( wmList
);
217 setMainWidget(mainWidget
);
220 centerOnScreen( this );
222 void addWM( const QString
& wm
)
224 // TODO: check if wm is installed
225 if( !KStandardDirs::findExe( wm
).isEmpty() )
227 wmList
->addItem( wm
);
230 QString
selectedWM() const { return wmList
->currentText(); }
236 int Application::crashes
= 0;
238 Application::Application( )
239 : KApplication( ), owner( screen_number
)
241 if( KCmdLineArgs::parsedArgs( "qt" )->isSet( "sync" ))
244 XSynchronize( display(), True
);
245 kDebug() << "Running KWin in sync mode";
247 KCmdLineArgs
* args
= KCmdLineArgs::parsedArgs();
248 KSharedConfig::Ptr config
= KGlobal::config();
249 if (!config
->isImmutable() && args
->isSet("lock"))
251 #warning this shouldn not be necessary
252 //config->setReadOnly(true);
253 config
->reparseConfiguration();
256 if (screen_number
== -1)
257 screen_number
= DefaultScreen(display());
259 if( !owner
.claim( args
->isSet( "replace" ), true ))
261 fputs(i18n("kwin: unable to claim manager selection, another wm running? (try using --replace)\n").toLocal8Bit(), stderr
);
264 connect( &owner
, SIGNAL( lostOwnership()), SLOT( lostSelection()));
266 KCrash::setEmergencySaveFunction( Application::crashHandler
);
267 crashes
= args
->getOption("crashes").toInt();
270 // Something has gone seriously wrong
271 AlternativeWMDialog dialog
;
272 QString cmd
= "kwin";
273 if( dialog
.exec() == QDialog::Accepted
)
275 cmd
= dialog
.selectedWM();
279 if( cmd
.length() > 500 )
281 kDebug() << "Command is too long, truncating";
284 kDebug() << "Starting" << cmd
<< "and exiting";
286 sprintf(buf
, "%s &", cmd
.toAscii().data());
290 // Disable compositing if we have had too many crashes
293 kDebug() << "Too many crashes recently, disabling compositing";
294 KConfigGroup
compgroup( config
, "Compositing" );
295 compgroup
.writeEntry( "Enabled", false );
297 // Reset crashes count if we stay up for more that 15 seconds
298 QTimer::singleShot( 15*1000, this, SLOT( resetCrashesCount() ));
300 // if there was already kwin running, it saved its configuration after loosing the selection -> reread
301 config
->reparseConfiguration();
303 initting
= true; // startup....
305 // install X11 error handler
306 XSetErrorHandler( x11ErrorHandler
);
308 // check whether another windowmanager is running
309 XSelectInput(display(), rootWindow(), SubstructureRedirectMask
);
310 syncX(); // trigger error now
314 initting
= false; // TODO
316 // This tries to detect compositing options and can use GLX. GLX problems
317 // (X errors) shouldn't cause kwin to abort, so this is out of the
318 // critical startup section where x errors cause kwin to abort.
319 options
= new Options
;
322 (void) new Workspace( isSessionRestored() );
324 syncX(); // trigger possible errors, there's still a chance to abort
326 initting
= false; // startup done, we are up and running now.
329 e
.xclient
.type
= ClientMessage
;
330 e
.xclient
.message_type
= XInternAtom( display(), "_KDE_SPLASH_PROGRESS", False
);
331 e
.xclient
.display
= display();
332 e
.xclient
.window
= rootWindow();
333 e
.xclient
.format
= 8;
334 strcpy( e
.xclient
.data
.b
, "wm" );
335 XSendEvent( display(), rootWindow(), False
, SubstructureNotifyMask
, &e
);
338 Application::~Application()
340 delete Workspace::self();
341 if( owner
.ownerWindow() != None
) // if there was no --replace (no new WM)
342 XSetInputFocus( display(), PointerRoot
, RevertToPointerRoot
, xTime() );
348 void Application::lostSelection()
351 delete Workspace::self();
352 // remove windowmanager privileges
353 XSelectInput(display(), rootWindow(), PropertyChangeMask
);
357 bool Application::x11EventFilter( XEvent
*e
)
359 if ( Workspace::self() && Workspace::self()->workspaceEvent( e
) )
361 return KApplication::x11EventFilter( e
);
364 bool Application::notify( QObject
* o
, QEvent
* e
)
366 if( Workspace::self()->workspaceEvent( e
))
368 return KApplication::notify( o
, e
);
371 static void sighandler(int)
373 QApplication::exit();
376 void Application::crashHandler(int signal
)
380 fprintf( stderr
, "Application::crashHandler() called with signal %d; recent crashes: %d\n", signal
, crashes
);
382 sprintf( cmd
, "kwin --crashes %d &", crashes
);
388 void Application::resetCrashesCount()
396 static const char version
[] = "3.0";
397 static const char description
[] = I18N_NOOP( "KDE window manager" );
400 KDE_EXPORT
int kdemain( int argc
, char * argv
[] )
402 bool restored
= false;
403 for (int arg
= 1; arg
< argc
; arg
++)
405 if (! qstrcmp(argv
[arg
], "-session"))
414 // we only do the multihead fork if we are not restored by the session
415 // manager, since the session manager will register multiple kwins,
416 // one for each screen...
417 QByteArray multiHead
= getenv("KDE_MULTIHEAD");
418 if (multiHead
.toLower() == "true")
421 Display
* dpy
= XOpenDisplay( NULL
);
424 fprintf(stderr
, "%s: FATAL ERROR while trying to open display %s\n",
425 argv
[0], XDisplayName(NULL
) );
429 int number_of_screens
= ScreenCount( dpy
);
430 KWin::screen_number
= DefaultScreen( dpy
);
431 int pos
; // temporarily needed to reconstruct DISPLAY var if multi-head
432 QByteArray display_name
= XDisplayString( dpy
);
433 XCloseDisplay( dpy
);
436 if ((pos
= display_name
.lastIndexOf('.')) != -1 )
437 display_name
.remove(pos
,10); // 10 is enough to be sure we removed ".s"
440 if (number_of_screens
!= 1)
442 for (int i
= 0; i
< number_of_screens
; i
++ )
444 // if execution doesn't pass by here, then kwin
445 // acts exactly as previously
446 if ( i
!= KWin::screen_number
&& fork() == 0 )
448 KWin::screen_number
= i
;
449 // break here because we are the child process, we don't
450 // want to fork() anymore
454 // in the next statement, display_name shouldn't contain a screen
455 // number. If it had it, it was removed at the "pos" check
456 envir
.sprintf("DISPLAY=%s.%d", display_name
.data(), KWin::screen_number
);
458 if (putenv( strdup(envir
.toAscii())) )
461 "%s: WARNING: unable to set DISPLAY environment variable\n",
469 KAboutData
aboutData( "kwin", 0, ki18n("KWin"),
470 version
, ki18n(description
), KAboutData::License_GPL
,
471 ki18n("(c) 1999-2005, The KDE Developers"));
472 aboutData
.addAuthor(ki18n("Matthias Ettrich"),KLocalizedString(), "ettrich@kde.org");
473 aboutData
.addAuthor(ki18n("Cristian Tibirna"),KLocalizedString(), "tibirna@kde.org");
474 aboutData
.addAuthor(ki18n("Daniel M. Duley"),KLocalizedString(), "mosfet@kde.org");
475 aboutData
.addAuthor(ki18n("Luboš Luňák"), ki18n( "Maintainer" ), "l.lunak@kde.org");
477 KCmdLineArgs::init(argc
, argv
, &aboutData
);
479 KCmdLineOptions args
;
480 args
.add("lock", ki18n("Disable configuration options"));
481 args
.add("replace", ki18n("Replace already-running ICCCM2.0-compliant window manager"));
482 args
.add("crashes <n>", ki18n("Indicate that KWin has recently crashed n times"));
483 KCmdLineArgs::addCmdLineOptions( args
);
485 if (signal(SIGTERM
, KWin::sighandler
) == SIG_IGN
)
486 signal(SIGTERM
, SIG_IGN
);
487 if (signal(SIGINT
, KWin::sighandler
) == SIG_IGN
)
488 signal(SIGINT
, SIG_IGN
);
489 if (signal(SIGHUP
, KWin::sighandler
) == SIG_IGN
)
490 signal(SIGHUP
, SIG_IGN
);
491 // HACK this is needed for AIGLX
492 setenv( "LIBGL_ALWAYS_INDIRECT","1", true );
494 KWin::SessionManager weAreIndeed
;
495 KWin::SessionSaveDoneHelper helper
;
496 KGlobal::locale()->insertCatalog( "kwin_effects" );
498 fcntl(XConnectionNumber(KWin::display()), F_SETFD
, 1);
501 if (KWin::screen_number
== 0)
502 appname
= "org.kde.kwin";
504 appname
.sprintf("org.kde.kwin-screen-%d", KWin::screen_number
);
506 QDBusConnection::sessionBus().interface()->registerService( appname
, QDBusConnectionInterface::DontQueueService
);