You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

553 lines
17 KiB

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