]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
adding option to enable tiling of images
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3lock - an improved version of slock
5  *
6  * i3lock © 2009 Michael Stapelberg and contributors
7  * slock  © 2006-2008 Anselm R Garbe
8  *
9  * See file LICENSE for license information.
10  *
11  * Note that on any error (calloc is out of memory for example)
12  * we do not do anything so that the user can fix the error by
13  * himself (kill X to get more free memory or stop some other
14  * program using SSH/console).
15  *
16  */
17 #define _XOPEN_SOURCE 500
18
19 #include <ctype.h>
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdint.h>
24 #include <string.h>
25 #include <math.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <X11/keysym.h>
29 #include <X11/Xlib.h>
30 #include <X11/Xutil.h>
31 #include <X11/xpm.h>
32 #include <X11/extensions/dpms.h>
33 #include <stdbool.h>
34 #include <getopt.h>
35
36 #include <security/pam_appl.h>
37
38 static char passwd[256];
39
40 /*
41  * displays an xpm image tiled over the whole screen
42  * (the image will be visible on all screens
43  * when using a multi monitor setup)
44  *
45  */
46 void tiling_image(XpmImage *image,
47         int disp_height, int disp_width,
48         Display *dpy,
49         Pixmap pix,
50         Window w,
51         GC gc) {
52     int rows = (int)ceil(disp_height / (float)image->height),
53         cols = (int)ceil(disp_width / (float)image->width);
54
55     int x = 0,
56         y = 0;
57
58     for(y = 0; y < rows; y++) {
59         for(x = 0; x < cols; x++) {
60             XCopyArea(dpy, pix, w, gc, 0, 0, image->width, image->height, image->width * x, image->height * y);
61         }
62     }
63 }
64
65 static void die(const char *errstr, ...) {
66         va_list ap;
67
68         va_start(ap, errstr);
69         vfprintf(stderr, errstr, ap);
70         va_end(ap);
71         exit(EXIT_FAILURE);
72 }
73
74 /*
75  * Returns the colorpixel to use for the given hex color (think of HTML).
76  *
77  * The hex_color may not start with #, for example FF00FF works.
78  *
79  * NOTE that get_colorpixel() does _NOT_ check the given color code for validity.
80  * This has to be done by the caller.
81  *
82  */
83 uint32_t get_colorpixel(char *hex) {
84         char strgroups[3][3] = {{hex[0], hex[1], '\0'},
85                                 {hex[2], hex[3], '\0'},
86                                 {hex[4], hex[5], '\0'}};
87         uint32_t rgb16[3] = {(strtol(strgroups[0], NULL, 16)),
88                              (strtol(strgroups[1], NULL, 16)),
89                              (strtol(strgroups[2], NULL, 16))};
90
91         return (rgb16[0] << 16) + (rgb16[1] << 8) + rgb16[2];
92 }
93
94 /*
95  * Check if given file can be opened => exists
96  *
97  */
98 bool file_exists(const char *filename)
99 {
100         FILE * file = fopen(filename, "r");
101         if(file)
102         {
103                 fclose(file);
104                 return true;
105         }
106         return false;
107 }
108
109 /*
110  * Puts the given XPM error code to stderr
111  *
112  */
113 void print_xpm_error(int err)
114 {
115         switch (err) {
116                 case XpmColorError:
117                         fprintf(stderr, "XPM: Could not parse or alloc requested color\n");
118                         break;
119                 case XpmOpenFailed:
120                         fprintf(stderr, "XPM: Cannot open file\n");
121                         break;
122                 case XpmFileInvalid:
123                         fprintf(stderr, "XPM: invalid XPM file\n");
124                         break;
125                 case XpmNoMemory:
126                         fprintf(stderr, "XPM: Not enough memory\n");
127                         break;
128                 case XpmColorFailed:
129                         fprintf(stderr, "XPM: Color not found\n");
130                         break;
131         }
132 }
133
134
135 /*
136  * Callback function for PAM. We only react on password request callbacks.
137  *
138  */
139 static int conv_callback(int num_msg, const struct pam_message **msg,
140                          struct pam_response **resp, void *appdata_ptr) {
141         if (num_msg == 0)
142                 return 1;
143
144         /* PAM expects an arry of responses, one for each message */
145         if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
146                 perror("calloc");
147                 return 1;
148         }
149
150         for (int c = 0; c < num_msg; c++) {
151                 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
152                     msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
153                         continue;
154
155                 /* return code is currently not used but should be set to zero */
156                 resp[c]->resp_retcode = 0;
157                 if ((resp[c]->resp = strdup(passwd)) == NULL) {
158                         perror("strdup");
159                         return 1;
160                 }
161         }
162
163         return 0;
164 }
165
166 int main(int argc, char *argv[]) {
167         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
168         char buf[32];
169         char *username;
170         int num, screen;
171
172         unsigned int len;
173         bool running = true;
174
175         /* By default, fork, don’t beep and don’t turn off monitor */
176         bool dont_fork = false;
177         bool beep = false;
178         bool dpms = false;
179         bool xpm_image = false;
180         bool tiling = false;
181         char xpm_image_path[256];
182         char color[7] = "ffffff"; // white
183         Cursor invisible;
184         Display *dpy;
185         KeySym ksym;
186         Pixmap pmap;
187         Window root, w;
188         XColor black, dummy;
189         XEvent ev;
190         XSetWindowAttributes wa;
191
192         pam_handle_t *handle;
193         struct pam_conv conv = {conv_callback, NULL};
194
195         char opt;
196         int optind = 0;
197         static struct option long_options[] = {
198                 {"version", no_argument, NULL, 'v'},
199                 {"nofork", no_argument, NULL, 'n'},
200                 {"beep", no_argument, NULL, 'b'},
201                 {"dpms", no_argument, NULL, 'd'},
202                 {"image", required_argument, NULL, 'i'},
203                 {"color", required_argument, NULL, 'c'},
204                 {"tiling", no_argument, NULL, 't'},
205                 {NULL, no_argument, NULL, 0}
206         };
207
208         while ((opt = getopt_long(argc, argv, "vnbdi:c:t", long_options, &optind)) != -1) {
209                 switch (opt) {
210                         case 'v':
211                                 die("i3lock-"VERSION", © 2009 Michael Stapelberg\n"
212                                     "based on slock, which is © 2006-2008 Anselm R Garbe\n");
213                         case 'n':
214                                 dont_fork = true;
215                                 break;
216                         case 'b':
217                                 beep = true;
218                                 break;
219                         case 'd':
220                                 dpms = true;
221                                 break;
222                         case 'i':
223                                 strncpy(xpm_image_path, optarg, 255);
224                                 xpm_image = true;
225                                 break;
226                         case 'c':
227                         {
228                                 char *arg = optarg;
229                                 /* Skip # if present */
230                                 if (arg[0] == '#')
231                                         arg++;
232
233                                 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
234                                         die("color is invalid, color must be given in 6-byte format: rrggbb\n");
235
236                                 break;
237                         }
238                         case 't':
239                                 tiling = true;
240                                 break;
241                         default:
242                                 die("i3lock: Unknown option. Syntax: i3lock [-v] [-n] [-b] [-d] [-i image.xpm] [-c color] [-t]\n");
243                 }
244         }
245
246         if ((username = getenv("USER")) == NULL)
247                 die("USER environment variable not set, please set it.\n");
248
249         int ret = pam_start("i3lock", username, &conv, &handle);
250         if (ret != PAM_SUCCESS)
251                 die("PAM: %s\n", pam_strerror(handle, ret));
252
253         if(!(dpy = XOpenDisplay(0)))
254                 die("i3lock: cannot open display\n");
255         screen = DefaultScreen(dpy);
256         root = RootWindow(dpy, screen);
257
258         if (!dont_fork) {
259                 if (fork() != 0)
260                         return 0;
261         }
262
263         /* init */
264         wa.override_redirect = 1;
265         wa.background_pixel = get_colorpixel(color);
266         w = XCreateWindow(dpy, root, 0, 0, DisplayWidth(dpy, screen), DisplayHeight(dpy, screen),
267                         0, DefaultDepth(dpy, screen), CopyFromParent,
268                         DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);
269         XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
270         pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
271         invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
272         XDefineCursor(dpy, w, invisible);
273         XMapRaised(dpy, w);
274
275         if (xpm_image && file_exists(xpm_image_path)) {
276                 GC gc = XDefaultGC(dpy, 0);
277                 int depth = DefaultDepth(dpy, screen);
278                 int disp_width = DisplayWidth(dpy, screen);
279                 int disp_height = DisplayHeight(dpy, screen);
280                 Pixmap pix = XCreatePixmap(dpy, w, disp_width, disp_height, depth);
281                 XpmImage xpm_image;
282                 XpmInfo xpm_info;
283
284                 int err = XpmReadFileToXpmImage(xpm_image_path, &xpm_image, &xpm_info);
285                 if (err != 0) {
286                         print_xpm_error(err);
287                         return 1;
288                 }
289
290                 err = XpmCreatePixmapFromXpmImage(dpy, w, &xpm_image, &pix, 0, 0);
291                 if (err != 0) {
292                         print_xpm_error(err);
293                         return 1;
294                 }
295
296                 if (tiling)
297                     tiling_image(&xpm_image, disp_height, disp_width, dpy, pix, w, gc);
298                 else
299                     XCopyArea(dpy, pix, w, gc, 0, 0, disp_width, disp_height, 0, 0);
300         }
301
302         for(len = 1000; len; len--) {
303                 if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask,
304                         GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
305                         break;
306                 usleep(1000);
307         }
308         if((running = running && (len > 0))) {
309                 for(len = 1000; len; len--) {
310                         if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
311                                 == GrabSuccess)
312                                 break;
313                         usleep(1000);
314                 }
315                 running = (len > 0);
316         }
317         len = 0;
318         XSync(dpy, False);
319
320         /* main event loop */
321         while(running && !XNextEvent(dpy, &ev)) {
322                 if (len == 0 && dpms && DPMSCapable(dpy)) {
323                         DPMSEnable(dpy);
324                         DPMSForceLevel(dpy, DPMSModeOff);
325                 }
326
327                 if(ev.type != KeyPress)
328                         continue;
329
330                 buf[0] = 0;
331                 num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
332                 if(IsKeypadKey(ksym)) {
333                         if(ksym == XK_KP_Enter)
334                                 ksym = XK_Return;
335                         else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
336                                 ksym = (ksym - XK_KP_0) + XK_0;
337                 }
338                 if(IsFunctionKey(ksym) ||
339                    IsKeypadKey(ksym) ||
340                    IsMiscFunctionKey(ksym) ||
341                    IsPFKey(ksym) ||
342                    IsPrivateKeypadKey(ksym))
343                         continue;
344                 switch(ksym) {
345                 case XK_Return:
346                         passwd[len] = 0;
347                         if ((ret = pam_authenticate(handle, 0)) == PAM_SUCCESS)
348                                 running = false;
349                         else {
350                                 fprintf(stderr, "PAM: %s\n", pam_strerror(handle, ret));
351                                 if (beep)
352                                         XBell(dpy, 100);
353                         }
354                         len = 0;
355                         break;
356                 case XK_Escape:
357                         len = 0;
358                         break;
359                 case XK_BackSpace:
360                         if (len > 0)
361                                 len--;
362                         break;
363                 default:
364                         if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) {
365                                 memcpy(passwd + len, buf, num);
366                                 len += num;
367                         }
368                         break;
369                 }
370         }
371         XUngrabPointer(dpy, CurrentTime);
372         XFreePixmap(dpy, pmap);
373         XDestroyWindow(dpy, w);
374         XCloseDisplay(dpy);
375         return 0;
376 }