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