1/********************************************************************
2 KWin - the KDE window manager
3 This file is part of the KDE project.
4
5Copyright (C) 1999, 2000 Matthias Ettrich <ettrich@kde.org>
6Copyright (C) 2003 Lubos Lunak <l.lunak@kde.org>
7
8This program is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 2 of the License, or
11(at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program. If not, see <http://www.gnu.org/licenses/>.
20*********************************************************************/
21
22#include "main.h"
23
24//#define QT_CLEAN_NAMESPACE
25#include <ksharedconfig.h>
26
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 <signal.h>
34#include <fcntl.h>
35#include <QX11Info>
36#include <stdio.h>
37#include <fixx11h.h>
38#include <kxerrorhandler.h>
39#include <kdefakes.h>
40#include <QtDBus/QtDBus>
41#include <QMessageBox>
42#include <QEvent>
43
44#include <kdialog.h>
45#include <kstandarddirs.h>
46#include <kdebug.h>
47#include <kde_file.h>
48#include <QLabel>
49#include <KComboBox>
50#include <QVBoxLayout>
51
52#include "config-workspace.h"
53
54#ifdef HAVE_UNISTD_H
55#include <unistd.h>
56#endif // HAVE_UNISTD_H
57
58#ifdef HAVE_MALLOC_H
59#include <malloc.h>
60#endif // HAVE_MALLOC_H
61
62#include <ksmserver_interface.h>
63
64#include "atoms.h"
65#include "options.h"
66#include "sm.h"
67#include "utils.h"
68#include "effects.h"
69#include "workspace.h"
70#include "xcbutils.h"
71
72#define INT8 _X11INT8
73#define INT32 _X11INT32
74#include <X11/Xproto.h>
75#undef INT8
76#undef INT32
77
78static bool isMultiHead()
79{
80 QByteArray multiHead = qgetenv("KDE_MULTIHEAD");
81 if (!multiHead.isEmpty()) {
82 return (multiHead.toLower() == "true");
83 }
84 return true;
85}
86
87namespace KWin
88{
89
90Options* options;
91
92Atoms* atoms;
93
94int screen_number = -1;
95bool is_multihead = false;
96
97bool initting = false;
98
99/**
100 * Whether to run Xlib in synchronous mode and print backtraces for X errors.
101 * Note that you most probably need to configure cmake with "-D__KDE_HAVE_GCC_VISIBILITY=0"
102 * and -rdynamic in CXXFLAGS for kBacktrace() to work.
103 */
104static bool kwin_sync = false;
105
106//************************************
107// KWinSelectionOwner
108//************************************
109
110KWinSelectionOwner::KWinSelectionOwner(int screen_P)
111 : KSelectionOwner(make_selection_atom(screen_P), screen_P)
112{
113}
114
115Atom KWinSelectionOwner::make_selection_atom(int screen_P)
116{
117 if (screen_P < 0)
118 screen_P = DefaultScreen(display());
119 char tmp[ 30 ];
120 sprintf(tmp, "WM_S%d", screen_P);
121 return XInternAtom(display(), tmp, False);
122}
123
124void KWinSelectionOwner::getAtoms()
125{
126 KSelectionOwner::getAtoms();
127 if (xa_version == None) {
128 Atom atoms[ 1 ];
129 const char* const names[] =
130 { "VERSION" };
131 XInternAtoms(display(), const_cast< char** >(names), 1, False, atoms);
132 xa_version = atoms[ 0 ];
133 }
134}
135
136void KWinSelectionOwner::replyTargets(Atom property_P, Window requestor_P)
137{
138 KSelectionOwner::replyTargets(property_P, requestor_P);
139 Atom atoms[ 1 ] = { xa_version };
140 // PropModeAppend !
141 XChangeProperty(display(), requestor_P, property_P, XA_ATOM, 32, PropModeAppend,
142 reinterpret_cast< unsigned char* >(atoms), 1);
143}
144
145bool KWinSelectionOwner::genericReply(Atom target_P, Atom property_P, Window requestor_P)
146{
147 if (target_P == xa_version) {
148 long version[] = { 2, 0 };
149 XChangeProperty(display(), requestor_P, property_P, XA_INTEGER, 32,
150 PropModeReplace, reinterpret_cast< unsigned char* >(&version), 2);
151 } else
152 return KSelectionOwner::genericReply(target_P, property_P, requestor_P);
153 return true;
154}
155
156Atom KWinSelectionOwner::xa_version = None;
157
158// errorMessage is only used ifndef NDEBUG, and only in one place.
159// it might be worth reevaluating why this is used? I don't know.
160#ifndef NDEBUG
161/**
162 * Outputs: "Error: <error> (<value>), Request: <request>(<value>), Resource: <value>"
163 */
164// This is copied from KXErrorHandler and modified to explicitly use known extensions
165static QByteArray errorMessage(const XErrorEvent& event, Display* dpy)
166{
167 QByteArray ret;
168 char tmp[256];
169 char num[256];
170 if (event.request_code < 128) {
171 // Core request
172 XGetErrorText(dpy, event.error_code, tmp, 255);
173 // The explanation in parentheses just makes
174 // it more verbose and is not really useful
175 if (char* paren = strchr(tmp, '('))
176 * paren = '\0';
177 // The various casts are to get overloads non-ambiguous :-/
178 ret = QByteArray("error: ") + (const char*)(tmp) + '[' + QByteArray::number(event.error_code) + ']';
179 sprintf(num, "%d", event.request_code);
180 XGetErrorDatabaseText(dpy, "XRequest", num, "<unknown>", tmp, 256);
181 ret += QByteArray(", request: ") + (const char*)(tmp) + '[' + QByteArray::number(event.request_code) + ']';
182 if (event.resourceid != 0)
183 ret += QByteArray(", resource: 0x") + QByteArray::number(qlonglong(event.resourceid), 16);
184 } else { // Extensions
185 // XGetErrorText() currently has a bug that makes it fail to find text
186 // for some errors (when error==error_base), also XGetErrorDatabaseText()
187 // requires the right extension name, so it is needed to get info about
188 // all extensions. However that is almost impossible:
189 // - Xlib itself has it, but in internal data.
190 // - Opening another X connection now can cause deadlock with server grabs.
191 // - Fetching it at startup means a bunch of roundtrips.
192
193 // KWin here explicitly uses known extensions.
194 XGetErrorText(dpy, event.error_code, tmp, 255);
195 int index = -1;
196 int base = 0;
197 QVector<Xcb::ExtensionData> extensions = Xcb::Extensions::self()->extensions();
198 for (int i = 0; i < extensions.size(); ++i) {
199 const Xcb::ExtensionData &extension = extensions.at(i);
200 if (extension.errorBase != 0 &&
201 event.error_code >= extension.errorBase && (index == -1 || extension.errorBase > base)) {
202 index = i;
203 base = extension.errorBase;
204 }
205 }
206 if (tmp == QString::number(event.error_code)) {
207 // XGetErrorText() failed or it has a bug that causes not finding all errors, check ourselves
208 if (index != -1) {
209 snprintf(num, 255, "%s.%d", extensions.at(index).name.constData(), event.error_code - base);
210 XGetErrorDatabaseText(dpy, "XProtoError", num, "<unknown>", tmp, 255);
211 } else
212 strcpy(tmp, "<unknown>");
213 }
214 if (char* paren = strchr(tmp, '('))
215 * paren = '\0';
216 if (index != -1)
217 ret = QByteArray("error: ") + (const char*)(tmp) + '[' + extensions.at(index).name +
218 '+' + QByteArray::number(event.error_code - base) + ']';
219 else
220 ret = QByteArray("error: ") + (const char*)(tmp) + '[' + QByteArray::number(event.error_code) + ']';
221 tmp[0] = '\0';
222 for (int i = 0; i < extensions.size(); ++i)
223 if (extensions.at(i).majorOpcode == event.request_code) {
224 snprintf(num, 255, "%s.%d", extensions.at(i).name.constData(), event.minor_code);
225 XGetErrorDatabaseText(dpy, "XRequest", num, "<unknown>", tmp, 255);
226 ret += QByteArray(", request: ") + (const char*)(tmp) + '[' +
227 extensions.at(i).name + '+' + QByteArray::number(event.minor_code) + ']';
228 }
229 if (tmp[0] == '\0') // Not found?
230 ret += QByteArray(", request <unknown> [") + QByteArray::number(event.request_code) + ':'
231 + QByteArray::number(event.minor_code) + ']';
232 if (event.resourceid != 0)
233 ret += QByteArray(", resource: 0x") + QByteArray::number(qlonglong(event.resourceid), 16);
234 }
235 return ret;
236}
237#endif
238
239static int x11ErrorHandler(Display* d, XErrorEvent* e)
240{
241 Q_UNUSED(d);
242 bool ignore_badwindow = true; // Might be temporary
243
244 if (initting && (e->request_code == X_ChangeWindowAttributes || e->request_code == X_GrabKey) &&
245 e->error_code == BadAccess) {
246 fputs(i18n("kwin: it looks like there's already a window manager running. kwin not started.\n").toLocal8Bit(), stderr);
247 exit(1);
248 }
249
250 if (ignore_badwindow && (e->error_code == BadWindow || e->error_code == BadColor))
251 return 0;
252
253#ifndef NDEBUG
254 //fprintf( stderr, "kwin: X Error (%s)\n", KXErrorHandler::errorMessage( *e, d ).data());
255 kWarning(1212) << "kwin: X Error (" << errorMessage(*e, d) << ")";
256#endif
257
258 if (kwin_sync)
259 fprintf(stderr, "%s\n", kBacktrace().toLocal8Bit().data());
260
261 return 0;
262}
263
264class AlternativeWMDialog : public KDialog
265{
266public:
267 AlternativeWMDialog()
268 : KDialog() {
269 setButtons(KDialog::Ok | KDialog::Cancel);
270
271 QWidget* mainWidget = new QWidget(this);
272 QVBoxLayout* layout = new QVBoxLayout(mainWidget);
273 QString text = i18n(
274 "KWin is unstable.\n"
275 "It seems to have crashed several times in a row.\n"
276 "You can select another window manager to run:");
277 QLabel* textLabel = new QLabel(text, mainWidget);
278 layout->addWidget(textLabel);
279 wmList = new KComboBox(mainWidget);
280 wmList->setEditable(true);
281 layout->addWidget(wmList);
282
283 addWM("metacity");
284 addWM("openbox");
285 addWM("fvwm2");
286 addWM(KWIN_NAME);
287
288 setMainWidget(mainWidget);
289
290 raise();
291 centerOnScreen(this);
292 }
293
294 void addWM(const QString& wm) {
295 // TODO: Check if WM is installed
296 if (!KStandardDirs::findExe(wm).isEmpty())
297 wmList->addItem(wm);
298 }
299 QString selectedWM() const {
300 return wmList->currentText();
301 }
302
303private:
304 KComboBox* wmList;
305};
306
307int Application::crashes = 0;
308
309Application::Application()
310 : KApplication()
311 , owner(screen_number)
312{
313 if (KCmdLineArgs::parsedArgs("qt")->isSet("sync")) {
314 kwin_sync = true;
315 XSynchronize(display(), True);
316 kDebug(1212) << "Running KWin in sync mode";
317 }
318 setQuitOnLastWindowClosed(false);
319 KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
320 KSharedConfig::Ptr config = KGlobal::config();
321 if (!config->isImmutable() && args->isSet("lock")) {
322 // TODO: This shouldn't be necessary
323 //config->setReadOnly( true );
324 config->reparseConfiguration();
325 }
326
327 if (screen_number == -1)
328 screen_number = DefaultScreen(display());
329
330 if (!owner.claim(args->isSet("replace"), true)) {
331 fputs(i18n("kwin: unable to claim manager selection, another wm running? (try using --replace)\n").toLocal8Bit(), stderr);
332 ::exit(1);
333 }
334 connect(&owner, SIGNAL(lostOwnership()), SLOT(lostSelection()));
335
336 KCrash::setEmergencySaveFunction(Application::crashHandler);
337 crashes = args->getOption("crashes").toInt();
338 if (crashes >= 4) {
339 // Something has gone seriously wrong
340 AlternativeWMDialog dialog;
341 QString cmd = KWIN_NAME;
342 if (dialog.exec() == QDialog::Accepted)
343 cmd = dialog.selectedWM();
344 else
345 ::exit(1);
346 if (cmd.length() > 500) {
347 kDebug(1212) << "Command is too long, truncating";
348 cmd = cmd.left(500);
349 }
350 kDebug(1212) << "Starting" << cmd << "and exiting";
351 char buf[1024];
352 sprintf(buf, "%s &", cmd.toAscii().data());
353 system(buf);
354 ::exit(1);
355 }
356 if (crashes >= 2) {
357 // Disable compositing if we have had too many crashes
358 kDebug(1212) << "Too many crashes recently, disabling compositing";
359 KConfigGroup compgroup(config, "Compositing");
360 compgroup.writeEntry("Enabled", false);
361 }
362 // Reset crashes count if we stay up for more that 15 seconds
363 QTimer::singleShot(15 * 1000, this, SLOT(resetCrashesCount()));
364
365 initting = true; // Startup...
366 // first load options - done internally by a different thread
367 options = new Options;
368
369 // Install X11 error handler
370 XSetErrorHandler(x11ErrorHandler);
371
372 // Check whether another windowmanager is running
373 XSelectInput(display(), rootWindow(), SubstructureRedirectMask);
374 syncX(); // Trigger error now
375
376 atoms = new Atoms;
377
378// initting = false; // TODO
379
380 // This tries to detect compositing options and can use GLX. GLX problems
381 // (X errors) shouldn't cause kwin to abort, so this is out of the
382 // critical startup section where x errors cause kwin to abort.
383
384 // create workspace.
385 (void) new Workspace(isSessionRestored());
386
387 syncX(); // Trigger possible errors, there's still a chance to abort
388
389 initting = false; // Startup done, we are up and running now.
390
391 XEvent e;
392 e.xclient.type = ClientMessage;
393 e.xclient.message_type = XInternAtom(display(), "_KDE_SPLASH_PROGRESS", False);
394 e.xclient.display = display();
395 e.xclient.window = rootWindow();
396 e.xclient.format = 8;
397 strcpy(e.xclient.data.b, "wm");
398 XSendEvent(display(), rootWindow(), False, SubstructureNotifyMask, &e);
399}
400
401Application::~Application()
402{
403 delete Workspace::self();
404 if (owner.ownerWindow() != None) // If there was no --replace (no new WM)
405 XSetInputFocus(display(), PointerRoot, RevertToPointerRoot, xTime());
406 delete options;
407 delete effects;
408 delete atoms;
409}
410
411void Application::lostSelection()
412{
413 sendPostedEvents();
414 delete Workspace::self();
415 // Remove windowmanager privileges
416 XSelectInput(display(), rootWindow(), PropertyChangeMask);
417 quit();
418}
419
420bool Application::x11EventFilter(XEvent* e)
421{
422 if (Workspace::self() && Workspace::self()->workspaceEvent(e))
423 return true;
424 return KApplication::x11EventFilter(e);
425}
426
427bool Application::notify(QObject* o, QEvent* e)
428{
429 if (Workspace::self()->workspaceEvent(e))
430 return true;
431 return KApplication::notify(o, e);
432}
433
434static void sighandler(int)
435{
436 QApplication::exit();
437}
438
439void Application::crashHandler(int signal)
440{
441 crashes++;
442
443 fprintf(stderr, "Application::crashHandler() called with signal %d; recent crashes: %d\n", signal, crashes);
444 char cmd[1024];
445 sprintf(cmd, "%s --crashes %d &",
446 QFile::encodeName(QCoreApplication::applicationFilePath()).constData(), crashes);
447
448 sleep(1);
449 system(cmd);
450}
451
452void Application::resetCrashesCount()
453{
454 crashes = 0;
455}
456
457} // namespace
458
459static const char version[] = KWIN_VERSION_STRING;
460static const char description[] = I18N_NOOP("KDE window manager");
461
462extern "C"
463KDE_EXPORT int kdemain(int argc, char * argv[])
464{
465#ifdef M_TRIM_THRESHOLD
466 // Prevent fragmentation of the heap by malloc (glibc).
467 //
468 // The default threshold is 128*1024, which can result in a large memory usage
469 // due to fragmentation especially if we use the raster graphicssystem. On the
470 // otherside if the threshold is too low, free() starts to permanently ask the kernel
471 // about shrinking the heap.
472#ifdef HAVE_UNISTD_H
473 const int pagesize = sysconf(_SC_PAGESIZE);
474#else
475 const int pagesize = 4*1024;
476#endif // HAVE_UNISTD_H
477 mallopt(M_TRIM_THRESHOLD, 5*pagesize);
478#endif // M_TRIM_THRESHOLD
479
480 // the raster graphicssystem has a quite terrible performance on the XRender backend or when not
481 // compositing at all while some to many decorations suffer from bad performance of the native
482 // graphicssystem (lack of implementation, QGradient internally uses the raster system and
483 // XPutImage's the result because some graphics drivers have insufficient or bad performing
484 // implementations of XRenderCreate*Gradient)
485 //
486 // Therefore we allow configurationa and do some automagic selection to discourage
487 // ""known to be stupid" ideas ;-P
488 // The invalid system parameter "" will use the systems default graphicssystem
489 // "!= XRender" is intended since eg. pot. SW backends likely would profit from raster as well
490 KConfigGroup config(KSharedConfig::openConfig(KWIN_CONFIG), "Compositing");
491 QString preferredSystem("native");
492 if (config.readEntry("Enabled", true) && config.readEntry("Backend", "OpenGL") != "XRender")
493 preferredSystem = "";
494 QApplication::setGraphicsSystem(config.readEntry("GraphicsSystem", preferredSystem));
495
496 Display* dpy = XOpenDisplay(NULL);
497 if (!dpy) {
498 fprintf(stderr, "%s: FATAL ERROR while trying to open display %s\n",
499 argv[0], XDisplayName(NULL));
500 exit(1);
501 }
502
503 int number_of_screens = ScreenCount(dpy);
504
505 // multi head
506 if (number_of_screens != 1 && isMultiHead()) {
507 KWin::is_multihead = true;
508 KWin::screen_number = DefaultScreen(dpy);
509 int pos; // Temporarily needed to reconstruct DISPLAY var if multi-head
510 QByteArray display_name = XDisplayString(dpy);
511 XCloseDisplay(dpy);
512 dpy = 0;
513
514 if ((pos = display_name.lastIndexOf('.')) != -1)
515 display_name.remove(pos, 10); // 10 is enough to be sure we removed ".s"
516
517 QString envir;
518 for (int i = 0; i < number_of_screens; i++) {
519 // If execution doesn't pass by here, then kwin
520 // acts exactly as previously
521 if (i != KWin::screen_number && fork() == 0) {
522 KWin::screen_number = i;
523 // Break here because we are the child process, we don't
524 // want to fork() anymore
525 break;
526 }
527 }
528 // In the next statement, display_name shouldn't contain a screen
529 // number. If it had it, it was removed at the "pos" check
530 envir.sprintf("DISPLAY=%s.%d", display_name.data(), KWin::screen_number);
531
532 if (putenv(strdup(envir.toAscii()))) {
533 fprintf(stderr, "%s: WARNING: unable to set DISPLAY environment variable\n", argv[0]);
534 perror("putenv()");
535 }
536 }
537
538 KAboutData aboutData(
539 KWIN_NAME, // The program name used internally
540 0, // The message catalog name. If null, program name is used instead
541 ki18n("KWin"), // A displayable program name string
542 version, // The program version string
543 ki18n(description), // Short description of what the app does
544 KAboutData::License_GPL, // The license this code is released under
545 ki18n("(c) 1999-2008, The KDE Developers")); // Copyright Statement
546 aboutData.addAuthor(ki18n("Matthias Ettrich"), KLocalizedString(), "ettrich@kde.org");
547 aboutData.addAuthor(ki18n("Cristian Tibirna"), KLocalizedString(), "tibirna@kde.org");
548 aboutData.addAuthor(ki18n("Daniel M. Duley"), KLocalizedString(), "mosfet@kde.org");
549 aboutData.addAuthor(ki18n("Luboš Luňák"), KLocalizedString(), "l.lunak@kde.org");
550 aboutData.addAuthor(ki18n("Martin Gräßlin"), ki18n("Maintainer"), "mgraesslin@kde.org");
551
552 KCmdLineArgs::init(argc, argv, &aboutData);
553
554 KCmdLineOptions args;
555 args.add("lock", ki18n("Disable configuration options"));
556 args.add("replace", ki18n("Replace already-running ICCCM2.0-compliant window manager"));
557 args.add("crashes <n>", ki18n("Indicate that KWin has recently crashed n times"));
558 KCmdLineArgs::addCmdLineOptions(args);
559
560 if (KDE_signal(SIGTERM, KWin::sighandler) == SIG_IGN)
561 KDE_signal(SIGTERM, SIG_IGN);
562 if (KDE_signal(SIGINT, KWin::sighandler) == SIG_IGN)
563 KDE_signal(SIGINT, SIG_IGN);
564 if (KDE_signal(SIGHUP, KWin::sighandler) == SIG_IGN)
565 KDE_signal(SIGHUP, SIG_IGN);
566
567 // Disable the glib event loop integration, since it seems to be responsible
568 // for several bug reports about high CPU usage (bug #239963)
569 setenv("QT_NO_GLIB", "1", true);
570
571 org::kde::KSMServerInterface ksmserver("org.kde.ksmserver", "/KSMServer", QDBusConnection::sessionBus());
572 ksmserver.suspendStartup(KWIN_NAME);
573 KWin::Application a;
574
575 ksmserver.resumeStartup(KWIN_NAME);
576 KWin::SessionManager weAreIndeed;
577 KWin::SessionSaveDoneHelper helper;
578 KGlobal::locale()->insertCatalog("kwin_effects");
579 KGlobal::locale()->insertCatalog("kwin_scripts");
580 KGlobal::locale()->insertCatalog("kwin_scripting");
581
582 // Announce when KWIN_DIRECT_GL is set for above HACK
583 if (qstrcmp(qgetenv("KWIN_DIRECT_GL"), "1") == 0)
584 kDebug(1212) << "KWIN_DIRECT_GL set, not forcing LIBGL_ALWAYS_INDIRECT=1";
585
586 fcntl(XConnectionNumber(KWin::display()), F_SETFD, 1);
587
588 QString appname;
589 if (KWin::screen_number == 0)
590 appname = "org.kde.kwin";
591 else
592 appname.sprintf("org.kde.kwin-screen-%d", KWin::screen_number);
593
594 QDBusConnection::sessionBus().interface()->registerService(
595 appname, QDBusConnectionInterface::DontQueueService);
596
597 return a.exec();
598}
599
600#include "main.moc"
601