/* * pm-inhibit - Power Management Inhibition Tool * Copyright (C) 2022 Damien Goutte-Gattat * * 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 3 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, see . */ #include "inhibitor.h" #include #include #include #define LOGIN1_NAME "org.freedesktop.login1" #define LOGIN1_PATH "/org/freekdesktop/login1" #define INHIBIT_NAME "org.freedesktop.PowerManagement.Inhibit" #define INHIBIT_PATH "/org/freedesktop/PowerManagement/Inhibit" Inhibitor::Inhibitor(const QString& program, const QString& reason) { m_cookie = nullptr; m_fallbackCookie = 0; /* First try the modern login1 interface. */ QDBusInterface manager(LOGIN1_NAME, LOGIN1_PATH, LOGIN1_NAME ".Manager", QDBusConnection::systemBus()); QDBusReply reply = manager.call("Inhibit", "idle", program, reason, "block"); if ( reply.isValid() ) { /* We need a copy of the file descriptor to prevent the lock from * being automatically released at the end of the current scope. */ m_cookie = new QDBusUnixFileDescriptor(reply.value()); } else { /* Fallback to the old PowerManagement interface. */ QDBusInterface inhibit(INHIBIT_NAME, INHIBIT_PATH, INHIBIT_NAME, QDBusConnection::sessionBus()); QDBusReply reply = inhibit.call("Inhibit", program, reason); if ( reply.isValid() ) { m_fallbackCookie = reply.value(); } } } Inhibitor::~Inhibitor() { if ( m_cookie != nullptr ) { /* Deleting this object will close the associated file * descriptor, which will in turn release the lock. */ delete m_cookie; } else if ( m_fallbackCookie != 0 ) { /* If we had to use the old interface to acquire the lock, it * has to be explicitly released. */ QDBusInterface inhibit(INHIBIT_NAME, INHIBIT_PATH, INHIBIT_NAME, QDBusConnection::sessionBus()); inhibit.call("UnInhibit", m_fallbackCookie); } } bool Inhibitor::isInhibited() { return m_cookie != nullptr || m_fallbackCookie != 0; }