PowerMonitor.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #include "PowerMonitor.h"
  2. #include <algorithm>
  3. #include <chrono>
  4. #include <cstdint>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <dbus/dbus.h>
  8. #include <fstream>
  9. #include <poll.h>
  10. #include <string>
  11. #include <sys/eventfd.h>
  12. #include <unistd.h>
  13. #include "WallpaperEngine/Desktop/DlopenX11.h"
  14. #include "WallpaperEngine/Desktop/SessionBus.h"
  15. #include "WallpaperEngine/Logging/Log.h"
  16. #include "WallpaperEngine/Logging/ThreadGuard.h"
  17. #ifdef ENABLE_WAYLAND
  18. #include "WallpaperEngine/Desktop/HostWayland.h"
  19. #include "ext-idle-notify-v1-protocol.h"
  20. #include <wayland-client.h>
  21. #endif
  22. using namespace WallpaperEngine::Desktop;
  23. namespace {
  24. constexpr auto BATTERY_INTERVAL = std::chrono::seconds (5);
  25. constexpr auto IDLE_POLL_ACTIVE = std::chrono::milliseconds (250);
  26. constexpr auto IDLE_POLL_MAX = std::chrono::milliseconds (5000);
  27. std::string readLine (const std::filesystem::path& path) {
  28. std::ifstream file (path);
  29. std::string line;
  30. std::getline (file, line);
  31. return line;
  32. }
  33. // MIT-SCREEN-SAVER through dlopen, libXss isn't a build dependency
  34. struct ScreenSaverInfo {
  35. unsigned long window;
  36. int state;
  37. int kind;
  38. unsigned long tilOrSince;
  39. unsigned long idle;
  40. unsigned long eventMask;
  41. };
  42. class X11Idle {
  43. public:
  44. ~X11Idle () {
  45. if (this->m_info != nullptr) {
  46. this->m_free (this->m_info);
  47. }
  48. }
  49. bool open () {
  50. if (!this->m_x.load ("libXss.so.1")) {
  51. return false;
  52. }
  53. this->m_free = this->m_x.x11Symbol<int (*) (void*)> ("XFree");
  54. this->m_rootWindow = this->m_x.x11Symbol<unsigned long (*) (void*)> ("XDefaultRootWindow");
  55. auto queryExtension = this->m_x.extensionSymbol<int (*) (void*, int*, int*)> ("XScreenSaverQueryExtension");
  56. auto allocInfo = this->m_x.extensionSymbol<ScreenSaverInfo* (*)()> ("XScreenSaverAllocInfo");
  57. this->m_query
  58. = this->m_x.extensionSymbol<int (*) (void*, unsigned long, ScreenSaverInfo*)> ("XScreenSaverQueryInfo");
  59. if (this->m_free == nullptr || this->m_rootWindow == nullptr || queryExtension == nullptr
  60. || allocInfo == nullptr || this->m_query == nullptr) {
  61. return false;
  62. }
  63. if (!this->m_x.connect ()) {
  64. return false;
  65. }
  66. int eventBase = 0;
  67. int errorBase = 0;
  68. if (!queryExtension (this->m_x.display (), &eventBase, &errorBase)) {
  69. return false;
  70. }
  71. this->m_info = allocInfo ();
  72. return this->m_info != nullptr;
  73. }
  74. std::optional<uint64_t> idleMilliseconds () {
  75. void* display = this->m_x.display ();
  76. if (!this->m_query (display, this->m_rootWindow (display), this->m_info)) {
  77. return std::nullopt;
  78. }
  79. return this->m_info->idle;
  80. }
  81. private:
  82. DlopenX11 m_x;
  83. ScreenSaverInfo* m_info = nullptr;
  84. int (*m_free) (void*) = nullptr;
  85. unsigned long (*m_rootWindow) (void*) = nullptr;
  86. int (*m_query) (void*, unsigned long, ScreenSaverInfo*) = nullptr;
  87. };
  88. std::optional<bool> upowerOnBattery (DBusConnection* bus) {
  89. DBusMessage* reply
  90. = getProperty (bus, "org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "OnBattery");
  91. if (reply == nullptr) {
  92. return std::nullopt;
  93. }
  94. std::optional<bool> result;
  95. DBusMessageIter variant;
  96. if (propertyValue (reply, variant) && dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_BOOLEAN) {
  97. dbus_bool_t value = FALSE;
  98. dbus_message_iter_get_basic (&variant, &value);
  99. result = value != FALSE;
  100. }
  101. dbus_message_unref (reply);
  102. return result;
  103. }
  104. std::optional<uint64_t> mutterIdleMilliseconds (DBusConnection* bus) {
  105. DBusMessage* call = dbus_message_new_method_call (
  106. "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor",
  107. "GetIdletime"
  108. );
  109. std::string error;
  110. DBusMessage* reply = callBlocking (bus, call, error);
  111. if (reply == nullptr) {
  112. return std::nullopt;
  113. }
  114. dbus_uint64_t idle = 0;
  115. const bool ok = dbus_message_get_args (reply, nullptr, DBUS_TYPE_UINT64, &idle, DBUS_TYPE_INVALID);
  116. dbus_message_unref (reply);
  117. return ok ? std::optional<uint64_t> (idle) : std::nullopt;
  118. }
  119. }
  120. std::optional<bool> WallpaperEngine::Desktop::sysfsOnBattery (const std::filesystem::path& powerSupplies) {
  121. std::error_code error;
  122. bool anyBattery = false;
  123. bool discharging = false;
  124. bool externalPower = false;
  125. for (const auto& entry : std::filesystem::directory_iterator (powerSupplies, error)) {
  126. const auto& dir = entry.path ();
  127. // mice, headsets and controllers have scope Device
  128. if (readLine (dir / "scope") == "Device") {
  129. continue;
  130. }
  131. const std::string type = readLine (dir / "type");
  132. if (type == "Battery") {
  133. anyBattery = true;
  134. discharging = discharging || readLine (dir / "status") == "Discharging";
  135. } else if (readLine (dir / "online") == "1") {
  136. externalPower = true;
  137. }
  138. }
  139. if (!anyBattery) {
  140. return std::nullopt;
  141. }
  142. return discharging && !externalPower;
  143. }
  144. struct PowerMonitor::Sources {
  145. DBusConnection* systemBus = nullptr;
  146. DBusConnection* sessionBus = nullptr;
  147. bool upowerWorks = true;
  148. bool mutterWorks = true;
  149. std::unique_ptr<X11Idle> x11;
  150. bool x11Tried = false;
  151. bool loggedUnavailable = false;
  152. #ifdef ENABLE_WAYLAND
  153. wl_display* display = nullptr;
  154. wl_registry* registry = nullptr;
  155. wl_seat* seat = nullptr;
  156. ext_idle_notifier_v1* notifier = nullptr;
  157. ext_idle_notification_v1* notification = nullptr;
  158. #endif
  159. #ifdef ENABLE_WAYLAND
  160. void disconnectWayland () {
  161. if (this->notification != nullptr) {
  162. ext_idle_notification_v1_destroy (this->notification);
  163. }
  164. if (this->notifier != nullptr) {
  165. ext_idle_notifier_v1_destroy (this->notifier);
  166. }
  167. if (this->seat != nullptr) {
  168. wl_seat_destroy (this->seat);
  169. }
  170. if (this->registry != nullptr) {
  171. wl_registry_destroy (this->registry);
  172. }
  173. if (this->display != nullptr) {
  174. wl_display_disconnect (this->display);
  175. }
  176. this->notification = nullptr;
  177. this->notifier = nullptr;
  178. this->seat = nullptr;
  179. this->registry = nullptr;
  180. this->display = nullptr;
  181. }
  182. #endif
  183. ~Sources () {
  184. #ifdef ENABLE_WAYLAND
  185. this->disconnectWayland ();
  186. #endif
  187. closeBus (this->systemBus);
  188. closeBus (this->sessionBus);
  189. }
  190. };
  191. #ifdef ENABLE_WAYLAND
  192. namespace {
  193. void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t version) {
  194. auto* sources = static_cast<PowerMonitor::Sources*> (data);
  195. if (std::strcmp (interface, wl_seat_interface.name) == 0 && sources->seat == nullptr) {
  196. sources->seat = static_cast<wl_seat*> (wl_registry_bind (registry, name, &wl_seat_interface, 1));
  197. } else if (std::strcmp (interface, ext_idle_notifier_v1_interface.name) == 0) {
  198. sources->notifier = static_cast<ext_idle_notifier_v1*> (
  199. wl_registry_bind (registry, name, &ext_idle_notifier_v1_interface, 1)
  200. );
  201. }
  202. }
  203. void registryGlobalRemove (void*, wl_registry*, uint32_t) { }
  204. const wl_registry_listener registryListener = {
  205. .global = registryGlobal,
  206. .global_remove = registryGlobalRemove,
  207. };
  208. void notificationIdled (void* data, ext_idle_notification_v1*) { static_cast<std::atomic<bool>*> (data)->store (true); }
  209. void notificationResumed (void* data, ext_idle_notification_v1*) {
  210. static_cast<std::atomic<bool>*> (data)->store (false);
  211. }
  212. const ext_idle_notification_v1_listener notificationListener = {
  213. .idled = notificationIdled,
  214. .resumed = notificationResumed,
  215. };
  216. }
  217. #endif
  218. PowerMonitor::PowerMonitor () : m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (new Sources) {
  219. // UPower and the compositor are queried on the thread, sysfs answers until then
  220. this->m_onBattery = sysfsOnBattery ("/sys/class/power_supply").value_or (false);
  221. #ifdef ENABLE_WAYLAND
  222. // main thread: connectWayland picks the route to the compositor once (Flatpak helper)
  223. if (const char* session = std::getenv ("XDG_SESSION_TYPE");
  224. session != nullptr && std::string_view (session) == "wayland" && std::getenv ("WAYLAND_DISPLAY") != nullptr) {
  225. this->m_sources->display = connectWayland ();
  226. }
  227. #endif
  228. this->m_thread
  229. = std::thread ([this] { WallpaperEngine::Logging::guardThread ("Power monitor", [this] { this->run (); }); });
  230. }
  231. PowerMonitor::~PowerMonitor () {
  232. this->m_stop = true;
  233. this->wake ();
  234. if (this->m_thread.joinable ()) {
  235. this->m_thread.join ();
  236. }
  237. delete this->m_sources;
  238. if (this->m_wakeFd >= 0) {
  239. close (this->m_wakeFd);
  240. }
  241. }
  242. void PowerMonitor::setIdleTimeout (int minutes) {
  243. this->m_idleMinutes = std::max (0, minutes);
  244. this->wake ();
  245. }
  246. void PowerMonitor::wake () const {
  247. if (this->m_wakeFd >= 0) {
  248. const uint64_t one = 1;
  249. std::ignore = write (this->m_wakeFd, &one, sizeof (one));
  250. }
  251. }
  252. void PowerMonitor::run () {
  253. using Clock = std::chrono::steady_clock;
  254. auto& sources = *this->m_sources;
  255. bool lastBattery = this->m_onBattery;
  256. sources.systemBus = privateBus (DBUS_BUS_SYSTEM);
  257. if (const auto onBattery = sources.systemBus != nullptr ? upowerOnBattery (sources.systemBus) : std::nullopt;
  258. onBattery.has_value ()) {
  259. this->m_onBattery = *onBattery;
  260. } else {
  261. sources.upowerWorks = false;
  262. }
  263. #ifdef ENABLE_WAYLAND
  264. if (sources.display != nullptr) {
  265. sources.registry = wl_display_get_registry (sources.display);
  266. wl_registry_add_listener (sources.registry, &registryListener, &sources);
  267. wl_display_roundtrip (sources.display);
  268. if (sources.seat == nullptr || sources.notifier == nullptr) {
  269. sLog.debug ("Power: compositor has no ext-idle-notify-v1");
  270. }
  271. }
  272. #endif
  273. auto nextBatteryCheck = Clock::now () + BATTERY_INTERVAL;
  274. #ifdef ENABLE_WAYLAND
  275. int appliedMinutes = 0;
  276. #endif
  277. while (!this->m_stop) {
  278. const auto now = Clock::now ();
  279. if (now >= nextBatteryCheck) {
  280. std::optional<bool> onBattery;
  281. if (sources.upowerWorks && sources.systemBus != nullptr) {
  282. onBattery = upowerOnBattery (sources.systemBus);
  283. }
  284. if (!onBattery.has_value ()) {
  285. onBattery = sysfsOnBattery ("/sys/class/power_supply");
  286. }
  287. this->m_onBattery = onBattery.value_or (false);
  288. nextBatteryCheck = now + BATTERY_INTERVAL;
  289. }
  290. if (this->m_onBattery != lastBattery) {
  291. lastBattery = this->m_onBattery;
  292. sLog.out ("Power: ", lastBattery ? "running on battery" : "on external power");
  293. }
  294. const int minutes = this->m_idleMinutes;
  295. bool waylandIdle = false;
  296. #ifdef ENABLE_WAYLAND
  297. waylandIdle = sources.display != nullptr && sources.seat != nullptr && sources.notifier != nullptr;
  298. if (waylandIdle && minutes != appliedMinutes) {
  299. if (sources.notification != nullptr) {
  300. ext_idle_notification_v1_destroy (sources.notification);
  301. sources.notification = nullptr;
  302. }
  303. this->m_idle = false;
  304. if (minutes > 0) {
  305. const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
  306. sources.notification = ext_idle_notifier_v1_get_idle_notification (
  307. sources.notifier, static_cast<uint32_t> (std::min<uint64_t> (timeout, UINT32_MAX)), sources.seat
  308. );
  309. ext_idle_notification_v1_add_listener (sources.notification, &notificationListener, &this->m_idle);
  310. }
  311. wl_display_flush (sources.display);
  312. }
  313. #endif
  314. auto wait = std::chrono::duration_cast<std::chrono::milliseconds> (nextBatteryCheck - Clock::now ());
  315. if (!waylandIdle && minutes > 0) {
  316. std::optional<uint64_t> idleMs;
  317. if (!sources.x11Tried) {
  318. sources.x11Tried = true;
  319. sources.x11 = std::make_unique<X11Idle> ();
  320. if (const char* session = std::getenv ("XDG_SESSION_TYPE");
  321. session == nullptr || std::string_view (session) != "x11" || !sources.x11->open ()) {
  322. sources.x11.reset ();
  323. }
  324. }
  325. if (sources.x11 != nullptr) {
  326. idleMs = sources.x11->idleMilliseconds ();
  327. }
  328. if (!idleMs.has_value () && sources.mutterWorks) {
  329. if (sources.sessionBus == nullptr) {
  330. sources.sessionBus = privateBus (DBUS_BUS_SESSION);
  331. }
  332. idleMs = sources.sessionBus != nullptr ? mutterIdleMilliseconds (sources.sessionBus) : std::nullopt;
  333. sources.mutterWorks = idleMs.has_value ();
  334. }
  335. if (idleMs.has_value ()) {
  336. const uint64_t timeout = static_cast<uint64_t> (minutes) * 60000u;
  337. this->m_idle = *idleMs >= timeout;
  338. const auto untilIdle = std::chrono::milliseconds (*idleMs >= timeout ? 0 : timeout - *idleMs);
  339. wait = std::min (wait, this->m_idle ? IDLE_POLL_ACTIVE : std::min (untilIdle, IDLE_POLL_MAX));
  340. } else if (!sources.loggedUnavailable) {
  341. sources.loggedUnavailable = true;
  342. sLog.error (
  343. "Power: --idle-pause has no idle source here (ext-idle-notify-v1, X11 screen saver or Mutter)"
  344. );
  345. }
  346. } else if (!waylandIdle) {
  347. this->m_idle = false;
  348. }
  349. #ifdef ENABLE_WAYLAND
  350. appliedMinutes = minutes;
  351. #endif
  352. pollfd fds[2] = {
  353. { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
  354. { .fd = -1, .events = POLLIN, .revents = 0 },
  355. };
  356. nfds_t count = 1;
  357. #ifdef ENABLE_WAYLAND
  358. if (sources.display != nullptr) {
  359. while (wl_display_prepare_read (sources.display) != 0) {
  360. wl_display_dispatch_pending (sources.display);
  361. }
  362. wl_display_flush (sources.display);
  363. fds[1].fd = wl_display_get_fd (sources.display);
  364. count = 2;
  365. }
  366. #endif
  367. poll (fds, count, static_cast<int> (std::max<int64_t> (0, wait.count ())));
  368. #ifdef ENABLE_WAYLAND
  369. if (sources.display != nullptr) {
  370. if (fds[1].revents & POLLIN) {
  371. wl_display_read_events (sources.display);
  372. } else {
  373. wl_display_cancel_read (sources.display);
  374. }
  375. if (fds[1].revents & (POLLERR | POLLHUP) || wl_display_dispatch_pending (sources.display) < 0) {
  376. sLog.error ("Power: lost the Wayland connection, idle detection stops");
  377. this->m_idle = false;
  378. sources.disconnectWayland ();
  379. }
  380. }
  381. #endif
  382. if (fds[0].revents & POLLIN) {
  383. uint64_t value;
  384. std::ignore = read (this->m_wakeFd, &value, sizeof (value));
  385. }
  386. }
  387. }