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