diff --git a/ksmserver/client.cpp b/ksmserver/client.cpp index 87a1627c9..cf06a4eda 100644 --- a/ksmserver/client.cpp +++ b/ksmserver/client.cpp @@ -1,184 +1,184 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Copyright 2005 Lubos Lunak relatively small extensions by Oswald Buddenhagen some code taken from the dcopserver (part of the KDE libraries), which is Copyright 1999 Matthias Ettrich Copyright 1999 Preston Brown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include #include "client.h" #include #include #ifdef HAVE_SYS_TIME_H #include #endif #include #include #include "server.h" extern KSMServer* the_server; KSMClient::KSMClient( SmsConn conn) { smsConn = conn; id = 0; resetState(); } KSMClient::~KSMClient() { foreach( SmProp *prop, properties ) SmFreeProperty( prop ); if (id) free((void*)id); } SmProp* KSMClient::property( const char* name ) const { foreach ( SmProp *prop, properties ) { if ( !qstrcmp( prop->name, name ) ) return prop; } return 0; } void KSMClient::resetState() { saveYourselfDone = false; pendingInteraction = false; waitForPhase2 = false; wasPhase2 = false; } /* * This fakes SmsGenerateClientID() in case we can't read our own hostname. * In this case SmsGenerateClientID() returns NULL, but we really want a * client ID, so we fake one. */ Q_GLOBAL_STATIC(QString, my_addr) char * safeSmsGenerateClientID( SmsConn /*c*/ ) { // Causes delays with misconfigured network :-/. // char *ret = SmsGenerateClientID(c); char* ret = NULL; if (!ret) { if (my_addr->isEmpty()) { -// qWarning("Can't get own host name. Your system is severely misconfigured\n"); +// qCWarning(KSMSERVER, "Can't get own host name. Your system is severely misconfigured\n"); /* Faking our IP address, the 0 below is "unknown" address format (1 would be IP, 2 would be DEC-NET format) */ char hostname[ 256 ]; if( gethostname( hostname, 255 ) != 0 ) my_addr->sprintf("0%.8x", KRandom::random()); else { // create some kind of hash for the hostname int addr[ 4 ] = { 0, 0, 0, 0 }; int pos = 0; for( unsigned int i = 0; i < strlen( hostname ); ++i, ++pos ) addr[ pos % 4 ] += hostname[ i ]; *my_addr = QStringLiteral( "0" ); for( int i = 0; i < 4; ++i ) *my_addr += QString::number( addr[ i ], 16 ); } } /* Needs to be malloc(), to look the same as libSM */ ret = (char *)malloc(1+my_addr->length()+13+10+4+1 + /*safeness*/ 10); static int sequence = 0; if (ret == NULL) return NULL; sprintf(ret, "1%s%.13ld%.10d%.4d", my_addr->toLatin1().constData(), (long)time(NULL), getpid(), sequence); sequence = (sequence + 1) % 10000; } return ret; } void KSMClient::registerClient( const char* previousId ) { id = previousId; if ( !id ) id = safeSmsGenerateClientID( smsConn ); SmsRegisterClientReply( smsConn, (char*) id ); SmsSaveYourself( smsConn, SmSaveLocal, false, SmInteractStyleNone, false ); SmsSaveComplete( smsConn ); the_server->clientRegistered( previousId ); } QString KSMClient::program() const { SmProp* p = property( SmProgram ); if ( !p || qstrcmp( p->type, SmARRAY8) || p->num_vals < 1) return QString(); return QLatin1String( (const char*) p->vals[0].value ); } QStringList KSMClient::restartCommand() const { QStringList result; SmProp* p = property( SmRestartCommand ); if ( !p || qstrcmp( p->type, SmLISTofARRAY8) || p->num_vals < 1) return result; for ( int i = 0; i < p->num_vals; i++ ) result +=QLatin1String( (const char*) p->vals[i].value ); return result; } QStringList KSMClient::discardCommand() const { QStringList result; SmProp* p = property( SmDiscardCommand ); if ( !p || qstrcmp( p->type, SmLISTofARRAY8) || p->num_vals < 1) return result; for ( int i = 0; i < p->num_vals; i++ ) result +=QLatin1String( (const char*) p->vals[i].value ); return result; } int KSMClient::restartStyleHint() const { SmProp* p = property( SmRestartStyleHint ); if ( !p || qstrcmp( p->type, SmCARD8) || p->num_vals < 1) return SmRestartIfRunning; return *((unsigned char*)p->vals[0].value); } QString KSMClient::userId() const { SmProp* p = property( SmUserID ); if ( !p || qstrcmp( p->type, SmARRAY8) || p->num_vals < 1) return QString(); return QLatin1String( (const char*) p->vals[0].value ); } diff --git a/ksmserver/logout-greeter/CMakeLists.txt b/ksmserver/logout-greeter/CMakeLists.txt index e9bf06226..e4dd4aaa0 100644 --- a/ksmserver/logout-greeter/CMakeLists.txt +++ b/ksmserver/logout-greeter/CMakeLists.txt @@ -1,18 +1,18 @@ -set(KSMSERVER_LOGOUT_GREETER_SRCS main.cpp ../shutdowndlg.cpp) +set(KSMSERVER_LOGOUT_GREETER_SRCS main.cpp ../shutdowndlg.cpp ../ksmserver_debug.cpp) add_executable(ksmserver-logout-greeter ${KSMSERVER_LOGOUT_GREETER_SRCS}) target_link_libraries(ksmserver-logout-greeter PW::KWorkspace Qt5::Widgets Qt5::Quick Qt5::X11Extras KF5::Declarative KF5::IconThemes KF5::I18n KF5::Package KF5::KDELibs4Support # Solid/PowerManagement KF5::WaylandClient ${X11_LIBRARIES} ) install(TARGETS ksmserver-logout-greeter DESTINATION ${KDE_INSTALL_LIBEXECDIR}) add_subdirectory(tests) diff --git a/ksmserver/main.cpp b/ksmserver/main.cpp index eea441f4a..37a2378d0 100644 --- a/ksmserver/main.cpp +++ b/ksmserver/main.cpp @@ -1,353 +1,354 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include "server.h" #include #include #include #include static const char version[] = "0.4"; static const char description[] = I18N_NOOP( "The reliable KDE session manager that talks the standard X11R6 \nsession management protocol (XSMP)." ); Display* dpy = 0; Colormap colormap = 0; Visual *visual = 0; extern KSMServer* the_server; void IoErrorHandler ( IceConn iceConn) { the_server->ioError( iceConn ); } bool writeTest(QByteArray path) { path += "/XXXXXX"; int fd = mkstemp(path.data()); if (fd == -1) return false; if (write(fd, "Hello World\n", 12) == -1) { int save_errno = errno; close(fd); unlink(path.data()); errno = save_errno; return false; } close(fd); unlink(path.data()); return true; } void checkComposite() { if( qgetenv( "KDE_SKIP_ARGB_VISUALS" ) == "1" ) return; // thanks to zack rusin and frederik for pointing me in the right direction // for the following bits of X11 code dpy = XOpenDisplay(0); // open default display if (!dpy) { - qCritical() << "Cannot connect to the X server"; + qCCritical(KSMSERVER) << "Cannot connect to the X server"; return; } int screen = DefaultScreen(dpy); int eventBase, errorBase; if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) { int nvi; XVisualInfo templ; templ.screen = screen; templ.depth = 32; templ.c_class = TrueColor; XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nvi); for (int i = 0; i < nvi; ++i) { XRenderPictFormat *format = XRenderFindVisualFormat(dpy, xvi[i].visual); if (format->type == PictTypeDirect && format->direct.alphaMask) { visual = xvi[i].visual; colormap = XCreateColormap(dpy, RootWindow(dpy, screen), visual, AllocNone); XFree(xvi); return; } } XFree(xvi); } XCloseDisplay( dpy ); dpy = NULL; } void sanity_check( int argc, char* argv[] ) { QString msg; QByteArray path = qgetenv("HOME"); const QByteArray readOnly = qgetenv("KDE_HOME_READONLY"); if (path.isEmpty()) { msg = i18n("$HOME not set!"); } if (msg.isEmpty() && access(path.data(), W_OK)) { if (errno == ENOENT) msg = i18n("$HOME directory (%1) does not exist.", QFile::decodeName(path)); else if (readOnly.isEmpty()) msg = i18n("No write access to $HOME directory (%1).", QFile::decodeName(path)); } if (msg.isEmpty() && access(path.data(), R_OK)) { if (errno == ENOENT) msg = i18n("$HOME directory (%1) does not exist.", QFile::decodeName(path)); else msg = i18n("No read access to $HOME directory (%1).", QFile::decodeName(path)); } if (msg.isEmpty() && readOnly.isEmpty() && !writeTest(path)) { if (errno == ENOSPC) msg = i18n("$HOME directory (%1) is out of disk space.", QFile::decodeName(path)); else msg = i18n("Writing to the $HOME directory (%2) failed with " "the error '%1'", QString::fromLocal8Bit(strerror(errno)), QFile::decodeName(path)); } if (msg.isEmpty()) { path = getenv("ICEAUTHORITY"); if (path.isEmpty()) { path = qgetenv("HOME"); path += "/.ICEauthority"; } if (access(path.data(), W_OK) && (errno != ENOENT)) msg = i18n("No write access to '%1'.", QFile::decodeName(path)); else if (access(path.data(), R_OK) && (errno != ENOENT)) msg = i18n("No read access to '%1'.", QFile::decodeName(path)); } if (msg.isEmpty()) { path = getenv("KDETMP"); if (path.isEmpty()) path = "/tmp"; if (!writeTest(path)) { if (errno == ENOSPC) msg = i18n("Temp directory (%1) is out of disk space.", QFile::decodeName(path)); else msg = i18n("Writing to the temp directory (%2) failed with\n " "the error '%1'", QString::fromLocal8Bit(strerror(errno)), QFile::decodeName(path)); } } if (msg.isEmpty() && (path != "/tmp")) { path = "/tmp"; if (!writeTest(path)) { if (errno == ENOSPC) msg = i18n("Temp directory (%1) is out of disk space."); else msg = i18n("Writing to the temp directory (%2) failed with\n " "the error '%1'", QString::fromLocal8Bit(strerror(errno)), QFile::decodeName(path)); } } if (msg.isEmpty()) { path += "/.ICE-unix"; if (access(path.data(), W_OK) && (errno != ENOENT)) msg = i18n("No write access to '%1'."); else if (access(path.data(), R_OK) && (errno != ENOENT)) msg = i18n("No read access to '%1'."); } if (!msg.isEmpty()) { const QString msg_pre = i18n("The following installation problem was detected\n" "while trying to start KDE:") + "\n\n "; const QString msg_post = i18n("\n\nKDE is unable to start.\n"); fputs(msg_pre.toUtf8().constData(), stderr); fprintf(stderr, "%s", msg.toUtf8().constData()); fputs(msg_post.toUtf8().constData(), stderr); QApplication a(argc, argv); const QString qmsg = msg_pre + msg + msg_post; KMessageBox::error(0, qmsg, i18n("Plasma Workspace installation problem!")); exit(255); } } extern "C" Q_DECL_EXPORT int kdemain( int argc, char* argv[] ) { sanity_check(argc, argv); putenv((char*)"SESSION_MANAGER="); checkComposite(); // force xcb QPA plugin as ksmserver is very X11 specific const QByteArray origQpaPlatform = qgetenv("QT_QPA_PLATFORM"); qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("xcb")); QQuickWindow::setDefaultAlphaBuffer(true); QApplication *a = new QApplication(argc, argv); // now the QPA platform is set, unset variable again to not launch apps with incorrect environment if (origQpaPlatform.isEmpty()) { qunsetenv("QT_QPA_PLATFORM"); } else { qputenv("QT_QPA_PLATFORM", origQpaPlatform); } QApplication::setApplicationName( QStringLiteral( "ksmserver") ); QApplication::setApplicationVersion( QString::fromLatin1( version ) ); QApplication::setOrganizationDomain( QStringLiteral( "kde.org") ); fcntl(ConnectionNumber(QX11Info::display()), F_SETFD, 1); a->setQuitOnLastWindowClosed(false); // #169486 QCommandLineParser parser; parser.setApplicationDescription(i18n(description)); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption restoreOption(QStringList() << QStringLiteral("r") << QStringLiteral("restore"), i18n("Restores the saved user session if available")); parser.addOption(restoreOption); QCommandLineOption wmOption(QStringList() << QStringLiteral("w") << QStringLiteral("windowmanager"), i18n("Starts in case no other window manager is \nparticipating in the session. Default is 'kwin'"), i18n("wm")); parser.addOption(wmOption); QCommandLineOption nolocalOption(QStringLiteral("nolocal"), i18n("Also allow remote connections")); parser.addOption(nolocalOption); QCommandLineOption lockscreenOption(QStringLiteral("lockscreen"), i18n("Starts the session in locked mode")); parser.addOption(lockscreenOption); QCommandLineOption noLockscreenOption(QStringLiteral("no-lockscreen"), i18n("Starts without lock screen support. Only needed if other component provides the lock screen.")); parser.addOption(noLockscreenOption); parser.process(*a); //TODO: should we still use this? // if( !QDBusConnection::sessionBus().interface()-> // registerService( QStringLiteral( "org.kde.ksmserver" ), // QDBusConnectionInterface::DontQueueService ) ) // { -// qWarning("Could not register with D-BUS. Aborting."); +// qCWarning(KSMSERVER, "Could not register with D-BUS. Aborting."); // return 1; // } QString wm = parser.value(wmOption); bool only_local = !parser.isSet(nolocalOption); #ifndef HAVE__ICETRANSNOLISTEN /* this seems strange, but the default is only_local, so if !only_local * the option --nolocal was given, and we warn (the option --nolocal * does nothing on this platform, as here the default is reversed) */ if (!only_local) { - qWarning("--nolocal is not supported on your platform. Sorry."); + qCWarning(KSMSERVER, "--nolocal is not supported on your platform. Sorry."); } only_local = false; #endif KSMServer::InitFlags flags = KSMServer::InitFlag::None; if (only_local) { flags |= KSMServer::InitFlag::OnlyLocal; } if (parser.isSet(lockscreenOption)) { flags |= KSMServer::InitFlag::ImmediateLockScreen; } if (parser.isSet(noLockscreenOption)) { flags |= KSMServer::InitFlag::NoLockScreen; } KSMServer *server = new KSMServer( wm, flags); // for the KDE-already-running check in startkde KSelectionOwner kde_running( "_KDE_RUNNING", 0 ); kde_running.claim( false ); IceSetIOErrorHandler( IoErrorHandler ); KConfigGroup config(KSharedConfig::openConfig(), "General"); int realScreenCount = ScreenCount( QX11Info::display() ); bool screenCountChanged = ( config.readEntry( "screenCount", realScreenCount ) != realScreenCount ); QString loginMode = config.readEntry( "loginMode", "restorePreviousLogout" ); if ( parser.isSet( restoreOption ) && ! screenCountChanged ) server->restoreSession( QStringLiteral( SESSION_BY_USER ) ); else if ( loginMode == QStringLiteral( "default" ) || screenCountChanged ) server->startDefaultSession(); else if ( loginMode == QStringLiteral( "restorePreviousLogout" ) ) server->restoreSession( QStringLiteral( SESSION_PREVIOUS_LOGOUT ) ); else if ( loginMode == QStringLiteral( "restoreSavedSession" ) ) server->restoreSession( QStringLiteral( SESSION_BY_USER ) ); else server->startDefaultSession(); KDBusService service(KDBusService::Unique); int ret = a->exec(); kde_running.release(); // needs to be done before QApplication destruction delete a; return ret; } diff --git a/ksmserver/server.cpp b/ksmserver/server.cpp index 89a820e3c..98e41dbc1 100644 --- a/ksmserver/server.cpp +++ b/ksmserver/server.cpp @@ -1,1118 +1,1118 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Copyright 2005 Lubos Lunak relatively small extensions by Oswald Buddenhagen some code taken from the dcopserver (part of the KDE libraries), which is Copyright 1999 Matthias Ettrich Copyright 1999 Preston Brown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include "server.h" #include "global.h" #include "client.h" #include "ksmserver_debug.h" #include "ksmserverinterfaceadaptor.h" #include "klocalizedstring.h" #include "kglobalaccel.h" #include #include // HAVE_LIMITS_H #include #include #include #include #include #ifdef HAVE_SYS_TIME_H #include #endif #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_LIMITS_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "switchuserdialog.h" KSMServer* the_server = 0; KSMServer* KSMServer::self() { return the_server; } /*! Utility function to execute a command on the local machine. Used * to restart applications. */ KProcess* KSMServer::startApplication( const QStringList& cmd, const QString& clientMachine, const QString& userId, bool wm ) { QStringList command = cmd; if ( command.isEmpty() ) return NULL; if ( !userId.isEmpty()) { struct passwd* pw = getpwuid( getuid()); if( pw != NULL && userId != QString::fromLocal8Bit( pw->pw_name )) { command.prepend( QStringLiteral("--") ); command.prepend( userId ); command.prepend( QStringLiteral("-u") ); command.prepend( QStandardPaths::findExecutable(QStringLiteral("kdesu"))); } } if ( !clientMachine.isEmpty() && clientMachine != QStringLiteral("localhost") ) { command.prepend( clientMachine ); command.prepend( xonCommand ); // "xon" by default } // TODO this function actually should not use KProcess at all and use klauncher (kdeinit) instead. // Klauncher should also have support for tracking whether the launched process is still alive // or not, so this should be redone. For now, use KProcess for wm's, as they need to be tracked, // klauncher for the rest where ksmserver doesn't care. if( wm ) { KProcess* process = new KProcess( this ); *process << command; // make it auto-delete connect(process, static_cast(&KProcess::error), process, &KProcess::deleteLater); connect(process, static_cast(&KProcess::finished), process, &KProcess::deleteLater); process->start(); return process; } else { int n = command.count(); org::kde::KLauncher klauncher(QStringLiteral("org.kde.klauncher5"), QStringLiteral("/KLauncher"), QDBusConnection::sessionBus()); QString app = command[0]; QStringList argList; for ( int i=1; i < n; i++) argList.append( command[i]); klauncher.exec_blind(app, argList ); return NULL; } } /*! Utility function to execute a command on the local machine. Used * to discard session data */ void KSMServer::executeCommand( const QStringList& command ) { if ( command.isEmpty() ) return; KProcess::execute( command ); } IceAuthDataEntry *authDataEntries = 0; static QTemporaryFile *remTempFile = 0; static IceListenObj *listenObjs = 0; int numTransports = 0; static bool only_local = 0; static Bool HostBasedAuthProc ( char* /*hostname*/) { if (only_local) return true; else return false; } Status KSMRegisterClientProc ( SmsConn /* smsConn */, SmPointer managerData, char * previousId ) { KSMClient* client = (KSMClient*) managerData; client->registerClient( previousId ); return 1; } void KSMInteractRequestProc ( SmsConn /* smsConn */, SmPointer managerData, int dialogType ) { the_server->interactRequest( (KSMClient*) managerData, dialogType ); } void KSMInteractDoneProc ( SmsConn /* smsConn */, SmPointer managerData, Bool cancelShutdown ) { the_server->interactDone( (KSMClient*) managerData, cancelShutdown ); } void KSMSaveYourselfRequestProc ( SmsConn smsConn , SmPointer /* managerData */, int saveType, Bool shutdown, int interactStyle, Bool fast, Bool global ) { if ( shutdown ) { the_server->shutdown( fast ? KWorkSpace::ShutdownConfirmNo : KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeDefault, KWorkSpace::ShutdownModeDefault ); } else if ( !global ) { SmsSaveYourself( smsConn, saveType, false, interactStyle, fast ); SmsSaveComplete( smsConn ); } // else checkpoint only, ksmserver does not yet support this // mode. Will come for KDE 3.1 } void KSMSaveYourselfPhase2RequestProc ( SmsConn /* smsConn */, SmPointer managerData ) { the_server->phase2Request( (KSMClient*) managerData ); } void KSMSaveYourselfDoneProc ( SmsConn /* smsConn */, SmPointer managerData, Bool success ) { the_server->saveYourselfDone( (KSMClient*) managerData, success ); } void KSMCloseConnectionProc ( SmsConn smsConn, SmPointer managerData, int count, char ** reasonMsgs ) { the_server->deleteClient( ( KSMClient* ) managerData ); if ( count ) SmFreeReasons( count, reasonMsgs ); IceConn iceConn = SmsGetIceConnection( smsConn ); SmsCleanUp( smsConn ); IceSetShutdownNegotiation (iceConn, False); IceCloseConnection( iceConn ); } void KSMSetPropertiesProc ( SmsConn /* smsConn */, SmPointer managerData, int numProps, SmProp ** props ) { KSMClient* client = ( KSMClient* ) managerData; for ( int i = 0; i < numProps; i++ ) { SmProp *p = client->property( props[i]->name ); if ( p ) { client->properties.removeAll( p ); SmFreeProperty( p ); } client->properties.append( props[i] ); if ( !qstrcmp( props[i]->name, SmProgram ) ) the_server->clientSetProgram( client ); } if ( numProps ) free( props ); } void KSMDeletePropertiesProc ( SmsConn /* smsConn */, SmPointer managerData, int numProps, char ** propNames ) { KSMClient* client = ( KSMClient* ) managerData; for ( int i = 0; i < numProps; i++ ) { SmProp *p = client->property( propNames[i] ); if ( p ) { client->properties.removeAll( p ); SmFreeProperty( p ); } } } void KSMGetPropertiesProc ( SmsConn smsConn, SmPointer managerData ) { KSMClient* client = ( KSMClient* ) managerData; SmProp** props = new SmProp*[client->properties.count()]; int i = 0; foreach( SmProp *prop, client->properties ) props[i++] = prop; SmsReturnProperties( smsConn, i, props ); delete [] props; } class KSMListener : public QSocketNotifier { public: KSMListener( IceListenObj obj ) : QSocketNotifier( IceGetListenConnectionNumber( obj ), QSocketNotifier::Read ) { listenObj = obj; } IceListenObj listenObj; }; class KSMConnection : public QSocketNotifier { public: KSMConnection( IceConn conn ) : QSocketNotifier( IceConnectionNumber( conn ), QSocketNotifier::Read ) { iceConn = conn; } IceConn iceConn; }; /* for printing hex digits */ static void fprintfhex (FILE *fp, unsigned int len, char *cp) { static const char hexchars[] = "0123456789abcdef"; for (; len > 0; len--, cp++) { unsigned char s = *cp; putc(hexchars[s >> 4], fp); putc(hexchars[s & 0x0f], fp); } } /* * We use temporary files which contain commands to add/remove entries from * the .ICEauthority file. */ static void write_iceauth (FILE *addfp, FILE *removefp, IceAuthDataEntry *entry) { fprintf (addfp, "add %s \"\" %s %s ", entry->protocol_name, entry->network_id, entry->auth_name); fprintfhex (addfp, entry->auth_data_length, entry->auth_data); fprintf (addfp, "\n"); fprintf (removefp, "remove protoname=%s protodata=\"\" netid=%s authname=%s\n", entry->protocol_name, entry->network_id, entry->auth_name); } #define MAGIC_COOKIE_LEN 16 Status SetAuthentication_local (int count, IceListenObj *listenObjs) { int i; for (i = 0; i < count; i ++) { char *prot = IceGetListenConnectionString(listenObjs[i]); if (!prot) continue; char *host = strchr(prot, '/'); char *sock = 0; if (host) { *host=0; host++; sock = strchr(host, ':'); if (sock) { *sock = 0; sock++; } } qCDebug(KSMSERVER) << "KSMServer: SetAProc_loc: conn " << (unsigned)i << ", prot=" << prot << ", file=" << sock; if (sock && !strcmp(prot, "local")) { chmod(sock, 0700); } IceSetHostBasedAuthProc (listenObjs[i], HostBasedAuthProc); free(prot); } return 1; } Status SetAuthentication (int count, IceListenObj *listenObjs, IceAuthDataEntry **authDataEntries) { QTemporaryFile addTempFile; remTempFile = new QTemporaryFile; if (!addTempFile.open() || !remTempFile->open()) return 0; if ((*authDataEntries = (IceAuthDataEntry *) malloc ( count * 2 * sizeof (IceAuthDataEntry))) == NULL) return 0; FILE *addAuthFile = fopen(QFile::encodeName(addTempFile.fileName()).constData(), "r+"); FILE *remAuthFile = fopen(QFile::encodeName(remTempFile->fileName()).constData(), "r+"); for (int i = 0; i < numTransports * 2; i += 2) { (*authDataEntries)[i].network_id = IceGetListenConnectionString (listenObjs[i/2]); (*authDataEntries)[i].protocol_name = (char *) "ICE"; (*authDataEntries)[i].auth_name = (char *) "MIT-MAGIC-COOKIE-1"; (*authDataEntries)[i].auth_data = IceGenerateMagicCookie (MAGIC_COOKIE_LEN); (*authDataEntries)[i].auth_data_length = MAGIC_COOKIE_LEN; (*authDataEntries)[i+1].network_id = IceGetListenConnectionString (listenObjs[i/2]); (*authDataEntries)[i+1].protocol_name = (char *) "XSMP"; (*authDataEntries)[i+1].auth_name = (char *) "MIT-MAGIC-COOKIE-1"; (*authDataEntries)[i+1].auth_data = IceGenerateMagicCookie (MAGIC_COOKIE_LEN); (*authDataEntries)[i+1].auth_data_length = MAGIC_COOKIE_LEN; write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i]); write_iceauth (addAuthFile, remAuthFile, &(*authDataEntries)[i+1]); IceSetPaAuthData (2, &(*authDataEntries)[i]); IceSetHostBasedAuthProc (listenObjs[i/2], HostBasedAuthProc); } fclose(addAuthFile); fclose(remAuthFile); QString iceAuth = QStandardPaths::findExecutable(QStringLiteral("iceauth")); if (iceAuth.isEmpty()) { - qWarning("KSMServer: could not find iceauth"); + qCWarning(KSMSERVER, "KSMServer: could not find iceauth"); return 0; } KProcess p; p << iceAuth << QStringLiteral("source") << addTempFile.fileName(); p.execute(); return (1); } /* * Free up authentication data. */ void FreeAuthenticationData(int count, IceAuthDataEntry *authDataEntries) { /* Each transport has entries for ICE and XSMP */ if (only_local) return; for (int i = 0; i < count * 2; i++) { free (authDataEntries[i].network_id); free (authDataEntries[i].auth_data); } free (authDataEntries); QString iceAuth = QStandardPaths::findExecutable(QStringLiteral("iceauth")); if (iceAuth.isEmpty()) { - qWarning("KSMServer: could not find iceauth"); + qCWarning(KSMSERVER, "KSMServer: could not find iceauth"); return; } if (remTempFile) { KProcess p; p << iceAuth << QStringLiteral("source") << remTempFile->fileName(); p.execute(); } delete remTempFile; remTempFile = 0; } static int Xio_ErrorHandler( Display * ) { - qWarning("ksmserver: Fatal IO error: client killed"); + qCWarning(KSMSERVER, "ksmserver: Fatal IO error: client killed"); // Don't do anything that might require the X connection if (the_server) { KSMServer *server = the_server; the_server = 0; server->cleanUp(); // Don't delete server!! } exit(0); // Don't report error, it's not our fault. return 0; // Bogus return value, notreached } void KSMServer::setupXIOErrorHandler() { XSetIOErrorHandler(Xio_ErrorHandler); } static void sighandler(int sig) { if (sig == SIGHUP) { signal(SIGHUP, sighandler); return; } if (the_server) { KSMServer *server = the_server; the_server = 0; server->cleanUp(); delete server; } if (qApp) qApp->quit(); //::exit(0); } void KSMWatchProc ( IceConn iceConn, IcePointer client_data, Bool opening, IcePointer* watch_data) { KSMServer* ds = ( KSMServer*) client_data; if (opening) { *watch_data = (IcePointer) ds->watchConnection( iceConn ); } else { ds->removeConnection( (KSMConnection*) *watch_data ); } } static Status KSMNewClientProc ( SmsConn conn, SmPointer manager_data, unsigned long* mask_ret, SmsCallbacks* cb, char** failure_reason_ret) { *failure_reason_ret = 0; void* client = ((KSMServer*) manager_data )->newClient( conn ); cb->register_client.callback = KSMRegisterClientProc; cb->register_client.manager_data = client; cb->interact_request.callback = KSMInteractRequestProc; cb->interact_request.manager_data = client; cb->interact_done.callback = KSMInteractDoneProc; cb->interact_done.manager_data = client; cb->save_yourself_request.callback = KSMSaveYourselfRequestProc; cb->save_yourself_request.manager_data = client; cb->save_yourself_phase2_request.callback = KSMSaveYourselfPhase2RequestProc; cb->save_yourself_phase2_request.manager_data = client; cb->save_yourself_done.callback = KSMSaveYourselfDoneProc; cb->save_yourself_done.manager_data = client; cb->close_connection.callback = KSMCloseConnectionProc; cb->close_connection.manager_data = client; cb->set_properties.callback = KSMSetPropertiesProc; cb->set_properties.manager_data = client; cb->delete_properties.callback = KSMDeletePropertiesProc; cb->delete_properties.manager_data = client; cb->get_properties.callback = KSMGetPropertiesProc; cb->get_properties.manager_data = client; *mask_ret = SmsRegisterClientProcMask | SmsInteractRequestProcMask | SmsInteractDoneProcMask | SmsSaveYourselfRequestProcMask | SmsSaveYourselfP2RequestProcMask | SmsSaveYourselfDoneProcMask | SmsCloseConnectionProcMask | SmsSetPropertiesProcMask | SmsDeletePropertiesProcMask | SmsGetPropertiesProcMask; return 1; } #ifdef HAVE__ICETRANSNOLISTEN extern "C" int _IceTransNoListen(const char * protocol); #endif KSMServer::KSMServer( const QString& windowManager, InitFlags flags ) : wmProcess( NULL ) , sessionGroup( QStringLiteral( "" ) ) , logoutEffectWidget( NULL ) { if (!flags.testFlag(InitFlag::NoLockScreen)) { ScreenLocker::KSldApp::self()->initialize(); if (flags.testFlag(InitFlag::ImmediateLockScreen)) { ScreenLocker::KSldApp::self()->lock(ScreenLocker::EstablishLock::Immediate); } } new KSMServerInterfaceAdaptor( this ); QDBusConnection::sessionBus().registerObject(QStringLiteral("/KSMServer"), this); kcminitSignals = NULL; the_server = this; clean = false; shutdownType = KWorkSpace::ShutdownTypeNone; state = Idle; dialogActive = false; saveSession = false; wmPhase1WaitingCount = 0; KConfigGroup config(KSharedConfig::openConfig(), "General"); clientInteracting = 0; xonCommand = config.readEntry( "xonCommand", "xon" ); selectWm( windowManager ); connect(&startupSuspendTimeoutTimer, &QTimer::timeout, this, &KSMServer::startupSuspendTimeout); connect(&pendingShutdown, &QTimer::timeout, this, &KSMServer::pendingShutdownTimeout); only_local = flags.testFlag(InitFlag::OnlyLocal); #ifdef HAVE__ICETRANSNOLISTEN if (only_local) _IceTransNoListen("tcp"); #else only_local = false; #endif char errormsg[256]; if (!SmsInitialize ( (char*) KSMVendorString, (char*) KSMReleaseString, KSMNewClientProc, (SmPointer) this, HostBasedAuthProc, 256, errormsg ) ) { - qWarning("KSMServer: could not register XSM protocol"); + qCWarning(KSMSERVER, "KSMServer: could not register XSM protocol"); } if (!IceListenForConnections (&numTransports, &listenObjs, 256, errormsg)) { - qWarning("KSMServer: Error listening for connections: %s", errormsg); - qWarning("KSMServer: Aborting."); + qCWarning(KSMSERVER, "KSMServer: Error listening for connections: %s", errormsg); + qCWarning(KSMSERVER, "KSMServer: Aborting."); exit(1); } { // publish available transports. QByteArray fName = QFile::encodeName(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QDir::separator() + QStringLiteral("KSMserver")); qCDebug(KSMSERVER) << fName; QString display = QString::fromLocal8Bit(::getenv("DISPLAY")); // strip the screen number from the display display.replace(QRegExp(QStringLiteral("\\.[0-9]+$")), QStringLiteral("")); int i; while( (i = display.indexOf(QLatin1Char(':'))) >= 0) display[i] = '_'; while( (i = display.indexOf(QLatin1Char('/'))) >= 0) display[i] = '_'; fName += '_'+display.toLocal8Bit(); FILE *f; f = ::fopen(fName.data(), "w+"); if (!f) { - qWarning("KSMServer: cannot open %s: %s", fName.data(), strerror(errno)); - qWarning("KSMServer: Aborting."); + qCWarning(KSMSERVER, "KSMServer: cannot open %s: %s", fName.data(), strerror(errno)); + qCWarning(KSMSERVER, "KSMServer: Aborting."); exit(1); } char* session_manager = IceComposeNetworkIdList(numTransports, listenObjs); fprintf(f, "%s\n%i\n", session_manager, getpid()); fclose(f); setenv( "SESSION_MANAGER", session_manager, true ); // Pass env. var to kdeinit. org::kde::KLauncher klauncher( QStringLiteral( "org.kde.klauncher5" ), QStringLiteral( "/KLauncher" ), QDBusConnection::sessionBus()); klauncher.setLaunchEnv( QStringLiteral( "SESSION_MANAGER" ), QString::fromLocal8Bit( (const char*) session_manager ) ); free(session_manager); } if (only_local) { if (!SetAuthentication_local(numTransports, listenObjs)) qFatal("KSMSERVER: authentication setup failed."); } else { if (!SetAuthentication(numTransports, listenObjs, &authDataEntries)) qFatal("KSMSERVER: authentication setup failed."); } IceAddConnectionWatch (KSMWatchProc, (IcePointer) this); KSMListener* con; for ( int i = 0; i < numTransports; i++) { fcntl( IceGetListenConnectionNumber( listenObjs[i] ), F_SETFD, FD_CLOEXEC ); con = new KSMListener( listenObjs[i] ); listener.append( con ); connect(con, &KSMListener::activated, this, &KSMServer::newConnection); } signal(SIGHUP, sighandler); signal(SIGTERM, sighandler); signal(SIGINT, sighandler); signal(SIGPIPE, SIG_IGN); connect(&protectionTimer, &QTimer::timeout, this, &KSMServer::protectionTimeout); connect(&restoreTimer, &QTimer::timeout, this, &KSMServer::tryRestoreNext); connect(qApp, &QApplication::aboutToQuit, this, &KSMServer::cleanUp); } KSMServer::~KSMServer() { qDeleteAll( listener ); the_server = 0; cleanUp(); } void KSMServer::cleanUp() { if (clean) return; clean = true; IceFreeListenObjs (numTransports, listenObjs); QByteArray fName = QFile::encodeName(QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + QLatin1Char('/') + QStringLiteral("KSMserver")); QString display = QString::fromLocal8Bit(::getenv("DISPLAY")); // strip the screen number from the display display.replace(QRegExp(QStringLiteral("\\.[0-9]+$")), QStringLiteral("")); int i; while( (i = display.indexOf(QLatin1Char(':'))) >= 0) display[i] = '_'; while( (i = display.indexOf(QLatin1Char('/'))) >= 0) display[i] = '_'; fName += '_'+display.toLocal8Bit(); ::unlink(fName.data()); FreeAuthenticationData(numTransports, authDataEntries); signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); runShutdownScripts(); KDisplayManager().shutdown( shutdownType, shutdownMode, bootOption ); } void* KSMServer::watchConnection( IceConn iceConn ) { KSMConnection* conn = new KSMConnection( iceConn ); connect(conn, &KSMConnection::activated, this, &KSMServer::processData); return (void*) conn; } void KSMServer::removeConnection( KSMConnection* conn ) { delete conn; } /*! Called from our IceIoErrorHandler */ void KSMServer::ioError( IceConn /*iceConn*/ ) { } void KSMServer::processData( int /*socket*/ ) { IceConn iceConn = ((KSMConnection*)sender())->iceConn; IceProcessMessagesStatus status = IceProcessMessages( iceConn, 0, 0 ); if ( status == IceProcessMessagesIOError ) { IceSetShutdownNegotiation( iceConn, False ); QList::iterator it = clients.begin(); QList::iterator const itEnd = clients.end(); while ( ( it != itEnd ) && *it && ( SmsGetIceConnection( ( *it )->connection() ) != iceConn ) ) ++it; if ( ( it != itEnd ) && *it ) { SmsConn smsConn = (*it)->connection(); deleteClient( *it ); SmsCleanUp( smsConn ); } (void) IceCloseConnection( iceConn ); } } KSMClient* KSMServer::newClient( SmsConn conn ) { KSMClient* client = new KSMClient( conn ); clients.append( client ); return client; } void KSMServer::deleteClient( KSMClient* client ) { if ( !clients.contains( client ) ) // paranoia return; clients.removeAll( client ); clientsToKill.removeAll( client ); clientsToSave.removeAll( client ); if ( client == clientInteracting ) { clientInteracting = 0; handlePendingInteractions(); } delete client; if ( state == Shutdown || state == Checkpoint || state == ClosingSubSession ) completeShutdownOrCheckpoint(); if ( state == Killing ) completeKilling(); else if ( state == KillingSubSession ) completeKillingSubSession(); if ( state == KillingWM ) completeKillingWM(); } void KSMServer::newConnection( int /*socket*/ ) { IceAcceptStatus status; IceConn iceConn = IceAcceptConnection( ((KSMListener*)sender())->listenObj, &status); if( iceConn == NULL ) return; IceSetShutdownNegotiation( iceConn, False ); IceConnectStatus cstatus; while ((cstatus = IceConnectionStatus (iceConn))==IceConnectPending) { (void) IceProcessMessages( iceConn, 0, 0 ); } if (cstatus != IceConnectAccepted) { if (cstatus == IceConnectIOError) qCDebug(KSMSERVER) << "IO error opening ICE Connection!"; else qCDebug(KSMSERVER) << "ICE Connection rejected!"; (void )IceCloseConnection (iceConn); return; } // don't leak the fd fcntl( IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC ); } QString KSMServer::currentSession() { if ( sessionGroup.startsWith( QLatin1String( "Session: " ) ) ) return sessionGroup.mid( 9 ); return QStringLiteral( "" ); // empty, not null, since used for KConfig::setGroup } void KSMServer::discardSession() { KConfigGroup config(KSharedConfig::openConfig(), sessionGroup ); int count = config.readEntry( "count", 0 ); foreach ( KSMClient *c, clients ) { QStringList discardCommand = c->discardCommand(); if ( discardCommand.isEmpty()) continue; // check that non of the old clients used the exactly same // discardCommand before we execute it. This used to be the // case up to KDE and Qt < 3.1 int i = 1; while ( i <= count && config.readPathEntry( QStringLiteral("discardCommand") + QString::number(i), QStringList() ) != discardCommand ) i++; if ( i <= count ) executeCommand( discardCommand ); } } void KSMServer::storeSession() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); config->reparseConfiguration(); // config may have changed in the KControl module KConfigGroup generalGroup(config, "General"); excludeApps = generalGroup.readEntry( "excludeApps" ).toLower() .split( QRegExp( QStringLiteral("[,:]") ), QString::SkipEmptyParts ); KConfigGroup configSessionGroup(config, sessionGroup); int count = configSessionGroup.readEntry( "count", 0 ); for ( int i = 1; i <= count; i++ ) { QStringList discardCommand = configSessionGroup.readPathEntry( QLatin1String("discardCommand") + QString::number(i), QStringList() ); if ( discardCommand.isEmpty()) continue; // check that non of the new clients uses the exactly same // discardCommand before we execute it. This used to be the // case up to KDE and Qt < 3.1 QList::iterator it = clients.begin(); QList::iterator const itEnd = clients.end(); while ( ( it != itEnd ) && *it && (discardCommand != ( *it )->discardCommand() ) ) ++it; if ( ( it != itEnd ) && *it ) continue; executeCommand( discardCommand ); } config->deleteGroup( sessionGroup ); //### does not work with global config object... KConfigGroup cg( config, sessionGroup); count = 0; if (state != ClosingSubSession) { // put the wm first foreach ( KSMClient *c, clients ) if ( c->program() == wm ) { clients.removeAll( c ); clients.prepend( c ); break; } } foreach ( KSMClient *c, clients ) { int restartHint = c->restartStyleHint(); if (restartHint == SmRestartNever) continue; QString program = c->program(); QStringList restartCommand = c->restartCommand(); if (program.isEmpty() && restartCommand.isEmpty()) continue; if (state == ClosingSubSession && ! clientsToSave.contains(c)) continue; // 'program' might be (mostly) fullpath, or (sometimes) just the name. // 'name' is just the name. QFileInfo info(program); const QString& name = info.fileName(); if ( excludeApps.contains(program.toLower()) || excludeApps.contains(name.toLower()) ) { continue; } count++; QString n = QString::number(count); cg.writeEntry( QStringLiteral("program")+n, program ); cg.writeEntry( QStringLiteral("clientId")+n, c->clientId() ); cg.writeEntry( QStringLiteral("restartCommand")+n, restartCommand ); cg.writePathEntry( QStringLiteral("discardCommand")+n, c->discardCommand() ); cg.writeEntry( QStringLiteral("restartStyleHint")+n, restartHint ); cg.writeEntry( QStringLiteral("userId")+n, c->userId() ); cg.writeEntry( QStringLiteral("wasWm")+n, isWM( c )); } cg.writeEntry( "count", count ); KConfigGroup cg2( config, "General"); cg2.writeEntry( "screenCount", ScreenCount(QX11Info::display())); storeLegacySession(config.data()); config->sync(); } QStringList KSMServer::sessionList() { QStringList sessions( QStringLiteral( "default" ) ); KSharedConfig::Ptr config = KSharedConfig::openConfig(); const QStringList groups = config->groupList(); for ( QStringList::ConstIterator it = groups.constBegin(); it != groups.constEnd(); ++it ) if ( (*it).startsWith( QLatin1String( "Session: " ) ) ) sessions << (*it).mid( 9 ); return sessions; } bool KSMServer::isWM( const KSMClient* client ) const { return isWM( client->program()); } bool KSMServer::isWM( const QString& command ) const { return command == wm; } bool KSMServer::defaultSession() const { return sessionGroup.isEmpty(); } // selection logic: // - $KDEWM is set - use that // - a wm is selected using the kcm - use that // - if that fails, just use KWin void KSMServer::selectWm( const QString& kdewm ) { wm = QStringLiteral( KWIN_BIN ); // defaults wmCommands = ( QStringList() << QStringLiteral( KWIN_BIN ) ); if( !kdewm.isEmpty()) { wmCommands = ( QStringList() << kdewm ); wm = kdewm; return; } KConfigGroup config(KSharedConfig::openConfig(), "General"); QString cfgwm = config.readEntry( "windowManager", "kwin" ); KDesktopFile file( QStandardPaths::AppDataLocation, QStringLiteral( "windowmanagers/" ) + cfgwm + QStringLiteral( ".desktop" ) ); if( file.noDisplay()) return; if( !file.tryExec()) return; QString testexec = file.desktopGroup().readEntry( "X-KDE-WindowManagerTestExec" ); if( !testexec.isEmpty()) { KProcess proc; proc.setShellCommand( testexec ); if( proc.execute() != 0 ) return; } QStringList cfgWmCommands = KShell::splitArgs( file.desktopGroup().readEntry( "Exec" )); if( cfgWmCommands.isEmpty()) return; QString smname = file.desktopGroup().readEntry( "X-KDE-WindowManagerId" ); // ok wm = smname.isEmpty() ? cfgwm : smname; wmCommands = cfgWmCommands; } void KSMServer::wmChanged() { KSharedConfig::openConfig()->reparseConfiguration(); selectWm( QStringLiteral( "" ) ); } void KSMServer::setupShortcuts() { if (KAuthorized::authorize( QStringLiteral( "logout" ))) { KActionCollection* actionCollection = new KActionCollection(this); QAction* a; a = actionCollection->addAction(QStringLiteral("Log Out")); a->setText(i18n("Log Out")); KGlobalAccel::self()->setShortcut(a, QList() << Qt::ALT+Qt::CTRL+Qt::Key_Delete); connect(a, &QAction::triggered, this, &KSMServer::defaultLogout); a = actionCollection->addAction(QStringLiteral("Log Out Without Confirmation")); a->setText(i18n("Log Out Without Confirmation")); KGlobalAccel::self()->setShortcut(a, QList() << Qt::ALT+Qt::CTRL+Qt::SHIFT+Qt::Key_Delete); connect(a, &QAction::triggered, this, &KSMServer::logoutWithoutConfirmation); a = actionCollection->addAction(QStringLiteral("Halt Without Confirmation")); a->setText(i18n("Halt Without Confirmation")); KGlobalAccel::self()->setShortcut(a, QList() << Qt::ALT+Qt::CTRL+Qt::SHIFT+Qt::Key_PageDown); connect(a, &QAction::triggered, this, &KSMServer::haltWithoutConfirmation); a = actionCollection->addAction(QStringLiteral("Reboot Without Confirmation")); a->setText(i18n("Reboot Without Confirmation")); KGlobalAccel::self()->setShortcut(a, QList() << Qt::ALT+Qt::CTRL+Qt::SHIFT+Qt::Key_PageUp); connect(a, &QAction::triggered, this, &KSMServer::rebootWithoutConfirmation); } } void KSMServer::defaultLogout() { shutdown(KWorkSpace::ShutdownConfirmYes, KWorkSpace::ShutdownTypeDefault, KWorkSpace::ShutdownModeDefault); } void KSMServer::logoutWithoutConfirmation() { shutdown(KWorkSpace::ShutdownConfirmNo, KWorkSpace::ShutdownTypeNone, KWorkSpace::ShutdownModeDefault); } void KSMServer::haltWithoutConfirmation() { shutdown(KWorkSpace::ShutdownConfirmNo, KWorkSpace::ShutdownTypeHalt, KWorkSpace::ShutdownModeDefault); } void KSMServer::rebootWithoutConfirmation() { shutdown(KWorkSpace::ShutdownConfirmNo, KWorkSpace::ShutdownTypeReboot, KWorkSpace::ShutdownModeDefault); } void KSMServer::openSwitchUserDialog() { KDisplayManager dm; if (!dm.isSwitchable()) { return; } QScopedPointer dlg(new KSMSwitchUserDialog(&dm)); dlg->exec(); } void KSMServer::runShutdownScripts() { const QStringList shutdownFolders = QStandardPaths::locateAll(QStandardPaths::GenericConfigLocation, QStringLiteral("plasma-workspace/shutdown"), QStandardPaths::LocateDirectory); foreach (const QString &shutDownFolder, shutdownFolders) { QDir dir(shutDownFolder); if (!dir.exists()) { continue; } const QStringList entries = dir.entryList(QDir::Files); foreach (const QString &file, entries) { // Don't execute backup files if (!file.endsWith(QLatin1Char('~')) && !file.endsWith(QStringLiteral(".bak")) && (file[0] != QLatin1Char('%') || !file.endsWith(QLatin1Char('%'))) && (file[0] != QLatin1Char('#') || !file.endsWith(QLatin1Char('#')))) { const QString fullPath = dir.absolutePath() + QLatin1Char('/') + file; qCDebug(KSMSERVER) << "running shutdown script" << fullPath; QProcess::execute(fullPath); } } } } diff --git a/ksmserver/shutdown.cpp b/ksmserver/shutdown.cpp index 60eb67268..a44deb05b 100644 --- a/ksmserver/shutdown.cpp +++ b/ksmserver/shutdown.cpp @@ -1,788 +1,788 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich relatively small extensions by Oswald Buddenhagen some code taken from the dcopserver (part of the KDE libraries), which is Copyright 1999 Matthias Ettrich Copyright 1999 Preston Brown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include #include // HAVE_LIMITS_H #include #include #include #include #include #include #ifdef HAVE_SYS_TIME_H #include #endif #include #include #include #include #include #include #include #include #include #ifdef HAVE_LIMITS_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include "server.h" #include "global.h" #include "client.h" #include #include #include #include #include void KSMServer::logout( int confirm, int sdtype, int sdmode ) { // KDE5: remove me if (sdtype == KWorkSpace::ShutdownTypeLogout) sdtype = KWorkSpace::ShutdownTypeNone; shutdown( (KWorkSpace::ShutdownConfirm)confirm, (KWorkSpace::ShutdownType)sdtype, (KWorkSpace::ShutdownMode)sdmode ); } bool KSMServer::canShutdown() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); config->reparseConfiguration(); // config may have changed in the KControl module KConfigGroup cg( config, "General"); return cg.readEntry( "offerShutdown", true ) && KDisplayManager().canShutdown(); } bool KSMServer::isShuttingDown() const { return state >= Shutdown; } bool readFromPipe(int pipe) { QFile readPipe; if (!readPipe.open(pipe, QIODevice::ReadOnly)) { return false; } QByteArray result = readPipe.readLine(); if (result.isEmpty()) { return false; } bool ok = false; const int number = result.toInt(&ok); if (!ok) { return false; } KSMServer::self()->shutdownType = KWorkSpace::ShutdownType(number); return true; } void KSMServer::shutdown( KWorkSpace::ShutdownConfirm confirm, KWorkSpace::ShutdownType sdtype, KWorkSpace::ShutdownMode sdmode ) { - qDebug() << "Shutdown called with confirm " << confirm + qCDebug(KSMSERVER) << "Shutdown called with confirm " << confirm << " type " << sdtype << " and mode " << sdmode; pendingShutdown.stop(); if( dialogActive ) return; if( state >= Shutdown ) // already performing shutdown return; if( state != Idle ) // performing startup { // perform shutdown as soon as startup is finished, in order to avoid saving partial session if( !pendingShutdown.isActive()) { pendingShutdown.start( 1000 ); pendingShutdown_confirm = confirm; pendingShutdown_sdtype = sdtype; pendingShutdown_sdmode = sdmode; } return; } KSharedConfig::Ptr config = KSharedConfig::openConfig(); config->reparseConfiguration(); // config may have changed in the KControl module KConfigGroup cg( config, "General"); bool logoutConfirmed = (confirm == KWorkSpace::ShutdownConfirmYes) ? false : (confirm == KWorkSpace::ShutdownConfirmNo) ? true : !cg.readEntry( "confirmLogout", true ); bool choose = false; bool maysd = false; if (cg.readEntry( "offerShutdown", true ) && KDisplayManager().canShutdown()) maysd = true; if (!maysd) { if (sdtype != KWorkSpace::ShutdownTypeNone && sdtype != KWorkSpace::ShutdownTypeDefault && logoutConfirmed) return; /* unsupported fast shutdown */ sdtype = KWorkSpace::ShutdownTypeNone; } else if (sdtype == KWorkSpace::ShutdownTypeDefault) { sdtype = (KWorkSpace::ShutdownType) cg.readEntry( "shutdownType", (int)KWorkSpace::ShutdownTypeNone ); choose = true; } if (sdmode == KWorkSpace::ShutdownModeDefault) sdmode = KWorkSpace::ShutdownModeInteractive; - qDebug() << "After modifications confirm is " << confirm + qCDebug(KSMSERVER) << "After modifications confirm is " << confirm << " type is " << sdtype << " and mode " << sdmode; QString bopt; if ( !logoutConfirmed ) { int pipeFds[2]; if (pipe(pipeFds) != 0) { return; } QProcess *p = new QProcess(this); p->setProgram(QStringLiteral(LOGOUT_GREETER_BIN)); QStringList arguments; if (maysd) { arguments << QStringLiteral("--shutdown-allowed"); } if (choose) { arguments << QStringLiteral("--choose"); } if (sdtype != KWorkSpace::ShutdownTypeDefault) { arguments << QStringLiteral("--mode"); switch (sdtype) { case KWorkSpace::ShutdownTypeHalt: arguments << QStringLiteral("shutdown"); break; case KWorkSpace::ShutdownTypeReboot: arguments << QStringLiteral("reboot"); break; case KWorkSpace::ShutdownTypeNone: default: // logout arguments << QStringLiteral("logout"); break; } } arguments << QStringLiteral("--mode-fd"); arguments << QString::number(pipeFds[1]); p->setArguments(arguments); const int resultPipe = pipeFds[0]; connect(p, static_cast(&QProcess::error), this, [this, resultPipe] { close(resultPipe); dialogActive = false; } ); connect(p, static_cast(&QProcess::finished), this, [this, resultPipe, sdmode, p] (int exitCode) { p->deleteLater(); dialogActive = false; if (exitCode != 0) { close(resultPipe); return; } QFutureWatcher *watcher = new QFutureWatcher(); QObject::connect(watcher, &QFutureWatcher::finished, this, [this, sdmode, watcher] { const bool result = watcher->result(); if (!result) { // it failed to read, don't logout return; } shutdownMode = sdmode; bootOption = QString(); performLogout(); }, Qt::QueuedConnection); QObject::connect(watcher, &QFutureWatcher::finished, watcher, &QFutureWatcher::deleteLater, Qt::QueuedConnection); watcher->setFuture(QtConcurrent::run(readFromPipe, resultPipe)); } ); dialogActive = true; p->start(); close(pipeFds[1]); } else { shutdownType = sdtype; shutdownMode = sdmode; bootOption = bopt; performLogout(); } } void KSMServer::performLogout() { // If the logout was confirmed, let's start a powermanagement inhibition. // We store the cookie so we can interrupt it if the logout will be canceled inhibitCookie = Solid::PowerManagement::beginSuppressingSleep(QStringLiteral("Shutting down system")); // shall we save the session on logout? KConfigGroup cg(KSharedConfig::openConfig(), "General"); saveSession = ( cg.readEntry( "loginMode", QStringLiteral( "restorePreviousLogout" ) ) == QStringLiteral( "restorePreviousLogout" ) ); - qDebug() << "saveSession is " << saveSession; + qCDebug(KSMSERVER) << "saveSession is " << saveSession; if ( saveSession ) sessionGroup = QStringLiteral( "Session: " ) + QString::fromLocal8Bit( SESSION_PREVIOUS_LOGOUT ); // Set the real desktop background to black so that exit looks // clean regardless of what was on "our" desktop. QPalette palette; palette.setColor( QApplication::desktop()->backgroundRole(), Qt::black ); QApplication::setPalette(palette); state = Shutdown; wmPhase1WaitingCount = 0; saveType = saveSession?SmSaveBoth:SmSaveGlobal; #ifndef NO_LEGACY_SESSION_MANAGEMENT performLegacySessionSave(); #endif startProtection(); foreach( KSMClient* c, clients ) { c->resetState(); // Whoever came with the idea of phase 2 got it backwards // unfortunately. Window manager should be the very first // one saving session data, not the last one, as possible // user interaction during session save may alter // window positions etc. // Moreover, KWin's focus stealing prevention would lead // to undesired effects while session saving (dialogs // wouldn't be activated), so it needs be assured that // KWin will turn it off temporarily before any other // user interaction takes place. // Therefore, make sure the WM finishes its phase 1 // before others a chance to change anything. // KWin will check if the session manager is ksmserver, // and if yes it will save in phase 1 instead of phase 2. if( isWM( c ) ) ++wmPhase1WaitingCount; } if (wmPhase1WaitingCount > 0) { foreach( KSMClient* c, clients ) { if( isWM( c ) ) SmsSaveYourself( c->connection(), saveType, true, SmInteractStyleAny, false ); } } else { // no WM, simply start them all foreach( KSMClient* c, clients ) SmsSaveYourself( c->connection(), saveType, true, SmInteractStyleAny, false ); } - qDebug() << "clients should be empty, " << clients.isEmpty(); + qCDebug(KSMSERVER) << "clients should be empty, " << clients.isEmpty(); if ( clients.isEmpty() ) completeShutdownOrCheckpoint(); dialogActive = false; } void KSMServer::pendingShutdownTimeout() { shutdown( pendingShutdown_confirm, pendingShutdown_sdtype, pendingShutdown_sdmode ); } void KSMServer::saveCurrentSession() { if ( state != Idle || dialogActive ) return; if ( currentSession().isEmpty() || currentSession() == QString::fromLocal8Bit( SESSION_PREVIOUS_LOGOUT ) ) sessionGroup = QStringLiteral("Session: ") + QString::fromLocal8Bit( SESSION_BY_USER ); state = Checkpoint; wmPhase1WaitingCount = 0; saveType = SmSaveLocal; saveSession = true; #ifndef NO_LEGACY_SESSION_MANAGEMENT performLegacySessionSave(); #endif foreach( KSMClient* c, clients ) { c->resetState(); if( isWM( c ) ) ++wmPhase1WaitingCount; } if (wmPhase1WaitingCount > 0) { foreach( KSMClient* c, clients ) { if( isWM( c ) ) SmsSaveYourself( c->connection(), saveType, false, SmInteractStyleNone, false ); } } else { foreach( KSMClient* c, clients ) SmsSaveYourself( c->connection(), saveType, false, SmInteractStyleNone, false ); } if ( clients.isEmpty() ) completeShutdownOrCheckpoint(); } void KSMServer::saveCurrentSessionAs( const QString &session ) { if ( state != Idle || dialogActive ) return; sessionGroup = QStringLiteral( "Session: " ) + session; saveCurrentSession(); } // callbacks void KSMServer::saveYourselfDone( KSMClient* client, bool success ) { if ( state == Idle ) { // State saving when it's not shutdown or checkpoint. Probably // a shutdown was canceled and the client is finished saving // only now. Discard the saved state in order to avoid // the saved data building up. QStringList discard = client->discardCommand(); if( !discard.isEmpty()) executeCommand( discard ); return; } if ( success ) { client->saveYourselfDone = true; completeShutdownOrCheckpoint(); } else { // fake success to make KDE's logout not block with broken // apps. A perfect ksmserver would display a warning box at // the very end. client->saveYourselfDone = true; completeShutdownOrCheckpoint(); } startProtection(); if( isWM( client ) && !client->wasPhase2 && wmPhase1WaitingCount > 0 ) { --wmPhase1WaitingCount; // WM finished its phase1, save the rest if( wmPhase1WaitingCount == 0 ) { foreach( KSMClient* c, clients ) if( !isWM( c )) SmsSaveYourself( c->connection(), saveType, saveType != SmSaveLocal, saveType != SmSaveLocal ? SmInteractStyleAny : SmInteractStyleNone, false ); } } } void KSMServer::interactRequest( KSMClient* client, int /*dialogType*/ ) { if ( state == Shutdown || state == ClosingSubSession ) client->pendingInteraction = true; else SmsInteract( client->connection() ); handlePendingInteractions(); } void KSMServer::interactDone( KSMClient* client, bool cancelShutdown_ ) { if ( client != clientInteracting ) return; // should not happen clientInteracting = 0; if ( cancelShutdown_ ) cancelShutdown( client ); else handlePendingInteractions(); } void KSMServer::phase2Request( KSMClient* client ) { client->waitForPhase2 = true; client->wasPhase2 = true; completeShutdownOrCheckpoint(); if( isWM( client ) && wmPhase1WaitingCount > 0 ) { --wmPhase1WaitingCount; // WM finished its phase1 and requests phase2, save the rest if( wmPhase1WaitingCount == 0 ) { foreach( KSMClient* c, clients ) if( !isWM( c )) SmsSaveYourself( c->connection(), saveType, saveType != SmSaveLocal, saveType != SmSaveLocal ? SmInteractStyleAny : SmInteractStyleNone, false ); } } } void KSMServer::handlePendingInteractions() { if ( clientInteracting ) return; foreach( KSMClient* c, clients ) { if ( c->pendingInteraction ) { clientInteracting = c; c->pendingInteraction = false; break; } } if ( clientInteracting ) { endProtection(); SmsInteract( clientInteracting->connection() ); } else { startProtection(); } } void KSMServer::cancelShutdown( KSMClient* c ) { clientInteracting = 0; qCDebug(KSMSERVER) << state; if ( state == ClosingSubSession ) { clientsToKill.clear(); clientsToSave.clear(); emit subSessionCloseCanceled(); } else { Solid::PowerManagement::stopSuppressingSleep(inhibitCookie); qCDebug(KSMSERVER) << "Client " << c->program() << " (" << c->clientId() << ") canceled shutdown."; // KNotification::event( QStringLiteral( "cancellogout" ), // i18n( "Logout canceled by '%1'", c->program()), // QPixmap() , 0l , KNotification::DefaultEvent ); foreach( KSMClient* c, clients ) { SmsShutdownCancelled( c->connection() ); if( c->saveYourselfDone ) { // Discard also saved state. QStringList discard = c->discardCommand(); if( !discard.isEmpty()) executeCommand( discard ); } } } state = Idle; } void KSMServer::startProtection() { KSharedConfig::Ptr config = KSharedConfig::openConfig(); config->reparseConfiguration(); // config may have changed in the KControl module KConfigGroup cg( config, "General" ); int timeout = cg.readEntry( "clientShutdownTimeoutSecs", 15 ) * 1000; protectionTimer.setSingleShot( true ); protectionTimer.start( timeout ); } void KSMServer::endProtection() { protectionTimer.stop(); } /* Internal protection slot, invoked when clients do not react during shutdown. */ void KSMServer::protectionTimeout() { if ( ( state != Shutdown && state != Checkpoint && state != ClosingSubSession ) || clientInteracting ) return; foreach( KSMClient* c, clients ) { if ( !c->saveYourselfDone && !c->waitForPhase2 ) { qCDebug(KSMSERVER) << "protectionTimeout: client " << c->program() << "(" << c->clientId() << ")"; c->saveYourselfDone = true; } } completeShutdownOrCheckpoint(); startProtection(); } void KSMServer::completeShutdownOrCheckpoint() { - qDebug() << "completeShutdownOrCheckpoint called"; + qCDebug(KSMSERVER) << "completeShutdownOrCheckpoint called"; if ( state != Shutdown && state != Checkpoint && state != ClosingSubSession ) return; QList pendingClients; if (state == ClosingSubSession) pendingClients = clientsToSave; else pendingClients = clients; foreach( KSMClient* c, pendingClients ) { if ( !c->saveYourselfDone && !c->waitForPhase2 ) return; // not done yet } // do phase 2 bool waitForPhase2 = false; foreach( KSMClient* c, pendingClients ) { if ( !c->saveYourselfDone && c->waitForPhase2 ) { c->waitForPhase2 = false; SmsSaveYourselfPhase2( c->connection() ); waitForPhase2 = true; } } if ( waitForPhase2 ) return; if ( saveSession ) storeSession(); else discardSession(); - qDebug() << "state is " << state; + qCDebug(KSMSERVER) << "state is " << state; if ( state == Shutdown ) { KNotification *n = KNotification::event(QStringLiteral("exitkde"), QString(), QPixmap(), 0l, KNotification::DefaultEvent); // Plasma says good bye connect(n, &KNotification::closed, this, &KSMServer::startKilling); state = WaitingForKNotify; // https://bugs.kde.org/show_bug.cgi?id=228005 // if sound is not working for some reason (e.g. no phonon // backends are installed) the closed() signal never happens // and logoutSoundFinished() never gets called. Add this timer to make // sure the shutdown procedure continues even if sound system is broken. QTimer::singleShot(5000, this, [=]{ if (state == WaitingForKNotify) { n->deleteLater(); startKilling(); } }); createLogoutEffectWidget(); } else if ( state == Checkpoint ) { foreach( KSMClient* c, clients ) { SmsSaveComplete( c->connection()); } state = Idle; } else { //ClosingSubSession startKillingSubSession(); } } void KSMServer::startKilling() { qCDebug(KSMSERVER) << "Starting killing clients"; if (state == Killing) { // we are already killing return; } // kill all clients state = Killing; foreach( KSMClient* c, clients ) { if( isWM( c )) // kill the WM as the last one in order to reduce flicker continue; - qCDebug(KSMSERVER) << "completeShutdown: client " << c->program() << "(" << c->clientId() << ")"; + qCDebug(KSMSERVER) << "startKilling: client " << c->program() << "(" << c->clientId() << ")"; SmsDie( c->connection() ); } qCDebug(KSMSERVER) << " We killed all clients. We have now clients.count()=" << clients.count() << endl; completeKilling(); QTimer::singleShot( 10000, this, &KSMServer::timeoutQuit ); } void KSMServer::completeKilling() { qCDebug(KSMSERVER) << "KSMServer::completeKilling clients.count()=" << clients.count() << endl; if( state == Killing ) { bool wait = false; foreach( KSMClient* c, clients ) { if( isWM( c )) continue; wait = true; // still waiting for clients to go away } if( wait ) return; killWM(); } } void KSMServer::killWM() { if( state != Killing ) return; delete logoutEffectWidget; qCDebug(KSMSERVER) << "Starting killing WM"; state = KillingWM; bool iswm = false; foreach( KSMClient* c, clients ) { if( isWM( c )) { iswm = true; qCDebug(KSMSERVER) << "killWM: client " << c->program() << "(" << c->clientId() << ")"; SmsDie( c->connection() ); } } if( iswm ) { completeKillingWM(); QTimer::singleShot( 5000, this, &KSMServer::timeoutWMQuit ); } else killingCompleted(); } void KSMServer::completeKillingWM() { qCDebug(KSMSERVER) << "KSMServer::completeKillingWM clients.count()=" << clients.count() << endl; if( state == KillingWM ) { if( clients.isEmpty()) killingCompleted(); } } // shutdown is fully complete void KSMServer::killingCompleted() { qApp->quit(); } void KSMServer::timeoutQuit() { foreach( KSMClient* c, clients ) { - qWarning() << "SmsDie timeout, client " << c->program() << "(" << c->clientId() << ")" ; + qCWarning(KSMSERVER) << "SmsDie timeout, client " << c->program() << "(" << c->clientId() << ")" ; } killWM(); } void KSMServer::timeoutWMQuit() { if( state == KillingWM ) { - qWarning() << "SmsDie WM timeout" ; + qCWarning(KSMSERVER) << "SmsDie WM timeout" ; } killingCompleted(); } void KSMServer::createLogoutEffectWidget() { // Ok, this is rather a hack. In order to fade the whole desktop when playing the logout // sound, killing applications and leaving KDE, create a dummy window that triggers // the logout fade effect again. logoutEffectWidget = new QWidget( NULL, Qt::X11BypassWindowManagerHint ); logoutEffectWidget->winId(); // workaround for Qt4.3 setWindowRole() assert logoutEffectWidget->setWindowRole( QStringLiteral( "logouteffect" ) ); // Qt doesn't set this on unmanaged windows //FIXME: or does it? XChangeProperty( QX11Info::display(), logoutEffectWidget->winId(), XInternAtom( QX11Info::display(), "WM_WINDOW_ROLE", False ), XA_STRING, 8, PropModeReplace, (unsigned char *)"logouteffect", strlen( "logouteffect" )); logoutEffectWidget->setGeometry( -100, -100, 1, 1 ); logoutEffectWidget->show(); } void KSMServer::saveSubSession(const QString &name, QStringList saveAndClose, QStringList saveOnly) { if( state != Idle ) { // performing startup qCDebug(KSMSERVER) << "not idle!" << state; return; } qCDebug(KSMSERVER) << name << saveAndClose << saveOnly; state = ClosingSubSession; saveType = SmSaveBoth; //both or local? what oes it mean? saveSession = true; sessionGroup = QStringLiteral( "SubSession: " ) + name; #ifndef NO_LEGACY_SESSION_MANAGEMENT //performLegacySessionSave(); FIXME #endif startProtection(); foreach( KSMClient* c, clients ) { if (saveAndClose.contains(QString::fromLocal8Bit(c->clientId()))) { c->resetState(); SmsSaveYourself( c->connection(), saveType, true, SmInteractStyleAny, false ); clientsToSave << c; clientsToKill << c; } else if (saveOnly.contains(QString::fromLocal8Bit(c->clientId()))) { c->resetState(); SmsSaveYourself( c->connection(), saveType, true, SmInteractStyleAny, false ); clientsToSave << c; } } completeShutdownOrCheckpoint(); } void KSMServer::startKillingSubSession() { qCDebug(KSMSERVER) << "Starting killing clients"; // kill all clients state = KillingSubSession; foreach( KSMClient* c, clientsToKill ) { qCDebug(KSMSERVER) << "completeShutdown: client " << c->program() << "(" << c->clientId() << ")"; SmsDie( c->connection() ); } qCDebug(KSMSERVER) << " We killed some clients. We have now clients.count()=" << clients.count() << endl; completeKillingSubSession(); QTimer::singleShot( 10000, this, &KSMServer::signalSubSessionClosed ); } void KSMServer::completeKillingSubSession() { qCDebug(KSMSERVER) << "KSMServer::completeKillingSubSession clients.count()=" << clients.count() << endl; if( state == KillingSubSession ) { bool wait = false; foreach( KSMClient* c, clientsToKill ) { if( isWM( c )) continue; wait = true; // still waiting for clients to go away } if( wait ) return; signalSubSessionClosed(); } } void KSMServer::signalSubSessionClosed() { if( state != KillingSubSession ) return; clientsToKill.clear(); clientsToSave.clear(); //TODO tell the subSession manager the close request was carried out //so that plasma can close its stuff state = Idle; qCDebug(KSMSERVER) << state; emit subSessionClosed(); } diff --git a/ksmserver/shutdowndlg.cpp b/ksmserver/shutdowndlg.cpp index 3fd9a1261..c393e3344 100644 --- a/ksmserver/shutdowndlg.cpp +++ b/ksmserver/shutdowndlg.cpp @@ -1,318 +1,318 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Copyright 2007 Urs Wolfer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include "shutdowndlg.h" -//include +#include "ksmserver_debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(Solid::PowerManagement::SleepState) KSMShutdownDlg::KSMShutdownDlg( QWindow* parent, bool maysd, bool choose, KWorkSpace::ShutdownType sdtype, const QString& theme, KWayland::Client::PlasmaShell *plasmaShell) : QQuickView(parent), m_result(false), m_theme(theme), m_waylandPlasmaShell(plasmaShell) // this is a WType_Popup on purpose. Do not change that! Not // having a popup here has severe side effects. { // window stuff setClearBeforeRendering(true); setColor(QColor(Qt::transparent)); setFlags(Qt::FramelessWindowHint | Qt::BypassWindowManagerHint); setResizeMode(QQuickView::SizeRootObjectToView); // Qt doesn't set this on unmanaged windows //FIXME: or does it? if (KWindowSystem::isPlatformX11()) { XChangeProperty( QX11Info::display(), winId(), XInternAtom( QX11Info::display(), "WM_WINDOW_ROLE", False ), XA_STRING, 8, PropModeReplace, (unsigned char *)"logoutdialog", strlen( "logoutdialog" )); XClassHint classHint; classHint.res_name = const_cast("ksmserver"); classHint.res_class = const_cast("ksmserver"); XSetClassHint(QX11Info::display(), winId(), &classHint); } //QQuickView *windowContainer = QQuickView::createWindowContainer(m_view, this); //windowContainer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); QQmlContext *context = rootContext(); context->setContextProperty(QStringLiteral("maysd"), maysd); context->setContextProperty(QStringLiteral("choose"), choose); context->setContextProperty(QStringLiteral("sdtype"), sdtype); QQmlPropertyMap *mapShutdownType = new QQmlPropertyMap(this); mapShutdownType->insert(QStringLiteral("ShutdownTypeDefault"), QVariant::fromValue(KWorkSpace::ShutdownTypeDefault)); mapShutdownType->insert(QStringLiteral("ShutdownTypeNone"), QVariant::fromValue(KWorkSpace::ShutdownTypeNone)); mapShutdownType->insert(QStringLiteral("ShutdownTypeReboot"), QVariant::fromValue(KWorkSpace::ShutdownTypeReboot)); mapShutdownType->insert(QStringLiteral("ShutdownTypeHalt"), QVariant::fromValue(KWorkSpace::ShutdownTypeHalt)); mapShutdownType->insert(QStringLiteral("ShutdownTypeLogout"), QVariant::fromValue(KWorkSpace::ShutdownTypeLogout)); context->setContextProperty(QStringLiteral("ShutdownType"), mapShutdownType); QQmlPropertyMap *mapSpdMethods = new QQmlPropertyMap(this); QSet spdMethods = Solid::PowerManagement::supportedSleepStates(); mapSpdMethods->insert(QStringLiteral("StandbyState"), QVariant::fromValue(spdMethods.contains(Solid::PowerManagement::StandbyState))); mapSpdMethods->insert(QStringLiteral("SuspendState"), QVariant::fromValue(spdMethods.contains(Solid::PowerManagement::SuspendState))); mapSpdMethods->insert(QStringLiteral("HibernateState"), QVariant::fromValue(spdMethods.contains(Solid::PowerManagement::HibernateState))); context->setContextProperty(QStringLiteral("spdMethods"), mapSpdMethods); QString bootManager = KConfig(QStringLiteral(KDE_CONFDIR "/kdm/kdmrc"), KConfig::SimpleConfig) .group("Shutdown") .readEntry("BootManager", "None"); context->setContextProperty(QStringLiteral("bootManager"), bootManager); QStringList options; int def, cur; if ( KDisplayManager().bootOptions( rebootOptions, def, cur ) ) { if ( cur > -1 ) { def = cur; } } QQmlPropertyMap *rebootOptionsMap = new QQmlPropertyMap(this); rebootOptionsMap->insert(QStringLiteral("options"), QVariant::fromValue(rebootOptions)); rebootOptionsMap->insert(QStringLiteral("default"), QVariant::fromValue(def)); context->setContextProperty(QStringLiteral("rebootOptions"), rebootOptionsMap); // engine stuff KDeclarative::KDeclarative kdeclarative; kdeclarative.setDeclarativeEngine(engine()); kdeclarative.initialize(); kdeclarative.setupBindings(); // windowContainer->installEventFilter(this); } void KSMShutdownDlg::init() { rootContext()->setContextProperty(QStringLiteral("screenGeometry"), screen()->geometry()); QString fileName; if(m_theme.isEmpty()) { KPackage::Package package = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/LookAndFeel")); KConfigGroup cg(KSharedConfig::openConfig(QStringLiteral("kdeglobals")), "KDE"); const QString packageName = cg.readEntry("LookAndFeelPackage", QString()); if (!packageName.isEmpty()) { package.setPath(packageName); } fileName = package.filePath("logoutmainscript"); } else fileName = m_theme; if (QFile::exists(fileName)) { //qCDebug(KSMSERVER) << "Using QML theme" << fileName; setSource(QUrl::fromLocalFile(fileName)); } else { - qWarning() << "Couldn't find a theme for the Shutdown dialog" << fileName; + qCWarning(KSMSERVER) << "Couldn't find a theme for the Shutdown dialog" << fileName; return; } if(!errors().isEmpty()) { - qWarning() << errors(); + qCWarning(KSMSERVER) << errors(); } connect(rootObject(), SIGNAL(logoutRequested()), SLOT(slotLogout())); connect(rootObject(), SIGNAL(haltRequested()), SLOT(slotHalt())); connect(rootObject(), SIGNAL(suspendRequested(int)), SLOT(slotSuspend(int)) ); connect(rootObject(), SIGNAL(rebootRequested()), SLOT(slotReboot())); connect(rootObject(), SIGNAL(rebootRequested2(int)), SLOT(slotReboot(int)) ); connect(rootObject(), SIGNAL(cancelRequested()), SLOT(reject())); connect(rootObject(), SIGNAL(lockScreenRequested()), SLOT(slotLockScreen())); connect(screen(), &QScreen::geometryChanged, this, [this] { setGeometry(screen()->geometry()); }); QQuickView::show(); requestActivate(); KWindowSystem::setState(winId(), NET::SkipTaskbar|NET::SkipPager); setKeyboardGrabEnabled(true); } void KSMShutdownDlg::resizeEvent(QResizeEvent *e) { QQuickView::resizeEvent( e ); if( KWindowSystem::compositingActive()) { //TODO: reenable window mask when we are without composite? // clearMask(); } else { // setMask(m_view->mask()); } } bool KSMShutdownDlg::event(QEvent *e) { if (e->type() == QEvent::PlatformSurface) { if (auto pe = dynamic_cast(e)) { switch (pe->surfaceEventType()) { case QPlatformSurfaceEvent::SurfaceCreated: setupWaylandIntegration(); KWindowEffects::enableBlurBehind(winId(), true); break; case QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed: delete m_shellSurface; m_shellSurface = nullptr; break; } } } return QQuickView::event(e); } void KSMShutdownDlg::setupWaylandIntegration() { if (m_shellSurface) { // already setup return; } using namespace KWayland::Client; if (!m_waylandPlasmaShell) { return; } Surface *s = Surface::fromWindow(this); if (!s) { return; } m_shellSurface = m_waylandPlasmaShell->createSurface(s, this); // TODO: set a proper window type to indicate to KWin that this is the logout dialog // maybe we need a dedicated type for it? m_shellSurface->setPosition(geometry().topLeft()); } void KSMShutdownDlg::slotLogout() { m_shutdownType = KWorkSpace::ShutdownTypeNone; accept(); } void KSMShutdownDlg::slotReboot() { // no boot option selected -> current m_bootOption.clear(); m_shutdownType = KWorkSpace::ShutdownTypeReboot; accept(); } void KSMShutdownDlg::slotReboot(int opt) { if (int(rebootOptions.size()) > opt) m_bootOption = rebootOptions[opt]; m_shutdownType = KWorkSpace::ShutdownTypeReboot; accept(); } void KSMShutdownDlg::slotLockScreen() { m_bootOption.clear(); QDBusMessage call = QDBusMessage::createMethodCall(QStringLiteral("org.kde.screensaver"), QStringLiteral("/ScreenSaver"), QStringLiteral("org.freedesktop.ScreenSaver"), QStringLiteral("Lock")); QDBusConnection::sessionBus().asyncCall(call); reject(); } void KSMShutdownDlg::slotHalt() { m_bootOption.clear(); m_shutdownType = KWorkSpace::ShutdownTypeHalt; accept(); } void KSMShutdownDlg::slotSuspend(int spdMethod) { m_bootOption.clear(); switch (spdMethod) { case Solid::PowerManagement::StandbyState: case Solid::PowerManagement::SuspendState: Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState, 0, 0); break; case Solid::PowerManagement::HibernateState: Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState, 0, 0); break; } reject(); } void KSMShutdownDlg::accept() { emit accepted(); } void KSMShutdownDlg::reject() { emit rejected(); } diff --git a/ksmserver/startup.cpp b/ksmserver/startup.cpp index 613676370..5031516d7 100644 --- a/ksmserver/startup.cpp +++ b/ksmserver/startup.cpp @@ -1,690 +1,690 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Copyright 2005 Lubos Lunak relatively small extensions by Oswald Buddenhagen some code taken from the dcopserver (part of the KDE libraries), which is Copyright 1999 Matthias Ettrich Copyright 1999 Preston Brown Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #include #include #include #include // HAVE_LIMITS_H #include #include #include #include #include #include #ifdef HAVE_SYS_TIME_H #include #endif #include #include #include #include #include #include #include #include #include #ifdef HAVE_LIMITS_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include "global.h" #include "server.h" #include "client.h" #include //#include "kdesktop_interface.h" #include #include #include "kcminit_interface.h" //#define KSMSERVER_STARTUP_DEBUG1 #ifdef KSMSERVER_STARTUP_DEBUG1 static QTime t; #endif // Put the notification in its own thread as it can happen that // PulseAudio will start initializing with this, so let's not // block the main thread with waiting for PulseAudio to start class NotificationThread : public QThread { Q_OBJECT void run() Q_DECL_OVERRIDE { // We cannot parent to the thread itself so let's create // a QObject on the stack and parent everythign to it QObject parent; KNotifyConfig notifyConfig(QStringLiteral("plasma_workspace"), QList< QPair >(), QStringLiteral("startkde")); const QString action = notifyConfig.readEntry(QStringLiteral("Action")); if (action.isEmpty() || !action.split('|').contains(QStringLiteral("Sound"))) { // no startup sound configured return; } Phonon::AudioOutput *m_audioOutput = new Phonon::AudioOutput(Phonon::NotificationCategory, &parent); QString soundFilename = notifyConfig.readEntry(QStringLiteral("Sound")); if (soundFilename.isEmpty()) { - qWarning() << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification"; + qCWarning(KSMSERVER) << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification"; return; } QUrl soundURL = QUrl(soundFilename); // this CTOR accepts both absolute paths (/usr/share/sounds/blabla.ogg and blabla.ogg) w/o screwing the scheme if (soundURL.isRelative() && !soundURL.toString().startsWith('/')) { // QUrl considers url.scheme.isEmpty() == url.isRelative() soundURL = QUrl::fromLocalFile(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("sounds/") + soundFilename)); if (soundURL.isEmpty()) { - qWarning() << "Audio notification requested, but sound file from notifyrc file was not found, aborting audio notification"; + qCWarning(KSMSERVER) << "Audio notification requested, but sound file from notifyrc file was not found, aborting audio notification"; return; } } Phonon::MediaObject *m = new Phonon::MediaObject(&parent); connect(m, &Phonon::MediaObject::finished, this, &NotificationThread::quit); Phonon::createPath(m, m_audioOutput); m->setCurrentSource(soundURL); m->play(); exec(); } }; /*! Restores the previous session. Ensures the window manager is running (if specified). */ void KSMServer::restoreSession( const QString &sessionName ) { if( state != Idle ) return; #ifdef KSMSERVER_STARTUP_DEBUG1 t.start(); #endif state = LaunchingWM; qCDebug(KSMSERVER) << "KSMServer::restoreSession " << sessionName; KSharedConfig::Ptr config = KSharedConfig::openConfig(); sessionGroup = QStringLiteral("Session: ") + sessionName; KConfigGroup configSessionGroup( config, sessionGroup); int count = configSessionGroup.readEntry( "count", 0 ); appsToStart = count; upAndRunning( QStringLiteral( "ksmserver" ) ); // find all commands to launch the wm in the session QList wmStartCommands; if ( !wm.isEmpty() ) { for ( int i = 1; i <= count; i++ ) { QString n = QString::number(i); if ( wm == configSessionGroup.readEntry( QStringLiteral("program")+n, QString() ) ) { wmStartCommands << configSessionGroup.readEntry( QStringLiteral("restartCommand")+n, QStringList() ); } } } if( wmStartCommands.isEmpty()) // otherwise use the configured default wmStartCommands << wmCommands; launchWM( wmStartCommands ); } /*! Starts the default session. Currently, that's the window manager only (if specified). */ void KSMServer::startDefaultSession() { if( state != Idle ) return; state = LaunchingWM; #ifdef KSMSERVER_STARTUP_DEBUG1 t.start(); #endif sessionGroup = QString(); upAndRunning( QStringLiteral( "ksmserver" ) ); launchWM( QList< QStringList >() << wmCommands ); } void KSMServer::launchWM( const QList< QStringList >& wmStartCommands ) { assert( state == LaunchingWM ); if (!(qEnvironmentVariableIsSet("WAYLAND_DISPLAY") || qEnvironmentVariableIsSet("WAYLAND_SOCKET"))) { // when we have a window manager, we start it first and give // it some time before launching other processes. Results in a // visually more appealing startup. wmProcess = startApplication( wmStartCommands[ 0 ], QString(), QString(), true ); connect( wmProcess, SIGNAL(error(QProcess::ProcessError)), SLOT(wmProcessChange())); connect( wmProcess, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(wmProcessChange())); } autoStart0(); } void KSMServer::clientSetProgram( KSMClient* client ) { if( client->program() == wm ) autoStart0(); } void KSMServer::wmProcessChange() { if( state != LaunchingWM ) { // don't care about the process when not in the wm-launching state anymore wmProcess = NULL; return; } if( wmProcess->state() == QProcess::NotRunning ) { // wm failed to launch for some reason, go with kwin instead - qWarning() << "Window manager" << wm << "failed to launch"; + qCWarning(KSMSERVER) << "Window manager" << wm << "failed to launch"; if( wm == QStringLiteral( KWIN_BIN ) ) return; // uhoh, kwin itself failed qCDebug(KSMSERVER) << "Launching KWin"; wm = QStringLiteral( KWIN_BIN ); wmCommands = ( QStringList() << QStringLiteral( KWIN_BIN ) ); // launch it launchWM( QList< QStringList >() << wmCommands ); return; } } void KSMServer::autoStart0() { if( state != LaunchingWM ) return; if( !checkStartupSuspend()) return; state = AutoStart0; #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER) << t.elapsed(); #endif autoStart(0); } void KSMServer::autoStart0Done() { if( state != AutoStart0 ) return; if( !checkStartupSuspend()) return; qCDebug(KSMSERVER) << "Autostart 0 done"; #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER) << t.elapsed(); #endif state = KcmInitPhase1; kcminitSignals = new QDBusInterface( QStringLiteral( "org.kde.kcminit"), QStringLiteral( "/kcminit" ), QStringLiteral( "org.kde.KCMInit" ), QDBusConnection::sessionBus(), this ); if( !kcminitSignals->isValid()) { - qWarning() << "kcminit not running? If we are running with mobile profile or in another platform other than X11 this is normal."; + qCWarning(KSMSERVER) << "kcminit not running? If we are running with mobile profile or in another platform other than X11 this is normal."; delete kcminitSignals; kcminitSignals = 0; QTimer::singleShot(0, this, &KSMServer::kcmPhase1Done); return; } connect( kcminitSignals, SIGNAL(phase1Done()), SLOT(kcmPhase1Done())); QTimer::singleShot( 10000, this, &KSMServer::kcmPhase1Timeout); // protection org::kde::KCMInit kcminit(QStringLiteral("org.kde.kcminit"), QStringLiteral("/kcminit"), QDBusConnection::sessionBus()); kcminit.runPhase1(); } void KSMServer::kcmPhase1Done() { if( state != KcmInitPhase1 ) return; qCDebug(KSMSERVER) << "Kcminit phase 1 done"; if (kcminitSignals) { disconnect( kcminitSignals, SIGNAL(phase1Done()), this, SLOT(kcmPhase1Done())); } autoStart1(); } void KSMServer::kcmPhase1Timeout() { if( state != KcmInitPhase1 ) return; qCDebug(KSMSERVER) << "Kcminit phase 1 timeout"; kcmPhase1Done(); } void KSMServer::autoStart1() { if( state != KcmInitPhase1 ) return; state = AutoStart1; #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER)<< t.elapsed(); #endif autoStart(1); } void KSMServer::autoStart1Done() { if( state != AutoStart1 ) return; if( !checkStartupSuspend()) return; qCDebug(KSMSERVER) << "Autostart 1 done"; setupShortcuts(); // done only here, because it needs kglobalaccel :-/ lastAppStarted = 0; lastIdStarted.clear(); state = Restoring; #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER)<< t.elapsed(); #endif if( defaultSession()) { autoStart2(); return; } tryRestoreNext(); } void KSMServer::clientRegistered( const char* previousId ) { if ( previousId && lastIdStarted == QString::fromLocal8Bit( previousId ) ) tryRestoreNext(); } void KSMServer::tryRestoreNext() { if( state != Restoring && state != RestoringSubSession ) return; restoreTimer.stop(); startupSuspendTimeoutTimer.stop(); KConfigGroup config(KSharedConfig::openConfig(), sessionGroup ); while ( lastAppStarted < appsToStart ) { lastAppStarted++; QString n = QString::number(lastAppStarted); QString clientId = config.readEntry( QStringLiteral("clientId")+n, QString() ); bool alreadyStarted = false; foreach ( KSMClient *c, clients ) { if ( QString::fromLocal8Bit( c->clientId() ) == clientId ) { alreadyStarted = true; break; } } if ( alreadyStarted ) continue; QStringList restartCommand = config.readEntry( QStringLiteral("restartCommand")+n, QStringList() ); if ( restartCommand.isEmpty() || (config.readEntry( QStringLiteral("restartStyleHint")+n, 0 ) == SmRestartNever)) { continue; } if ( wm == config.readEntry( QStringLiteral("program")+n, QString() ) ) continue; // wm already started if( config.readEntry( QStringLiteral( "wasWm" )+n, false )) continue; // it was wm before, but not now, don't run it (some have --replace in command :( ) startApplication( restartCommand, config.readEntry( QStringLiteral("clientMachine")+n, QString() ), config.readEntry( QStringLiteral("userId")+n, QString() )); lastIdStarted = clientId; if ( !lastIdStarted.isEmpty() ) { restoreTimer.setSingleShot( true ); restoreTimer.start( 2000 ); return; // we get called again from the clientRegistered handler } } //all done appsToStart = 0; lastIdStarted.clear(); if (state == Restoring) autoStart2(); else { //subsession state = Idle; emit subSessionOpened(); } } void KSMServer::autoStart2() { if( state != Restoring ) return; if( !checkStartupSuspend()) return; state = FinishingStartup; #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER)<< t.elapsed(); #endif waitAutoStart2 = true; waitKcmInit2 = true; autoStart(2); QTimer::singleShot( 10000, this, &KSMServer::autoStart2Done); //In case klauncher never returns QDBusInterface kded( QStringLiteral( "org.kde.kded5" ), QStringLiteral( "/kded" ), QStringLiteral( "org.kde.kded5" ) ); kded.call( QStringLiteral( "loadSecondPhase" ) ); #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER)<< "kded" << t.elapsed(); #endif runUserAutostart(); if (kcminitSignals) { connect( kcminitSignals, SIGNAL(phase2Done()), SLOT(kcmPhase2Done())); QTimer::singleShot( 10000, this, &KSMServer::kcmPhase2Timeout); // protection org::kde::KCMInit kcminit(QStringLiteral("org.kde.kcminit"), QStringLiteral("/kcminit"), QDBusConnection::sessionBus()); kcminit.runPhase2(); } else { QTimer::singleShot(0, this, &KSMServer::kcmPhase2Done); } if( !defaultSession()) restoreLegacySession(KSharedConfig::openConfig().data()); qCDebug(KSMSERVER) << "Starting notification thread"; NotificationThread *loginSound = new NotificationThread(); // Delete the thread when finished connect(loginSound, &NotificationThread::finished, loginSound, &NotificationThread::deleteLater); loginSound->start(); } void KSMServer::runUserAutostart() { // Now let's execute the scripts in the KDE-specific autostart-scripts folder. const QString autostartFolder = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QDir::separator() + QStringLiteral("autostart-scripts"); QDir dir(autostartFolder); if (!dir.exists()) { // Create dir in all cases, so that users can find it :-) dir.mkpath(QStringLiteral(".")); if (!migrateKDE4Autostart(autostartFolder)) { return; } } const QStringList entries = dir.entryList(QDir::Files); foreach (const QString &file, entries) { // Don't execute backup files if (!file.endsWith(QLatin1Char('~')) && !file.endsWith(QStringLiteral(".bak")) && (file[0] != QLatin1Char('%') || !file.endsWith(QLatin1Char('%'))) && (file[0] != QLatin1Char('#') || !file.endsWith(QLatin1Char('#')))) { const QString fullPath = dir.absolutePath() + QLatin1Char('/') + file; qCInfo(KSMSERVER) << "Starting autostart script " << fullPath; auto p = new QProcess; //deleted in onFinished lambda p->start(fullPath); connect(p, static_cast(&QProcess::finished), [p](int exitCode) { qCInfo(KSMSERVER) << "autostart script" << p->program() << "finished with exit code " << exitCode; p->deleteLater(); }); } } } bool KSMServer::migrateKDE4Autostart(const QString &autostartFolder) { // Migrate user autostart from kde4 Kdelibs4Migration migration; if (!migration.kdeHomeFound()) { return false; } // KDEHOME/Autostart was the default value for KGlobalSettings::autostart() QString oldAutostart = migration.kdeHome() + QStringLiteral("/Autostart"); // That path could be customized in kdeglobals const QString oldKdeGlobals = migration.locateLocal("config", QStringLiteral("kdeglobals")); if (!oldKdeGlobals.isEmpty()) { oldAutostart = KConfig(oldKdeGlobals).group("Paths").readEntry("Autostart", oldAutostart); } const QDir oldFolder(oldAutostart); qCDebug(KSMSERVER) << "Copying autostart files from" << oldFolder.path(); const QStringList entries = oldFolder.entryList(QDir::Files); foreach (const QString &file, entries) { const QString src = oldFolder.absolutePath() + QLatin1Char('/') + file; const QString dest = autostartFolder + QLatin1Char('/') + file; QFileInfo info(src); bool success; if (info.isSymLink()) { // This will only work with absolute symlink targets success = QFile::link(info.symLinkTarget(), dest); } else { success = QFile::copy(src, dest); } if (!success) { qCWarning(KSMSERVER) << "Error copying" << src << "to" << dest; } } return true; } void KSMServer::autoStart2Done() { if( state != FinishingStartup ) return; qCDebug(KSMSERVER) << "Autostart 2 done"; waitAutoStart2 = false; finishStartup(); } void KSMServer::kcmPhase2Done() { if( state != FinishingStartup ) return; qCDebug(KSMSERVER) << "Kcminit phase 2 done"; if (kcminitSignals) { disconnect( kcminitSignals, SIGNAL(phase2Done()), this, SLOT(kcmPhase2Done())); delete kcminitSignals; kcminitSignals = 0; } waitKcmInit2 = false; finishStartup(); } void KSMServer::kcmPhase2Timeout() { if( !waitKcmInit2 ) return; qCDebug(KSMSERVER) << "Kcminit phase 2 timeout"; kcmPhase2Done(); } void KSMServer::finishStartup() { if( state != FinishingStartup ) return; if( waitAutoStart2 || waitKcmInit2 ) return; upAndRunning( QStringLiteral( "ready" ) ); #ifdef KSMSERVER_STARTUP_DEBUG1 qCDebug(KSMSERVER)<< t.elapsed(); #endif state = Idle; setupXIOErrorHandler(); // From now on handle X errors as normal shutdown. } bool KSMServer::checkStartupSuspend() { if( startupSuspendCount.isEmpty()) return true; // wait for the phase to finish if( !startupSuspendTimeoutTimer.isActive()) { startupSuspendTimeoutTimer.setSingleShot( true ); startupSuspendTimeoutTimer.start( 10000 ); } return false; } void KSMServer::suspendStartup( const QString &app ) { if( !startupSuspendCount.contains( app )) startupSuspendCount[ app ] = 0; ++startupSuspendCount[ app ]; } void KSMServer::resumeStartup( const QString &app ) { if( !startupSuspendCount.contains( app )) return; if( --startupSuspendCount[ app ] == 0 ) { startupSuspendCount.remove( app ); if( startupSuspendCount.isEmpty() && startupSuspendTimeoutTimer.isActive()) { startupSuspendTimeoutTimer.stop(); resumeStartupInternal(); } } } void KSMServer::startupSuspendTimeout() { qCDebug(KSMSERVER) << "Startup suspend timeout:" << state; resumeStartupInternal(); } void KSMServer::resumeStartupInternal() { startupSuspendCount.clear(); switch( state ) { case LaunchingWM: autoStart0(); break; case AutoStart0: autoStart0Done(); break; case AutoStart1: autoStart1Done(); break; case Restoring: autoStart2(); break; default: - qWarning() << "Unknown resume startup state" ; + qCWarning(KSMSERVER) << "Unknown resume startup state" ; break; } } void KSMServer::upAndRunning( const QString& msg ) { QDBusMessage ksplashProgressMessage = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KSplash"), QStringLiteral("/KSplash"), QStringLiteral("org.kde.KSplash"), QStringLiteral("setStage")); ksplashProgressMessage.setArguments(QList() << msg); QDBusConnection::sessionBus().asyncCall(ksplashProgressMessage); } void KSMServer::restoreSubSession( const QString& name ) { sessionGroup = QStringLiteral( "SubSession: " ) + name; KConfigGroup configSessionGroup( KSharedConfig::openConfig(), sessionGroup); int count = configSessionGroup.readEntry( "count", 0 ); appsToStart = count; lastAppStarted = 0; lastIdStarted.clear(); state = RestoringSubSession; tryRestoreNext(); } void KSMServer::autoStart(int phase) { if (m_autoStart.phase() >= phase) { return; } m_autoStart.setPhase(phase); if (phase == 0) { m_autoStart.loadAutoStartList(); } QTimer::singleShot(0, this, &KSMServer::slotAutoStart); } void KSMServer::slotAutoStart() { do { QString serviceName = m_autoStart.startService(); if (serviceName.isEmpty()) { // Done if (!m_autoStart.phaseDone()) { m_autoStart.setPhaseDone(); switch (m_autoStart.phase()) { case 0: autoStart0Done(); break; case 1: autoStart1Done(); break; case 2: autoStart2Done(); break; } } return; } KService service(serviceName); qCInfo(KSMSERVER) << "Starting autostart service " << serviceName; auto p = new QProcess(this); p->start(service.exec()); connect(p, static_cast(&QProcess::finished), [p](int exitCode) { qCInfo(KSMSERVER) << "autostart service" << p->program() << "finished with exit code " << exitCode; p->deleteLater(); }); } while (true); // Loop till we find a service that we can start. } #include "startup.moc" diff --git a/ksmserver/switchuserdialog.cpp b/ksmserver/switchuserdialog.cpp index 26d67102c..f4f643642 100644 --- a/ksmserver/switchuserdialog.cpp +++ b/ksmserver/switchuserdialog.cpp @@ -1,118 +1,119 @@ /* * Copyright 2015 Kai Uwe Broulik * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "switchuserdialog.h" #include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include KSMSwitchUserDialog::KSMSwitchUserDialog(KDisplayManager *dm, QWindow *parent) : QQuickView(parent) , m_displayManager(dm) { setClearBeforeRendering(true); setColor(QColor(Qt::transparent)); setFlags(Qt::FramelessWindowHint | Qt::BypassWindowManagerHint); QPoint globalPosition(QCursor::pos()); foreach (QScreen *s, QGuiApplication::screens()) { if (s->geometry().contains(globalPosition)) { setScreen(s); break; } } // Qt doesn't set this on unmanaged windows //FIXME: or does it? XChangeProperty( QX11Info::display(), winId(), XInternAtom( QX11Info::display(), "WM_WINDOW_ROLE", False ), XA_STRING, 8, PropModeReplace, (unsigned char *)"logoutdialog", strlen( "logoutdialog" )); rootContext()->setContextProperty(QStringLiteral("screenGeometry"), screen()->geometry()); setModality(Qt::ApplicationModal); KDeclarative::KDeclarative kdeclarative; kdeclarative.setDeclarativeEngine(engine()); //kdeclarative.initialize(); kdeclarative.setupBindings(); KPackage::Package package = KPackage::PackageLoader::self()->loadPackage("Plasma/LookAndFeel"); KConfigGroup cg(KSharedConfig::openConfig("kdeglobals"), "KDE"); const QString packageName = cg.readEntry("LookAndFeelPackage", QString()); if (!packageName.isEmpty()) { package.setPath(packageName); } const QString fileName = package.filePath("userswitchermainscript"); if (QFile::exists(fileName)) { setSource(QUrl::fromLocalFile(fileName)); } else { - qWarning() << "Couldn't find a theme for the Switch User dialog" << fileName; + qCWarning(KSMSERVER) << "Couldn't find a theme for the Switch User dialog" << fileName; return; } setPosition(screen()->virtualGeometry().center().x() - width() / 2, screen()->virtualGeometry().center().y() - height() / 2); if (!errors().isEmpty()) { - qWarning() << errors(); + qCWarning(KSMSERVER) << errors(); } connect(rootObject(), SIGNAL(dismissed()), this, SIGNAL(dismissed())); show(); requestActivate(); KWindowSystem::setState(winId(), NET::SkipTaskbar | NET::SkipPager); } void KSMSwitchUserDialog::exec() { QEventLoop loop; connect(this, &KSMSwitchUserDialog::dismissed, &loop, &QEventLoop::quit); loop.exec(); }