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