xdisplay_c.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdio.h> /* For fputs() */
  2. #include <stdlib.h> /* For atexit() */
  3. #include <X11/Xlib.h>
  4. static Display *mainDisplay = NULL;
  5. static int registered = 0;
  6. static char *displayName = NULL;
  7. static int hasDisplayNameChanged = 0;
  8. void XCloseMainDisplay(void) {
  9. if (mainDisplay != NULL) {
  10. XCloseDisplay(mainDisplay);
  11. mainDisplay = NULL;
  12. }
  13. }
  14. Display *XGetMainDisplay(void) {
  15. /* Close the display if displayName has changed */
  16. if (hasDisplayNameChanged) {
  17. XCloseMainDisplay();
  18. hasDisplayNameChanged = 0;
  19. }
  20. if (mainDisplay == NULL) {
  21. /* First try the user set displayName */
  22. mainDisplay = XOpenDisplay(displayName);
  23. /* Then try using environment variable DISPLAY */
  24. if (mainDisplay == NULL && displayName != NULL) {
  25. mainDisplay = XOpenDisplay(NULL);
  26. }
  27. /* Fall back to the most likely :0.0*/
  28. if (mainDisplay == NULL) {
  29. mainDisplay = XOpenDisplay(":0.0");
  30. }
  31. if (mainDisplay == NULL) {
  32. fputs("Could not open main display\n", stderr);
  33. } else if (!registered) {
  34. atexit(&XCloseMainDisplay);
  35. registered = 1;
  36. }
  37. }
  38. return mainDisplay;
  39. }
  40. void setXDisplay(char *name) {
  41. displayName = strdup(name);
  42. hasDisplayNameChanged = 1;
  43. }
  44. char *getXDisplay(void) {
  45. return displayName;
  46. }