SessionMonitor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. #include "SessionMonitor.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <chrono>
  5. #include <cstdint>
  6. #include <cstdlib>
  7. #include <cstring>
  8. #include <memory>
  9. #include <optional>
  10. #include <poll.h>
  11. #include <string>
  12. #include <string_view>
  13. #include <sys/eventfd.h>
  14. #include <sys/socket.h>
  15. #include <tuple>
  16. #include <unistd.h>
  17. #include "WallpaperEngine/Desktop/DlopenX11.h"
  18. #include "WallpaperEngine/Desktop/HyprlandIPC.h"
  19. #include "WallpaperEngine/Desktop/SessionBus.h"
  20. #include "WallpaperEngine/Logging/Log.h"
  21. #include "WallpaperEngine/Logging/ThreadGuard.h"
  22. #include "nlohmann/json.hpp"
  23. #if defined(ENABLE_WAYLAND) && defined(ENABLE_KDE_FEATURES)
  24. #define LWE_KWIN_DPMS 1
  25. #include <vector>
  26. #include <wayland-client.h>
  27. #include "WallpaperEngine/Desktop/HostWayland.h"
  28. #include "WallpaperEngine/Desktop/KDESession.h"
  29. #include "kwin-dpms-protocol.h"
  30. #endif
  31. using namespace WallpaperEngine::Desktop;
  32. namespace {
  33. // signals can be missed when a screen locker restarts, so the state is asked again now and then
  34. constexpr auto RECHECK_INTERVAL = std::chrono::seconds (30);
  35. constexpr int DPMS_POLL_MS = 1000;
  36. struct ScreenSaverName {
  37. const char* service;
  38. const char* path;
  39. const char* interface;
  40. };
  41. constexpr std::array SCREEN_SAVERS = {
  42. ScreenSaverName { "org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver" },
  43. ScreenSaverName { "org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver" },
  44. ScreenSaverName { "org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "org.gnome.ScreenSaver" },
  45. ScreenSaverName { "org.cinnamon.ScreenSaver", "/org/cinnamon/ScreenSaver", "org.cinnamon.ScreenSaver" },
  46. ScreenSaverName { "org.mate.ScreenSaver", "/org/mate/ScreenSaver", "org.mate.ScreenSaver" },
  47. };
  48. // DPMS through dlopen, libXext isn't a build dependency
  49. class X11Dpms {
  50. public:
  51. bool open () {
  52. if (!this->m_x.load ("libXext.so.6")) {
  53. return false;
  54. }
  55. auto queryExtension = this->m_x.extensionSymbol<int (*) (void*, int*, int*)> ("DPMSQueryExtension");
  56. auto capable = this->m_x.extensionSymbol<int (*) (void*)> ("DPMSCapable");
  57. this->m_info = this->m_x.extensionSymbol<int (*) (void*, unsigned short*, unsigned char*)> ("DPMSInfo");
  58. if (queryExtension == nullptr || capable == nullptr || this->m_info == nullptr) {
  59. return false;
  60. }
  61. if (!this->m_x.connect ()) {
  62. return false;
  63. }
  64. int eventBase = 0;
  65. int errorBase = 0;
  66. return queryExtension (this->m_x.display (), &eventBase, &errorBase) && capable (this->m_x.display ());
  67. }
  68. /** DPMS off, standby and suspend all mean a blank screen. Nothing when DPMS is not enabled on the server */
  69. std::optional<bool> blanked () {
  70. unsigned short level = 0;
  71. unsigned char enabled = 0;
  72. if (!this->m_info (this->m_x.display (), &level, &enabled)) {
  73. return std::nullopt;
  74. }
  75. return enabled != 0 && level != 0;
  76. }
  77. private:
  78. DlopenX11 m_x;
  79. int (*m_info) (void*, unsigned short*, unsigned char*) = nullptr;
  80. };
  81. #ifdef LWE_KWIN_DPMS
  82. // KWin's org_kde_kwin_dpms: the compositor tells the state of each output, nothing is ever requested (the protocol
  83. // has a set request). Other compositors don't offer the manager and the connection is dropped again
  84. class KWinDpms {
  85. public:
  86. explicit KWinDpms (wl_display* display) : m_display (display) { }
  87. ~KWinDpms () {
  88. this->m_outputs.clear ();
  89. if (this->m_manager != nullptr) {
  90. org_kde_kwin_dpms_manager_destroy (this->m_manager);
  91. }
  92. if (this->m_registry != nullptr) {
  93. wl_registry_destroy (this->m_registry);
  94. }
  95. wl_display_disconnect (this->m_display);
  96. }
  97. KWinDpms (const KWinDpms&) = delete;
  98. KWinDpms& operator= (const KWinDpms&) = delete;
  99. bool open () {
  100. this->m_registry = wl_display_get_registry (this->m_display);
  101. wl_registry_add_listener (this->m_registry, &registryListener, this);
  102. if (!this->roundtrip () || this->m_manager == nullptr) {
  103. return false;
  104. }
  105. for (const auto& output : this->m_outputs) {
  106. this->attach (*output);
  107. }
  108. return this->roundtrip ();
  109. }
  110. [[nodiscard]] int fd () const { return wl_display_get_fd (this->m_display); }
  111. [[nodiscard]] bool failed () const { return wl_display_get_error (this->m_display) != 0; }
  112. void beforePoll () {
  113. while (wl_display_prepare_read (this->m_display) != 0) {
  114. wl_display_dispatch_pending (this->m_display);
  115. }
  116. wl_display_flush (this->m_display);
  117. }
  118. void afterPoll (const bool readable) {
  119. if (readable) {
  120. wl_display_read_events (this->m_display);
  121. } else {
  122. wl_display_cancel_read (this->m_display);
  123. }
  124. wl_display_dispatch_pending (this->m_display);
  125. }
  126. [[nodiscard]] bool allOff () const {
  127. return !this->m_outputs.empty () && std::ranges::all_of (this->m_outputs, [] (const auto& output) {
  128. return output->mode != ORG_KDE_KWIN_DPMS_MODE_ON;
  129. });
  130. }
  131. private:
  132. static constexpr int ROUNDTRIP_MS = 2000;
  133. bool roundtrip () {
  134. bool done = false;
  135. wl_callback* callback = wl_display_sync (this->m_display);
  136. wl_callback_add_listener (callback, &syncListener, &done);
  137. const auto deadline = std::chrono::steady_clock::now () + std::chrono::milliseconds (ROUNDTRIP_MS);
  138. while (!done && !this->failed ()) {
  139. const auto left
  140. = std::chrono::duration_cast<std::chrono::milliseconds> (deadline - std::chrono::steady_clock::now ());
  141. if (left.count () <= 0) {
  142. break;
  143. }
  144. this->beforePoll ();
  145. pollfd pending = { .fd = this->fd (), .events = POLLIN, .revents = 0 };
  146. const int ready = poll (&pending, 1, static_cast<int> (left.count ()));
  147. this->afterPoll (ready > 0);
  148. }
  149. if (!done) {
  150. wl_callback_destroy (callback);
  151. }
  152. return done;
  153. }
  154. static void syncDone (void* data, wl_callback*, uint32_t) { *static_cast<bool*> (data) = true; }
  155. static constexpr wl_callback_listener syncListener = { .done = syncDone };
  156. struct Output {
  157. uint32_t name = 0;
  158. wl_output* output = nullptr;
  159. org_kde_kwin_dpms* dpms = nullptr;
  160. uint32_t mode = ORG_KDE_KWIN_DPMS_MODE_ON;
  161. ~Output () {
  162. if (this->dpms != nullptr) {
  163. org_kde_kwin_dpms_release (this->dpms);
  164. }
  165. if (this->output != nullptr) {
  166. wl_output_destroy (this->output);
  167. }
  168. }
  169. };
  170. void attach (Output& output) const {
  171. if (output.dpms == nullptr && this->m_manager != nullptr) {
  172. output.dpms = org_kde_kwin_dpms_manager_get (this->m_manager, output.output);
  173. org_kde_kwin_dpms_add_listener (output.dpms, &dpmsListener, &output);
  174. }
  175. }
  176. static void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t) {
  177. auto* self = static_cast<KWinDpms*> (data);
  178. if (std::strcmp (interface, org_kde_kwin_dpms_manager_interface.name) == 0) {
  179. self->m_manager = static_cast<org_kde_kwin_dpms_manager*> (
  180. wl_registry_bind (registry, name, &org_kde_kwin_dpms_manager_interface, 1)
  181. );
  182. } else if (std::strcmp (interface, wl_output_interface.name) == 0) {
  183. auto& output = self->m_outputs.emplace_back (std::make_unique<Output> ());
  184. output->name = name;
  185. output->output = static_cast<wl_output*> (wl_registry_bind (registry, name, &wl_output_interface, 1));
  186. self->attach (*output);
  187. }
  188. }
  189. static void registryGlobalRemove (void* data, wl_registry*, uint32_t name) {
  190. std::erase_if (static_cast<KWinDpms*> (data)->m_outputs, [name] (const auto& output) {
  191. return output->name == name;
  192. });
  193. }
  194. static void dpmsSupported (void*, org_kde_kwin_dpms*, uint32_t) { }
  195. static void dpmsMode (void* data, org_kde_kwin_dpms*, uint32_t mode) { static_cast<Output*> (data)->mode = mode; }
  196. static void dpmsDone (void*, org_kde_kwin_dpms*) { }
  197. static constexpr wl_registry_listener registryListener = {
  198. .global = registryGlobal,
  199. .global_remove = registryGlobalRemove,
  200. };
  201. static constexpr org_kde_kwin_dpms_listener dpmsListener = {
  202. .supported = dpmsSupported,
  203. .mode = dpmsMode,
  204. .done = dpmsDone,
  205. };
  206. wl_display* m_display;
  207. wl_registry* m_registry = nullptr;
  208. org_kde_kwin_dpms_manager* m_manager = nullptr;
  209. std::vector<std::unique_ptr<Output>> m_outputs;
  210. };
  211. #endif
  212. // sway and Hyprland blank an output without telling its clients (wlr-output-management still says enabled, and sway
  213. // keeps sending frame callbacks), but both list the power state of their outputs on the IPC socket. Only read, asked
  214. // once a second like an X server's DPMS
  215. class OutputPower {
  216. public:
  217. static std::unique_ptr<OutputPower> detect () {
  218. const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
  219. if (const char* sway = std::getenv ("SWAYSOCK"); sway != nullptr && *sway != '\0') {
  220. return std::unique_ptr<OutputPower> (new OutputPower (Kind::Sway, sway));
  221. }
  222. if (auto hypr = findHyprlandSocket (
  223. runtime != nullptr ? runtime : "", std::getenv ("HYPRLAND_INSTANCE_SIGNATURE"),
  224. std::getenv ("WAYLAND_DISPLAY"), std::getenv ("XDG_CURRENT_DESKTOP")
  225. );
  226. !hypr.empty ()) {
  227. return std::unique_ptr<OutputPower> (new OutputPower (Kind::Hyprland, hypr));
  228. }
  229. return nullptr;
  230. }
  231. [[nodiscard]] std::optional<bool> blanked () const {
  232. const auto reply
  233. = this->m_kind == Kind::Sway ? this->swayOutputs () : hyprlandRequest (this->m_path, "j/monitors");
  234. if (!reply.has_value ()) {
  235. return std::nullopt;
  236. }
  237. const auto outputs = nlohmann::json::parse (*reply, nullptr, false);
  238. if (!outputs.is_array ()) {
  239. return std::nullopt;
  240. }
  241. const char* key = this->m_kind == Kind::Sway ? "power" : "dpmsStatus";
  242. bool any = false;
  243. for (const auto& output : outputs) {
  244. if (!output.is_object ()) {
  245. return std::nullopt;
  246. }
  247. if (this->m_kind == Kind::Sway) {
  248. const auto active = output.find ("active");
  249. if (active != output.end () && !active->is_boolean ()) {
  250. return std::nullopt;
  251. }
  252. if (active == output.end () || !active->get<bool> ()) {
  253. continue;
  254. }
  255. }
  256. const auto state = output.find (key);
  257. if (state == output.end () || !state->is_boolean ()) {
  258. return std::nullopt;
  259. }
  260. if (state->get<bool> ()) {
  261. return false;
  262. }
  263. any = true;
  264. }
  265. return any;
  266. }
  267. private:
  268. enum class Kind { Sway, Hyprland };
  269. OutputPower (const Kind kind, std::string path) : m_kind (kind), m_path (std::move (path)) { }
  270. [[nodiscard]] std::optional<std::string> swayOutputs () const {
  271. const int fd = connectUnixSocket (this->m_path, 100000);
  272. if (fd < 0) {
  273. return std::nullopt;
  274. }
  275. std::optional<std::string> result;
  276. constexpr std::string_view MAGIC = "i3-ipc";
  277. char request[MAGIC.size () + 8] = {};
  278. const uint32_t type = 3;
  279. std::copy (MAGIC.begin (), MAGIC.end (), request);
  280. std::memcpy (request + MAGIC.size () + 4, &type, sizeof (type));
  281. char header[sizeof (request)];
  282. if (send (fd, request, sizeof (request), MSG_NOSIGNAL) == static_cast<ssize_t> (sizeof (request))
  283. && recvAll (fd, header, sizeof (header))) {
  284. uint32_t length = 0;
  285. std::memcpy (&length, header + MAGIC.size (), sizeof (length));
  286. // a monitor list is a few KB, anything near a megabyte is not one
  287. if (length < (1u << 20)) {
  288. std::string payload (length, '\0');
  289. if (recvAll (fd, payload.data (), length)) {
  290. result = std::move (payload);
  291. }
  292. }
  293. }
  294. close (fd);
  295. return result;
  296. }
  297. static bool recvAll (const int fd, char* data, const size_t size) {
  298. size_t done = 0;
  299. while (done < size) {
  300. const ssize_t got = recv (fd, data + done, size - done, 0);
  301. if (got <= 0) {
  302. return false;
  303. }
  304. done += static_cast<size_t> (got);
  305. }
  306. return true;
  307. }
  308. Kind m_kind;
  309. std::string m_path;
  310. };
  311. DBusMessage* methodCall (const char* service, const char* path, const char* interface, const char* method) {
  312. DBusMessage* call = dbus_message_new_method_call (service, path, interface, method);
  313. // asking must never start a screen saver the session doesn't run
  314. dbus_message_set_auto_start (call, FALSE);
  315. return call;
  316. }
  317. std::optional<bool> readBoolean (DBusMessage* reply) {
  318. DBusMessageIter iter;
  319. dbus_bool_t value = FALSE;
  320. if (!dbus_message_iter_init (reply, &iter)) {
  321. return std::nullopt;
  322. }
  323. if (dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_VARIANT) {
  324. DBusMessageIter variant;
  325. dbus_message_iter_recurse (&iter, &variant);
  326. if (dbus_message_iter_get_arg_type (&variant) != DBUS_TYPE_BOOLEAN) {
  327. return std::nullopt;
  328. }
  329. dbus_message_iter_get_basic (&variant, &value);
  330. return value != FALSE;
  331. }
  332. if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_BOOLEAN) {
  333. return std::nullopt;
  334. }
  335. dbus_message_iter_get_basic (&iter, &value);
  336. return value != FALSE;
  337. }
  338. std::optional<bool> screenSaverActive (DBusConnection* bus, const ScreenSaverName& name) {
  339. std::string error;
  340. DBusMessage* reply = callBlocking (bus, methodCall (name.service, name.path, name.interface, "GetActive"), error);
  341. if (reply == nullptr) {
  342. return std::nullopt;
  343. }
  344. const auto active = readBoolean (reply);
  345. dbus_message_unref (reply);
  346. return active;
  347. }
  348. std::string logindSessionPath (DBusConnection* bus) {
  349. const auto objectPath = [] (DBusMessage* reply) -> std::string {
  350. const char* path = nullptr;
  351. std::string result;
  352. if (reply != nullptr) {
  353. if (dbus_message_get_args (reply, nullptr, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID)) {
  354. result = path;
  355. }
  356. dbus_message_unref (reply);
  357. }
  358. return result;
  359. };
  360. std::string error;
  361. DBusMessage* byPid = methodCall (
  362. "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID"
  363. );
  364. const auto pid = static_cast<dbus_uint32_t> (getpid ());
  365. dbus_message_append_args (byPid, DBUS_TYPE_UINT32, &pid, DBUS_TYPE_INVALID);
  366. if (auto path = objectPath (callBlocking (bus, byPid, error)); !path.empty ()) {
  367. return path;
  368. }
  369. // a Flatpak's pid is not the one logind knows
  370. if (const char* id = std::getenv ("XDG_SESSION_ID"); id != nullptr && *id != '\0') {
  371. DBusMessage* byId = methodCall (
  372. "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSession"
  373. );
  374. dbus_message_append_args (byId, DBUS_TYPE_STRING, &id, DBUS_TYPE_INVALID);
  375. return objectPath (callBlocking (bus, byId, error));
  376. }
  377. return {};
  378. }
  379. std::optional<bool> logindLockedHint (DBusConnection* bus, const std::string& session) {
  380. DBusMessage* reply = getProperty (
  381. bus, "org.freedesktop.login1", session.c_str (), "org.freedesktop.login1.Session", "LockedHint", false
  382. );
  383. if (reply == nullptr) {
  384. return std::nullopt;
  385. }
  386. const auto hint = readBoolean (reply);
  387. dbus_message_unref (reply);
  388. return hint;
  389. }
  390. // 0 is on, 1 standby, 2 suspend, 3 off
  391. std::optional<bool> mutterDisplayOff (DBusConnection* bus) {
  392. DBusMessage* reply = getProperty (
  393. bus, "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig",
  394. "PowerSaveMode", false
  395. );
  396. if (reply == nullptr) {
  397. return std::nullopt;
  398. }
  399. std::optional<bool> off;
  400. DBusMessageIter variant;
  401. if (propertyValue (reply, variant) && dbus_message_iter_get_arg_type (&variant) == DBUS_TYPE_INT32) {
  402. dbus_int32_t mode = 0;
  403. dbus_message_iter_get_basic (&variant, &mode);
  404. off = mode > 0;
  405. }
  406. dbus_message_unref (reply);
  407. return off;
  408. }
  409. void addMatch (DBusConnection* bus, const std::string& rule) {
  410. DBusError error;
  411. dbus_error_init (&error);
  412. dbus_bus_add_match (bus, rule.c_str (), &error);
  413. if (dbus_error_is_set (&error)) {
  414. dbus_error_free (&error);
  415. }
  416. }
  417. }
  418. struct SessionMonitor::Sources {
  419. DBusConnection* systemBus = nullptr;
  420. DBusConnection* sessionBus = nullptr;
  421. std::string session;
  422. std::atomic<bool> changed = true;
  423. // the argument of the last ActiveChanged, -1 before the first one; a locker that doesn't answer GetActive still
  424. // sends it
  425. std::atomic<int> screenSaverSignal = -1;
  426. bool hint = false;
  427. bool screenSaver = false;
  428. std::unique_ptr<X11Dpms> dpms;
  429. std::unique_ptr<OutputPower> outputPower;
  430. bool outputsOff = false;
  431. std::chrono::steady_clock::time_point outputsChecked {};
  432. bool mutterOff = false;
  433. #ifdef LWE_KWIN_DPMS
  434. wl_display* kwinDisplay = nullptr;
  435. std::unique_ptr<KWinDpms> kwin;
  436. #endif
  437. };
  438. namespace {
  439. DBusHandlerResult noteSignal (DBusConnection*, DBusMessage* message, void* data) {
  440. auto& sources = *static_cast<SessionMonitor::Sources*> (data);
  441. if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) {
  442. return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
  443. }
  444. dbus_bool_t active = FALSE;
  445. if (dbus_message_is_signal (message, "org.freedesktop.ScreenSaver", "ActiveChanged")
  446. || dbus_message_is_signal (message, "org.gnome.ScreenSaver", "ActiveChanged")
  447. || dbus_message_is_signal (message, "org.cinnamon.ScreenSaver", "ActiveChanged")
  448. || dbus_message_is_signal (message, "org.mate.ScreenSaver", "ActiveChanged")) {
  449. if (dbus_message_get_args (message, nullptr, DBUS_TYPE_BOOLEAN, &active, DBUS_TYPE_INVALID)) {
  450. sources.screenSaverSignal = active != FALSE;
  451. }
  452. }
  453. sources.changed = true;
  454. return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
  455. }
  456. }
  457. SessionMonitor::SessionMonitor () :
  458. m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (std::make_unique<Sources> ()) {
  459. #ifdef LWE_KWIN_DPMS
  460. // main thread: connectWayland picks the route to the compositor once (Flatpak helper)
  461. if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type != nullptr && std::string_view (type) == "wayland"
  462. && std::getenv ("WAYLAND_DISPLAY") != nullptr && isKDESession ()) {
  463. this->m_sources->kwinDisplay = connectWayland ();
  464. }
  465. #endif
  466. try {
  467. this->m_thread = std::thread ([this] {
  468. WallpaperEngine::Logging::guardThread ("Session monitor", [this] { this->run (); });
  469. });
  470. } catch (...) {
  471. if (this->m_wakeFd >= 0) {
  472. close (this->m_wakeFd);
  473. }
  474. #ifdef LWE_KWIN_DPMS
  475. if (this->m_sources->kwinDisplay != nullptr) {
  476. wl_display_disconnect (this->m_sources->kwinDisplay);
  477. }
  478. #endif
  479. throw;
  480. }
  481. }
  482. SessionMonitor::~SessionMonitor () {
  483. this->m_stop = true;
  484. this->wake ();
  485. if (this->m_thread.joinable ()) {
  486. this->m_thread.join ();
  487. }
  488. closeBus (this->m_sources->systemBus);
  489. closeBus (this->m_sources->sessionBus);
  490. if (this->m_wakeFd >= 0) {
  491. close (this->m_wakeFd);
  492. }
  493. }
  494. void SessionMonitor::wake () const {
  495. if (this->m_wakeFd >= 0) {
  496. const uint64_t one = 1;
  497. std::ignore = write (this->m_wakeFd, &one, sizeof (one));
  498. }
  499. }
  500. void SessionMonitor::run () {
  501. auto& sources = *this->m_sources;
  502. sources.systemBus = privateBus (DBUS_BUS_SYSTEM);
  503. sources.sessionBus = privateBus (DBUS_BUS_SESSION);
  504. if (sources.systemBus != nullptr) {
  505. sources.session = logindSessionPath (sources.systemBus);
  506. if (!sources.session.empty ()) {
  507. addMatch (
  508. sources.systemBus,
  509. "type='signal',sender='org.freedesktop.login1',path='" + sources.session
  510. + "',interface='org.freedesktop.DBus.Properties'"
  511. );
  512. addMatch (
  513. sources.systemBus,
  514. "type='signal',sender='org.freedesktop.login1',path='" + sources.session
  515. + "',interface='org.freedesktop.login1.Session'"
  516. );
  517. dbus_connection_add_filter (sources.systemBus, noteSignal, &sources, nullptr);
  518. } else {
  519. sLog.debug ("Lock: no logind session, relying on the screen saver");
  520. }
  521. }
  522. if (sources.sessionBus != nullptr) {
  523. for (const auto& name : SCREEN_SAVERS) {
  524. addMatch (
  525. sources.sessionBus,
  526. std::string ("type='signal',interface='") + name.interface + "',member='ActiveChanged'"
  527. );
  528. }
  529. addMatch (
  530. sources.sessionBus,
  531. "type='signal',sender='org.gnome.Mutter.DisplayConfig',interface='org.freedesktop.DBus.Properties'"
  532. );
  533. dbus_connection_add_filter (sources.sessionBus, noteSignal, &sources, nullptr);
  534. }
  535. // an X server tells nothing by itself, it is asked once a second
  536. if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type == nullptr || std::string_view (type) == "x11") {
  537. sources.dpms = std::make_unique<X11Dpms> ();
  538. if (!sources.dpms->open ()) {
  539. sources.dpms.reset ();
  540. }
  541. }
  542. if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type != nullptr && std::string_view (type) == "wayland") {
  543. sources.outputPower = OutputPower::detect ();
  544. }
  545. #ifdef LWE_KWIN_DPMS
  546. if (sources.kwinDisplay != nullptr) {
  547. sources.kwin = std::make_unique<KWinDpms> (sources.kwinDisplay);
  548. sources.kwinDisplay = nullptr;
  549. if (!sources.kwin->open ()) {
  550. sLog.debug ("Display: no org_kde_kwin_dpms, relying on frame callbacks");
  551. sources.kwin.reset ();
  552. }
  553. }
  554. #endif
  555. auto nextRecheck = std::chrono::steady_clock::now ();
  556. while (!this->m_stop) {
  557. if (sources.changed.exchange (false) || std::chrono::steady_clock::now () >= nextRecheck) {
  558. nextRecheck = std::chrono::steady_clock::now () + RECHECK_INTERVAL;
  559. // a call that timed out says nothing, the state from before stays
  560. if (!sources.session.empty ()) {
  561. if (const auto hint = logindLockedHint (sources.systemBus, sources.session); hint.has_value ()) {
  562. sources.hint = *hint;
  563. }
  564. }
  565. std::optional<bool> active;
  566. bool saverOnBus = false;
  567. if (sources.sessionBus != nullptr) {
  568. for (const auto& name : SCREEN_SAVERS) {
  569. if (this->m_stop) {
  570. break;
  571. }
  572. saverOnBus = saverOnBus || dbus_bus_name_has_owner (sources.sessionBus, name.service, nullptr);
  573. if (const auto answer = screenSaverActive (sources.sessionBus, name); answer.has_value ()) {
  574. active = active.value_or (false) || *answer;
  575. }
  576. }
  577. }
  578. if (this->m_stop) {
  579. break;
  580. }
  581. // a locker that went away while locked never sends ActiveChanged(false)
  582. sources.screenSaver = active.value_or (saverOnBus && sources.screenSaverSignal == 1);
  583. if (sources.sessionBus != nullptr) {
  584. if (const auto off = mutterDisplayOff (sources.sessionBus); off.has_value ()) {
  585. sources.mutterOff = *off;
  586. }
  587. }
  588. const bool locked = sources.hint || sources.screenSaver;
  589. if (locked != this->m_locked) {
  590. this->m_locked = locked;
  591. sLog.out (
  592. "Lock: session ", locked ? "locked" : "unlocked", " (logind hint ", sources.hint ? "set" : "clear",
  593. ", screen saver ", sources.screenSaver ? "active" : "inactive", ")"
  594. );
  595. }
  596. }
  597. pollfd fds[4] = {
  598. { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
  599. { .fd = -1, .events = POLLIN, .revents = 0 },
  600. { .fd = -1, .events = POLLIN, .revents = 0 },
  601. { .fd = -1, .events = POLLIN, .revents = 0 },
  602. };
  603. // the blocking calls above read the socket and queue whatever else arrived, poll never sees that again
  604. bool queued = false;
  605. for (int i = 0; i < 2; i++) {
  606. DBusConnection* bus = i == 0 ? sources.systemBus : sources.sessionBus;
  607. if (bus != nullptr && dbus_connection_get_is_connected (bus)) {
  608. int fd = -1;
  609. dbus_connection_get_unix_fd (bus, &fd);
  610. fds[1 + i].fd = fd;
  611. queued = queued || dbus_connection_get_dispatch_status (bus) == DBUS_DISPATCH_DATA_REMAINS;
  612. }
  613. }
  614. bool displayOff = sources.mutterOff;
  615. if (sources.dpms != nullptr) {
  616. displayOff = displayOff || sources.dpms->blanked ().value_or (false);
  617. }
  618. if (sources.outputPower != nullptr) {
  619. const auto now = std::chrono::steady_clock::now ();
  620. if (now - sources.outputsChecked >= std::chrono::milliseconds (DPMS_POLL_MS)) {
  621. sources.outputsOff = sources.outputPower->blanked ().value_or (false);
  622. sources.outputsChecked = now;
  623. }
  624. displayOff = displayOff || sources.outputsOff;
  625. }
  626. #ifdef LWE_KWIN_DPMS
  627. if (sources.kwin != nullptr) {
  628. if (sources.kwin->failed ()) {
  629. sLog.debug ("Display: lost the Wayland connection used for KWin's DPMS state");
  630. sources.kwin.reset ();
  631. } else {
  632. displayOff = displayOff || sources.kwin->allOff ();
  633. sources.kwin->beforePoll ();
  634. fds[3].fd = sources.kwin->fd ();
  635. }
  636. }
  637. #endif
  638. if (displayOff != this->m_displayOff) {
  639. this->m_displayOff = displayOff;
  640. sLog.out ("Display: ", displayOff ? "blanked (DPMS)" : "on again");
  641. }
  642. auto untilRecheck
  643. = std::chrono::duration_cast<std::chrono::milliseconds> (nextRecheck - std::chrono::steady_clock::now ());
  644. if (sources.dpms != nullptr || sources.outputPower != nullptr) {
  645. untilRecheck = std::min (untilRecheck, std::chrono::milliseconds (DPMS_POLL_MS));
  646. }
  647. poll (fds, 4, queued ? 0 : static_cast<int> (std::max<int64_t> (1, untilRecheck.count ())));
  648. #ifdef LWE_KWIN_DPMS
  649. if (sources.kwin != nullptr) {
  650. sources.kwin->afterPoll ((fds[3].revents & POLLIN) != 0);
  651. }
  652. #endif
  653. if (fds[0].revents & POLLIN) {
  654. uint64_t value;
  655. std::ignore = read (this->m_wakeFd, &value, sizeof (value));
  656. }
  657. // unread messages count against the session bus quota, read them even when only the other bus spoke
  658. for (DBusConnection* bus : { sources.systemBus, sources.sessionBus }) {
  659. if (bus != nullptr) {
  660. drainBus (bus);
  661. }
  662. }
  663. }
  664. }