]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
handle screen resolution images and redraw the lock window
[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
26 #ifndef NOLIBCAIRO
27 #include <cairo.h>
28 #include <cairo/cairo-xcb.h>
29 #endif
30
31 #include "keysym2ucs.h"
32 #include "ucs2_to_utf8.h"
33 #include "xcb.h"
34 #include "cursors.h"
35
36 static xcb_connection_t *conn;
37 static xcb_cursor_t cursor;
38 static xcb_key_symbols_t *symbols;
39 static xcb_screen_t *scr;
40 static pam_handle_t *pam_handle;
41 static int input_position = 0;
42 /* holds the password you enter (in UTF-8) */
43 static char password[512];
44 static bool modeswitch_active = false;
45 static int modeswitchmask;
46 static int numlockmask;
47 static bool beep = false;
48
49 #ifndef NOLIBCAIRO
50 static cairo_surface_t *img = NULL;
51 static bool tile = false;
52 #endif
53
54 /*
55  * Draws global image with fill color onto a pixmap with the given
56  * resolution and returns it.
57  *
58  */
59 xcb_pixmap_t draw_image(xcb_visualtype_t *vistype, u_int32_t* resolution, char* color) {
60     xcb_pixmap_t bg_pixmap = XCB_NONE;
61
62 #ifndef NOLIBCAIRO
63     if (!img)
64         return bg_pixmap;
65
66     bg_pixmap = create_bg_pixmap(conn, scr, resolution, color);
67     /* Initialize cairo */
68     cairo_surface_t *output;
69     output = cairo_xcb_surface_create(conn, bg_pixmap, vistype,
70              resolution[0], resolution[1]);
71     cairo_t *ctx = cairo_create(output);
72     if (!tile) {
73         cairo_set_source_surface(ctx, img, 0, 0);
74         cairo_paint(ctx);
75     } else {
76         /* create a pattern and fill a rectangle as big as the screen */
77         cairo_pattern_t *pattern;
78         pattern = cairo_pattern_create_for_surface(img);
79         cairo_set_source(ctx, pattern);
80         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
81         cairo_rectangle(ctx, 0, 0, resolution[0], resolution[1]);
82         cairo_fill(ctx);
83         cairo_pattern_destroy(pattern);
84     }
85     cairo_surface_destroy(output);
86     cairo_destroy(ctx);
87 #endif
88     return bg_pixmap;
89 }
90
91 static void input_done() {
92     if (input_position == 0)
93         return;
94
95     /* TODO: change cursor during authentication? */
96     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
97         printf("successfully authenticated\n");
98         exit(0);
99     }
100
101     fprintf(stderr, "Authentication failure\n");
102
103     /* beep on authentication failure, if enabled */
104     if (beep) {
105         xcb_bell(conn, 100);
106         xcb_flush(conn);
107     }
108 }
109
110 /*
111  * Called when the user releases a key. We need to leave the Mode_switch
112  * state when the user releases the Mode_switch key.
113  *
114  */
115 static void handle_key_release(xcb_key_release_event_t *event) {
116     //printf("releasing %d, state raw = %d\n", event->detail, event->state);
117
118     /* fix state */
119     event->state &= ~numlockmask;
120
121     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
122     if (sym == XK_Mode_switch) {
123         //printf("Mode switch disabled\n");
124         modeswitch_active = false;
125     }
126 }
127
128 /*
129  * Handle key presses. Fixes state, then looks up the key symbol for the
130  * given keycode, then looks up the key symbol (as UCS-2), converts it to
131  * UTF-8 and stores it in the password array.
132  *
133  */
134 static void handle_key_press(xcb_key_press_event_t *event) {
135     //printf("keypress %d, state raw = %d\n", event->detail, event->state);
136
137     xcb_keysym_t sym0, sym1, sym;
138     if (modeswitch_active) {
139         sym0 = xcb_key_press_lookup_keysym(symbols, event, 4);
140         sym1 = xcb_key_press_lookup_keysym(symbols, event, 5);
141     } else {
142         sym0 = xcb_key_press_lookup_keysym(symbols, event, 0);
143         sym1 = xcb_key_press_lookup_keysym(symbols, event, 1);
144     }
145     switch (sym0) {
146     case XK_Mode_switch:
147         //printf("Mode switch enabled\n");
148         modeswitch_active = true;
149         return;
150
151     case XK_Return:
152     case XK_KP_Enter:
153         input_done();
154     case XK_Escape:
155         input_position = 0;
156         password[input_position] = '\0';
157         return;
158
159     case XK_BackSpace:
160         if (input_position == 0)
161             return;
162
163         /* decrement input_position to point to the previous glyph */
164         u8_dec(password, &input_position);
165         password[input_position] = '\0';
166         //printf("new input position = %d, new password = %s\n", input_position, password);
167         return;
168     }
169
170     if ((input_position + 8) >= sizeof(password))
171         return;
172
173     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
174         /* this key was a keypad key */
175         if ((event->state & XCB_MOD_MASK_SHIFT))
176             sym = sym0;
177         else sym = sym1;
178     } else {
179         if ((event->state & XCB_MOD_MASK_SHIFT))
180             sym = sym1;
181         else sym = sym0;
182     }
183
184 #if 0
185     /* FIXME: handle all of these? */
186     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
187     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
188     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
189     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
190     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
191     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
192     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
193 #endif
194
195     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
196         return;
197
198     //printf("sym = %c (%d)\n", sym, sym);
199
200     /* convert the keysym to UCS */
201     uint16_t ucs = keysym2ucs(sym);
202     if ((int16_t)ucs == -1) {
203         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
204         return;
205     }
206
207     /* store the UCS in a string to convert it */
208     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
209
210     /* store it in the password array as UTF-8 */
211     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
212     password[input_position] = '\0';
213     //printf("current password = %s\n", password);
214 }
215
216 /*
217  * A visibility notify event will be received when the visibility (= can the
218  * user view the complete window) changes, so for example when a popup overlays
219  * some area of the i3lock window.
220  *
221  * In this case, we raise our window on top so that the popup (or whatever is
222  * hiding us) gets hidden.
223  *
224  */
225 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
226     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
227         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
228         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
229         xcb_flush(conn);
230     }
231 }
232
233 /*
234  * Called when the keyboard mapping changes. We update our symbols and re-grab
235  * pointer/keyboard.
236  *
237  */
238 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
239     xcb_refresh_keyboard_mapping(symbols, event);
240
241     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
242     xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
243     grab_pointer_and_keyboard(conn, scr, cursor);
244
245     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
246     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
247
248     xcb_flush(conn);
249 }
250
251 /*
252  * Called when the properties on the root window change, e.g. when the screen
253  * resolution changes. If so we update the window to cover the whole screen
254  * and also redraw the image, if any.
255  *
256  */
257 void handle_screen_resize(xcb_visualtype_t *vistype, xcb_window_t win, uint32_t* last_resolution, char* color) {
258     xcb_get_geometry_cookie_t geomc;
259     xcb_get_geometry_reply_t *geom;
260     geomc = xcb_get_geometry(conn, scr->root);
261     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL) {
262       return;
263     }
264
265     if (last_resolution[0] == geom->width && last_resolution[1] == geom->height)
266       return;
267
268     last_resolution[0] = geom->width;
269     last_resolution[1] = geom->height;
270
271     if (img) {
272         xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution, color);
273         xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
274     }
275
276     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
277     xcb_configure_window(conn, win, mask, last_resolution);
278     xcb_flush(conn);
279 }
280
281 /*
282  * Callback function for PAM. We only react on password request callbacks.
283  *
284  */
285 static int conv_callback(int num_msg, const struct pam_message **msg,
286                          struct pam_response **resp, void *appdata_ptr)
287 {
288     if (num_msg == 0)
289         return 1;
290
291     /* PAM expects an array of responses, one for each message */
292     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
293         perror("calloc");
294         return 1;
295     }
296
297     for (int c = 0; c < num_msg; c++) {
298         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
299             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
300             continue;
301
302         /* return code is currently not used but should be set to zero */
303         resp[c]->resp_retcode = 0;
304         if ((resp[c]->resp = strdup(password)) == NULL) {
305             perror("strdup");
306             return 1;
307         }
308     }
309
310     return 0;
311 }
312
313 int main(int argc, char *argv[]) {
314     bool dont_fork = false;
315     bool dpms = false;
316     char color[7] = "ffffff";
317     char *username;
318 #ifndef NOLIBCAIRO
319     char *image_path = NULL;
320 #endif
321     int ret;
322     struct pam_conv conv = {conv_callback, NULL};
323     int screen;
324     xcb_visualtype_t *vistype;
325     xcb_generic_event_t *event;
326     xcb_window_t win;
327     int curs_choice = CURS_NONE;
328     char o;
329     int optind = 0;
330     struct option longopts[] = {
331         {"version", no_argument, NULL, 'v'},
332         {"nofork", no_argument, NULL, 'n'},
333         {"beep", no_argument, NULL, 'b'},
334         {"dpms", no_argument, NULL, 'd'},
335         {"color", required_argument, NULL, 'c'},
336         {"pointer", required_argument, NULL , 'p'},
337 #ifndef NOLIBCAIRO
338         {"image", required_argument, NULL, 'i'},
339         {"tiling", no_argument, NULL, 't'},
340 #endif
341         {NULL, no_argument, NULL, 0}
342     };
343
344     if ((username = getenv("USER")) == NULL)
345         errx(1, "USER environment variable not set, please set it.\n");
346
347     while ((o = getopt_long(argc, argv, "vnbdc:p:"
348 #ifndef NOLIBCAIRO
349         "i:t"
350 #endif
351         , longopts, &optind)) != -1) {
352         switch (o) {
353         case 'v':
354             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2011 Michael Stapelberg\n");
355         case 'n':
356             dont_fork = true;
357             break;
358         case 'b':
359             beep = true;
360             break;
361         case 'd':
362             dpms = true;
363             break;
364         case 'c': {
365             char *arg = optarg;
366
367             /* Skip # if present */
368             if (arg[0] == '#')
369                 arg++;
370
371             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
372                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
373
374             break;
375         }
376 #ifndef NOLIBCAIRO
377         case 'i':
378             image_path = strdup(optarg);
379             break;
380         case 't':
381             tile = true;
382             break;
383 #endif
384         case 'p':
385             if (!strcmp(optarg, "win")) {
386                 curs_choice = CURS_WIN;
387             }
388             if (!strcmp(optarg, "default")) {
389                 curs_choice = CURS_DEFAULT;
390             }
391             break;
392         default:
393             errx(1, "i3lock: Unknown option. Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-p win|default]"
394 #ifndef NOLIBCAIRO
395             " [-i image.png] [-t]"
396 #else
397             " (compiled with NOLIBCAIRO)"
398 #endif
399             "\n");
400         }
401     }
402
403     /* Initialize PAM */
404     ret = pam_start("i3lock", username, &conv, &pam_handle);
405     if (ret != PAM_SUCCESS)
406         errx(EXIT_FAILURE, "PAM: %s\n", pam_strerror(pam_handle, ret));
407
408     /* Initialize connection to X11 */
409     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
410         xcb_connection_has_error(conn))
411         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
412
413     if (!dont_fork) {
414         /* In the parent process, we exit */
415         if (fork() != 0)
416             return 0;
417     }
418
419     /* if DPMS is enabled, check if the X server really supports it */
420     if (dpms) {
421         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
422         xcb_dpms_capable_reply_t *dpmsr;
423         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
424             fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
425             dpms = false;
426         }
427     }
428
429     scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
430     vistype = get_root_visual_type(scr);
431
432     uint32_t last_resolution[2] = {scr->width_in_pixels, scr->height_in_pixels};
433
434
435
436 #ifndef NOLIBCAIRO
437     if (image_path) {
438         /* Create a pixmap to render on, fill it with the background color */
439         img = cairo_image_surface_create_from_png(image_path);
440     }
441 #endif
442
443     /* Pixmap on which the image is rendered to (if any) */
444     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution, color);
445
446     /* open the fullscreen window, already with the correct pixmap in place */
447     win = open_fullscreen_window(conn, scr, color, bg_pixmap);
448
449     cursor = create_cursor(conn, scr, win, curs_choice);
450
451     grab_pointer_and_keyboard(conn, scr, cursor);
452
453     symbols = xcb_key_symbols_alloc(conn);
454     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
455     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
456
457     if (dpms)
458         dpms_turn_off_screen(conn);
459
460     while ((event = xcb_wait_for_event(conn))) {
461         if (event->response_type == 0)
462             errx(1, "XCB: Invalid event received");
463
464         /* Strip off the highest bit (set if the event is generated) */
465         int type = (event->response_type & 0x7F);
466
467         if (type == XCB_KEY_PRESS) {
468             handle_key_press((xcb_key_press_event_t*)event);
469             continue;
470         }
471
472         if (type == XCB_KEY_RELEASE) {
473             handle_key_release((xcb_key_release_event_t*)event);
474
475             /* If this was the backspace or escape key we are back at an
476              * empty input, so turn off the screen if DPMS is enabled */
477             if (dpms && input_position == 0)
478                 dpms_turn_off_screen(conn);
479
480             continue;
481         }
482
483         if (type == XCB_VISIBILITY_NOTIFY) {
484             handle_visibility_notify((xcb_visibility_notify_event_t*)event);
485             continue;
486         }
487
488         if (type == XCB_MAPPING_NOTIFY) {
489             handle_mapping_notify((xcb_mapping_notify_event_t*)event);
490             continue;
491         }
492
493         if (type == XCB_CONFIGURE_NOTIFY) {
494             handle_screen_resize(vistype, win, last_resolution, color);
495             continue;
496         }
497
498         printf("WARNING: unhandled event of type %d\n", type);
499     }
500
501     return 0;
502 }