| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486 |
- #include "PowerMonitor.h"
- #include <algorithm>
- #include <chrono>
- #include <cstdint>
- #include <cstdlib>
- #include <cstring>
- #include <dbus/dbus.h>
- #include <fstream>
- #include <poll.h>
- #include <string>
- #include <sys/eventfd.h>
- #include <unistd.h>
- #include "WallpaperEngine/Desktop/DlopenX11.h"
- #include "WallpaperEngine/Desktop/SessionBus.h"
- #include "WallpaperEngine/Logging/Log.h"
- #include "WallpaperEngine/Logging/ThreadGuard.h"
- #ifdef ENABLE_WAYLAND
- #include "WallpaperEngine/Desktop/HostWayland.h"
- #include "ext-idle-notify-v1-protocol.h"
- #include <wayland-client.h>
- #endif
- using namespace WallpaperEngine::Desktop;
- namespace {
- constexpr auto BATTERY_INTERVAL = std::chrono::seconds (5);
- constexpr auto IDLE_POLL_ACTIVE = std::chrono::milliseconds (250);
- constexpr auto IDLE_POLL_MAX = std::chrono::milliseconds (5000);
- std::string readLine (const std::filesystem::path& path) {
- std::ifstream file (path);
- std::string line;
- std::getline (file, line);
- return line;
- }
- // MIT-SCREEN-SAVER through dlopen, libXss isn't a build dependency
- struct ScreenSaverInfo {
- unsigned long window;
- int state;
- int kind;
- unsigned long tilOrSince;
- unsigned long idle;
- unsigned long eventMask;
- };
- class X11Idle {
- public:
- ~X11Idle () {
- if (this->m_info != nullptr) {
- this->m_free (this->m_info);
- }
- }
- bool open () {
- if (!this->m_x.load ("libXss.so.1")) {
- return false;
- }
- this->m_free = this->m_x.x11Symbol<int (*) (void*)> ("XFree");
- this->m_rootWindow = this->m_x.x11Symbol<unsigned long (*) (void*)> ("XDefaultRootWindow");
- auto queryExtension = this->m_x.extensionSymbol<int (*) (void*, int*, int*)> ("XScreenSaverQueryExtension");
- auto allocInfo = this->m_x.extensionSymbol<ScreenSaverInfo* (*)()> ("XScreenSaverAllocInfo");
- this->m_query
- = this->m_x.extensionSymbol<int (*) (void*, unsigned long, ScreenSaverInfo*)> ("XScreenSaverQueryInfo");
- if (this->m_free == nullptr || this->m_rootWindow == nullptr || queryExtension == nullptr
- || allocInfo == nullptr || this->m_query == nullptr) {
- return false;
- }
- if (!this->m_x.connect ()) {
- return false;
- }
- int eventBase = 0;
- int errorBase = 0;
- if (!queryExtension (this->m_x.display (), &eventBase, &errorBase)) {
- return false;
- }
- this->m_info = allocInfo ();
- return this->m_info != nullptr;
- }
- std::optional<uint64_t> idleMilliseconds () {
- void* display = this->m_x.display ();
- if (!this->m_query (display, this->m_rootWindow (display), this->m_info)) {
- return std::nullopt;
- }
- return this->m_info->idle;
- }
- private:
- DlopenX11 m_x;
- ScreenSaverInfo* m_info = nullptr;
- int (*m_free) (void*) = nullptr;
- unsigned long (*m_rootWindow) (void*) = nullptr;
- int (*m_query) (void*, unsigned long, ScreenSaverInfo*) = nullptr;
- };
- std::optional<bool> upowerOnBattery (DBusConnection* bus) {
- DBusMessage* reply
- = getProperty (bus, "org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "OnBattery");
- if (reply == nullptr) {
- return std::nullopt;
- }
- std::optional<bool> result;
- DBusMessageIter variant;
- if (propertyValue (reply, variant) && dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_BOOLEAN) {
- dbus_bool_t value = FALSE;
- dbus_message_iter_get_basic (&variant, &value);
- result = value != FALSE;
- }
- dbus_message_unref (reply);
- return result;
- }
- std::optional<uint64_t> mutterIdleMilliseconds (DBusConnection* bus) {
- DBusMessage* call = dbus_message_new_method_call (
- "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor",
- "GetIdletime"
- );
- std::string error;
- DBusMessage* reply = callBlocking (bus, call, error);
- if (reply == nullptr) {
- return std::nullopt;
- }
- dbus_uint64_t idle = 0;
- const bool ok = dbus_message_get_args (reply, nullptr, DBUS_TYPE_UINT64, &idle, DBUS_TYPE_INVALID);
- dbus_message_unref (reply);
- return ok ? std::optional<uint64_t> (idle) : std::nullopt;
- }
- }
- std::optional<bool> WallpaperEngine::Desktop::sysfsOnBattery (const std::filesystem::path& powerSupplies) {
- std::error_code error;
- bool anyBattery = false;
- bool discharging = false;
- bool externalPower = false;
- for (const auto& entry : std::filesystem::directory_iterator (powerSupplies, error)) {
- const auto& dir = entry.path ();
- // mice, headsets and controllers have scope Device
- if (readLine (dir / "scope") == "Device") {
- continue;
- }
- const std::string type = readLine (dir / "type");
- if (type == "Battery") {
- anyBattery = true;
- discharging = discharging || readLine (dir / "status") == "Discharging";
- } else if (readLine (dir / "online") == "1") {
- externalPower = true;
- }
- }
- if (!anyBattery) {
- return std::nullopt;
- }
- return discharging && !externalPower;
- }
- struct PowerMonitor::Sources {
- DBusConnection* systemBus = nullptr;
- DBusConnection* sessionBus = nullptr;
- bool upowerWorks = true;
- bool mutterWorks = true;
- std::unique_ptr<X11Idle> x11;
- bool x11Tried = false;
- bool loggedUnavailable = false;
- #ifdef ENABLE_WAYLAND
- wl_display* display = nullptr;
- wl_registry* registry = nullptr;
- wl_seat* seat = nullptr;
- ext_idle_notifier_v1* notifier = nullptr;
- ext_idle_notification_v1* notification = nullptr;
- #endif
- #ifdef ENABLE_WAYLAND
- void disconnectWayland () {
- if (this->notification != nullptr) {
- ext_idle_notification_v1_destroy (this->notification);
- }
- if (this->notifier != nullptr) {
- ext_idle_notifier_v1_destroy (this->notifier);
- }
- if (this->seat != nullptr) {
- wl_seat_destroy (this->seat);
- }
- if (this->registry != nullptr) {
- wl_registry_destroy (this->registry);
- }
- if (this->display != nullptr) {
- wl_display_disconnect (this->display);
- }
- this->notification = nullptr;
- this->notifier = nullptr;
- this->seat = nullptr;
- this->registry = nullptr;
- this->display = nullptr;
- }
- #endif
- ~Sources () {
- #ifdef ENABLE_WAYLAND
- this->disconnectWayland ();
- #endif
- closeBus (this->systemBus);
- closeBus (this->sessionBus);
- }
- };
- #ifdef ENABLE_WAYLAND
- namespace {
- void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
- auto* sources = static_cast<PowerMonitor::Sources*> (data);
- if (std::strcmp (interface, wl_seat_interface.name) == 0 && sources->seat == nullptr) {
- sources->seat = static_cast<wl_seat*> (wl_registry_bind (registry, name, &wl_seat_interface, 1));
- } else if (std::strcmp (interface, ext_idle_notifier_v1_interface.name) == 0) {
- sources->notifier = static_cast<ext_idle_notifier_v1*> (
- wl_registry_bind (registry, name, &ext_idle_notifier_v1_interface, 1)
- );
- }
- }
- void registryGlobalRemove (void*, wl_registry*, uint32_t) { }
- const wl_registry_listener registryListener = {
- .global = registryGlobal,
- .global_remove = registryGlobalRemove,
- };
- void notificationIdled (void* data, ext_idle_notification_v1*) { static_cast<std::atomic<bool>*> (data)->store (true); }
- void notificationResumed (void* data, ext_idle_notification_v1*) {
- static_cast<std::atomic<bool>*> (data)->store (false);
- }
- const ext_idle_notification_v1_listener notificationListener = {
- .idled = notificationIdled,
- .resumed = notificationResumed,
- };
- }
- #endif
- PowerMonitor::PowerMonitor () : m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (new Sources) {
- // UPower and the compositor are queried on the thread, sysfs answers until then
- this->m_onBattery = sysfsOnBattery ("/sys/class/power_supply").value_or (false);
- #ifdef ENABLE_WAYLAND
- // main thread: connectWayland picks the route to the compositor once (Flatpak helper)
- if (const char* session = std::getenv ("XDG_SESSION_TYPE");
- session != nullptr && std::string_view (session) == "wayland" && std::getenv ("WAYLAND_DISPLAY") != nullptr) {
- this->m_sources->display = connectWayland ();
- }
- #endif
- this->m_thread
- = std::thread ([this] { WallpaperEngine::Logging::guardThread ("Power monitor", [this] { this->run (); }); });
- }
- PowerMonitor::~PowerMonitor () {
- this->m_stop = true;
- this->wake ();
- if (this->m_thread.joinable ()) {
- this->m_thread.join ();
- }
- delete this->m_sources;
- if (this->m_wakeFd >= 0) {
- close (this->m_wakeFd);
- }
- }
- void PowerMonitor::setIdleTimeout (int minutes) {
- this->m_idleMinutes = std::max (0, minutes);
- this->wake ();
- }
- void PowerMonitor::wake () const {
- if (this->m_wakeFd >= 0) {
- const uint64_t one = 1;
- std::ignore = write (this->m_wakeFd, &one, sizeof (one));
- }
- }
- void PowerMonitor::run () {
- using Clock = std::chrono::steady_clock;
- auto& sources = *this->m_sources;
- bool lastBattery = this->m_onBattery;
- sources.systemBus = privateBus (DBUS_BUS_SYSTEM);
- if (const auto onBattery = sources.systemBus != nullptr ? upowerOnBattery (sources.systemBus) : std::nullopt;
- onBattery.has_value ()) {
- this->m_onBattery = *onBattery;
- } else {
- sources.upowerWorks = false;
- }
- #ifdef ENABLE_WAYLAND
- if (sources.display != nullptr) {
- sources.registry = wl_display_get_registry (sources.display);
- wl_registry_add_listener (sources.registry, ®istryListener, &sources);
- wl_display_roundtrip (sources.display);
- if (sources.seat == nullptr || sources.notifier == nullptr) {
- sLog.debug ("Power: compositor has no ext-idle-notify-v1");
- }
- }
- #endif
- auto nextBatteryCheck = Clock::now () + BATTERY_INTERVAL;
- #ifdef ENABLE_WAYLAND
- int appliedMinutes = 0;
- #endif
- while (!this->m_stop) {
- const auto now = Clock::now ();
- if (now >= nextBatteryCheck) {
- std::optional<bool> onBattery;
- if (sources.upowerWorks && sources.systemBus != nullptr) {
- onBattery = upowerOnBattery (sources.systemBus);
- }
- if (!onBattery.has_value ()) {
- onBattery = sysfsOnBattery ("/sys/class/power_supply");
- }
- this->m_onBattery = onBattery.value_or (false);
- nextBatteryCheck = now + BATTERY_INTERVAL;
- }
- if (this->m_onBattery != lastBattery) {
- lastBattery = this->m_onBattery;
- sLog.out ("Power: ", lastBattery ? "running on battery" : "on external power");
- }
- const int minutes = this->m_idleMinutes;
- bool waylandIdle = false;
- #ifdef ENABLE_WAYLAND
- waylandIdle = sources.display != nullptr && sources.seat != nullptr && sources.notifier != nullptr;
- if (waylandIdle && minutes != appliedMinutes) {
- if (sources.notification != nullptr) {
- ext_idle_notification_v1_destroy (sources.notification);
- sources.notification = nullptr;
- }
- this->m_idle = false;
- if (minutes > 0) {
- const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
- sources.notification = ext_idle_notifier_v1_get_idle_notification (
- sources.notifier, static_cast<uint32_t> (std::min<uint64_t> (timeout, UINT32_MAX)), sources.seat
- );
- ext_idle_notification_v1_add_listener (sources.notification, ¬ificationListener, &this->m_idle);
- }
- wl_display_flush (sources.display);
- }
- #endif
- auto wait = std::chrono::duration_cast<std::chrono::milliseconds> (nextBatteryCheck - Clock::now ());
- if (!waylandIdle && minutes > 0) {
- std::optional<uint64_t> idleMs;
- if (!sources.x11Tried) {
- sources.x11Tried = true;
- sources.x11 = std::make_unique<X11Idle> ();
- if (const char* session = std::getenv ("XDG_SESSION_TYPE");
- session == nullptr || std::string_view (session) != "x11" || !sources.x11->open ()) {
- sources.x11.reset ();
- }
- }
- if (sources.x11 != nullptr) {
- idleMs = sources.x11->idleMilliseconds ();
- }
- if (!idleMs.has_value () && sources.mutterWorks) {
- if (sources.sessionBus == nullptr) {
- sources.sessionBus = privateBus (DBUS_BUS_SESSION);
- }
- idleMs = sources.sessionBus != nullptr ? mutterIdleMilliseconds (sources.sessionBus) : std::nullopt;
- sources.mutterWorks = idleMs.has_value ();
- }
- if (idleMs.has_value ()) {
- const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
- this->m_idle = *idleMs >= timeout;
- const auto untilIdle = std::chrono::milliseconds (*idleMs >= timeout ? 0 : timeout - *idleMs);
- wait = std::min (wait, this->m_idle ? IDLE_POLL_ACTIVE : std::min (untilIdle, IDLE_POLL_MAX));
- } else if (!sources.loggedUnavailable) {
- sources.loggedUnavailable = true;
- sLog.error (
- "Power: --idle-pause has no idle source here (ext-idle-notify-v1, X11 screen saver or Mutter)"
- );
- }
- } else if (!waylandIdle) {
- this->m_idle = false;
- }
- #ifdef ENABLE_WAYLAND
- appliedMinutes = minutes;
- #endif
- pollfd fds[2] = {
- { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
- { .fd = -1, .events = POLLIN, .revents = 0 },
- };
- nfds_t count = 1;
- #ifdef ENABLE_WAYLAND
- if (sources.display != nullptr) {
- while (wl_display_prepare_read (sources.display) != 0) {
- wl_display_dispatch_pending (sources.display);
- }
- wl_display_flush (sources.display);
- fds[1].fd = wl_display_get_fd (sources.display);
- count = 2;
- }
- #endif
- poll (fds, count, static_cast<int> (std::max<int64_t> (0, wait.count ())));
- #ifdef ENABLE_WAYLAND
- if (sources.display != nullptr) {
- if (fds[1].revents & POLLIN) {
- wl_display_read_events (sources.display);
- } else {
- wl_display_cancel_read (sources.display);
- }
- if (fds[1].revents & (POLLERR | POLLHUP) || wl_display_dispatch_pending (sources.display) < 0) {
- sLog.error ("Power: lost the Wayland connection, idle detection stops");
- this->m_idle = false;
- sources.disconnectWayland ();
- }
- }
- #endif
- if (fds[0].revents & POLLIN) {
- uint64_t value;
- std::ignore = read (this->m_wakeFd, &value, sizeof (value));
- }
- }
- }
|