diff --git a/startkde/plasma-session/startup.cpp b/startkde/plasma-session/startup.cpp index 7059a6d5a..69be43841 100644 --- a/startkde/plasma-session/startup.cpp +++ b/startkde/plasma-session/startup.cpp @@ -1,426 +1,454 @@ /***************************************************************** 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 "debug.h" #include "kcminit_interface.h" #include "kded_interface.h" #include #include "ksmserver_interface.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "startupadaptor.h" class Phase: public KCompositeJob { Q_OBJECT public: Phase(const AutoStart &autostart, QObject *parent) : KCompositeJob(parent) , m_autostart(autostart) {} 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(); } } protected: const AutoStart m_autostart; }; class StartupPhase0: public Phase { Q_OBJECT public: StartupPhase0(const AutoStart& autostart, QObject *parent) : Phase(autostart, parent) {} void start() override { qCDebug(PLASMA_SESSION) << "Phase 0"; addSubjob(new AutoStartAppsJob(m_autostart, 0)); addSubjob(new KCMInitJob()); addSubjob(new SleepJob()); } }; class StartupPhase1: public Phase { Q_OBJECT public: StartupPhase1(const AutoStart& autostart, QObject *parent) : Phase(autostart, parent) {} void start() override { qCDebug(PLASMA_SESSION) << "Phase 1"; addSubjob(new AutoStartAppsJob(m_autostart, 1)); } }; class StartupPhase2: public Phase { Q_OBJECT public: StartupPhase2(const AutoStart& autostart, QObject *parent) : Phase(autostart, parent) {} void runUserAutostart(); bool migrateKDE4Autostart(const QString &folder); void start() override { qCDebug(PLASMA_SESSION) << "Phase 2"; addSubjob(new AutoStartAppsJob(m_autostart, 2)); addSubjob(new KDEDInitJob()); runUserAutostart(); } }; SleepJob::SleepJob() { } void SleepJob::start() { auto t = new QTimer(this); connect(t, &QTimer::timeout, this, [this]() {emitResult();}); t->start(100); } // 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(QLatin1String("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(PLASMA_SESSION) << "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(PLASMA_SESSION) << "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(QObject *parent): QObject(parent) { new StartupAdaptor(this); QDBusConnection::sessionBus().registerObject(QStringLiteral("/Startup"), QStringLiteral("org.kde.Startup"), this); QDBusConnection::sessionBus().registerService(QStringLiteral("org.kde.Startup")); + upAndRunning(QStringLiteral("ksmserver")); const AutoStart autostart; - auto phase0 = new StartupPhase0(autostart, this); - auto phase1 = new StartupPhase1(autostart, this); - auto phase2 = new StartupPhase2(autostart, this); - auto restoreSession = new RestoreSessionJob(); - - // this includes starting kwin (currently) - // forward our arguments into ksmserver to match startplasma expectations - QStringList arguments = qApp->arguments(); - arguments.removeFirst(); - auto ksmserverJob = new StartServiceJob(QStringLiteral("ksmserver"), arguments, QStringLiteral("org.kde.ksmserver")); - - connect(ksmserverJob, &KJob::finished, phase0, &KJob::start); - - connect(phase0, &KJob::finished, phase1, &KJob::start); - - connect(phase1, &KJob::finished, restoreSession, &KJob::start); - connect(restoreSession, &KJob::finished, phase2, &KJob::start); - upAndRunning(QStringLiteral("ksmserver")); + KJob* phase1; + const QVector sequence = { + new StartProcessJob(QStringLiteral("kcminit_startup"), {}), + new StartServiceJob(QStringLiteral("kded5"), {}, QStringLiteral("org.kde.kded"), QProcess::systemEnvironment() << QStringList{ QStringLiteral("KDED_STARTED_BY_KDEINIT=1") }), + new StartServiceJob(QStringLiteral("ksmserver"), QCoreApplication::instance()->arguments().mid(1), QStringLiteral("org.kde.ksmserver")), + new StartupPhase0(autostart, this), + phase1 = new StartupPhase1(autostart, this), + new RestoreSessionJob(), + new StartupPhase2(autostart, this), + }; + KJob* last = nullptr; + for(KJob* job : sequence) { + if (last) { + connect(last, &KJob::finished, job, &KJob::start); + } + last = job; + } 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); + loginSound->start(); + }); - ksmserverJob->start(); + connect(sequence.last(), &KJob::finished, this, &Startup::finishStartup); + sequence.first()->start(); } 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(PLASMA_SESSION) << "Finished"; upAndRunning(QStringLiteral("ready")); } void Startup::updateLaunchEnv(const QString &key, const QString &value) { qputenv(key.toLatin1(), value.toLatin1()); } KCMInitJob::KCMInitJob() : KJob() { } void KCMInitJob::start() { org::kde::KCMInit kcminit(QStringLiteral("org.kde.kcminit"), QStringLiteral("/kcminit"), QDBusConnection::sessionBus()); kcminit.setTimeout(10 * 1000); QDBusPendingReply pending = kcminit.runPhase1(); 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(PLASMA_SESSION()); org::kde::kded5 kded( QStringLiteral("org.kde.kded5"), QStringLiteral("/kded"), QDBusConnection::sessionBus()); auto pending = kded.loadSecondPhase(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [this]() {emitResult();}); connect(watcher, &QDBusPendingCallWatcher::finished, watcher, &QObject::deleteLater); } RestoreSessionJob::RestoreSessionJob(): KJob() {} void RestoreSessionJob::start() { OrgKdeKSMServerInterfaceInterface ksmserverIface(QStringLiteral("org.kde.ksmserver"), QStringLiteral("/KSMServer"), QDBusConnection::sessionBus()); auto pending = ksmserverIface.restoreSession(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [this]() {emitResult();}); connect(watcher, &QDBusPendingCallWatcher::finished, watcher, &QObject::deleteLater); } 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); for (const QString &file : entries) { // Don't execute backup files if (!file.endsWith(QLatin1Char('~')) && !file.endsWith(QLatin1String(".bak")) && (file[0] != QLatin1Char('%') || !file.endsWith(QLatin1Char('%'))) && (file[0] != QLatin1Char('#') || !file.endsWith(QLatin1Char('#')))) { const QString fullPath = dir.absolutePath() + QLatin1Char('/') + file; qCInfo(PLASMA_SESSION) << "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(PLASMA_SESSION) << "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(PLASMA_SESSION) << "Copying autostart files from" << oldFolder.path(); const QStringList entries = oldFolder.entryList(QDir::Files); for (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(PLASMA_SESSION) << "Error copying" << src << "to" << dest; } } return true; } AutoStartAppsJob::AutoStartAppsJob(const AutoStart & autostart, int phase) : m_autoStart(autostart) { m_autoStart.setPhase(phase); } void AutoStartAppsJob::start() { qCDebug(PLASMA_SESSION); 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(PLASMA_SESSION) << "failed to parse" << serviceName << "for autostart"; continue; } qCInfo(PLASMA_SESSION) << "Starting autostart service " << serviceName << arguments; auto program = arguments.takeFirst(); if (!QProcess::startDetached(program, arguments)) qCWarning(PLASMA_SESSION) << "could not start" << serviceName << ":" << program << arguments; } while (true); }); } -StartServiceJob::StartServiceJob(const QString &process, const QStringList &args, const QString &serviceId): +StartServiceJob::StartServiceJob(const QString &process, const QStringList &args, const QString &serviceId, const QStringList &env): KJob(), m_process(process), - m_args(args) + m_args(args), + m_env(env) { auto watcher = new QDBusServiceWatcher(serviceId, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForRegistration, this); connect(watcher, &QDBusServiceWatcher::serviceRegistered, this, &StartServiceJob::emitResult); } void StartServiceJob::start() { - QProcess::startDetached(m_process, m_args); + QProcess* p = new QProcess(this); + p->setEnvironment(m_env); + if (!p->startDetached(m_process, m_args)) + qCWarning(PLASMA_SESSION) << "error starting process" << m_process << m_args; + + connect(p, &QProcess::errorOccurred, this, [this] (QProcess::ProcessError error) { + qCWarning(PLASMA_SESSION) << "error on process" << error << m_process << m_args; + }); } +StartProcessJob::StartProcessJob(const QString &process, const QStringList &args, const QStringList &env) + : KJob() + , m_process(new QProcess(this)) +{ + m_process->setProgram(process); + m_process->setArguments(args); + m_process->setEnvironment(env); + + connect(m_process, &QProcess::errorOccurred, this, [process, args] (QProcess::ProcessError error) { + qCWarning(PLASMA_SESSION) << "error starting process" << error << process << args; + }); + connect(m_process, &QProcess::started, this, &StartProcessJob::emitResult); +} + +void StartProcessJob::start() +{ + if (!m_process->startDetached()) + qCWarning(PLASMA_SESSION) << "error starting process" << m_process->program(); +} #include "startup.moc" diff --git a/startkde/plasma-session/startup.h b/startkde/plasma-session/startup.h index 33e5e23af..7f3595a8f 100644 --- a/startkde/plasma-session/startup.h +++ b/startkde/plasma-session/startup.h @@ -1,103 +1,119 @@ /***************************************************************** 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 QProcess; + class Startup : public QObject { Q_OBJECT public: Startup(QObject *parent); void upAndRunning( const QString& msg ); void finishStartup(); public Q_SLOTS: // alternatively we could drop this and have a rule that we /always/ launch everything through klauncher // need resolution from frameworks discussion on kdeinit void updateLaunchEnv(const QString &key, const QString &value); private: void autoStart(int phase); }; class SleepJob: public KJob { Q_OBJECT public: SleepJob(); void start() override; }; class KCMInitJob: public KJob { Q_OBJECT public: KCMInitJob(); void start() override; }; class KDEDInitJob: public KJob { Q_OBJECT public: KDEDInitJob(); void start() override; }; class AutoStartAppsJob: public KJob { Q_OBJECT public: AutoStartAppsJob(const AutoStart &autoStart, int phase); void start() override; private: AutoStart m_autoStart; }; +/** + * Launches a process, and waits for the process to start + */ +class StartProcessJob: public KJob +{ + Q_OBJECT +public: + StartProcessJob(const QString &process, const QStringList &args, const QStringList &env = {}); + void start() override; +private: + QProcess* m_process; +}; + /** * Launches a process, and waits for the service to appear on the session bus */ class StartServiceJob: public KJob { Q_OBJECT public: - StartServiceJob(const QString &process, const QStringList &args, const QString &serviceId); + StartServiceJob(const QString &process, const QStringList &args, const QString &serviceId, const QStringList &env = {}); void start() override; private: const QString m_process; const QStringList m_args; + const QStringList m_env; }; class RestoreSessionJob: public KJob { Q_OBJECT public: RestoreSessionJob(); void start() override; private: }; diff --git a/startkde/startplasma-waylandsession.cpp b/startkde/startplasma-waylandsession.cpp index 87c71c6b3..70a3ae7a0 100644 --- a/startkde/startplasma-waylandsession.cpp +++ b/startkde/startplasma-waylandsession.cpp @@ -1,76 +1,73 @@ /* This file is part of the KDE project Copyright (C) 2019 Aleix Pol Gonzalez This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "startplasma.h" int main(int /*argc*/, char** /*argv*/) { // Boot sequence: // // kdeinit is used to fork off processes which improves memory usage // and startup time. // // * kdeinit starts klauncher first. // * Then kded is started. kded is responsible for keeping the sycoca // database up to date. When an up to date database is present it goes // into the background and the startup continues. // * Then kdeinit starts kcminit. kcminit performs initialisation of // certain devices according to the user's settings // // * Then ksmserver is started which takes control of the rest of the startup sequence runStartupConfig(); setupFontDpi(); QScopedPointer ksplash(setupKSplash()); qputenv("PLASMA_USE_QT_SCALING", "1"); out << "startplasma-waylandsession: Starting up..."; if (qEnvironmentVariableIsSet("DISPLAY")) { setupX11(); } else { qWarning() << "running kwin without Xwayland support"; } setupGSLib(); if (!syncDBusEnvironment()) { out << "Could not sync environment to dbus.\n"; return 2; } - if (!startKDEInit()) - return 3; - if (!startKSMServer(true)) return 4; // Anything after here is logout // It is not called after shutdown/restart waitForKonqi(); out << "startplasma-waylandsession: Shutting down...\n"; runSync(QStringLiteral("kdeinit5_shutdown"), {}); cleanupX11(); out << "startplasma-waylandsession: Done.\n"; return 0; } diff --git a/startkde/startplasma-x11.cpp b/startkde/startplasma-x11.cpp index 3314b6283..3a0dabbe8 100644 --- a/startkde/startplasma-x11.cpp +++ b/startkde/startplasma-x11.cpp @@ -1,122 +1,119 @@ /* This file is part of the KDE project Copyright (C) 2019 Aleix Pol Gonzalez This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "startplasma.h" #include #include #include #include void sighupHandler(int) { out << "GOT SIGHUP\n"; } int main(int /*argc*/, char** /*argv*/) { // When the X server dies we get a HUP signal from xinit. We must ignore it // because we still need to do some cleanup. signal(SIGHUP, sighupHandler); // Boot sequence: // // kdeinit is used to fork off processes which improves memory usage // and startup time. // // * kdeinit starts klauncher first. // * Then kded is started. kded is responsible for keeping the sycoca // database up to date. When an up to date database is present it goes // into the background and the startup continues. // * Then kdeinit starts kcminit. kcminit performs initialisation of // certain devices according to the user's settings // // * Then ksmserver is started which takes control of the rest of the startup sequence // Check if a Plasma session already is running and whether it's possible to connect to X switch (kCheckRunning()) { case NoX11: out << "$DISPLAY is not set or cannot connect to the X server.\n"; return 1; case PlasmaRunning: messageBox(QStringLiteral("Plasma seems to be already running on this display.\n")); return 1; case NoPlasmaRunning: break; } createConfigDirectory(); runStartupConfig(); //Do not sync any of this section with the wayland versions as there scale factors are //sent properly over wl_output { KConfig cfg(QStringLiteral("kdeglobals")); KConfigGroup kscreenGroup = cfg.group("KScreen"); const auto screenScaleFactors = kscreenGroup.readEntry("ScreenScaleFactors", QByteArray()); if (!screenScaleFactors.isEmpty()) { qputenv("QT_SCREEN_SCALE_FACTORS", screenScaleFactors); qreal scaleFactor = qFloor(kscreenGroup.readEntry("ScaleFactor", 1.0)); if (scaleFactor > 1) { qputenv("GDK_SCALE", QByteArray::number(scaleFactor, 'g', 0)); qputenv("GDK_DPI_SCALE", QByteArray::number(1.0/scaleFactor, 'g', 3)); } } } setupCursor(false); setupFontDpi(); QScopedPointer ksplash(setupKSplash()); runEnvironmentScripts(); out << "startkde: Starting up...\n"; setupPlasmaEnvironment(); setupX11(); if (!syncDBusEnvironment()) { // Startup error messageBox(QStringLiteral("Could not sync environment to dbus.\n")); return 1; } - if (!startKDEInit()) - return 1; - if (!startKSMServer(false)) return 1; // Anything after here is logout // It is not called after shutdown/restart waitForKonqi(); out << "startkde: Shutting down...\n"; runSync(QStringLiteral("kdeinit5_shutdown"), {}); cleanupPlasmaEnvironment(); cleanupX11(); out << "startkde: Done.\n"; return 0; } diff --git a/startkde/startplasma.cpp b/startkde/startplasma.cpp index 4c9f5cef6..8feb6d847 100644 --- a/startkde/startplasma.cpp +++ b/startkde/startplasma.cpp @@ -1,407 +1,394 @@ /* This file is part of the KDE project Copyright (C) 2019 Aleix Pol Gonzalez This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include "startplasma.h" QTextStream out(stderr); void messageBox(const QString &text) { out << text; runSync(QStringLiteral("xmessage"), {QStringLiteral("-geometry"), QStringLiteral("500x100"), text}); } QStringList allServices(const QLatin1String& prefix) { QDBusConnectionInterface *bus = QDBusConnection::sessionBus().interface(); const QStringList services = bus->registeredServiceNames(); QMap servicesWithAliases; for (const QString &serviceName : services) { QDBusReply reply = bus->serviceOwner(serviceName); QString owner = reply; if (owner.isEmpty()) owner = serviceName; servicesWithAliases[owner].append(serviceName); } QStringList names; for (auto it = servicesWithAliases.constBegin(); it != servicesWithAliases.constEnd(); ++it) { if (it.value().startsWith(prefix)) names << it.value(); } names.removeDuplicates(); names.sort(); return names; } int runSync(const QString& program, const QStringList &args, const QStringList &env) { QProcess p; if (!env.isEmpty()) p.setEnvironment(QProcess::systemEnvironment() << env); p.setProcessChannelMode(QProcess::ForwardedChannels); p.start(program, args); // qDebug() << "started..." << program << args; p.waitForFinished(-1); if (p.exitCode()) { qWarning() << program << args << "exited with code" << p.exitCode(); } return p.exitCode(); } void sourceFiles(const QStringList &files) { QStringList filteredFiles; std::copy_if(files.begin(), files.end(), std::back_inserter(filteredFiles), [](const QString& i){ return QFileInfo(i).isReadable(); } ); if (filteredFiles.isEmpty()) return; filteredFiles.prepend(QStringLiteral(CMAKE_INSTALL_FULL_LIBEXECDIR "/plasma-sourceenv.sh")); QProcess p; p.start(QStringLiteral("/bin/sh"), filteredFiles); p.waitForFinished(-1); const auto fullEnv = p.readAllStandardOutput(); auto envs = fullEnv.split('\0'); for (auto &env: envs) { if (env.startsWith("_=") || env.startsWith("SHLVL")) continue; const int idx = env.indexOf('='); if (Q_UNLIKELY(idx <= 0)) continue; if (qgetenv(env.left(idx)) != env.mid(idx+1)) { // qDebug() << "setting..." << env.left(idx) << env.mid(idx+1) << "was" << qgetenv(env.left(idx)); qputenv(env.left(idx), env.mid(idx+1)); } } } void createConfigDirectory() { const QString configDir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); if (!QDir().mkpath(configDir)) out << "Could not create config directory XDG_CONFIG_HOME: " << configDir << '\n'; } void runStartupConfig() { //export LC_* variables set by kcmshell5 formats into environment //so it can be picked up by QLocale and friends. KConfig config(QStringLiteral("plasma-localerc")); KConfigGroup formatsConfig = KConfigGroup(&config, "Formats"); const auto lcValues = { "LANG", "LC_NUMERIC", "LC_TIME", "LC_MONETARY", "LC_MEASUREMENT", "LC_COLLATE", "LC_CTYPE" }; for (auto lc : lcValues) { const QString value = formatsConfig.readEntry(lc, QString()); if (!value.isEmpty()) { qputenv(lc, value.toUtf8()); } } KConfigGroup languageConfig = KConfigGroup(&config, "Translations"); const QString value = languageConfig.readEntry("LANGUAGE", QString()); if (!value.isEmpty()) { qputenv("LANGUAGE", value.toUtf8()); } if (!formatsConfig.hasKey("LANG") && !qEnvironmentVariableIsEmpty("LANG")) { formatsConfig.writeEntry("LANG", qgetenv("LANG")); formatsConfig.sync(); } } void setupCursor(bool wayland) { const KConfig cfg(QStringLiteral("kcminputrc")); const KConfigGroup inputCfg = cfg.group("Mouse"); const auto kcminputrc_mouse_cursorsize = inputCfg.readEntry("cursorSize", QString()); const auto kcminputrc_mouse_cursortheme = inputCfg.readEntry("cursorTheme", QStringLiteral("breeze_cursors")); if (!kcminputrc_mouse_cursortheme.isEmpty() || !kcminputrc_mouse_cursorsize.isEmpty()) { #ifdef XCURSOR_PATH QByteArray path(XCURSOR_PATH); path.replace("$XCURSOR_PATH", qgetenv("XCURSOR_PATH")); qputenv("XCURSOR_PATH", path); #endif } //TODO: consider linking directly const int applyMouseStatus = wayland ? 0 : runSync(QStringLiteral("kapplymousetheme"), { kcminputrc_mouse_cursortheme, kcminputrc_mouse_cursorsize }); if (applyMouseStatus == 10) { qputenv("XCURSOR_THEME", "breeze_cursors"); } else if (!kcminputrc_mouse_cursortheme.isEmpty()) { qputenv("XCURSOR_THEME", kcminputrc_mouse_cursortheme.toUtf8()); } if (!kcminputrc_mouse_cursorsize.isEmpty()) { qputenv("XCURSOR_SIZE", kcminputrc_mouse_cursorsize.toUtf8()); } } // Source scripts found in /plasma-workspace/env/*.sh // (where correspond to the system and user's configuration // directory. // // This is where you can define environment variables that will be available to // all KDE programs, so this is where you can run agents using e.g. eval `ssh-agent` // or eval `gpg-agent --daemon`. // Note: if you do that, you should also put "ssh-agent -k" as a shutdown script // // (see end of this file). // For anything else (that doesn't set env vars, or that needs a window manager), // better use the Autostart folder. void runEnvironmentScripts() { QStringList scripts; const auto locations = QStandardPaths::locateAll(QStandardPaths::GenericConfigLocation, QStringLiteral("plasma-workspace/env"), QStandardPaths::LocateDirectory); for (const QString & location : locations) { QDir dir(location); const auto dirScripts = dir.entryInfoList({QStringLiteral("*.sh")}); for (const auto script : dirScripts) { scripts << script.absoluteFilePath(); } } sourceFiles(scripts); } // Mark that full KDE session is running (e.g. Konqueror preloading works only // with full KDE running). The KDE_FULL_SESSION property can be detected by // any X client connected to the same X session, even if not launched // directly from the KDE session but e.g. using "ssh -X", kdesu. $KDE_FULL_SESSION // however guarantees that the application is launched in the same environment // like the KDE session and that e.g. KDE utilities/libraries are available. // KDE_FULL_SESSION property is also only available since KDE 3.5.5. // The matching tests are: // For $KDE_FULL_SESSION: // if test -n "$KDE_FULL_SESSION"; then ... whatever // For KDE_FULL_SESSION property (on X11): // xprop -root | grep "^KDE_FULL_SESSION" >/dev/null 2>/dev/null // if test $? -eq 0; then ... whatever // // Additionally there is $KDE_SESSION_UID with the uid // of the user running the KDE session. It should be rarely needed (e.g. // after sudo to prevent desktop-wide functionality in the new user's kded). // // Since KDE4 there is also KDE_SESSION_VERSION, containing the major version number. // void setupPlasmaEnvironment() { //Manually disable auto scaling because we are scaling above //otherwise apps that manually opt in for high DPI get auto scaled by the developer AND manually scaled by us qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0"); qputenv("KDE_FULL_SESSION", "true"); qputenv("KDE_SESSION_VERSION", "5"); qputenv("KDE_SESSION_UID", QByteArray::number(getuid())); qputenv("XDG_CURRENT_DESKTOP", "KDE"); } void setupX11() { // Set a left cursor instead of the standard X11 "X" cursor, since I've heard // from some users that they're confused and don't know what to do. This is // especially necessary on slow machines, where starting KDE takes one or two // minutes until anything appears on the screen. // // If the user has overwritten fonts, the cursor font may be different now // so don't move this up. runSync(QStringLiteral("xsetroot"), {QStringLiteral("-cursor_name"), QStringLiteral("left_ptr")}); runSync(QStringLiteral("xprop"), {QStringLiteral("-root"), QStringLiteral("-f"), QStringLiteral("KDE_FULL_SESSION"), QStringLiteral("8t"), QStringLiteral("-set"), QStringLiteral("KDE_FULL_SESSION"), QStringLiteral("true")}); runSync(QStringLiteral("xprop"), {QStringLiteral("-root"), QStringLiteral("-f"), QStringLiteral("KDE_SESSION_VERSION"), QStringLiteral("32c"), QStringLiteral("-set"), QStringLiteral("KDE_SESSION_VERSION"), QStringLiteral("5")}); } void cleanupX11() { runSync(QStringLiteral("xprop"), { QStringLiteral("-root"), QStringLiteral("-remove"), QStringLiteral("KDE_FULL_SESSION") }); runSync(QStringLiteral("xprop"), { QStringLiteral("-root"), QStringLiteral("-remove"), QStringLiteral("KDE_SESSION_VERSION") }); } // TODO: Check if Necessary void cleanupPlasmaEnvironment() { qunsetenv("KDE_FULL_SESSION"); qunsetenv("KDE_SESSION_VERSION"); qunsetenv("KDE_SESSION_UID"); } // kwin_wayland can possibly also start dbus-activated services which need env variables. // In that case, the update in startplasma might be too late. bool syncDBusEnvironment() { int exitCode; // At this point all environment variables are set, let's send it to the DBus session server to update the activation environment if (!QStandardPaths::findExecutable(QStringLiteral("dbus-update-activation-environment")).isEmpty()) { exitCode = runSync(QStringLiteral("dbus-update-activation-environment"), { QStringLiteral("--systemd"), QStringLiteral("--all") }); } else { exitCode = runSync(QStringLiteral(CMAKE_INSTALL_FULL_LIBEXECDIR "/ksyncdbusenv"), {}); } return exitCode == 0; } void setupFontDpi() { KConfig cfg(QStringLiteral("kcmfonts")); KConfigGroup fontsCfg(&cfg, "General"); if (!fontsCfg.hasKey("forceFontDPI")) { return; } //TODO port to c++? const QByteArray input = "Xft.dpi: " + QByteArray::number(fontsCfg.readEntry("forceFontDPI", 0)); QProcess p; p.start(QStringLiteral("xrdb"), { QStringLiteral("-quiet"), QStringLiteral("-merge"), QStringLiteral("-nocpp") }); p.setProcessChannelMode(QProcess::ForwardedChannels); p.write(input); p.closeWriteChannel(); p.waitForFinished(-1); } static bool desktopLockedAtStart = false; QProcess* setupKSplash() { const auto dlstr = qgetenv("DESKTOP_LOCKED"); desktopLockedAtStart = dlstr == "true" || dlstr == "1"; qunsetenv("DESKTOP_LOCKED"); // Don't want it in the environment QProcess* p = nullptr; if (!desktopLockedAtStart) { const KConfig cfg(QStringLiteral("ksplashrc")); // the splashscreen and progress indicator KConfigGroup ksplashCfg = cfg.group("KSplash"); if (ksplashCfg.readEntry("Engine", QStringLiteral("KSplashQML")) == QLatin1String("KSplashQML")) { p = new QProcess; p->start(QStringLiteral("ksplashqml"), { ksplashCfg.readEntry("Theme", QStringLiteral("Breeze")) }); } } return p; } void setupGSLib() // Get Ghostscript to look into user's KDE fonts dir for additional Fontmap { const QByteArray usr_fdir = QFile::encodeName(QDir::home().absoluteFilePath(QStringLiteral(".fonts"))); if (qEnvironmentVariableIsSet("GS_LIB")) { qputenv("GS_LIB", usr_fdir + ':' + qgetenv("GS_LIB")); } else { qputenv("GS_LIB", usr_fdir); } } -bool startKDEInit() +bool startKSMServer(bool wayland) { - // We set LD_BIND_NOW to increase the efficiency of kdeinit. - // kdeinit unsets this variable before loading applications. - const int exitCode = runSync(QStringLiteral(CMAKE_INSTALL_FULL_LIBEXECDIR_KF5 "/start_kdeinit_wrapper"), { QStringLiteral("--kded"), QStringLiteral("+kcminit_startup") }, { QStringLiteral("LD_BIND_NOW=true") }); - if (exitCode != 0) { - messageBox(QStringLiteral("startkde: Could not start kdeinit5. Check your installation.")); - return false; - } - OrgKdeKSplashInterface iface(QStringLiteral("org.kde.KSplash"), QStringLiteral("/KSplash"), QDBusConnection::sessionBus()); iface.setStage(QStringLiteral("kinit")); - return true; -} - -bool startKSMServer(bool wayland) -{ // finally, give the session control to the session manager // see kdebase/ksmserver for the description of the rest of the startup sequence // if the KDEWM environment variable has been set, then it will be used as KDE's // window manager instead of kwin. // if KDEWM is not set, ksmserver will ensure kwin is started. // kwrapper5 is used to reduce startup time and memory usage // kwrapper5 does not return useful error codes such as the exit code of ksmserver. // We only check for 255 which means that the ksmserver process could not be // started, any problems thereafter, e.g. ksmserver failing to initialize, // will remain undetected. // If the session should be locked from the start (locked autologin), // lock now and do the rest of the KDE startup underneath the locker. QStringList ksmserverOptions; if (wayland) { ksmserverOptions << QStringLiteral("--no-lockscreen"); } else { if (qEnvironmentVariableIsSet("KDEWM")) { ksmserverOptions << QStringLiteral("--windowmanager") << qEnvironmentVariable("KDEWM"); } if (desktopLockedAtStart) { ksmserverOptions << QStringLiteral("--lockscreen"); } } const auto exitCode = runSync(QStringLiteral(CMAKE_INSTALL_FULL_BINDIR "/plasma_session"), ksmserverOptions); if (exitCode == 255) { // Startup error messageBox(QStringLiteral("startkde: Could not start ksmserver. Check your installation.\n")); return false; } return true; } void waitForKonqi() { const KConfig cfg(QStringLiteral("startkderc")); const KConfigGroup grp = cfg.group("WaitForDrKonqi"); bool wait_drkonqi = grp.readEntry("Enabled", true); if (wait_drkonqi) { // wait for remaining drkonqi instances with timeout (in seconds) const int wait_drkonqi_timeout = grp.readEntry("Timeout", 900) * 1000; QElapsedTimer wait_drkonqi_counter; wait_drkonqi_counter.start(); QStringList services = allServices(QLatin1String("org.kde.drkonqi-")); while (!services.isEmpty()) { sleep(5); services = allServices(QLatin1String("org.kde.drkonqi-")); if (wait_drkonqi_counter.elapsed() >= wait_drkonqi_timeout) { // ask remaining drkonqis to die in a graceful way for (const auto &service: services) { QDBusInterface iface(service, QStringLiteral("/MainApplication")); iface.call(QStringLiteral("quit")); } break; } } } }