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