#include "autostart_manager.h" #include #include #include #include #include #include namespace { const QString launchAgentLabel = QStringLiteral("com.clouck.clock"); } bool AutoStartManager::enableForCurrentApplication() { #ifdef Q_OS_MAC return enableForPath(QCoreApplication::applicationFilePath()); #else return false; #endif } bool AutoStartManager::enableForPath(const QString &executablePath) { #ifdef Q_OS_MAC const QString agentPath = launchAgentPath(); if (agentPath.isEmpty()) { return false; } const QFileInfo agentFileInfo(agentPath); if (!QDir().mkpath(agentFileInfo.absolutePath())) { return false; } QSaveFile agentFile(agentPath); if (!agentFile.open(QIODevice::WriteOnly | QIODevice::Text)) { return false; } agentFile.write(launchAgentContents(executablePath).toUtf8()); return agentFile.commit(); #else Q_UNUSED(executablePath); return false; #endif } bool AutoStartManager::disable() { #ifdef Q_OS_MAC const QString agentPath = launchAgentPath(); if (agentPath.isEmpty() || !QFile::exists(agentPath)) { return true; // already gone — desired state reached } return QFile::remove(agentPath); #else return false; #endif } bool AutoStartManager::isEnabled() { #ifdef Q_OS_MAC return QFile::exists(launchAgentPath()); #else return false; #endif } QString AutoStartManager::launchAgentContents(const QString &executablePath) { QString contents; QXmlStreamWriter writer(&contents); writer.setAutoFormatting(true); writer.writeStartDocument(); writer.writeDTD(""); writer.writeStartElement("plist"); writer.writeAttribute("version", "1.0"); writer.writeStartElement("dict"); writer.writeTextElement("key", "Label"); writer.writeTextElement("string", launchAgentLabel); writer.writeTextElement("key", "ProgramArguments"); writer.writeStartElement("array"); writer.writeTextElement("string", executablePath); writer.writeEndElement(); writer.writeTextElement("key", "RunAtLoad"); writer.writeEmptyElement("true"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); return contents; } QString AutoStartManager::launchAgentPath() { const QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); if (homePath.isEmpty()) { return QString(); } return QDir(homePath).filePath("Library/LaunchAgents/" + launchAgentLabel + ".plist"); }