diff --git a/ksmserver/startup.cpp b/ksmserver/startup.cpp index 0bbfec86c..49080df1c 100644 --- a/ksmserver/startup.cpp +++ b/ksmserver/startup.cpp @@ -1,409 +1,391 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2000 Matthias Ettrich Copyright 2005 Lubos Lunak Copyright 2018 David Edmundson 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 "startup.h" #include "server.h" #include #include // HAVE_LIMITS_H #include #include #include "kcminit_interface.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class Phase: public KCompositeJob { Q_OBJECT public: Phase(QObject *parent): KCompositeJob(parent) {} bool addSubjob(KJob *job) override { bool rc = KCompositeJob::addSubjob(job); job->start(); return rc; } void slotResult(KJob *job) override { KCompositeJob::slotResult(job); if (!hasSubjobs()) { emitResult(); } } }; class StartupPhase0: public Phase { Q_OBJECT public: StartupPhase0(QObject *parent) : Phase(parent) {} void start() override { qCDebug(KSMSERVER) << "Phase 0"; addSubjob(new AutoStartAppsJob(0)); addSubjob(new KCMInitJob(1)); } }; class StartupPhase1: public Phase { Q_OBJECT public: StartupPhase1(QObject *parent) : Phase(parent) {} void start() override { qCDebug(KSMSERVER) << "Phase 1"; addSubjob(new AutoStartAppsJob(1)); } }; class StartupPhase2: public Phase { Q_OBJECT public: StartupPhase2(QObject *parent) : Phase(parent) {} void runUserAutostart(); bool migrateKDE4Autostart(const QString &folder); void start() override { qCDebug(KSMSERVER) << "Phase 2"; addSubjob(new AutoStartAppsJob(2)); addSubjob(new KDEDInitJob()); addSubjob(new KCMInitJob(2)); runUserAutostart(); } }; // 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() 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(QLatin1Char('|')).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()) { qCWarning(KSMSERVER) << "Audio notification requested, but no sound file provided in notifyrc file, aborting audio notification"; return; } QUrl soundURL; const auto dataLocations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); for (const QString &dataLocation: dataLocations) { soundURL = QUrl::fromUserInput(soundFilename, dataLocation + QStringLiteral("/sounds"), QUrl::AssumeLocalFile); if (soundURL.isLocalFile() && QFile::exists(soundURL.toLocalFile())) { break; } else if (!soundURL.isLocalFile() && soundURL.isValid()) { break; } soundURL.clear(); } if (soundURL.isEmpty()) { 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(); } }; Startup::Startup(KSMServer *parent): QObject(parent), ksmserver(parent) { auto phase0 = new StartupPhase0(this); auto phase1 = new StartupPhase1(this); auto phase2 = new StartupPhase2(this); auto restoreSession = new RestoreSessionJob(ksmserver); connect(ksmserver, &KSMServer::windowManagerLoaded, phase0, &KJob::start); connect(phase0, &KJob::finished, phase1, &KJob::start); connect(phase1, &KJob::finished, this, [=]() { ksmserver->setupShortcuts(); // done only here, because it needs kglobalaccel :-/ }); connect(phase1, &KJob::finished, restoreSession, &KJob::start); connect(restoreSession, &KJob::finished, phase2, &KJob::start); connect(phase1, &KJob::finished, this, []() { NotificationThread *loginSound = new NotificationThread(); connect(loginSound, &NotificationThread::finished, loginSound, &NotificationThread::deleteLater); loginSound->start();}); connect(phase2, &KJob::finished, this, &Startup::finishStartup); } void Startup::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 Startup::finishStartup() { qCDebug(KSMSERVER) << "Finished"; ksmserver->state = KSMServer::Idle; ksmserver->setupXIOErrorHandler(); upAndRunning(QStringLiteral("ready")); } KCMInitJob::KCMInitJob(int phase) :m_phase(phase) { } void KCMInitJob::start() { - //FIXME - replace all this with just a DBus call with a timeout and make kcminit delay the reply till it's done - - auto kcminitSignals = new QDBusInterface( QStringLiteral( "org.kde.kcminit"), - QStringLiteral( "/kcminit" ), - QStringLiteral( "org.kde.KCMInit" ), - QDBusConnection::sessionBus(), this ); - if( !kcminitSignals->isValid()) { - qCWarning(KSMSERVER) << "kcminit not running? If we are running with mobile profile or in another platform other than X11 this is normal."; - QTimer::singleShot(0, this, &KCMInitJob::done); - return; - } - if (m_phase == 1) { - connect( kcminitSignals, SIGNAL(phase1Done()), this, SLOT(done())); - } else { - connect( kcminitSignals, SIGNAL(phase2Done()), this, SLOT(done())); - } - QTimer::singleShot( 10000, this, &KCMInitJob::done); // protection - org::kde::KCMInit kcminit(QStringLiteral("org.kde.kcminit"), QStringLiteral("/kcminit"), QDBusConnection::sessionBus()); + kcminit.setTimeout(10 * 1000); + QDBusPendingReply pending; if (m_phase == 1) { - kcminit.runPhase1(); + pending = kcminit.runPhase1(); } else { - kcminit.runPhase2(); + pending = kcminit.runPhase2(); } -} - -void KCMInitJob::done() -{ - emitResult(); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending, this); + connect(watcher, &QDBusPendingCallWatcher::finished, this, [this]() {emitResult();}); + connect(watcher, &QDBusPendingCallWatcher::finished, watcher, &QObject::deleteLater); } KDEDInitJob::KDEDInitJob() { } void KDEDInitJob::start() { qCDebug(KSMSERVER()); QDBusInterface kded( QStringLiteral( "org.kde.kded5" ), QStringLiteral( "/kded" ), QStringLiteral( "org.kde.kded5" ) ); auto pending = kded.asyncCall( QStringLiteral( "loadSecondPhase" ) ); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [this]() {emitResult();}); connect(watcher, &QDBusPendingCallWatcher::finished, watcher, &QObject::deleteLater); } RestoreSessionJob::RestoreSessionJob(KSMServer *server): KJob(), m_ksmserver(server) {} void RestoreSessionJob::start() { if (m_ksmserver->defaultSession()) { QTimer::singleShot(0, this, [this]() {emitResult();}); return; } m_ksmserver->lastAppStarted = 0; m_ksmserver->lastIdStarted.clear(); m_ksmserver->state = KSMServer::Restoring; connect(m_ksmserver, &KSMServer::sessionRestored, this, [this]() {emitResult();}); m_ksmserver->tryRestoreNext(); } void StartupPhase2::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 KProcess; //deleted in onFinished lambda p->setProgram(fullPath); p->start(); connect(p, static_cast(&QProcess::finished), [p](int exitCode) { qCInfo(KSMSERVER) << "autostart script" << p->program() << "finished with exit code " << exitCode; p->deleteLater(); }); } } } bool StartupPhase2::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; } AutoStartAppsJob::AutoStartAppsJob(int phase) { m_autoStart.loadAutoStartList(); //FIXME, share this between jobs m_autoStart.setPhase(phase); } void AutoStartAppsJob::start() { qCDebug(KSMSERVER()); QTimer::singleShot(0, this, [=]() { do { QString serviceName = m_autoStart.startService(); if (serviceName.isEmpty()) { // Done if (!m_autoStart.phaseDone()) { m_autoStart.setPhaseDone(); } emitResult(); return; } KService service(serviceName); auto arguments = KIO::DesktopExecParser(service, QList()).resultingArguments(); if (arguments.isEmpty()) { qCWarning(KSMSERVER) << "failed to parse" << serviceName << "for autostart"; continue; } qCInfo(KSMSERVER) << "Starting autostart service " << serviceName << arguments; auto program = arguments.takeFirst(); if (!QProcess::startDetached(program, arguments)) qCWarning(KSMSERVER) << "could not start" << serviceName << ":" << program << arguments; } while (true); }); } #include "startup.moc" diff --git a/ksmserver/startup.h b/ksmserver/startup.h index bbda63291..70849417b 100644 --- a/ksmserver/startup.h +++ b/ksmserver/startup.h @@ -1,89 +1,87 @@ /***************************************************************** ksmserver - the KDE session management server Copyright 2018 David Edmundson 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. ******************************************************************/ #pragma once #include #include #include "autostart.h" class KProcess; class KSMServer; class KCompositeJob; class Startup : public QObject { Q_OBJECT public: Startup(KSMServer *parent); void upAndRunning( const QString& msg ); void finishStartup(); private: void autoStart(int phase); private: KSMServer *ksmserver = nullptr; }; class KCMInitJob: public KJob { Q_OBJECT public: KCMInitJob(int phase); void start() override; -public Q_SLOTS: - void done(); private: int m_phase; }; class KDEDInitJob: public KJob { Q_OBJECT public: KDEDInitJob(); void start() override; }; class AutoStartAppsJob: public KJob { Q_OBJECT public: AutoStartAppsJob(int phase); void start() override; private: AutoStart m_autoStart; }; class RestoreSessionJob: public KJob { Q_OBJECT public: RestoreSessionJob(KSMServer *ksmserver); void start() override; private: KSMServer *m_ksmserver; }; diff --git a/startkde/kcminit/main.cpp b/startkde/kcminit/main.cpp index 1349d773f..954d44bd5 100644 --- a/startkde/kcminit/main.cpp +++ b/startkde/kcminit/main.cpp @@ -1,244 +1,242 @@ /* Copyright (c) 1999 Matthias Hoelzer-Kluepfel 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) any later version. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include "main.h" #include "klauncher_iface.h" #ifdef XCB_FOUND #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include static int ready[ 2 ]; static bool startup = false; static void sendReady() { if( ready[ 1 ] == -1 ) return; char c = 0; write( ready[ 1 ], &c, 1 ); close( ready[ 1 ] ); ready[ 1 ] = -1; } static void waitForReady() { char c = 1; close( ready[ 1 ] ); read( ready[ 0 ], &c, 1 ); close( ready[ 0 ] ); } bool KCMInit::runModule(const QString &libName, KService::Ptr service) { QString KCMINIT_PREFIX=QStringLiteral("kcminit_"); const QVariant tmp = service->property(QStringLiteral("X-KDE-Init-Symbol"), QVariant::String); QString kcminit; if( tmp.isValid() ) { kcminit = tmp.toString(); if( !kcminit.startsWith( KCMINIT_PREFIX ) ) kcminit = KCMINIT_PREFIX + kcminit; } else kcminit = KCMINIT_PREFIX + libName; // get the kcminit_ function QFunctionPointer init = QLibrary::resolve(KPluginLoader::findPlugin(libName), kcminit.toUtf8().constData()); if (init) { // initialize the module qDebug() << "Initializing " << libName << ": " << kcminit; init(); return true; } else { qWarning() << "Module" << libName << "was not found or does not actually have a kcminit function"; } return false; } void KCMInit::runModules( int phase ) { QString KCMINIT_PREFIX=QStringLiteral("kcminit_"); foreach (const KService::Ptr & service, list) { const QVariant tmp = service->property(QStringLiteral("X-KDE-Init-Library"), QVariant::String); QString library; if( tmp.isValid() ) { library = tmp.toString(); if( !library.startsWith( KCMINIT_PREFIX ) ) library = KCMINIT_PREFIX + library; } else { library = service->library(); } if (library.isEmpty()) { qWarning() << Q_FUNC_INFO << "library is empty, skipping"; continue; // Skip } // see ksmserver's README for the description of the phases const QVariant vphase = service->property(QStringLiteral("X-KDE-Init-Phase"), QVariant::Int ); int libphase = 1; if( vphase.isValid() ) libphase = vphase.toInt(); if( phase != -1 && libphase != phase ) continue; // try to load the library if (!alreadyInitialized.contains(library)) { runModule(library, service); alreadyInitialized.insert(library); } } } KCMInit::KCMInit( const QCommandLineParser& args ) { QString arg; if (args.positionalArguments().size() == 1) { arg = args.positionalArguments().first(); } if (args.isSet(QStringLiteral("list"))) { list = KServiceTypeTrader::self()->query( QStringLiteral("KCModuleInit") ); foreach (const KService::Ptr & service, list) { if (service->library().isEmpty()) continue; // Skip printf("%s\n", QFile::encodeName(service->desktopEntryName()).data()); } return; } if (!arg.isEmpty()) { QString module = arg; if (!module.endsWith(QLatin1String(".desktop"))) module += QLatin1String(".desktop"); KService::Ptr serv = KService::serviceByStorageId( module ); if ( !serv || serv->library().isEmpty() ) { qCritical() << i18n("Module %1 not found", module); return; } else { list.append(serv); } } else { // locate the desktop files list = KServiceTypeTrader::self()->query( QStringLiteral("KCModuleInit") ); } if( startup ) { runModules( 0 ); // Tell KSplash that KCMInit has started QDBusMessage ksplashProgressMessage = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KSplash"), QStringLiteral("/KSplash"), QStringLiteral("org.kde.KSplash"), QStringLiteral("setStage")); ksplashProgressMessage.setArguments(QList() << QStringLiteral("kcminit")); QDBusConnection::sessionBus().asyncCall(ksplashProgressMessage); sendReady(); QTimer::singleShot( 300 * 1000, qApp, &QCoreApplication::quit); // just in case QDBusConnection::sessionBus().registerObject(QStringLiteral("/kcminit"), this, QDBusConnection::ExportScriptableContents); QDBusConnection::sessionBus().registerService(QStringLiteral("org.kde.kcminit")); qApp->exec(); // wait for runPhase1() and runPhase2() } else runModules( -1 ); // all phases } KCMInit::~KCMInit() { sendReady(); } void KCMInit::runPhase1() { runModules( 1 ); - emit phase1Done(); } void KCMInit::runPhase2() { runModules( 2 ); - emit phase2Done(); qApp->exit( 0 ); } extern "C" Q_DECL_EXPORT int kdemain(int argc, char *argv[]) { // kdeinit waits for kcminit to finish, but during KDE startup // only important kcm's are started very early in the login process, // the rest is delayed, so fork and make parent return after the initial phase pipe( ready ); if( fork() != 0 ) { waitForReady(); return 0; } close( ready[ 0 ] ); startup = ( strcmp( argv[ 0 ], "kcminit_startup" ) == 0 ); // started from startkde? KWorkSpace::detectPlatform(argc, argv); QGuiApplication::setDesktopSettingsAware(false); QGuiApplication app(argc, argv); //gui is needed for several modules KLocalizedString::setApplicationDomain("kcminit"); KAboutData about(QStringLiteral("kcminit"), i18n("KCMInit"), QString(), i18n("KCMInit - runs startup initialization for Control Modules."), KAboutLicense::GPL); KAboutData::setApplicationData(about); QCommandLineParser parser; about.setupCommandLine(&parser); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("list"), i18n("List modules that are run at startup"))); parser.addPositionalArgument(QStringLiteral("module"), i18n("Configuration module to run")); parser.process(app); about.processCommandLine(&parser); KCMInit kcminit( parser ); return 0; } diff --git a/startkde/kcminit/main.h b/startkde/kcminit/main.h index 591a4625f..6248216b4 100644 --- a/startkde/kcminit/main.h +++ b/startkde/kcminit/main.h @@ -1,50 +1,47 @@ /* Copyright (c) 1999 Matthias Hoelzer-Kluepfel 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) any later version. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MAIN_H #define MAIN_H #include #include #include class KCmdLineArgs; class KCMInit : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KCMInit") public Q_SLOTS: //dbus Q_SCRIPTABLE void runPhase1(); Q_SCRIPTABLE void runPhase2(); - Q_SIGNALS: //dbus signal - Q_SCRIPTABLE void phase1Done(); - Q_SCRIPTABLE void phase2Done(); public: explicit KCMInit( const QCommandLineParser& args ); ~KCMInit() override; private: bool runModule(const QString &libName, KService::Ptr service); void runModules( int phase ); KService::List list; QSet alreadyInitialized; }; #endif // MAIN_H