Make a branch to make krunner Good Enough For Aaron™.
[kdebase/uwolfer.git] / workspace / kwin / main.cpp
blob07f768fbfa98578d1be4cfd7da43c4d53ac10666
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 <QtDBus/QtDBus>
42 #include <kdialog.h>
43 #include <kstandarddirs.h>
44 #include <kdebug.h>
45 #include <QLabel>
46 #include <QComboBox>
47 #include <QVBoxLayout>
49 #include "atoms.h"
50 #include "options.h"
51 #include "sm.h"
52 #include "utils.h"
53 #include "effects.h"
55 #define INT8 _X11INT8
56 #define INT32 _X11INT32
57 #include <X11/Xproto.h>
58 #undef INT8
59 #undef INT32
61 namespace KWin
64 Options* options;
66 Atoms* atoms;
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>"
79 QByteArray ret;
80 char tmp[ 256 ];
81 char num[ 256 ];
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 );
95 else // extensions
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.
106 int nextensions;
107 const char** extensions;
108 int* majors;
109 int* error_bases;
110 Extensions::fillExtensionsData( extensions, nextensions, majors, error_bases );
111 XGetErrorText( dpy, event.error_code, tmp, 255 );
112 int index = -1;
113 int base = 0;
114 for( int i = 0;
115 i < nextensions;
116 ++i )
117 if( error_bases[ i ] != 0
118 && event.error_code >= error_bases[ i ] && ( index == -1 || error_bases[ i ] > base ))
120 index = i;
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
125 if( index != -1 )
127 snprintf( num, 255, "%s.%d", extensions[ index ], event.error_code - base );
128 XGetErrorDatabaseText( dpy, "XProtoError", num, "<unknown>", tmp, 255 );
130 else
131 strcpy( tmp, "<unknown>" );
133 if( char* paren = strchr( tmp, '(' ))
134 *paren = '\0';
135 if( index != -1 )
136 ret = QByteArray( "error: " ) + (const char*)tmp + '[' + (const char*)extensions[ index ]
137 + '+' + QByteArray::number( event.error_code - base ) + ']';
138 else
139 ret = QByteArray( "error: " ) + (const char*)tmp + '[' + QByteArray::number( event.error_code ) + ']';
140 tmp[ 0 ] = '\0';
141 for( int i = 0;
142 i < nextensions;
143 ++i )
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 );
157 return ret;
160 static
161 int x11ErrorHandler(Display *d, XErrorEvent *e)
163 bool ignore_badwindow = true; //maybe temporary
165 if (initting &&
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);
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 kDebug() << kBacktrace();
185 if (initting)
187 fputs(i18n("kwin: failure during initialization; aborting").toLocal8Bit(), stderr);
188 exit(1);
190 return 0;
194 class AlternativeWMDialog : public KDialog
196 public:
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 );
212 addWM( "metacity" );
213 addWM( "openbox" );
214 addWM( "fvwm2" );
215 addWM( "kwin" );
217 setMainWidget(mainWidget);
219 raise();
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(); }
232 private:
233 QComboBox* wmList;
236 int Application::crashes = 0;
238 Application::Application( )
239 : KApplication( ), owner( screen_number )
241 if( KCmdLineArgs::parsedArgs( "qt" )->isSet( "sync" ))
243 kwin_sync = true;
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);
262 ::exit(1);
264 connect( &owner, SIGNAL( lostOwnership()), SLOT( lostSelection()));
266 KCrash::setEmergencySaveFunction( Application::crashHandler );
267 crashes = args->getOption("crashes").toInt();
268 if(crashes >= 4)
270 // Something has gone seriously wrong
271 AlternativeWMDialog dialog;
272 QString cmd = "kwin";
273 if( dialog.exec() == QDialog::Accepted )
275 cmd = dialog.selectedWM();
277 else
278 ::exit(1);
279 if( cmd.length() > 500 )
281 kDebug() << "Command is too long, truncating";
282 cmd = cmd.left(500);
284 kDebug() << "Starting" << cmd << "and exiting";
285 char buf[1024];
286 sprintf(buf, "%s &", cmd.toAscii().data());
287 system(buf);
288 ::exit(1);
290 // Disable compositing if we have had too many crashes
291 if( crashes >= 2 )
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
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;
394 } // namespace
396 static const char version[] = "3.0";
397 static const char description[] = I18N_NOOP( "KDE window manager" );
399 extern "C"
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"))
407 restored = true;
408 break;
412 if (! restored)
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 );
422 if ( !dpy )
424 fprintf(stderr, "%s: FATAL ERROR while trying to open display %s\n",
425 argv[0], XDisplayName(NULL ) );
426 exit (1);
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 );
434 dpy = 0;
436 if ((pos = display_name.lastIndexOf('.')) != -1 )
437 display_name.remove(pos,10); // 10 is enough to be sure we removed ".s"
439 QString envir;
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
451 break;
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())) )
460 fprintf(stderr,
461 "%s: WARNING: unable to set DISPLAY environment variable\n",
462 argv[0]);
463 perror("putenv()");
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 );
493 KWin::Application a;
494 KWin::SessionManager weAreIndeed;
495 KWin::SessionSaveDoneHelper helper;
496 KGlobal::locale()->insertCatalog( "kwin_effects" );
498 fcntl(XConnectionNumber(KWin::display()), F_SETFD, 1);
500 QString appname;
501 if (KWin::screen_number == 0)
502 appname = "org.kde.kwin";
503 else
504 appname.sprintf("org.kde.kwin-screen-%d", KWin::screen_number);
506 QDBusConnection::sessionBus().interface()->registerService( appname, QDBusConnectionInterface::DontQueueService );
508 return a.exec();
511 #include "main.moc"