You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

763 lines
23 KiB

15 years ago
12 years ago
  1. /*
  2. * vim:ts=4:sw=4:expandtab
  3. *
  4. * © 2010-2013 Michael Stapelberg
  5. *
  6. * See LICENSE for licensing information
  7. *
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <stdbool.h>
  14. #include <stdint.h>
  15. #include <xcb/xcb.h>
  16. #include <xcb/dpms.h>
  17. #include <err.h>
  18. #include <assert.h>
  19. #include <security/pam_appl.h>
  20. #include <X11/Xlib-xcb.h>
  21. #include <getopt.h>
  22. #include <string.h>
  23. #include <ev.h>
  24. #include <sys/mman.h>
  25. #include <sys/wait.h>
  26. #include <X11/XKBlib.h>
  27. #include <X11/extensions/XKBfile.h>
  28. #include <xkbcommon/xkbcommon.h>
  29. #include <cairo.h>
  30. #include <cairo/cairo-xcb.h>
  31. #include "i3lock.h"
  32. #include "xcb.h"
  33. #include "cursors.h"
  34. #include "unlock_indicator.h"
  35. #include "xinerama.h"
  36. /* We need this for libxkbfile */
  37. static Display *display;
  38. char color[7] = "ffffff";
  39. uint32_t last_resolution[2];
  40. xcb_window_t win;
  41. static xcb_cursor_t cursor;
  42. static pam_handle_t *pam_handle;
  43. int input_position = 0;
  44. /* Holds the password you enter (in UTF-8). */
  45. static char password[512];
  46. static bool beep = false;
  47. bool debug_mode = false;
  48. static bool dpms = false;
  49. bool unlock_indicator = true;
  50. static bool dont_fork = false;
  51. struct ev_loop *main_loop;
  52. static struct ev_timer *clear_pam_wrong_timeout;
  53. extern unlock_state_t unlock_state;
  54. extern pam_state_t pam_state;
  55. static struct xkb_state *xkb_state;
  56. static struct xkb_context *xkb_context;
  57. static struct xkb_keymap *xkb_keymap;
  58. cairo_surface_t *img = NULL;
  59. bool tile = false;
  60. bool ignore_empty_password = false;
  61. /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
  62. #define isutf(c) (((c) & 0xC0) != 0x80)
  63. /*
  64. * Decrements i to point to the previous unicode glyph
  65. *
  66. */
  67. void u8_dec(char *s, int *i) {
  68. (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
  69. }
  70. /*
  71. * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
  72. * Necessary so that we can properly let xkbcommon track the keyboard state and
  73. * translate keypresses to utf-8.
  74. *
  75. * Ideally, xkbcommon would ship something like this itself, but as of now
  76. * (version 0.2.0), it doesnt.
  77. *
  78. * TODO: Once xcb-xkb is enabled by default and released, we should port this
  79. * code to xcb-xkb. See also https://github.com/xkbcommon/libxkbcommon/issues/1
  80. *
  81. */
  82. static bool load_keymap(void) {
  83. bool ret = false;
  84. XkbFileInfo result;
  85. memset(&result, '\0', sizeof(result));
  86. result.xkb = XkbGetKeyboard(display, XkbAllMapComponentsMask, XkbUseCoreKbd);
  87. if (result.xkb == NULL) {
  88. fprintf(stderr, "[i3lock] XKB: XkbGetKeyboard failed\n");
  89. return false;
  90. }
  91. FILE *temp = tmpfile();
  92. if (temp == NULL) {
  93. fprintf(stderr, "[i3lock] could not create tempfile\n");
  94. return false;
  95. }
  96. bool ok = XkbWriteXKBKeymap(temp, &result, false, false, NULL, NULL);
  97. if (!ok) {
  98. fprintf(stderr, "[i3lock] XkbWriteXKBKeymap failed\n");
  99. goto out;
  100. }
  101. rewind(temp);
  102. if (xkb_context == NULL) {
  103. if ((xkb_context = xkb_context_new(0)) == NULL) {
  104. fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
  105. goto out;
  106. }
  107. }
  108. if (xkb_keymap != NULL)
  109. xkb_keymap_unref(xkb_keymap);
  110. if ((xkb_keymap = xkb_keymap_new_from_file(xkb_context, temp, XKB_KEYMAP_FORMAT_TEXT_V1, 0)) == NULL) {
  111. fprintf(stderr, "[i3lock] xkb_keymap_new_from_file failed\n");
  112. goto out;
  113. }
  114. struct xkb_state *new_state = xkb_state_new(xkb_keymap);
  115. if (new_state == NULL) {
  116. fprintf(stderr, "[i3lock] xkb_state_new failed\n");
  117. goto out;
  118. }
  119. /* Get the initial modifier state to be in sync with the X server.
  120. * See https://github.com/xkbcommon/libxkbcommon/issues/1 for why we ignore
  121. * the base and latched fields. */
  122. XkbStateRec state_rec;
  123. XkbGetState(display, XkbUseCoreKbd, &state_rec);
  124. xkb_state_update_mask(new_state,
  125. 0, 0, state_rec.locked_mods,
  126. 0, 0, state_rec.locked_group);
  127. if (xkb_state != NULL)
  128. xkb_state_unref(xkb_state);
  129. xkb_state = new_state;
  130. ret = true;
  131. out:
  132. XkbFreeKeyboard(result.xkb, XkbAllComponentsMask, true);
  133. fclose(temp);
  134. return ret;
  135. }
  136. /*
  137. * Clears the memory which stored the password to be a bit safer against
  138. * cold-boot attacks.
  139. *
  140. */
  141. static void clear_password_memory(void) {
  142. /* A volatile pointer to the password buffer to prevent the compiler from
  143. * optimizing this out. */
  144. volatile char *vpassword = password;
  145. for (int c = 0; c < sizeof(password); c++)
  146. /* We store a non-random pattern which consists of the (irrelevant)
  147. * index plus (!) the value of the beep variable. This prevents the
  148. * compiler from optimizing the calls away, since the value of 'beep'
  149. * is not known at compile-time. */
  150. vpassword[c] = c + (int)beep;
  151. }
  152. /*
  153. * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
  154. * authentication event.
  155. *
  156. */
  157. static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
  158. DEBUG("clearing pam wrong\n");
  159. pam_state = STATE_PAM_IDLE;
  160. unlock_state = STATE_STARTED;
  161. redraw_screen();
  162. /* Now free this timeout. */
  163. ev_timer_stop(main_loop, clear_pam_wrong_timeout);
  164. free(clear_pam_wrong_timeout);
  165. clear_pam_wrong_timeout = NULL;
  166. }
  167. static void clear_input(void) {
  168. input_position = 0;
  169. clear_password_memory();
  170. password[input_position] = '\0';
  171. /* Hide the unlock indicator after a bit if the password buffer is
  172. * empty. */
  173. start_clear_indicator_timeout();
  174. unlock_state = STATE_BACKSPACE_ACTIVE;
  175. redraw_screen();
  176. unlock_state = STATE_KEY_PRESSED;
  177. }
  178. static void auth_failed(void) {
  179. if (debug_mode)
  180. fprintf(stderr, "Authentication failure\n");
  181. pam_state = STATE_PAM_WRONG;
  182. clear_input();
  183. redraw_screen();
  184. /* Clear this state after 2 seconds (unless the user enters another
  185. * password during that time). */
  186. ev_now_update(main_loop);
  187. if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
  188. ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
  189. ev_timer_start(main_loop, clear_pam_wrong_timeout);
  190. }
  191. /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
  192. * too early. */
  193. stop_clear_indicator_timeout();
  194. /* beep on authentication failure, if enabled */
  195. if (beep) {
  196. xcb_bell(conn, 100);
  197. xcb_flush(conn);
  198. }
  199. }
  200. static void child_cb(EV_P_ ev_child *child_watcher, int revents) {
  201. if (child_watcher->rstatus != 0) {
  202. DEBUG("Authentication successfull\n");
  203. clear_password_memory();
  204. exit(0);
  205. } else {
  206. auth_failed();
  207. }
  208. ev_child_stop(main_loop, child_watcher);
  209. free(child_watcher);
  210. }
  211. static void input_done(void) {
  212. if (pam_state == STATE_PAM_VERIFY) {
  213. return;
  214. }
  215. if (clear_pam_wrong_timeout) {
  216. ev_timer_stop(main_loop, clear_pam_wrong_timeout);
  217. free(clear_pam_wrong_timeout);
  218. clear_pam_wrong_timeout = NULL;
  219. }
  220. pam_state = STATE_PAM_VERIFY;
  221. redraw_screen();
  222. /* fork to unblock pam_authenticate */
  223. pid_t cpid = fork();
  224. if (cpid == 0) {
  225. exit(pam_authenticate(pam_handle, 0) == PAM_SUCCESS);
  226. } else if (cpid > 0) {
  227. struct ev_child *child_watcher = calloc(sizeof(struct ev_io), 1);
  228. ev_child_init(child_watcher, child_cb, cpid, 0);
  229. ev_child_set(child_watcher, cpid, 0);
  230. ev_child_start(EV_DEFAULT_ child_watcher);
  231. } else if (cpid < 0) {
  232. DEBUG("Could not fork");
  233. if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
  234. DEBUG("successfully authenticated\n");
  235. clear_password_memory();
  236. exit(0);
  237. }
  238. auth_failed();
  239. }
  240. }
  241. /*
  242. * Called when the user releases a key. We need to leave the Mode_switch
  243. * state when the user releases the Mode_switch key.
  244. *
  245. */
  246. static void handle_key_release(xcb_key_release_event_t *event) {
  247. xkb_state_update_key(xkb_state, event->detail, XKB_KEY_UP);
  248. }
  249. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  250. redraw_screen();
  251. ev_timer_stop(main_loop, w);
  252. free(w);
  253. }
  254. /*
  255. * Handle key presses. Fixes state, then looks up the key symbol for the
  256. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  257. * UTF-8 and stores it in the password array.
  258. *
  259. */
  260. static void handle_key_press(xcb_key_press_event_t *event) {
  261. xkb_keysym_t ksym;
  262. char buffer[128];
  263. int n;
  264. bool ctrl;
  265. ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
  266. ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
  267. xkb_state_update_key(xkb_state, event->detail, XKB_KEY_DOWN);
  268. /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
  269. memset(buffer, '\0', sizeof(buffer));
  270. n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
  271. switch (ksym) {
  272. case XKB_KEY_Return:
  273. case XKB_KEY_KP_Enter:
  274. case XKB_KEY_XF86ScreenSaver:
  275. if (ignore_empty_password && input_position == 0) {
  276. clear_input();
  277. return;
  278. }
  279. password[input_position] = '\0';
  280. unlock_state = STATE_KEY_PRESSED;
  281. redraw_screen();
  282. input_done();
  283. return;
  284. case XKB_KEY_u:
  285. if (ctrl) {
  286. DEBUG("C-u pressed\n");
  287. clear_input();
  288. return;
  289. }
  290. break;
  291. case XKB_KEY_Escape:
  292. clear_input();
  293. return;
  294. case XKB_KEY_BackSpace:
  295. if (input_position == 0)
  296. return;
  297. /* decrement input_position to point to the previous glyph */
  298. u8_dec(password, &input_position);
  299. password[input_position] = '\0';
  300. /* Hide the unlock indicator after a bit if the password buffer is
  301. * empty. */
  302. start_clear_indicator_timeout();
  303. unlock_state = STATE_BACKSPACE_ACTIVE;
  304. redraw_screen();
  305. unlock_state = STATE_KEY_PRESSED;
  306. return;
  307. }
  308. if ((input_position + 8) >= sizeof(password))
  309. return;
  310. #if 0
  311. /* FIXME: handle all of these? */
  312. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  313. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  314. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  315. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  316. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  317. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  318. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  319. #endif
  320. if (n < 2)
  321. return;
  322. /* store it in the password array as UTF-8 */
  323. memcpy(password+input_position, buffer, n-1);
  324. input_position += n-1;
  325. DEBUG("current password = %.*s\n", input_position, password);
  326. unlock_state = STATE_KEY_ACTIVE;
  327. redraw_screen();
  328. unlock_state = STATE_KEY_PRESSED;
  329. struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
  330. if (timeout) {
  331. ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
  332. ev_timer_start(main_loop, timeout);
  333. }
  334. stop_clear_indicator_timeout();
  335. }
  336. /*
  337. * A visibility notify event will be received when the visibility (= can the
  338. * user view the complete window) changes, so for example when a popup overlays
  339. * some area of the i3lock window.
  340. *
  341. * In this case, we raise our window on top so that the popup (or whatever is
  342. * hiding us) gets hidden.
  343. *
  344. */
  345. static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
  346. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  347. uint32_t values[] = { XCB_STACK_MODE_ABOVE };
  348. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  349. xcb_flush(conn);
  350. }
  351. }
  352. /*
  353. * Called when the keyboard mapping changes. We update our symbols.
  354. *
  355. */
  356. static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
  357. /* We ignore errors — if the new keymap cannot be loaded it’s better if the
  358. * screen stays locked and the user intervenes by using killall i3lock. */
  359. (void)load_keymap();
  360. }
  361. /*
  362. * Called when the properties on the root window change, e.g. when the screen
  363. * resolution changes. If so we update the window to cover the whole screen
  364. * and also redraw the image, if any.
  365. *
  366. */
  367. void handle_screen_resize(void) {
  368. xcb_get_geometry_cookie_t geomc;
  369. xcb_get_geometry_reply_t *geom;
  370. geomc = xcb_get_geometry(conn, screen->root);
  371. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  372. return;
  373. if (last_resolution[0] == geom->width &&
  374. last_resolution[1] == geom->height) {
  375. free(geom);
  376. return;
  377. }
  378. last_resolution[0] = geom->width;
  379. last_resolution[1] = geom->height;
  380. free(geom);
  381. redraw_screen();
  382. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  383. xcb_configure_window(conn, win, mask, last_resolution);
  384. xcb_flush(conn);
  385. xinerama_query_screens();
  386. redraw_screen();
  387. }
  388. /*
  389. * Callback function for PAM. We only react on password request callbacks.
  390. *
  391. */
  392. static int conv_callback(int num_msg, const struct pam_message **msg,
  393. struct pam_response **resp, void *appdata_ptr)
  394. {
  395. if (num_msg == 0)
  396. return 1;
  397. /* PAM expects an array of responses, one for each message */
  398. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  399. perror("calloc");
  400. return 1;
  401. }
  402. for (int c = 0; c < num_msg; c++) {
  403. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  404. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  405. continue;
  406. /* return code is currently not used but should be set to zero */
  407. resp[c]->resp_retcode = 0;
  408. if ((resp[c]->resp = strdup(password)) == NULL) {
  409. perror("strdup");
  410. return 1;
  411. }
  412. }
  413. return 0;
  414. }
  415. /*
  416. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  417. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  418. *
  419. */
  420. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  421. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  422. }
  423. /*
  424. * Flush before blocking (and waiting for new events)
  425. *
  426. */
  427. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  428. xcb_flush(conn);
  429. }
  430. /*
  431. * Instead of polling the X connection socket we leave this to
  432. * xcb_poll_for_event() which knows better than we can ever know.
  433. *
  434. */
  435. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  436. xcb_generic_event_t *event;
  437. while ((event = xcb_poll_for_event(conn)) != NULL) {
  438. if (event->response_type == 0) {
  439. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  440. if (debug_mode)
  441. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  442. error->sequence, error->error_code);
  443. free(event);
  444. continue;
  445. }
  446. /* Strip off the highest bit (set if the event is generated) */
  447. int type = (event->response_type & 0x7F);
  448. switch (type) {
  449. case XCB_KEY_PRESS:
  450. handle_key_press((xcb_key_press_event_t*)event);
  451. break;
  452. case XCB_KEY_RELEASE:
  453. handle_key_release((xcb_key_release_event_t*)event);
  454. /* If this was the backspace or escape key we are back at an
  455. * empty input, so turn off the screen if DPMS is enabled */
  456. if (dpms && input_position == 0)
  457. dpms_turn_off_screen(conn);
  458. break;
  459. case XCB_VISIBILITY_NOTIFY:
  460. handle_visibility_notify((xcb_visibility_notify_event_t*)event);
  461. break;
  462. case XCB_MAP_NOTIFY:
  463. if (!dont_fork) {
  464. /* After the first MapNotify, we never fork again. We don’t
  465. * expect to get another MapNotify, but better be sure */
  466. dont_fork = true;
  467. /* In the parent process, we exit */
  468. if (fork() != 0)
  469. exit(0);
  470. ev_loop_fork(EV_DEFAULT);
  471. }
  472. break;
  473. case XCB_MAPPING_NOTIFY:
  474. handle_mapping_notify((xcb_mapping_notify_event_t*)event);
  475. break;
  476. case XCB_CONFIGURE_NOTIFY:
  477. handle_screen_resize();
  478. break;
  479. }
  480. free(event);
  481. }
  482. }
  483. int main(int argc, char *argv[]) {
  484. char *username;
  485. char *image_path = NULL;
  486. int ret;
  487. struct pam_conv conv = {conv_callback, NULL};
  488. int curs_choice = CURS_NONE;
  489. int o;
  490. int optind = 0;
  491. struct option longopts[] = {
  492. {"version", no_argument, NULL, 'v'},
  493. {"nofork", no_argument, NULL, 'n'},
  494. {"beep", no_argument, NULL, 'b'},
  495. {"dpms", no_argument, NULL, 'd'},
  496. {"color", required_argument, NULL, 'c'},
  497. {"pointer", required_argument, NULL , 'p'},
  498. {"debug", no_argument, NULL, 0},
  499. {"help", no_argument, NULL, 'h'},
  500. {"no-unlock-indicator", no_argument, NULL, 'u'},
  501. {"image", required_argument, NULL, 'i'},
  502. {"tiling", no_argument, NULL, 't'},
  503. {"ignore-empty-password", no_argument, NULL, 'e'},
  504. {NULL, no_argument, NULL, 0}
  505. };
  506. if ((username = getenv("USER")) == NULL)
  507. errx(1, "USER environment variable not set, please set it.\n");
  508. while ((o = getopt_long(argc, argv, "hvnbdc:p:ui:te", longopts, &optind)) != -1) {
  509. switch (o) {
  510. case 'v':
  511. errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
  512. case 'n':
  513. dont_fork = true;
  514. break;
  515. case 'b':
  516. beep = true;
  517. break;
  518. case 'd':
  519. dpms = true;
  520. break;
  521. case 'c': {
  522. char *arg = optarg;
  523. /* Skip # if present */
  524. if (arg[0] == '#')
  525. arg++;
  526. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  527. errx(1, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  528. break;
  529. }
  530. case 'u':
  531. unlock_indicator = false;
  532. break;
  533. case 'i':
  534. image_path = strdup(optarg);
  535. break;
  536. case 't':
  537. tile = true;
  538. break;
  539. case 'p':
  540. if (!strcmp(optarg, "win")) {
  541. curs_choice = CURS_WIN;
  542. } else if (!strcmp(optarg, "default")) {
  543. curs_choice = CURS_DEFAULT;
  544. } else {
  545. errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  546. }
  547. break;
  548. case 'e':
  549. ignore_empty_password = true;
  550. break;
  551. case 0:
  552. if (strcmp(longopts[optind].name, "debug") == 0)
  553. debug_mode = true;
  554. break;
  555. default:
  556. errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  557. " [-i image.png] [-t] [-e]"
  558. );
  559. }
  560. }
  561. /* We need (relatively) random numbers for highlighting a random part of
  562. * the unlock indicator upon keypresses. */
  563. srand(time(NULL));
  564. /* Initialize PAM */
  565. ret = pam_start("i3lock", username, &conv, &pam_handle);
  566. if (ret != PAM_SUCCESS)
  567. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  568. /* Using mlock() as non-super-user seems only possible in Linux. Users of other
  569. * operating systems should use encrypted swap/no swap (or remove the ifdef and
  570. * run i3lock as super-user). */
  571. #if defined(__linux__)
  572. /* Lock the area where we store the password in memory, we don’t want it to
  573. * be swapped to disk. Since Linux 2.6.9, this does not require any
  574. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  575. if (mlock(password, sizeof(password)) != 0)
  576. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  577. #endif
  578. /* Initialize connection to X11 */
  579. if ((display = XOpenDisplay(NULL)) == NULL)
  580. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  581. XSetEventQueueOwner(display, XCBOwnsEventQueue);
  582. conn = XGetXCBConnection(display);
  583. /* Double checking that connection is good and operatable with xcb */
  584. if (xcb_connection_has_error(conn))
  585. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  586. /* When we cannot initially load the keymap, we better exit */
  587. if (!load_keymap())
  588. errx(EXIT_FAILURE, "Could not load keymap");
  589. xinerama_init();
  590. xinerama_query_screens();
  591. /* if DPMS is enabled, check if the X server really supports it */
  592. if (dpms) {
  593. xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
  594. xcb_dpms_capable_reply_t *dpmsr;
  595. if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
  596. if (!dpmsr->capable) {
  597. if (debug_mode)
  598. fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
  599. dpms = false;
  600. }
  601. free(dpmsr);
  602. }
  603. }
  604. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  605. last_resolution[0] = screen->width_in_pixels;
  606. last_resolution[1] = screen->height_in_pixels;
  607. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  608. (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
  609. if (image_path) {
  610. /* Create a pixmap to render on, fill it with the background color */
  611. img = cairo_image_surface_create_from_png(image_path);
  612. /* In case loading failed, we just pretend no -i was specified. */
  613. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  614. fprintf(stderr, "Could not load image \"%s\": %s\n",
  615. image_path, cairo_status_to_string(cairo_surface_status(img)));
  616. img = NULL;
  617. }
  618. }
  619. /* Pixmap on which the image is rendered to (if any) */
  620. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  621. /* open the fullscreen window, already with the correct pixmap in place */
  622. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  623. xcb_free_pixmap(conn, bg_pixmap);
  624. cursor = create_cursor(conn, screen, win, curs_choice);
  625. grab_pointer_and_keyboard(conn, screen, cursor);
  626. /* Load the keymap again to sync the current modifier state. Since we first
  627. * loaded the keymap, there might have been changes, but starting from now,
  628. * we should get all key presses/releases due to having grabbed the
  629. * keyboard. */
  630. (void)load_keymap();
  631. if (dpms)
  632. dpms_turn_off_screen(conn);
  633. /* Initialize the libev event loop. */
  634. main_loop = EV_DEFAULT;
  635. if (main_loop == NULL)
  636. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  637. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  638. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  639. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  640. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  641. ev_io_start(main_loop, xcb_watcher);
  642. ev_check_init(xcb_check, xcb_check_cb);
  643. ev_check_start(main_loop, xcb_check);
  644. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  645. ev_prepare_start(main_loop, xcb_prepare);
  646. /* Invoke the event callback once to catch all the events which were
  647. * received up until now. ev will only pick up new events (when the X11
  648. * file descriptor becomes readable). */
  649. ev_invoke(main_loop, xcb_check, 0);
  650. ev_loop(main_loop, 0);
  651. }