not quite so much needs to be delayed to the init() function
[personal-kdebase.git] / workspace / kwin / main.cpp
blob98333454290299212ec00d438f4145c9c4d97434
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 *********************************************************************/
22 #include "main.h"
24 //#define QT_CLEAN_NAMESPACE
25 #include <ksharedconfig.h>
27 #include <kglobal.h>
28 #include <klocale.h>
29 #include <stdlib.h>
30 #include <kcmdlineargs.h>
31 #include <kaboutdata.h>
32 #include <kcrash.h>
33 #include <unistd.h>
34 #include <signal.h>
35 #include <fcntl.h>
36 #include <QX11Info>
37 #include <stdio.h>
38 #include <fixx11h.h>
39 #include <kxerrorhandler.h>
40 #include <kdefakes.h>
41 #include <QtDBus/QtDBus>
43 #include <kdialog.h>
44 #include <kstandarddirs.h>
45 #include <kdebug.h>
46 #include <QLabel>
47 #include <QComboBox>
48 #include <QVBoxLayout>
50 #include "atoms.h"
51 #include "options.h"
52 #include "sm.h"
53 #include "utils.h"
54 #include "effects.h"
56 #define INT8 _X11INT8
57 #define INT32 _X11INT32
58 #include <X11/Xproto.h>
59 #undef INT8
60 #undef INT32
62 namespace KWin
65 Options* options;
67 Atoms* atoms;
69 int screen_number = -1;
71 static bool initting = false;
73 /**
74 * Whether to run Xlib in synchronous mode and print backtraces for X errors.
75 * Note that you most probably need to configure cmake with "-D__KDE_HAVE_GCC_VISIBILITY=0"
76 * and -rdynamic in CXXFLAGS for kBacktrace() to work.
78 static bool kwin_sync = false;
80 /**
81 * Outputs: "Error: <error> (<value>), Request: <request>(<value>), Resource: <value>"
83 // This is copied from KXErrorHandler and modified to explicitly use known extensions
84 static QByteArray errorMessage( const XErrorEvent& event, Display* dpy )
86 QByteArray ret;
87 char tmp[256];
88 char num[256];
89 if( event.request_code < 128 )
90 { // Core request
91 XGetErrorText( dpy, event.error_code, tmp, 255 );
92 // The explanation in parentheses just makes
93 // it more verbose and is not really useful
94 if( char* paren = strchr( tmp, '(' ))
95 *paren = '\0';
96 // The various casts are to get overloads non-ambiguous :-/
97 ret = QByteArray( "error: " ) + (const char*)( tmp ) + '[' + QByteArray::number( event.error_code ) + ']';
98 sprintf( num, "%d", event.request_code );
99 XGetErrorDatabaseText( dpy, "XRequest", num, "<unknown>", tmp, 256 );
100 ret += QByteArray( ", request: " ) + (const char*)( tmp ) + '[' + QByteArray::number( event.request_code ) + ']';
101 if( event.resourceid != 0 )
102 ret += QByteArray( ", resource: 0x" ) + QByteArray::number( qlonglong( event.resourceid ), 16 );
104 else // Extensions
106 // XGetErrorText() currently has a bug that makes it fail to find text
107 // for some errors (when error==error_base), also XGetErrorDatabaseText()
108 // requires the right extension name, so it is needed to get info about
109 // all extensions. However that is almost impossible:
110 // - Xlib itself has it, but in internal data.
111 // - Opening another X connection now can cause deadlock with server grabs.
112 // - Fetching it at startup means a bunch of roundtrips.
114 // KWin here explicitly uses known extensions.
115 int nextensions;
116 const char** extensions;
117 int* majors;
118 int* error_bases;
119 Extensions::fillExtensionsData( extensions, nextensions, majors, error_bases );
120 XGetErrorText( dpy, event.error_code, tmp, 255 );
121 int index = -1;
122 int base = 0;
123 for( int i = 0; i < nextensions; ++i )
124 if( error_bases[i] != 0 &&
125 event.error_code >= error_bases[i] && ( index == -1 || error_bases[i] > base ))
127 index = i;
128 base = error_bases[i];
130 if( tmp == QString::number( event.error_code ))
131 { // XGetErrorText() failed or it has a bug that causes not finding all errors, check ourselves
132 if( index != -1 )
134 snprintf( num, 255, "%s.%d", extensions[index], event.error_code - base );
135 XGetErrorDatabaseText( dpy, "XProtoError", num, "<unknown>", tmp, 255 );
137 else
138 strcpy( tmp, "<unknown>" );
140 if( char* paren = strchr( tmp, '(' ))
141 *paren = '\0';
142 if( index != -1 )
143 ret = QByteArray( "error: " ) + (const char*)( tmp ) + '[' + (const char*)( extensions[index] ) +
144 '+' + QByteArray::number( event.error_code - base ) + ']';
145 else
146 ret = QByteArray( "error: " ) + (const char*)( tmp ) + '[' + QByteArray::number( event.error_code ) + ']';
147 tmp[0] = '\0';
148 for( int i = 0; i < nextensions; ++i )
149 if( majors[i] == event.request_code )
151 snprintf( num, 255, "%s.%d", extensions[i], event.minor_code );
152 XGetErrorDatabaseText( dpy, "XRequest", num, "<unknown>", tmp, 255 );
153 ret += QByteArray( ", request: " ) + (const char*)( tmp ) + '[' +
154 (const char*)( extensions[i] ) + '+' + QByteArray::number( event.minor_code ) + ']';
156 if( tmp[0] == '\0' ) // Not found?
157 ret += QByteArray( ", request <unknown> [" ) + QByteArray::number( event.request_code ) + ':'
158 + QByteArray::number( event.minor_code ) + ']';
159 if( event.resourceid != 0 )
160 ret += QByteArray( ", resource: 0x" ) + QByteArray::number( qlonglong( event.resourceid ), 16 );
162 return ret;
165 static int x11ErrorHandler( Display* d, XErrorEvent* e )
167 bool ignore_badwindow = true; // Might be temporary
169 if( initting && ( e->request_code == X_ChangeWindowAttributes || 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 );
173 exit(1);
176 if( ignore_badwindow && ( e->error_code == BadWindow || e->error_code == BadColor ))
177 return 0;
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() );
182 if( kwin_sync )
183 fprintf( stderr, "%s\n", kBacktrace().toLocal8Bit().data() );
185 if( initting )
187 fputs( i18n( "kwin: failure during initialization; aborting").toLocal8Bit(), stderr );
188 exit( 1 );
190 return 0;
193 class AlternativeWMDialog : public KDialog
195 public:
196 AlternativeWMDialog()
197 : KDialog()
199 setButtons( KDialog::Ok | KDialog::Cancel );
201 QWidget* mainWidget = new QWidget( this );
202 QVBoxLayout* layout = new QVBoxLayout( mainWidget );
203 QString text = i18n(
204 "KWin is unstable.\n"
205 "It seems to have crashed several times in a row.\n"
206 "You can select another window manager to run:" );
207 QLabel* textLabel = new QLabel( text, mainWidget );
208 layout->addWidget( textLabel );
209 wmList = new QComboBox( mainWidget );
210 wmList->setEditable( true );
211 layout->addWidget( wmList );
213 addWM( "metacity" );
214 addWM( "openbox" );
215 addWM( "fvwm2" );
216 addWM( "kwin" );
218 setMainWidget( mainWidget );
220 raise();
221 centerOnScreen( this );
224 void addWM( const QString& wm )
226 // TODO: Check if WM is installed
227 if( !KStandardDirs::findExe( wm ).isEmpty() )
228 wmList->addItem( wm );
230 QString selectedWM() const
231 { return wmList->currentText(); }
233 private:
234 QComboBox* wmList;
237 int Application::crashes = 0;
239 Application::Application()
240 : KApplication()
241 , owner( screen_number )
243 if( KCmdLineArgs::parsedArgs( "qt" )->isSet( "sync" ))
245 kwin_sync = true;
246 XSynchronize( display(), True );
247 kDebug( 1212 ) << "Running KWin in sync mode";
249 KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
250 KSharedConfig::Ptr config = KGlobal::config();
251 if( !config->isImmutable() && args->isSet( "lock" ))
253 #ifdef __GNUC__
254 #warning this shouldn not be necessary
255 #endif
256 //config->setReadOnly( true );
257 config->reparseConfiguration();
260 if( screen_number == -1 )
261 screen_number = DefaultScreen( display() );
263 if( !owner.claim( args->isSet( "replace" ), true ))
265 fputs( i18n( "kwin: unable to claim manager selection, another wm running? (try using --replace)\n" ).toLocal8Bit(), stderr );
266 ::exit( 1 );
268 connect( &owner, SIGNAL( lostOwnership() ), SLOT( lostSelection() ));
270 KCrash::setEmergencySaveFunction( Application::crashHandler );
271 crashes = args->getOption( "crashes" ).toInt();
272 if( crashes >= 4 )
273 { // Something has gone seriously wrong
274 AlternativeWMDialog dialog;
275 QString cmd = "kwin";
276 if( dialog.exec() == QDialog::Accepted )
277 cmd = dialog.selectedWM();
278 else
279 ::exit( 1 );
280 if( cmd.length() > 500 )
282 kDebug( 1212 ) << "Command is too long, truncating";
283 cmd = cmd.left( 500 );
285 kDebug( 1212 ) << "Starting" << cmd << "and exiting";
286 char buf[1024];
287 sprintf( buf, "%s &", cmd.toAscii().data() );
288 system( buf );
289 ::exit( 1 );
291 if( crashes >= 2 )
292 { // Disable compositing if we have had too many crashes
293 kDebug( 1212 ) << "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 KWin was already 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
312 atoms = new Atoms;
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;
321 // create workspace.
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.
328 XEvent e;
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() );
343 delete options;
344 delete effects;
345 delete atoms;
348 void Application::lostSelection()
350 sendPostedEvents();
351 delete Workspace::self();
352 // Remove windowmanager privileges
353 XSelectInput( display(), rootWindow(), PropertyChangeMask );
354 quit();
357 bool Application::x11EventFilter( XEvent* e )
359 if( Workspace::self() && Workspace::self()->workspaceEvent( e ))
360 return true;
361 return KApplication::x11EventFilter( e );
364 bool Application::notify( QObject* o, QEvent* e )
366 if( Workspace::self()->workspaceEvent( e ))
367 return true;
368 return KApplication::notify( o, e );
371 static void sighandler( int )
373 QApplication::exit();
376 void Application::crashHandler( int signal )
378 crashes++;
380 fprintf( stderr, "Application::crashHandler() called with signal %d; recent crashes: %d\n", signal, crashes );
381 char cmd[1024];
382 sprintf( cmd, "kwin --crashes %d &", crashes );
384 sleep( 1 );
385 system( cmd );
388 void Application::resetCrashesCount()
390 crashes = 0;
393 } // namespace
395 static const char version[] = KDE_VERSION_STRING;
396 static const char description[] = I18N_NOOP( "KDE window manager" );
398 extern "C"
399 KDE_EXPORT int kdemain( int argc, char * argv[] )
401 bool restored = false;
402 for( int arg = 1; arg < argc; arg++ )
404 if( !qstrcmp( argv[arg], "-session" ))
406 restored = true;
407 break;
411 if( !restored )
412 { // We only do the multihead fork if we are not restored by the session
413 // manager, since the session manager will register multiple kwins,
414 // one for each screen...
415 QByteArray multiHead = getenv( "KDE_MULTIHEAD" );
416 if( multiHead.toLower() == "true" )
418 Display* dpy = XOpenDisplay( NULL );
419 if( !dpy )
421 fprintf( stderr, "%s: FATAL ERROR while trying to open display %s\n",
422 argv[0], XDisplayName( NULL ));
423 exit( 1 );
426 int number_of_screens = ScreenCount( dpy );
427 KWin::screen_number = DefaultScreen( dpy );
428 int pos; // Temporarily needed to reconstruct DISPLAY var if multi-head
429 QByteArray display_name = XDisplayString( dpy );
430 XCloseDisplay( dpy );
431 dpy = 0;
433 if(( pos = display_name.lastIndexOf( '.' )) != -1 )
434 display_name.remove( pos, 10 ); // 10 is enough to be sure we removed ".s"
436 QString envir;
437 if( number_of_screens != 1 )
439 for( int i = 0; i < number_of_screens; i++ )
441 // If execution doesn't pass by here, then kwin
442 // acts exactly as previously
443 if( i != KWin::screen_number && fork() == 0 )
445 KWin::screen_number = i;
446 // Break here because we are the child process, we don't
447 // want to fork() anymore
448 break;
451 // In the next statement, display_name shouldn't contain a screen
452 // number. If it had it, it was removed at the "pos" check
453 envir.sprintf( "DISPLAY=%s.%d", display_name.data(), KWin::screen_number );
455 if( putenv( strdup( envir.toAscii() )))
457 fprintf( stderr, "%s: WARNING: unable to set DISPLAY environment variable\n", argv[0] );
458 perror("putenv()");
464 KAboutData aboutData(
465 "kwin", // The program name used internally
466 0, // The message catalog name. If null, program name is used instead
467 ki18n( "KWin" ), // A displayable program name string
468 version, // The program version string
469 ki18n( description ), // Short description of what the app does
470 KAboutData::License_GPL, // The license this code is released under
471 ki18n( "(c) 1999-2008, The KDE Developers" )); // Copyright Statement
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 );
492 // HACK: This is needed for AIGLX
493 if( qstrcmp( getenv( "KWIN_DIRECT_GL" ), "1" ) != 0 )
494 setenv( "LIBGL_ALWAYS_INDIRECT","1", true );
496 // HACK: this is needed to work around a Qt4.4.0RC1 bug (#157659)
497 setenv( "QT_SLOW_TOPLEVEL_RESIZE", "1", true );
499 KWin::Application a;
500 KWin::SessionManager weAreIndeed;
501 KWin::SessionSaveDoneHelper helper;
502 KGlobal::locale()->insertCatalog( "kwin_effects" );
504 // Announce when KWIN_DIRECT_GL is set for above HACK
505 if( qstrcmp( getenv( "KWIN_DIRECT_GL" ), "1" ) == 0 )
506 kDebug( 1212 ) << "KWIN_DIRECT_GL set, not forcing LIBGL_ALWAYS_INDIRECT=1";
508 fcntl( XConnectionNumber( KWin::display() ), F_SETFD, 1 );
510 QString appname;
511 if( KWin::screen_number == 0 )
512 appname = "org.kde.kwin";
513 else
514 appname.sprintf( "org.kde.kwin-screen-%d", KWin::screen_number );
516 QDBusConnection::sessionBus().interface()->registerService(
517 appname, QDBusConnectionInterface::DontQueueService );
519 return a.exec();
522 #include "main.moc"