pragma Singleton

// ─────────────────────────────────────────────────────────────────────────────
// Idle inhibit — the replacement for the GNOME Caffeine extension.
//
// Implemented with systemd-inhibit rather than the Wayland idle-inhibit
// protocol because the Wayland version is scoped to a surface (it would only
// hold while some window of ours is mapped) and it cannot block *sleep*, only
// the screensaver. A logind lock covers both, and outlives any UI.
// ─────────────────────────────────────────────────────────────────────────────

import Quickshell
import Quickshell.Io
import QtQuick

Singleton {
    id: root

    // Writable: the quick-settings tile and the bar indicator both bind to it.
    property bool enabled: false

    function toggle(): void {
        root.enabled = !root.enabled;
    }

    // `sleep infinity` is the process the lock is held *for*: systemd releases
    // the inhibitor when its child exits, so stopping this Process (SIGTERM)
    // is all that's needed to drop it.
    Process {
        command: ["systemd-inhibit", "--what=idle:sleep", "--mode=block", "--who=Panama", "--why=Caffeine", "sleep", "infinity"]
        running: root.enabled

        onExited: (code, status) => {
            // Only interesting if it died while we still wanted the lock.
            if (root.enabled)
                console.warn("Caffeine: systemd-inhibit exited unexpectedly, code", code);
        }
    }
}
