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