X11Output.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. #include "X11Output.h"
  2. #include "GLFWOutputViewport.h"
  3. #include "WallpaperEngine/Logging/Log.h"
  4. #include <algorithm>
  5. #include <cstdlib>
  6. #include <unistd.h>
  7. #include <X11/Xatom.h>
  8. #include <X11/Xlib.h>
  9. #include <X11/Xutil.h>
  10. #include <X11/extensions/Xrandr.h>
  11. #include <X11/extensions/shape.h>
  12. using namespace WallpaperEngine::Render::Drivers::Output;
  13. void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
  14. const auto context = static_cast<X11Output*> (userdata);
  15. sLog.debugerror ("Critical XServer error detected. Attempting to recover...");
  16. context->reset ();
  17. }
  18. int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
  19. sLog.debugerror ("Detected X error");
  20. return 0;
  21. }
  22. int CustomXIOErrorHandler (Display* dsp) {
  23. sLog.debugerror ("Detected X error");
  24. return 0;
  25. }
  26. X11Output::X11Output (ApplicationContext& context, VideoDriver& driver) :
  27. Output (context, driver), m_display (nullptr), m_pixmap (None), m_root (None), m_gc (None), m_imageData (nullptr),
  28. m_imageSize (0), m_image (nullptr) {
  29. // not chaining the previous handler: it could stop the app under weird circumstances
  30. XSetErrorHandler (CustomXErrorHandler);
  31. XSetIOErrorHandler (CustomXIOErrorHandler);
  32. this->loadScreenInfo ();
  33. }
  34. X11Output::~X11Output () { this->free (); }
  35. void X11Output::reset () {
  36. this->free ();
  37. this->loadScreenInfo ();
  38. // TODO: bring back resetting the fullscreen detector here
  39. }
  40. void X11Output::free () {
  41. // m_viewports holds non-owning aliases, m_screens owns the objects
  42. for (const auto& screen : this->m_screens) {
  43. delete screen;
  44. }
  45. this->m_screens.clear ();
  46. this->m_viewports.clear ();
  47. // XDestroyImage() frees m_imageData itself
  48. if (this->m_desktopWindow != None) {
  49. XDestroyWindow (this->m_display, this->m_desktopWindow);
  50. this->m_desktopWindow = None;
  51. this->m_desktopWindowMapped = false;
  52. }
  53. XDestroyImage (this->m_image);
  54. this->m_imageData = nullptr;
  55. XFreeGC (this->m_display, this->m_gc);
  56. XFreePixmap (this->m_display, this->m_pixmap);
  57. XCloseDisplay (this->m_display);
  58. }
  59. void* X11Output::getImageBuffer () const { return this->m_imageData; }
  60. bool X11Output::renderVFlip () const { return false; }
  61. bool X11Output::renderMultiple () const { return this->m_viewports.size () > 1; }
  62. bool X11Output::haveImageBuffer () const { return true; }
  63. uint32_t X11Output::getImageBufferSize () const { return this->m_imageSize; }
  64. void X11Output::loadScreenInfo () {
  65. this->m_display = XOpenDisplay (nullptr);
  66. // recover from X disconnections instead of aborting
  67. #ifdef HAVE_XSETIOERROREXITHANDLER
  68. XSetIOErrorExitHandler (this->m_display, CustomXIOErrorExitHandler, this);
  69. #endif /* HAVE_XSETIOERROREXITHANDLER */
  70. int xrandr_result, xrandr_error;
  71. if (!XRRQueryExtension (this->m_display, &xrandr_result, &xrandr_error)) {
  72. sLog.error ("XRandr is not present, cannot detect specified screens, running in window mode");
  73. return;
  74. }
  75. this->m_root = DefaultRootWindow (this->m_display);
  76. this->m_fullWidth = DisplayWidth (this->m_display, DefaultScreen (this->m_display));
  77. this->m_fullHeight = DisplayHeight (this->m_display, DefaultScreen (this->m_display));
  78. XRRScreenResources* screenResources = XRRGetScreenResources (this->m_display, DefaultRootWindow (this->m_display));
  79. if (screenResources == nullptr) {
  80. sLog.error ("Cannot detect screen sizes using xrandr, running in window mode");
  81. return;
  82. }
  83. discoverOutputs (screenResources);
  84. XRRFreeScreenResources (screenResources);
  85. validateOutputs ();
  86. initX11Background ();
  87. }
  88. void X11Output::discoverOutputs (XRRScreenResources* screenResources) {
  89. for (int i = 0; i < screenResources->noutput; i++) {
  90. const XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs[i]);
  91. if (info == nullptr || info->connection != RR_Connected) {
  92. continue;
  93. }
  94. XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc);
  95. if (crtc == nullptr) {
  96. continue;
  97. }
  98. bool inSpanGroup = false;
  99. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  100. for (const auto& screen : spanGroup.screens) {
  101. if (screen == info->name) {
  102. inSpanGroup = true;
  103. break;
  104. }
  105. }
  106. if (inSpanGroup) {
  107. break;
  108. }
  109. }
  110. if (inSpanGroup
  111. || this->m_context.settings.general.screenBackgrounds.find (info->name)
  112. != this->m_context.settings.general.screenBackgrounds.end ()) {
  113. sLog.out (
  114. "Found requested screen: ", info->name, " -> ", crtc->x, "x", crtc->y, ":", crtc->width, "x",
  115. crtc->height
  116. );
  117. auto* vp = new GLFWOutputViewport { { crtc->x, crtc->y, crtc->width, crtc->height }, info->name };
  118. vp->globalPosition = { crtc->x, crtc->y };
  119. vp->logicalSize = { crtc->width, crtc->height };
  120. this->m_screens.push_back (vp);
  121. this->m_viewports[info->name] = vp;
  122. }
  123. XRRFreeCrtcInfo (crtc);
  124. }
  125. }
  126. void X11Output::validateOutputs () const {
  127. bool any = false;
  128. for (const auto& o : this->m_screens) {
  129. const auto cur = this->m_context.settings.general.screenBackgrounds.find (o->name);
  130. if (cur != this->m_context.settings.general.screenBackgrounds.end ()) {
  131. any = true;
  132. break;
  133. }
  134. for (const auto& spanGroup : this->m_context.settings.general.spanGroups) {
  135. for (const auto& screen : spanGroup.screens) {
  136. if (screen == o->name) {
  137. any = true;
  138. break;
  139. }
  140. }
  141. if (any) {
  142. break;
  143. }
  144. }
  145. if (any) {
  146. break;
  147. }
  148. }
  149. if (!any) {
  150. sLog.error ("No outputs could be initialized, please check the parameters and try again");
  151. sLog.error ("Detected outputs:");
  152. for (const auto& o : this->m_screens) {
  153. sLog.error (" ", o->name);
  154. }
  155. sLog.error ("Requested: ");
  156. for (const auto& o : this->m_context.settings.general.screenBackgrounds | std::views::keys) {
  157. sLog.error (" ", o);
  158. }
  159. sLog.exception ("Cannot continue...");
  160. }
  161. }
  162. void X11Output::initX11Background () {
  163. this->m_pixmap = XCreatePixmap (this->m_display, this->m_root, this->m_fullWidth, this->m_fullHeight, 24);
  164. this->m_gc = XCreateGC (this->m_display, this->m_pixmap, 0, nullptr);
  165. XFillRectangle (this->m_display, this->m_pixmap, this->m_gc, 0, 0, this->m_fullWidth, this->m_fullHeight);
  166. XSetWindowBackgroundPixmap (this->m_display, this->m_root, this->m_pixmap);
  167. // XCreateImage() frees this with free(), so malloc() it
  168. this->m_imageSize = this->m_fullWidth * this->m_fullHeight * 4;
  169. this->m_imageData = static_cast<char*> (malloc (this->m_imageSize));
  170. this->m_image = XCreateImage (
  171. this->m_display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, this->m_fullWidth, this->m_fullHeight, 32, 0
  172. );
  173. this->m_driver.resizeWindow ({ this->m_fullWidth, this->m_fullHeight });
  174. }
  175. void X11Output::updateRender () const {
  176. XPutImage (
  177. this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, this->m_fullHeight
  178. );
  179. // _XROOTPMAP_ID/ESETROOT_PMAP_ID tell compositors about the background pixmap and force a refresh (picom)
  180. const Atom prop_root = XInternAtom (this->m_display, "_XROOTPMAP_ID", False);
  181. const Atom prop_esetroot = XInternAtom (this->m_display, "ESETROOT_PMAP_ID", False);
  182. XChangeProperty (
  183. this->m_display, this->m_root, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char*)&this->m_pixmap, 1
  184. );
  185. XChangeProperty (
  186. this->m_display, this->m_root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char*)&this->m_pixmap, 1
  187. );
  188. XClearWindow (this->m_display, this->m_root);
  189. this->updateDesktopWindow ();
  190. if (this->m_desktopWindowMapped) {
  191. XClearWindow (this->m_display, this->m_desktopWindow);
  192. }
  193. XFlush (this->m_display);
  194. }
  195. std::vector<Window> X11Output::stackingOrder () const {
  196. // bottom to top, the root's children without EWMH
  197. const Atom stackingAtom = XInternAtom (this->m_display, "_NET_CLIENT_LIST_STACKING", False);
  198. Atom type;
  199. int format;
  200. unsigned long count, remaining;
  201. unsigned char* data = nullptr;
  202. std::vector<Window> windows;
  203. if (XGetWindowProperty (
  204. this->m_display, this->m_root, stackingAtom, 0, 4096, False, XA_WINDOW, &type, &format, &count, &remaining,
  205. &data
  206. ) == Success
  207. && data != nullptr && format == 32) {
  208. const auto* list = reinterpret_cast<const Window*> (data);
  209. windows.assign (list, list + count);
  210. }
  211. if (data != nullptr) {
  212. XFree (data);
  213. }
  214. if (windows.empty ()) {
  215. Window rootReturn, parent;
  216. Window* children = nullptr;
  217. unsigned int childCount = 0;
  218. if (XQueryTree (this->m_display, this->m_root, &rootReturn, &parent, &children, &childCount)) {
  219. windows.assign (children, children + childCount);
  220. }
  221. if (children != nullptr) {
  222. XFree (children);
  223. }
  224. }
  225. return windows;
  226. }
  227. bool X11Output::isDesktopType (Window window) const {
  228. const Atom typeAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE", False);
  229. const Atom desktopAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
  230. Atom type;
  231. int format;
  232. unsigned long count, remaining;
  233. unsigned char* data = nullptr;
  234. bool desktop = false;
  235. if (XGetWindowProperty (
  236. this->m_display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data
  237. ) == Success
  238. && data != nullptr && format == 32) {
  239. const auto* atoms = reinterpret_cast<const Atom*> (data);
  240. desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
  241. }
  242. if (data != nullptr) {
  243. XFree (data);
  244. }
  245. return desktop;
  246. }
  247. Window X11Output::findCoveringDesktopWindow (const std::vector<Window>& stacking) const {
  248. for (const Window window : stacking) {
  249. if (window == this->m_desktopWindow || !this->isDesktopType (window)) {
  250. continue;
  251. }
  252. XWindowAttributes attributes;
  253. // 32 bit windows are translucent (nemo-desktop shows the root)
  254. if (!XGetWindowAttributes (this->m_display, window, &attributes) || attributes.map_state != IsViewable
  255. || attributes.depth == 32) {
  256. continue;
  257. }
  258. int x = 0, y = 0;
  259. Window child;
  260. XTranslateCoordinates (this->m_display, window, this->m_root, 0, 0, &x, &y, &child);
  261. const bool covers = std::ranges::any_of (this->m_screens, [&] (const OutputViewport* screen) {
  262. const auto& area = screen->viewport;
  263. return x <= area.x && y <= area.y && x + attributes.width >= area.x + area.z
  264. && y + attributes.height >= area.y + area.w;
  265. });
  266. if (covers) {
  267. return window;
  268. }
  269. }
  270. return None;
  271. }
  272. void X11Output::createDesktopWindow () const {
  273. // override redirect so no WM frame (xfwm4) eats the clicks, updateDesktopWindow () keeps the stacking
  274. XSetWindowAttributes attributes {};
  275. attributes.background_pixmap = this->m_pixmap;
  276. attributes.override_redirect = True;
  277. this->m_desktopWindow = XCreateWindow (
  278. this->m_display, this->m_root, 0, 0, this->m_fullWidth, this->m_fullHeight, 0, CopyFromParent, InputOutput,
  279. CopyFromParent, CWBackPixmap | CWOverrideRedirect, &attributes
  280. );
  281. const auto atom = [this] (const char* name) { return XInternAtom (this->m_display, name, False); };
  282. const Atom desktopType = atom ("_NET_WM_WINDOW_TYPE_DESKTOP");
  283. XChangeProperty (
  284. this->m_display, this->m_desktopWindow, atom ("_NET_WM_WINDOW_TYPE"), XA_ATOM, 32, PropModeReplace,
  285. reinterpret_cast<const unsigned char*> (&desktopType), 1
  286. );
  287. const Atom states[]
  288. = { atom ("_NET_WM_STATE_STICKY"), atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
  289. XChangeProperty (
  290. this->m_display, this->m_desktopWindow, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
  291. reinterpret_cast<const unsigned char*> (states), 3
  292. );
  293. const unsigned long allDesktops = 0xFFFFFFFF;
  294. XChangeProperty (
  295. this->m_display, this->m_desktopWindow, atom ("_NET_WM_DESKTOP"), XA_CARDINAL, 32, PropModeReplace,
  296. reinterpret_cast<const unsigned char*> (&allDesktops), 1
  297. );
  298. // 2 keeps compositors (xfwm4) from unredirecting it above every other window
  299. const unsigned long keepComposited = 2;
  300. XChangeProperty (
  301. this->m_display, this->m_desktopWindow, atom ("_NET_WM_BYPASS_COMPOSITOR"), XA_CARDINAL, 32, PropModeReplace,
  302. reinterpret_cast<const unsigned char*> (&keepComposited), 1
  303. );
  304. const unsigned long pid = getpid ();
  305. XChangeProperty (
  306. this->m_display, this->m_desktopWindow, atom ("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace,
  307. reinterpret_cast<const unsigned char*> (&pid), 1
  308. );
  309. char name[] = "linux-wallpaperengine";
  310. XClassHint classHint { name, name };
  311. XSetClassHint (this->m_display, this->m_desktopWindow, &classHint);
  312. XStoreName (this->m_display, this->m_desktopWindow, name);
  313. // empty input region, clicks reach their desktop window
  314. XShapeCombineRectangles (this->m_display, this->m_desktopWindow, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
  315. }
  316. Window X11Output::topLevelOf (Window window) const {
  317. Window rootReturn, parent, *children = nullptr;
  318. unsigned int count;
  319. while (XQueryTree (this->m_display, window, &rootReturn, &parent, &children, &count)) {
  320. if (children != nullptr) {
  321. XFree (children);
  322. children = nullptr;
  323. }
  324. if (parent == this->m_root || parent == None) {
  325. return window;
  326. }
  327. window = parent;
  328. }
  329. return window;
  330. }
  331. void X11Output::updateDesktopWindow () const {
  332. // root restacks and (un)maps may have moved windows around ours
  333. bool restacked = false;
  334. while (XPending (this->m_display)) {
  335. XEvent event;
  336. XNextEvent (this->m_display, &event);
  337. restacked |= event.type == ConfigureNotify || event.type == MapNotify || event.type == UnmapNotify
  338. || event.type == DestroyNotify;
  339. }
  340. const auto now = std::chrono::steady_clock::now ();
  341. // desktops can also (re)start their desktop window after us
  342. if (now < this->m_nextDesktopCheck && !restacked) {
  343. return;
  344. }
  345. this->m_nextDesktopCheck = now + std::chrono::seconds (2);
  346. const Window covering = this->findCoveringDesktopWindow (this->stackingOrder ());
  347. if (covering == None) {
  348. if (this->m_desktopWindowMapped) {
  349. XUnmapWindow (this->m_display, this->m_desktopWindow);
  350. this->m_desktopWindowMapped = false;
  351. sLog.out ("The desktop window covering the root window is gone, drawing into the root window again");
  352. }
  353. return;
  354. }
  355. if (this->m_desktopWindow == None) {
  356. this->createDesktopWindow ();
  357. XSelectInput (this->m_display, this->m_root, SubstructureNotifyMask);
  358. }
  359. if (!this->m_desktopWindowMapped) {
  360. XMapWindow (this->m_display, this->m_desktopWindow);
  361. this->m_desktopWindowMapped = true;
  362. sLog.out ("A desktop window covers the root window, drawing into a desktop window of our own above it");
  363. }
  364. // right above their desktop window's top level, below everything else
  365. const Window theirs = this->topLevelOf (covering);
  366. Window rootReturn, parent, *children = nullptr;
  367. unsigned int count = 0;
  368. bool inPlace = false;
  369. if (XQueryTree (this->m_display, this->m_root, &rootReturn, &parent, &children, &count)) {
  370. const Window* end = children + count;
  371. const Window* their = std::find (children, children + count, theirs);
  372. inPlace = their != end && their + 1 != end && *(their + 1) == this->m_desktopWindow;
  373. }
  374. if (children != nullptr) {
  375. XFree (children);
  376. }
  377. if (!inPlace) {
  378. XWindowChanges changes {};
  379. changes.sibling = theirs;
  380. changes.stack_mode = Above;
  381. XConfigureWindow (this->m_display, this->m_desktopWindow, CWSibling | CWStackMode, &changes);
  382. }
  383. }