]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
d236adfcac2b4f378643be98a261f9230dd30237
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010-2011 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/keysym.h>
23 #include <getopt.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ev.h>
27
28
29 #ifndef NOLIBCAIRO
30 #include <cairo.h>
31 #include <cairo/cairo-xcb.h>
32 #endif
33
34 #include "keysym2ucs.h"
35 #include "ucs2_to_utf8.h"
36 #include "xcb.h"
37 #include "cursors.h"
38
39 #define BUTTON_RADIUS 90
40 #define BUTTON_SPACE (BUTTON_RADIUS + 5)
41 #define BUTTON_CENTER (BUTTON_RADIUS + 5)
42 #define BUTTON_DIAMETER (5 * BUTTON_SPACE)
43
44 static char color[7] = "ffffff";
45 static uint32_t last_resolution[2];
46 static xcb_connection_t *conn;
47 static xcb_window_t win;
48 static xcb_visualtype_t *vistype;
49 static xcb_cursor_t cursor;
50 static xcb_key_symbols_t *symbols;
51 static xcb_screen_t *scr;
52 static pam_handle_t *pam_handle;
53 static int input_position = 0;
54 /* holds the password you enter (in UTF-8) */
55 static char password[512];
56 static bool modeswitch_active = false;
57 static bool iso_level3_shift_active = false;
58 static bool iso_level5_shift_active = false;
59 static int modeswitchmask;
60 static int numlockmask;
61 static bool beep = false;
62 static bool debug_mode = false;
63 static bool dpms = false;
64 static bool unlock_indicator = true;
65 static struct ev_loop *main_loop;
66 static struct ev_timer *clear_pam_wrong_timeout;
67 static struct ev_timer *clear_indicator_timeout;
68
69 static enum {
70     STATE_STARTED = 0,          /* default state */
71     STATE_KEY_PRESSED = 1,      /* key was pressed, show unlock indicator */
72     STATE_KEY_ACTIVE = 2,       /* a key was pressed recently, highlight part
73                                    of the unlock indicator. */
74     STATE_BACKSPACE_ACTIVE = 3  /* backspace was pressed recently, highlight
75                                    part of the unlock indicator in red. */
76 } unlock_state;
77
78 static enum {
79     STATE_PAM_IDLE = 0,         /* no PAM interaction at the moment */
80     STATE_PAM_VERIFY = 1,       /* currently verifying the password via PAM */
81     STATE_PAM_WRONG = 2         /* the password was wrong */
82 } pam_state;
83
84 #define DEBUG(fmt, ...) do { \
85     if (debug_mode) \
86         printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
87 } while (0)
88
89 #ifndef NOLIBCAIRO
90 static cairo_surface_t *img = NULL;
91 static bool tile = false;
92 #endif
93
94 /*
95  * Draws global image with fill color onto a pixmap with the given
96  * resolution and returns it.
97  *
98  */
99 static xcb_pixmap_t draw_image(xcb_visualtype_t *vistype, u_int32_t* resolution) {
100     xcb_pixmap_t bg_pixmap = XCB_NONE;
101
102 #ifndef NOLIBCAIRO
103     bg_pixmap = create_bg_pixmap(conn, scr, resolution, color);
104     /* Initialize cairo */
105     cairo_surface_t *output;
106     output = cairo_xcb_surface_create(conn, bg_pixmap, vistype,
107              resolution[0], resolution[1]);
108     cairo_t *ctx = cairo_create(output);
109     if (img) {
110         if (!tile) {
111             cairo_set_source_surface(ctx, img, 0, 0);
112             cairo_paint(ctx);
113         } else {
114             /* create a pattern and fill a rectangle as big as the screen */
115             cairo_pattern_t *pattern;
116             pattern = cairo_pattern_create_for_surface(img);
117             cairo_set_source(ctx, pattern);
118             cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
119             cairo_rectangle(ctx, 0, 0, resolution[0], resolution[1]);
120             cairo_fill(ctx);
121             cairo_pattern_destroy(pattern);
122         }
123     }
124
125     if (unlock_state >= STATE_KEY_PRESSED && unlock_indicator) {
126         cairo_pattern_t *outer_pat = NULL;
127
128         outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
129         switch (pam_state) {
130             case STATE_PAM_VERIFY:
131                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 0, 250.0/255);
132                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 0, 250.0/255);
133                 break;
134             case STATE_PAM_WRONG:
135                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 255.0/250, 139.0/255, 0);
136                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 125.0/255, 51.0/255, 0);
137                 break;
138             case STATE_PAM_IDLE:
139                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 125.0/255, 0);
140                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 125.0/255, 0);
141                 break;
142         }
143
144         /* Draw a (centered) circle with transparent background. */
145         cairo_set_line_width(ctx, 10.0);
146         cairo_arc(ctx,
147                   (resolution[0] / 2) /* x */,
148                   (resolution[1] / 2) /* y */,
149                   BUTTON_RADIUS /* radius */,
150                   0 /* start */,
151                   2 * M_PI /* end */);
152
153         /* Use the appropriate color for the different PAM states
154          * (currently verifying, wrong password, or default) */
155         switch (pam_state) {
156             case STATE_PAM_VERIFY:
157                 cairo_set_source_rgba(ctx, 0, 114.0/255, 255.0/255, 0.75);
158                 break;
159             case STATE_PAM_WRONG:
160                 cairo_set_source_rgba(ctx, 250.0/255, 0, 0, 0.75);
161                 break;
162             default:
163                 cairo_set_source_rgba(ctx, 0, 0, 0, 0.75);
164                 break;
165         }
166         cairo_fill_preserve(ctx);
167         cairo_set_source(ctx, outer_pat);
168         cairo_stroke(ctx);
169
170         /* Draw an inner seperator line. */
171         cairo_set_source_rgb(ctx, 0, 0, 0);
172         cairo_set_line_width(ctx, 2.0);
173         cairo_arc(ctx,
174                   (resolution[0] / 2) /* x */,
175                   (resolution[1] / 2) /* y */,
176                   BUTTON_RADIUS - 5 /* radius */,
177                   0,
178                   2 * M_PI);
179         cairo_stroke(ctx);
180
181         cairo_set_line_width(ctx, 10.0);
182
183         /* Display a (centered) text of the current PAM state. */
184         char *text = NULL;
185         switch (pam_state) {
186             case STATE_PAM_VERIFY:
187                 text = "verifying…";
188                 break;
189             case STATE_PAM_WRONG:
190                 text = "wrong!";
191                 break;
192             default:
193                 break;
194         }
195
196         if (text) {
197             cairo_text_extents_t extents;
198             double x, y;
199
200             cairo_set_source_rgb(ctx, 0, 0, 0);
201             cairo_set_font_size(ctx, 28.0);
202
203             cairo_text_extents(ctx, text, &extents);
204             x = (resolution[0] / 2.0) - ((extents.width / 2) + extents.x_bearing);
205             y = (resolution[1] / 2.0) - ((extents.height / 2) + extents.y_bearing);
206
207             cairo_move_to(ctx, x, y);
208             cairo_show_text(ctx, text);
209             cairo_close_path(ctx);
210         }
211
212         /* After the user pressed any valid key or the backspace key, we
213          * highlight a random part of the unlock indicator to confirm this
214          * keypress. */
215         if (unlock_state == STATE_KEY_ACTIVE ||
216             unlock_state == STATE_BACKSPACE_ACTIVE) {
217             cairo_new_sub_path(ctx);
218             double highlight_start = (rand() % (int)(2 * M_PI * 100)) / 100.0;
219             DEBUG("Highlighting part %.2f\n", highlight_start);
220             cairo_arc(ctx, resolution[0] / 2 /* x */, resolution[1] / 2 /* y */,
221                       BUTTON_RADIUS /* radius */, highlight_start,
222                       highlight_start + (M_PI / 3.0));
223             if (unlock_state == STATE_KEY_ACTIVE) {
224                 /* For normal keys, we use a lighter green. */
225                 outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
226                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 219.0/255, 0);
227                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 219.0/255, 0);
228             } else {
229                 /* For backspace, we use red. */
230                 outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
231                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 219.0/255, 139.0/255, 0);
232                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 219.0/255, 51.0/255, 0);
233             }
234             cairo_set_source(ctx, outer_pat);
235             cairo_stroke(ctx);
236
237             /* Draw two little separators for the highlighted part of the
238              * unlock indicator. */
239             cairo_set_source_rgb(ctx, 0, 0, 0);
240             cairo_arc(ctx,
241                       (resolution[0] / 2) /* x */,
242                       (resolution[1] / 2) /* y */,
243                       BUTTON_RADIUS /* radius */,
244                       highlight_start /* start */,
245                       highlight_start + (M_PI / 128.0) /* end */);
246             cairo_stroke(ctx);
247             cairo_arc(ctx,
248                       (resolution[0] / 2) /* x */,
249                       (resolution[1] / 2) /* y */,
250                       BUTTON_RADIUS /* radius */,
251                       highlight_start + (M_PI / 3.0) /* start */,
252                       (highlight_start + (M_PI / 3.0)) + (M_PI / 128.0) /* end */);
253             cairo_stroke(ctx);
254         }
255     }
256
257     cairo_surface_destroy(output);
258     cairo_destroy(ctx);
259 #endif
260     return bg_pixmap;
261 }
262
263 /*
264  * Calls draw_image on a new pixmap and swaps that with the current pixmap
265  *
266  */
267 static void redraw_screen() {
268     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
269     xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
270     /* XXX: Possible optimization: Only update the area in the middle of the
271      * screen instead of the whole screen. */
272     xcb_clear_area(conn, 0, win, 0, 0, scr->width_in_pixels, scr->height_in_pixels);
273     xcb_free_pixmap(conn, bg_pixmap);
274     xcb_flush(conn);
275 }
276
277 /*
278  * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
279  * authentication event.
280  *
281  */
282 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
283     DEBUG("clearing pam wrong\n");
284     pam_state = STATE_PAM_IDLE;
285     unlock_state = STATE_STARTED;
286     redraw_screen();
287 }
288
289 /*
290  * Hides the unlock indicator completely when there is no content in the
291  * password buffer.
292  *
293  */
294 static void clear_indicator(EV_P_ ev_timer *w, int revents) {
295     if (input_position == 0) {
296         DEBUG("Clear indicator\n");
297         unlock_state = STATE_STARTED;
298     } else unlock_state = STATE_KEY_PRESSED;
299     redraw_screen();
300 }
301
302 /*
303  * (Re-)starts the clear_indicator timeout. Called after pressing backspace or
304  * after an unsuccessful authentication attempt.
305  *
306  */
307 static void start_clear_indicator_timeout() {
308     if (clear_indicator_timeout) {
309         ev_timer_stop(main_loop, clear_indicator_timeout);
310         ev_timer_set(clear_indicator_timeout, 1.0, 0.);
311         ev_timer_start(main_loop, clear_indicator_timeout);
312     } else {
313         clear_indicator_timeout = calloc(sizeof(struct ev_timer), 1);
314         ev_timer_init(clear_indicator_timeout, clear_indicator, 1.0, 0.);
315         ev_timer_start(main_loop, clear_indicator_timeout);
316     }
317 }
318
319 static void input_done() {
320     if (input_position == 0)
321         return;
322
323     if (clear_pam_wrong_timeout) {
324         ev_timer_stop(main_loop, clear_pam_wrong_timeout);
325         clear_pam_wrong_timeout = NULL;
326     }
327
328     pam_state = STATE_PAM_VERIFY;
329     redraw_screen();
330
331     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
332         printf("successfully authenticated\n");
333         exit(0);
334     }
335
336     fprintf(stderr, "Authentication failure\n");
337
338     pam_state = STATE_PAM_WRONG;
339     redraw_screen();
340
341     /* Clear this state after 2 seconds (unless the user enters another
342      * password during that time). */
343     ev_now_update(main_loop);
344     clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1);
345     ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
346     ev_timer_start(main_loop, clear_pam_wrong_timeout);
347
348     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
349      * too early. */
350     if (clear_indicator_timeout) {
351         ev_timer_stop(main_loop, clear_indicator_timeout);
352         clear_indicator_timeout = NULL;
353     }
354
355     /* beep on authentication failure, if enabled */
356     if (beep) {
357         xcb_bell(conn, 100);
358         xcb_flush(conn);
359     }
360 }
361
362 /*
363  * Called when the user releases a key. We need to leave the Mode_switch
364  * state when the user releases the Mode_switch key.
365  *
366  */
367 static void handle_key_release(xcb_key_release_event_t *event) {
368     DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
369           event->detail, event->state, modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
370
371     /* We don’t care about the column here and just use the first symbol. Since
372      * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
373      * Also, if we would use the current column, we would look in the wrong
374      * place. */
375     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
376     if (sym == XK_Mode_switch) {
377         //printf("Mode switch disabled\n");
378         modeswitch_active = false;
379     } else if (sym == XK_ISO_Level3_Shift) {
380         iso_level3_shift_active = false;
381     } else if (sym == XK_ISO_Level5_Shift) {
382         iso_level5_shift_active = false;
383     }
384     DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
385           modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
386 }
387
388 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
389     redraw_screen();
390 }
391
392 /*
393  * Handle key presses. Fixes state, then looks up the key symbol for the
394  * given keycode, then looks up the key symbol (as UCS-2), converts it to
395  * UTF-8 and stores it in the password array.
396  *
397  */
398 static void handle_key_press(xcb_key_press_event_t *event) {
399     DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
400           event->detail, event->state, modeswitch_active, iso_level3_shift_active);
401
402     xcb_keysym_t sym0, sym1, sym;
403     /* For each keycode, there is a list of symbols. The list could look like this:
404      * $ xmodmap -pke | grep 'keycode  38'
405      * keycode  38 = a A adiaeresis Adiaeresis o O
406      * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
407      * with "a" on my keyboard) are "a A ä Ä o O".
408      * Another form to display the same information is using xkbcomp:
409      * $ xkbcomp $DISPLAY /tmp/xkb.dump
410      * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
411      *
412      * symbols[Group1]= [               a,               A,               o,               O ],
413      * symbols[Group2]= [      adiaeresis,      Adiaeresis ]
414      *
415      * So there are two *groups*, one containing 'a A' and one containing 'ä
416      * Ä'. You can use Mode_switch to switch between these groups. You can use
417      * ISO_Level3_Shift to reach the 'o O' part of the first group (it’s the
418      * same group, just an even higher shift level).
419      *
420      * So, using the "logical" XKB information, the following lookup will be
421      * performed:
422      *
423      * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
424      * Mode_switch active: group 2, column 0 and 1
425      * ISO_Level3_Shift active: group 1, column 2 and 3
426      *
427      * Using the column index which xcb_key_press_lookup_keysym uses (and
428      * xmodmap prints out), the following lookup will be performed:
429      *
430      * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
431      * Mode_switch active: column 2 and 3
432      * ISO_Level3_Shift active: column 4 and 5
433      */
434     int base_column = 0;
435     if (modeswitch_active)
436         base_column = 2;
437     if (iso_level3_shift_active)
438         base_column = 4;
439     if (iso_level5_shift_active)
440         base_column = 6;
441     sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
442     sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
443     switch (sym0) {
444     case XK_Mode_switch:
445         DEBUG("Mode switch enabled\n");
446         modeswitch_active = true;
447         return;
448     case XK_ISO_Level3_Shift:
449         DEBUG("ISO_Level3_Shift enabled\n");
450         iso_level3_shift_active = true;
451         return;
452     case XK_ISO_Level5_Shift:
453         DEBUG("ISO_Level5_Shift enabled\n");
454         iso_level5_shift_active = true;
455         return;
456     case XK_Return:
457     case XK_KP_Enter:
458         input_done();
459     case XK_Escape:
460         input_position = 0;
461         password[input_position] = '\0';
462         return;
463
464     case XK_BackSpace:
465         if (input_position == 0)
466             return;
467
468         /* decrement input_position to point to the previous glyph */
469         u8_dec(password, &input_position);
470         password[input_position] = '\0';
471
472         /* Clear this state after 2 seconds (unless the user enters another
473          * password during that time). */
474         start_clear_indicator_timeout();
475         unlock_state = STATE_BACKSPACE_ACTIVE;
476         redraw_screen();
477         unlock_state = STATE_KEY_PRESSED;
478         //printf("new input position = %d, new password = %s\n", input_position, password);
479         return;
480     }
481
482     if ((input_position + 8) >= sizeof(password))
483         return;
484
485     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
486         /* this key was a keypad key */
487         if ((event->state & XCB_MOD_MASK_SHIFT))
488             sym = sym0;
489         else sym = sym1;
490     } else {
491         if ((event->state & XCB_MOD_MASK_SHIFT))
492             sym = sym1;
493         else sym = sym0;
494     }
495
496 #if 0
497     /* FIXME: handle all of these? */
498     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
499     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
500     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
501     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
502     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
503     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
504     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
505 #endif
506
507     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
508         return;
509
510     DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
511
512     /* convert the keysym to UCS */
513     uint16_t ucs = keysym2ucs(sym);
514     if ((int16_t)ucs == -1) {
515         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
516         return;
517     }
518
519     /* store the UCS in a string to convert it */
520     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
521     DEBUG("input part = %s\n", inp);
522
523     /* store it in the password array as UTF-8 */
524     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
525     password[input_position] = '\0';
526     DEBUG("current password = %s\n", password);
527
528     unlock_state = STATE_KEY_ACTIVE;
529     redraw_screen();
530     unlock_state = STATE_KEY_PRESSED;
531
532     struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
533     ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
534     ev_timer_start(main_loop, timeout);
535
536     if (clear_indicator_timeout) {
537         ev_timer_stop(main_loop, clear_indicator_timeout);
538         clear_indicator_timeout = NULL;
539     }
540 }
541
542 /*
543  * A visibility notify event will be received when the visibility (= can the
544  * user view the complete window) changes, so for example when a popup overlays
545  * some area of the i3lock window.
546  *
547  * In this case, we raise our window on top so that the popup (or whatever is
548  * hiding us) gets hidden.
549  *
550  */
551 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
552     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
553         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
554         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
555         xcb_flush(conn);
556     }
557 }
558
559 /*
560  * Called when the keyboard mapping changes. We update our symbols.
561  *
562  */
563 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
564     xcb_refresh_keyboard_mapping(symbols, event);
565
566     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
567     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
568 }
569
570 /*
571  * Called when the properties on the root window change, e.g. when the screen
572  * resolution changes. If so we update the window to cover the whole screen
573  * and also redraw the image, if any.
574  *
575  */
576 void handle_screen_resize(xcb_visualtype_t *vistype, xcb_window_t win, uint32_t* last_resolution) {
577     xcb_get_geometry_cookie_t geomc;
578     xcb_get_geometry_reply_t *geom;
579     geomc = xcb_get_geometry(conn, scr->root);
580     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL) {
581       return;
582     }
583
584     if (last_resolution[0] == geom->width && last_resolution[1] == geom->height)
585       return;
586
587     last_resolution[0] = geom->width;
588     last_resolution[1] = geom->height;
589
590 #ifndef NOLIBCAIRO
591     if (img) {
592         xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
593         xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
594         xcb_free_pixmap(conn, bg_pixmap);
595     }
596 #endif
597
598     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
599     xcb_configure_window(conn, win, mask, last_resolution);
600     xcb_flush(conn);
601 }
602
603 /*
604  * Callback function for PAM. We only react on password request callbacks.
605  *
606  */
607 static int conv_callback(int num_msg, const struct pam_message **msg,
608                          struct pam_response **resp, void *appdata_ptr)
609 {
610     if (num_msg == 0)
611         return 1;
612
613     /* PAM expects an array of responses, one for each message */
614     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
615         perror("calloc");
616         return 1;
617     }
618
619     for (int c = 0; c < num_msg; c++) {
620         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
621             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
622             continue;
623
624         /* return code is currently not used but should be set to zero */
625         resp[c]->resp_retcode = 0;
626         if ((resp[c]->resp = strdup(password)) == NULL) {
627             perror("strdup");
628             return 1;
629         }
630     }
631
632     return 0;
633 }
634
635 /*
636  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
637  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
638  *
639  */
640 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
641     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
642 }
643
644 /*
645  * Flush before blocking (and waiting for new events)
646  *
647  */
648 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
649     xcb_flush(conn);
650 }
651
652 /*
653  * Instead of polling the X connection socket we leave this to
654  * xcb_poll_for_event() which knows better than we can ever know.
655  *
656  */
657 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
658     xcb_generic_event_t *event;
659
660     while ((event = xcb_poll_for_event(conn)) != NULL) {
661         if (event->response_type == 0) {
662             xcb_generic_error_t *error = (xcb_generic_error_t*)event;
663             fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
664                     error->sequence, error->error_code);
665             free(event);
666             continue;
667         }
668
669         /* Strip off the highest bit (set if the event is generated) */
670         int type = (event->response_type & 0x7F);
671
672         if (type == XCB_KEY_PRESS) {
673             handle_key_press((xcb_key_press_event_t*)event);
674             continue;
675         }
676
677         if (type == XCB_KEY_RELEASE) {
678             handle_key_release((xcb_key_release_event_t*)event);
679
680             /* If this was the backspace or escape key we are back at an
681              * empty input, so turn off the screen if DPMS is enabled */
682             if (dpms && input_position == 0)
683                 dpms_turn_off_screen(conn);
684
685             continue;
686         }
687
688         if (type == XCB_VISIBILITY_NOTIFY) {
689             handle_visibility_notify((xcb_visibility_notify_event_t*)event);
690             continue;
691         }
692
693         if (type == XCB_MAPPING_NOTIFY) {
694             handle_mapping_notify((xcb_mapping_notify_event_t*)event);
695             continue;
696         }
697
698         if (type == XCB_CONFIGURE_NOTIFY) {
699             handle_screen_resize(vistype, win, last_resolution);
700             continue;
701         }
702
703         printf("WARNING: unhandled event of type %d\n", type);
704
705         free(event);
706     }
707 }
708
709 int main(int argc, char *argv[]) {
710     bool dont_fork = false;
711     char *username;
712 #ifndef NOLIBCAIRO
713     char *image_path = NULL;
714 #endif
715     int ret;
716     struct pam_conv conv = {conv_callback, NULL};
717     int screen;
718     int curs_choice = CURS_NONE;
719     char o;
720     int optind = 0;
721     struct option longopts[] = {
722         {"version", no_argument, NULL, 'v'},
723         {"nofork", no_argument, NULL, 'n'},
724         {"beep", no_argument, NULL, 'b'},
725         {"dpms", no_argument, NULL, 'd'},
726         {"color", required_argument, NULL, 'c'},
727         {"pointer", required_argument, NULL , 'p'},
728         {"debug", no_argument, NULL, 0},
729         {"help", no_argument, NULL, 'h'},
730         {"no-unlock-indicator", no_argument, NULL, 'u'},
731 #ifndef NOLIBCAIRO
732         {"image", required_argument, NULL, 'i'},
733         {"tiling", no_argument, NULL, 't'},
734 #endif
735         {NULL, no_argument, NULL, 0}
736     };
737
738     if ((username = getenv("USER")) == NULL)
739         errx(1, "USER environment variable not set, please set it.\n");
740
741     while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
742 #ifndef NOLIBCAIRO
743         "i:t"
744 #endif
745         , longopts, &optind)) != -1) {
746         switch (o) {
747         case 'v':
748             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2011 Michael Stapelberg");
749         case 'n':
750             dont_fork = true;
751             break;
752         case 'b':
753             beep = true;
754             break;
755         case 'd':
756             dpms = true;
757             break;
758         case 'c': {
759             char *arg = optarg;
760
761             /* Skip # if present */
762             if (arg[0] == '#')
763                 arg++;
764
765             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
766                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
767
768             break;
769         }
770         case 'u':
771             unlock_indicator = false;
772             break;
773 #ifndef NOLIBCAIRO
774         case 'i':
775             image_path = strdup(optarg);
776             break;
777         case 't':
778             tile = true;
779             break;
780 #endif
781         case 'p':
782             if (!strcmp(optarg, "win")) {
783                 curs_choice = CURS_WIN;
784             } else if (!strcmp(optarg, "default")) {
785                 curs_choice = CURS_DEFAULT;
786             } else {
787                 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
788             }
789             break;
790         case 0:
791             if (strcmp(longopts[optind].name, "debug") == 0)
792                 debug_mode = true;
793             break;
794         default:
795             errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
796 #ifndef NOLIBCAIRO
797             " [-i image.png] [-t]"
798 #else
799             " (compiled with NOLIBCAIRO)"
800 #endif
801             );
802         }
803     }
804
805     /* We need (relatively) random numbers for highlighting a random part of
806      * the unlock indicator upon keypresses. */
807     srand(time(NULL));
808
809     /* Initialize PAM */
810     ret = pam_start("i3lock", username, &conv, &pam_handle);
811     if (ret != PAM_SUCCESS)
812         errx(EXIT_FAILURE, "PAM: %s\n", pam_strerror(pam_handle, ret));
813
814     /* Initialize connection to X11 */
815     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
816         xcb_connection_has_error(conn))
817         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
818
819     if (!dont_fork) {
820         /* In the parent process, we exit */
821         if (fork() != 0)
822             return 0;
823     }
824
825     /* if DPMS is enabled, check if the X server really supports it */
826     if (dpms) {
827         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
828         xcb_dpms_capable_reply_t *dpmsr;
829         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
830             fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
831             dpms = false;
832         }
833     }
834
835     scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
836     vistype = get_root_visual_type(scr);
837
838     last_resolution[0] = scr->width_in_pixels;
839     last_resolution[1] = scr->height_in_pixels;
840
841
842 #ifndef NOLIBCAIRO
843     if (image_path) {
844         /* Create a pixmap to render on, fill it with the background color */
845         img = cairo_image_surface_create_from_png(image_path);
846     }
847 #endif
848
849     /* Pixmap on which the image is rendered to (if any) */
850     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
851
852     /* open the fullscreen window, already with the correct pixmap in place */
853     win = open_fullscreen_window(conn, scr, color, bg_pixmap);
854     xcb_free_pixmap(conn, bg_pixmap);
855
856     cursor = create_cursor(conn, scr, win, curs_choice);
857
858     grab_pointer_and_keyboard(conn, scr, cursor);
859
860     symbols = xcb_key_symbols_alloc(conn);
861     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
862     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
863
864     if (dpms)
865         dpms_turn_off_screen(conn);
866
867     /* Initialize the libev event loop. */
868     main_loop = EV_DEFAULT;
869     if (main_loop == NULL)
870         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
871
872     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
873     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
874     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
875
876     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
877     ev_io_start(main_loop, xcb_watcher);
878
879     ev_check_init(xcb_check, xcb_check_cb);
880     ev_check_start(main_loop, xcb_check);
881
882     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
883     ev_prepare_start(main_loop, xcb_prepare);
884
885     xcb_flush(conn);
886     ev_loop(main_loop, 0);
887 }