// SPDX-License-Identifier: GPL-3.0-or-later #include "app/session.h" #include "app/paths.h" #include #include #include #include #include #include #include #include #include #include namespace xpl { namespace { QStringList groupArgs(const QStringList &groups) { QStringList args; for (const QString &g : groups) args << QStringLiteral("--group") << g; return args; } } // namespace bool Session::writeConfig(const QString &file, const QStringList &groups, const QString &key, const QString &value, bool notify) { QStringList argv{QStringLiteral("kwriteconfig6")}; if (notify) argv << QStringLiteral("--notify"); argv << QStringLiteral("--file") << file << groupArgs(groups) << QStringLiteral("--key") << key << value; return run(argv).ok(); } bool Session::deleteConfig(const QString &file, const QStringList &groups, const QString &key, bool notify) { QStringList argv{QStringLiteral("kwriteconfig6")}; if (notify) argv << QStringLiteral("--notify"); argv << QStringLiteral("--file") << file << groupArgs(groups) << QStringLiteral("--key") << key << QStringLiteral("--delete"); return run(argv).ok(); } QString Session::readConfig(const QString &file, const QStringList &groups, const QString &key) { return QString::fromUtf8(run(QStringList{QStringLiteral("kreadconfig6"), QStringLiteral("--file"), file} + groupArgs(groups) + QStringList{QStringLiteral("--key"), key}) .out) .trimmed(); } void Session::reconfigureKWin() { call(QStringLiteral("org.kde.KWin"), QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"), QStringLiteral("reconfigure")); } bool Session::waitForPlasmaShell(int ms) { // Until its scripting interface answers (it takes a few seconds). // (Each try one short call: a hung shell costs its timeout, not a minute.) QElapsedTimer clock; clock.start(); while (clock.elapsed() < ms) { if (shellAnswers(int(std::clamp(ms - clock.elapsed(), 100, 3000)))) return true; QThread::msleep(500); } return false; } void Session::restartPlasmaShell(const std::function &whileStopped) { const QString unit = QStringLiteral("plasma-plasmashell.service"); const bool systemd = QString::fromUtf8(run({QStringLiteral("systemctl"), QStringLiteral("--user"), QStringLiteral("show"), unit, QStringLiteral("-p"), QStringLiteral("LoadState"), QStringLiteral("--value")}).out) .trimmed() == QLatin1String("loaded"); // What it saw and did, step by step, kept beside the shell's own log: // a restart that went wrong leaves its account. QElapsedTimer since; since.start(); QStringList account; const auto note = [&](const QString &line) { account << QStringLiteral("%1 ms: %2").arg(since.elapsed()).arg(line); }; const auto shellPids = [this] { return QString::fromUtf8(run(host::pgrepArgv(QStringLiteral("plasmashell"))).out).split(QLatin1Char('\n'), Qt::SkipEmptyParts); }; const auto goneWithin = [&](int ms) { QElapsedTimer clock; clock.start(); while (!shellPids().isEmpty()) { if (clock.elapsed() >= ms) return false; QThread::msleep(200); } return true; }; // A shell still starting -- restarted a moment ago by something else, // plasma-apply-lookandfeel for one -- can hang on its way out (Plasma // 6.6's Wayland clipboard): up first, then down. (A while, not forever: // one that never answers is past asking.) const QStringList pids = shellPids(); note(QStringLiteral("systemd: %1; shells: %2").arg(systemd ? QStringLiteral("yes") : QStringLiteral("no"), pids.isEmpty() ? QStringLiteral("none") : pids.join(QLatin1Char(' ')))); if (!pids.isEmpty()) note(waitForPlasmaShell(10000) ? QStringLiteral("it answers") : QStringLiteral("it doesn't answer")); // (Without systemd, the new shell is started from here -- in the old // one's environment, the session's, whatever this program was run from.) QStringList sessionEnv; if (QFile environ(QStringLiteral("/proc/%1/environ").arg(pids.value(0))); !systemd && !pids.isEmpty() && environ.open(QIODevice::ReadOnly)) for (const QByteArray &line : environ.readAll().split('\0')) if (line.contains('=')) sessionEnv << QString::fromLocal8Bit(line); // Asked to go -- neither way waiting on it here: a shell hung on its way // out would hold this up for good. if (systemd) run({QStringLiteral("systemctl"), QStringLiteral("--user"), QStringLiteral("--no-block"), QStringLiteral("stop"), unit}); else if (!pids.isEmpty()) note(startDetached({QStringLiteral("kquitapp6"), QStringLiteral("plasmashell")}) ? QStringLiteral("asked to quit") : QStringLiteral("kquitapp6 didn't start")); // ...then made to: 20 s is a shell that isn't leaving. if (goneWithin(stopDeadlineMs)) { note(QStringLiteral("gone")); } else { for (const QString &signal : {QStringLiteral("-TERM"), QStringLiteral("-KILL")}) { const QStringList left = shellPids(); for (const QString &pid : left) run({QStringLiteral("kill"), signal, pid}); note(QStringLiteral("still there: kill %1 %2").arg(signal, left.join(QLatin1Char(' ')))); if (goneWithin(3000)) { note(QStringLiteral("gone")); break; } } } if (whileStopped) whileStopped(); note(QStringLiteral("starting it; shells now: %1").arg(shellPids().join(QLatin1Char(' ')))); if (systemd) { // (systemd allows the unit 3 starts a minute, and an apply and a reset // -- each restarting it, plasma-apply-lookandfeel too -- can need more) run({QStringLiteral("systemctl"), QStringLiteral("--user"), QStringLiteral("reset-failed"), unit}); run({QStringLiteral("systemctl"), QStringLiteral("--user"), QStringLiteral("start"), unit}); } else { // (Its output kept: what Plasma says is how its problems are found.) startDetached({QStringLiteral("plasmashell")}, sessionEnv, paths::data() + QLatin1String("/plasmashell.log")); } note(waitForPlasmaShell() ? QStringLiteral("a shell answers") : QStringLiteral("no shell answers")); note(QStringLiteral("shells: %1").arg(shellPids().join(QLatin1Char(' ')))); QDir().mkpath(paths::data()); QFile out(paths::data() + QLatin1String("/plasmashell-restart.log")); if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) out.write(account.join(QLatin1Char('\n')).toUtf8() + '\n'); } host::Result LiveSession::run(const QStringList &argv) { return host::run(argv); } bool LiveSession::startDetached(const QStringList &argv, const QStringList &environment, const QString &log) { if (argv.isEmpty()) return false; QProcess process; process.setProgram(argv.first()); process.setArguments(argv.mid(1)); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if (!environment.isEmpty()) { env.clear(); for (const QString &line : environment) env.insert(line.section(QLatin1Char('='), 0, 0), line.section(QLatin1Char('='), 1)); const QByteArray plugins = qgetenv("QT_PLUGIN_PATH"); if (plugins.isEmpty()) env.remove(QStringLiteral("QT_PLUGIN_PATH")); else env.insert(QStringLiteral("QT_PLUGIN_PATH"), QString::fromLocal8Bit(plugins)); } // (Never the offscreen platform the command line runs in, main.cpp: // not for a program started for the desktop.) if (env.value(QStringLiteral("QT_QPA_PLATFORM")) == QLatin1String("offscreen")) env.remove(QStringLiteral("QT_QPA_PLATFORM")); process.setProcessEnvironment(env); // (and none of this program's output: a detached program holding it // open keeps whatever reads it -- a terminal's pipe, SSH -- waiting) process.setStandardInputFile(QProcess::nullDevice()); if (log.isEmpty()) { process.setStandardOutputFile(QProcess::nullDevice()); process.setStandardErrorFile(QProcess::nullDevice()); } else { QDir().mkpath(QFileInfo(log).absolutePath()); QFile::remove(log + QLatin1String(".old")); QFile::rename(log, log + QLatin1String(".old")); process.setStandardOutputFile(log, QIODevice::Append); process.setStandardErrorFile(log, QIODevice::Append); } return process.startDetached(); } bool LiveSession::shellAnswers(int ms) { QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.plasmashell"), QStringLiteral("/PlasmaShell"), QStringLiteral("org.kde.PlasmaShell"), QStringLiteral("evaluateScript")); message << QStringLiteral("print('up')"); const QDBusReply reply = QDBusConnection::sessionBus().call(message, QDBus::Block, qMax(100, ms)); return reply.isValid() && reply.value().trimmed() == QLatin1String("up"); } std::optional LiveSession::script(const QString &js, QString *error) { QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.plasmashell"), QStringLiteral("/PlasmaShell"), QStringLiteral("org.kde.PlasmaShell"), QStringLiteral("evaluateScript")); message << js; const QDBusReply reply = QDBusConnection::sessionBus().call(message, QDBus::Block, 60000); if (!reply.isValid()) { if (error) *error = reply.error().message(); return std::nullopt; } return reply.value().trimmed(); } bool LiveSession::call(const QString &service, const QString &path, const QString &interface, const QString &method, const QVariantList &arguments) { QDBusMessage message = QDBusMessage::createMethodCall(service, path, interface, method); message.setArguments(arguments); return QDBusConnection::sessionBus().call(message, QDBus::Block, 30000).type() != QDBusMessage::ErrorMessage; } std::optional LiveSession::query(const QString &service, const QString &path, const QString &interface, const QString &method, const QVariantList &arguments) { QDBusMessage message = QDBusMessage::createMethodCall(service, path, interface, method); message.setArguments(arguments); const QDBusMessage reply = QDBusConnection::sessionBus().call(message, QDBus::Block, 10000); if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) return std::nullopt; return reply.arguments().first(); } void LiveSession::signal(const QString &path, const QString &interface, const QString &name, const QVariantList &arguments) { QDBusMessage message = QDBusMessage::createSignal(path, interface, name); message.setArguments(arguments); QDBusConnection::sessionBus().send(message); } } // namespace xpl