]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
e3d1e761391589c1307e6f69f7af3ac3cb79f4a0
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010-2012 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 <xcb/xcb_keysyms.h>
18 #include <err.h>
19 #include <assert.h>
20 #include <security/pam_appl.h>
21 /* FIXME: can we get rid of this header? */
22 #include <X11/Xutil.h>
23 #include <X11/keysym.h>
24 #include <getopt.h>
25 #include <string.h>
26 #include <ev.h>
27 #include <sys/mman.h>
28
29
30 #ifndef NOLIBCAIRO
31 #include <cairo.h>
32 #include <cairo/cairo-xcb.h>
33 #endif
34
35 #include "keysym2ucs.h"
36 #include "ucs2_to_utf8.h"
37 #include "xcb.h"
38 #include "cursors.h"
39 #include "unlock_indicator.h"
40 #include "xinerama.h"
41
42 char color[7] = "ffffff";
43 uint32_t last_resolution[2];
44 xcb_window_t win;
45 static xcb_cursor_t cursor;
46 static xcb_key_symbols_t *symbols;
47 static pam_handle_t *pam_handle;
48 int input_position = 0;
49 /* Holds the password you enter (in UTF-8). */
50 static char password[512];
51 static bool modeswitch_active = false;
52 static bool iso_level3_shift_active = false;
53 static bool iso_level5_shift_active = false;
54 static int numlockmask;
55 static int shiftlockmask;
56 static int capslockmask;
57 static bool beep = false;
58 static bool debug_mode = false;
59 static bool dpms = false;
60 bool unlock_indicator = true;
61 static bool dont_fork = false;
62 struct ev_loop *main_loop;
63 static struct ev_timer *clear_pam_wrong_timeout;
64 extern unlock_state_t unlock_state;
65 extern pam_state_t pam_state;
66
67 #define DEBUG(fmt, ...) do { \
68     if (debug_mode) \
69         printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
70 } while (0)
71
72 #ifndef NOLIBCAIRO
73 cairo_surface_t *img = NULL;
74 bool tile = false;
75 #endif
76
77 /*
78  * Clears the memory which stored the password to be a bit safer against
79  * cold-boot attacks.
80  *
81  */
82 static void clear_password_memory() {
83     /* A volatile pointer to the password buffer to prevent the compiler from
84      * optimizing this out. */
85     volatile char *vpassword = password;
86     for (int c = 0; c < sizeof(password); c++)
87         /* We store a non-random pattern which consists of the (irrelevant)
88          * index plus (!) the value of the beep variable. This prevents the
89          * compiler from optimizing the calls away, since the value of 'beep'
90          * is not known at compile-time. */
91         vpassword[c] = c + (int)beep;
92 }
93
94
95 /*
96  * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
97  * authentication event.
98  *
99  */
100 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
101     DEBUG("clearing pam wrong\n");
102     pam_state = STATE_PAM_IDLE;
103     unlock_state = STATE_STARTED;
104     redraw_screen();
105
106     /* Now free this timeout. */
107     ev_timer_stop(main_loop, clear_pam_wrong_timeout);
108     free(clear_pam_wrong_timeout);
109     clear_pam_wrong_timeout = NULL;
110 }
111
112 static void input_done() {
113     if (input_position == 0)
114         return;
115
116     if (clear_pam_wrong_timeout) {
117         ev_timer_stop(main_loop, clear_pam_wrong_timeout);
118         free(clear_pam_wrong_timeout);
119         clear_pam_wrong_timeout = NULL;
120     }
121
122     pam_state = STATE_PAM_VERIFY;
123     redraw_screen();
124
125     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
126         printf("successfully authenticated\n");
127         clear_password_memory();
128         exit(0);
129     }
130
131     fprintf(stderr, "Authentication failure\n");
132
133     pam_state = STATE_PAM_WRONG;
134     redraw_screen();
135
136     /* Clear this state after 2 seconds (unless the user enters another
137      * password during that time). */
138     ev_now_update(main_loop);
139     if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
140         ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
141         ev_timer_start(main_loop, clear_pam_wrong_timeout);
142     }
143
144     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
145      * too early. */
146     stop_clear_indicator_timeout();
147
148     /* beep on authentication failure, if enabled */
149     if (beep) {
150         xcb_bell(conn, 100);
151         xcb_flush(conn);
152     }
153 }
154
155 /*
156  * Called when the user releases a key. We need to leave the Mode_switch
157  * state when the user releases the Mode_switch key.
158  *
159  */
160 static void handle_key_release(xcb_key_release_event_t *event) {
161     DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
162           event->detail, event->state, modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
163
164     /* We don’t care about the column here and just use the first symbol. Since
165      * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
166      * Also, if we would use the current column, we would look in the wrong
167      * place. */
168     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
169     if (sym == XK_Mode_switch) {
170         //printf("Mode switch disabled\n");
171         modeswitch_active = false;
172     } else if (sym == XK_ISO_Level3_Shift) {
173         iso_level3_shift_active = false;
174     } else if (sym == XK_ISO_Level5_Shift) {
175         iso_level5_shift_active = false;
176     }
177     DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
178           modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
179 }
180
181 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
182     redraw_screen();
183
184     ev_timer_stop(main_loop, w);
185     free(w);
186 }
187
188 /*
189  * Handle key presses. Fixes state, then looks up the key symbol for the
190  * given keycode, then looks up the key symbol (as UCS-2), converts it to
191  * UTF-8 and stores it in the password array.
192  *
193  */
194 static void handle_key_press(xcb_key_press_event_t *event) {
195     DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
196           event->detail, event->state, modeswitch_active, iso_level3_shift_active);
197
198     xcb_keysym_t sym0, sym1, sym;
199     /* For each keycode, there is a list of symbols. The list could look like this:
200      * $ xmodmap -pke | grep 'keycode  38'
201      * keycode  38 = a A adiaeresis Adiaeresis o O
202      * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
203      * with "a" on my keyboard) are "a A ä Ä o O".
204      * Another form to display the same information is using xkbcomp:
205      * $ xkbcomp $DISPLAY /tmp/xkb.dump
206      * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
207      *
208      * symbols[Group1]= [               a,               A,               o,               O ],
209      * symbols[Group2]= [      adiaeresis,      Adiaeresis ]
210      *
211      * So there are two *groups*, one containing 'a A' and one containing 'ä
212      * Ä'. You can use Mode_switch to switch between these groups. You can use
213      * ISO_Level3_Shift to reach the 'o O' part of the first group (it’s the
214      * same group, just an even higher shift level).
215      *
216      * So, using the "logical" XKB information, the following lookup will be
217      * performed:
218      *
219      * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
220      * Mode_switch active: group 2, column 0 and 1
221      * ISO_Level3_Shift active: group 1, column 2 and 3
222      *
223      * Using the column index which xcb_key_press_lookup_keysym uses (and
224      * xmodmap prints out), the following lookup will be performed:
225      *
226      * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
227      * Mode_switch active: column 2 and 3
228      * ISO_Level3_Shift active: column 4 and 5
229      */
230     int base_column = 0;
231     if (modeswitch_active)
232         base_column = 2;
233     if (iso_level3_shift_active)
234         base_column = 4;
235     if (iso_level5_shift_active)
236         base_column = 6;
237     sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
238     sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
239     switch (sym0) {
240     case XK_Mode_switch:
241         DEBUG("Mode switch enabled\n");
242         modeswitch_active = true;
243         return;
244     case XK_ISO_Level3_Shift:
245         DEBUG("ISO_Level3_Shift enabled\n");
246         iso_level3_shift_active = true;
247         return;
248     case XK_ISO_Level5_Shift:
249         DEBUG("ISO_Level5_Shift enabled\n");
250         iso_level5_shift_active = true;
251         return;
252     case XK_Return:
253     case XK_KP_Enter:
254         input_done();
255     case XK_Escape:
256         input_position = 0;
257         clear_password_memory();
258         password[input_position] = '\0';
259
260         /* Hide the unlock indicator after a bit if the password buffer is
261          * empty. */
262         start_clear_indicator_timeout();
263         unlock_state = STATE_BACKSPACE_ACTIVE;
264         redraw_screen();
265         unlock_state = STATE_KEY_PRESSED;
266         return;
267
268     case XK_BackSpace:
269         if (input_position == 0)
270             return;
271
272         /* decrement input_position to point to the previous glyph */
273         u8_dec(password, &input_position);
274         password[input_position] = '\0';
275
276         /* Hide the unlock indicator after a bit if the password buffer is
277          * empty. */
278         start_clear_indicator_timeout();
279         unlock_state = STATE_BACKSPACE_ACTIVE;
280         redraw_screen();
281         unlock_state = STATE_KEY_PRESSED;
282         return;
283     }
284
285     if ((input_position + 8) >= sizeof(password))
286         return;
287
288     /* Whether the user currently holds down the shift key. */
289     bool shift = (event->state & XCB_MOD_MASK_SHIFT);
290
291     /* Whether Caps Lock (all lowercase alphabetic keys will be replaced by
292      * their uppercase variant) is active at the moment. */
293     bool capslock = (event->state & capslockmask);
294
295     /* Whether Shift Lock (shift state is reversed) is active at the moment. */
296     bool shiftlock = (event->state & shiftlockmask);
297
298     /* Whether Caps Lock or Shift Lock is active at the moment. */
299     bool lock = (capslock || shiftlock);
300
301     DEBUG("shift = %d, lock = %d, capslock = %d, shiftlock = %d\n",
302           shift, lock, capslock, shiftlock);
303
304     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
305         /* this key was a keypad key */
306         if (shift || shiftlock)
307             sym = sym0;
308         else sym = sym1;
309     } else {
310         xcb_keysym_t upper, lower;
311         XConvertCase(sym0, (KeySym*)&lower, (KeySym*)&upper);
312         DEBUG("sym0 = %c (%d), sym1 = %c (%d), lower = %c (%d), upper = %c (%d)\n",
313               sym0, sym0, sym1, sym1, lower, lower, upper, upper);
314         /* If there is no difference between the uppercase and lowercase
315          * variant of this key, we consider Caps Lock off — it is only relevant
316          * for alphabetic keys, unlike Shift Lock. */
317         if (lower == upper) {
318             capslock = false;
319             lock = (capslock || shiftlock);
320             DEBUG("lower == upper, now shift = %d, lock = %d, capslock = %d, shiftlock = %d\n",
321                   shift, lock, capslock, shiftlock);
322         }
323
324         /* In two different cases we need to use the uppercase keysym:
325          * 1) The user holds shift, no lock is active.
326          * 2) Any of the two locks is active.
327          */
328         if ((shift && !lock) || (!shift && lock))
329             sym = sym1;
330         else sym = sym0;
331     }
332
333 #if 0
334     /* FIXME: handle all of these? */
335     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
336     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
337     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
338     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
339     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
340     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
341     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
342 #endif
343
344     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
345         return;
346
347     DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
348
349     /* convert the keysym to UCS */
350     uint16_t ucs = keysym2ucs(sym);
351     if ((int16_t)ucs == -1) {
352         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
353         return;
354     }
355
356     /* store the UCS in a string to convert it */
357     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
358     DEBUG("input part = %s\n", inp);
359
360     /* store it in the password array as UTF-8 */
361     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
362     password[input_position] = '\0';
363     DEBUG("current password = %s\n", password);
364
365     unlock_state = STATE_KEY_ACTIVE;
366     redraw_screen();
367     unlock_state = STATE_KEY_PRESSED;
368
369     struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
370     if (timeout) {
371         ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
372         ev_timer_start(main_loop, timeout);
373     }
374
375     stop_clear_indicator_timeout();
376 }
377
378 /*
379  * A visibility notify event will be received when the visibility (= can the
380  * user view the complete window) changes, so for example when a popup overlays
381  * some area of the i3lock window.
382  *
383  * In this case, we raise our window on top so that the popup (or whatever is
384  * hiding us) gets hidden.
385  *
386  */
387 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
388     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
389         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
390         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
391         xcb_flush(conn);
392     }
393 }
394
395 /*
396  * Called when the keyboard mapping changes. We update our symbols.
397  *
398  */
399 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
400     xcb_refresh_keyboard_mapping(symbols, event);
401
402     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
403 }
404
405 /*
406  * Called when the properties on the root window change, e.g. when the screen
407  * resolution changes. If so we update the window to cover the whole screen
408  * and also redraw the image, if any.
409  *
410  */
411 void handle_screen_resize() {
412     xcb_get_geometry_cookie_t geomc;
413     xcb_get_geometry_reply_t *geom;
414     geomc = xcb_get_geometry(conn, screen->root);
415     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
416         return;
417
418     if (last_resolution[0] == geom->width &&
419         last_resolution[1] == geom->height) {
420         free(geom);
421         return;
422     }
423
424     last_resolution[0] = geom->width;
425     last_resolution[1] = geom->height;
426
427     free(geom);
428
429 #ifndef NOLIBCAIRO
430     redraw_screen();
431 #endif
432
433     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
434     xcb_configure_window(conn, win, mask, last_resolution);
435     xcb_flush(conn);
436 }
437
438 /*
439  * Callback function for PAM. We only react on password request callbacks.
440  *
441  */
442 static int conv_callback(int num_msg, const struct pam_message **msg,
443                          struct pam_response **resp, void *appdata_ptr)
444 {
445     if (num_msg == 0)
446         return 1;
447
448     /* PAM expects an array of responses, one for each message */
449     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
450         perror("calloc");
451         return 1;
452     }
453
454     for (int c = 0; c < num_msg; c++) {
455         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
456             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
457             continue;
458
459         /* return code is currently not used but should be set to zero */
460         resp[c]->resp_retcode = 0;
461         if ((resp[c]->resp = strdup(password)) == NULL) {
462             perror("strdup");
463             return 1;
464         }
465     }
466
467     return 0;
468 }
469
470 /*
471  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
472  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
473  *
474  */
475 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
476     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
477 }
478
479 /*
480  * Flush before blocking (and waiting for new events)
481  *
482  */
483 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
484     xcb_flush(conn);
485 }
486
487 /*
488  * Instead of polling the X connection socket we leave this to
489  * xcb_poll_for_event() which knows better than we can ever know.
490  *
491  */
492 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
493     xcb_generic_event_t *event;
494
495     while ((event = xcb_poll_for_event(conn)) != NULL) {
496         if (event->response_type == 0) {
497             xcb_generic_error_t *error = (xcb_generic_error_t*)event;
498             fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
499                     error->sequence, error->error_code);
500             free(event);
501             continue;
502         }
503
504         /* Strip off the highest bit (set if the event is generated) */
505         int type = (event->response_type & 0x7F);
506         switch (type) {
507             case XCB_KEY_PRESS:
508                 handle_key_press((xcb_key_press_event_t*)event);
509                 break;
510
511             case XCB_KEY_RELEASE:
512                 handle_key_release((xcb_key_release_event_t*)event);
513
514                 /* If this was the backspace or escape key we are back at an
515                  * empty input, so turn off the screen if DPMS is enabled */
516                 if (dpms && input_position == 0)
517                     dpms_turn_off_screen(conn);
518
519                 break;
520
521             case XCB_VISIBILITY_NOTIFY:
522                 handle_visibility_notify((xcb_visibility_notify_event_t*)event);
523                 break;
524
525             case XCB_MAP_NOTIFY:
526                 if (!dont_fork) {
527                     /* After the first MapNotify, we never fork again. We don’t
528                      * expect to get another MapNotify, but better be sure… */
529                     dont_fork = true;
530
531                     /* In the parent process, we exit */
532                     if (fork() != 0)
533                         exit(0);
534                 }
535                 break;
536
537             case XCB_MAPPING_NOTIFY:
538                 handle_mapping_notify((xcb_mapping_notify_event_t*)event);
539                 break;
540
541             case XCB_CONFIGURE_NOTIFY:
542                 handle_screen_resize();
543                 break;
544         }
545
546         free(event);
547     }
548 }
549
550 int main(int argc, char *argv[]) {
551     char *username;
552 #ifndef NOLIBCAIRO
553     char *image_path = NULL;
554 #endif
555     int ret;
556     struct pam_conv conv = {conv_callback, NULL};
557     int nscreen;
558     int curs_choice = CURS_NONE;
559     char o;
560     int optind = 0;
561     struct option longopts[] = {
562         {"version", no_argument, NULL, 'v'},
563         {"nofork", no_argument, NULL, 'n'},
564         {"beep", no_argument, NULL, 'b'},
565         {"dpms", no_argument, NULL, 'd'},
566         {"color", required_argument, NULL, 'c'},
567         {"pointer", required_argument, NULL , 'p'},
568         {"debug", no_argument, NULL, 0},
569         {"help", no_argument, NULL, 'h'},
570         {"no-unlock-indicator", no_argument, NULL, 'u'},
571 #ifndef NOLIBCAIRO
572         {"image", required_argument, NULL, 'i'},
573         {"tiling", no_argument, NULL, 't'},
574 #endif
575         {NULL, no_argument, NULL, 0}
576     };
577
578     if ((username = getenv("USER")) == NULL)
579         errx(1, "USER environment variable not set, please set it.\n");
580
581     while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
582 #ifndef NOLIBCAIRO
583         "i:t"
584 #endif
585         , longopts, &optind)) != -1) {
586         switch (o) {
587         case 'v':
588             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
589         case 'n':
590             dont_fork = true;
591             break;
592         case 'b':
593             beep = true;
594             break;
595         case 'd':
596             dpms = true;
597             break;
598         case 'c': {
599             char *arg = optarg;
600
601             /* Skip # if present */
602             if (arg[0] == '#')
603                 arg++;
604
605             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
606                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
607
608             break;
609         }
610         case 'u':
611             unlock_indicator = false;
612             break;
613 #ifndef NOLIBCAIRO
614         case 'i':
615             image_path = strdup(optarg);
616             break;
617         case 't':
618             tile = true;
619             break;
620 #endif
621         case 'p':
622             if (!strcmp(optarg, "win")) {
623                 curs_choice = CURS_WIN;
624             } else if (!strcmp(optarg, "default")) {
625                 curs_choice = CURS_DEFAULT;
626             } else {
627                 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
628             }
629             break;
630         case 0:
631             if (strcmp(longopts[optind].name, "debug") == 0)
632                 debug_mode = true;
633             break;
634         default:
635             errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
636 #ifndef NOLIBCAIRO
637             " [-i image.png] [-t]"
638 #else
639             " (compiled with NOLIBCAIRO)"
640 #endif
641             );
642         }
643     }
644
645     /* We need (relatively) random numbers for highlighting a random part of
646      * the unlock indicator upon keypresses. */
647     srand(time(NULL));
648
649     /* Initialize PAM */
650     ret = pam_start("i3lock", username, &conv, &pam_handle);
651     if (ret != PAM_SUCCESS)
652         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
653
654     /* Lock the area where we store the password in memory, we don’t want it to
655      * be swapped to disk. Since Linux 2.6.9, this does not require any
656      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
657     if (mlock(password, sizeof(password)) != 0)
658         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
659
660     /* Initialize connection to X11 */
661     if ((conn = xcb_connect(NULL, &nscreen)) == NULL ||
662         xcb_connection_has_error(conn))
663         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
664
665     xinerama_init();
666     xinerama_query_screens();
667
668     /* if DPMS is enabled, check if the X server really supports it */
669     if (dpms) {
670         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
671         xcb_dpms_capable_reply_t *dpmsr;
672         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
673             if (!dpmsr->capable) {
674                 fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
675                 dpms = false;
676             }
677             free(dpmsr);
678         }
679     }
680
681     screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
682
683     last_resolution[0] = screen->width_in_pixels;
684     last_resolution[1] = screen->height_in_pixels;
685
686
687 #ifndef NOLIBCAIRO
688     if (image_path) {
689         /* Create a pixmap to render on, fill it with the background color */
690         img = cairo_image_surface_create_from_png(image_path);
691     }
692 #endif
693
694     /* Pixmap on which the image is rendered to (if any) */
695     xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
696
697     /* open the fullscreen window, already with the correct pixmap in place */
698     win = open_fullscreen_window(conn, screen, color, bg_pixmap);
699     xcb_free_pixmap(conn, bg_pixmap);
700
701     cursor = create_cursor(conn, screen, win, curs_choice);
702
703     grab_pointer_and_keyboard(conn, screen, cursor);
704
705     symbols = xcb_key_symbols_alloc(conn);
706     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
707     shiftlockmask = get_mod_mask(conn, symbols, XK_Shift_Lock);
708     capslockmask = get_mod_mask(conn, symbols, XK_Caps_Lock);
709
710     DEBUG("shift lock mask = %d\n", shiftlockmask);
711     DEBUG("caps lock mask = %d\n", capslockmask);
712
713     if (dpms)
714         dpms_turn_off_screen(conn);
715
716     /* Initialize the libev event loop. */
717     main_loop = EV_DEFAULT;
718     if (main_loop == NULL)
719         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
720
721     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
722     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
723     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
724
725     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
726     ev_io_start(main_loop, xcb_watcher);
727
728     ev_check_init(xcb_check, xcb_check_cb);
729     ev_check_start(main_loop, xcb_check);
730
731     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
732     ev_prepare_start(main_loop, xcb_prepare);
733
734     /* Invoke the event callback once to catch all the events which were
735      * received up until now. ev will only pick up new events (when the X11
736      * file descriptor becomes readable). */
737     ev_invoke(main_loop, xcb_check, 0);
738     ev_loop(main_loop, 0);
739 }