]> git.armaanb.net Git - dmenu.git/blob - dmenu.c
unboolify dmenu
[dmenu.git] / dmenu.c
1 /* See LICENSE file for copyright and license details. */
2 #include <ctype.h>
3 #include <locale.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <strings.h>
8 #include <time.h>
9
10 #include <X11/Xlib.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xutil.h>
13 #ifdef XINERAMA
14 #include <X11/extensions/Xinerama.h>
15 #endif
16 #include <X11/Xft/Xft.h>
17
18 #include "drw.h"
19 #include "util.h"
20
21 /* macros */
22 #define INTERSECT(x,y,w,h,r)  (MAX(0, MIN((x)+(w),(r).x_org+(r).width)  - MAX((x),(r).x_org)) \
23                              * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
24 #define LENGTH(X)             (sizeof X / sizeof X[0])
25 #define TEXTNW(X,N)           (drw_font_getexts_width(drw->fonts[0], (X), (N)))
26 #define TEXTW(X)              (drw_text(drw, 0, 0, 0, 0, (X), 0) + drw->fonts[0]->h)
27
28 /* enums */
29 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
30
31 struct item {
32         char *text;
33         struct item *left, *right;
34         int out;
35 };
36
37 static char text[BUFSIZ] = "";
38 static int bh, mw, mh;
39 static int sw, sh; /* X display screen geometry width, height */
40 static int inputw, promptw;
41 static size_t cursor;
42 static struct item *items = NULL;
43 static struct item *matches, *matchend;
44 static struct item *prev, *curr, *next, *sel;
45 static int mon = -1, screen;
46
47 static Atom clip, utf8;
48 static Display *dpy;
49 static Window root, win;
50 static XIC xic;
51
52 static ClrScheme scheme[SchemeLast];
53 static Drw *drw;
54
55 #include "config.h"
56
57 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
58 static char *(*fstrstr)(const char *, const char *) = strstr;
59
60 static void
61 appenditem(struct item *item, struct item **list, struct item **last)
62 {
63         if (*last)
64                 (*last)->right = item;
65         else
66                 *list = item;
67
68         item->left = *last;
69         item->right = NULL;
70         *last = item;
71 }
72
73 static void
74 calcoffsets(void)
75 {
76         int i, n;
77
78         if (lines > 0)
79                 n = lines * bh;
80         else
81                 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
82         /* calculate which items will begin the next page and previous page */
83         for (i = 0, next = curr; next; next = next->right)
84                 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
85                         break;
86         for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
87                 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
88                         break;
89 }
90
91 static void
92 cleanup(void)
93 {
94         size_t i;
95
96         XUngrabKey(dpy, AnyKey, AnyModifier, root);
97         for (i = 0; i < SchemeLast; i++) {
98                 drw_clr_free(scheme[i].bg);
99                 drw_clr_free(scheme[i].fg);
100         }
101         drw_free(drw);
102         XSync(dpy, False);
103         XCloseDisplay(dpy);
104 }
105
106 static char *
107 cistrstr(const char *s, const char *sub)
108 {
109         size_t len;
110
111         for (len = strlen(sub); *s; s++)
112                 if (!strncasecmp(s, sub, len))
113                         return (char *)s;
114         return NULL;
115 }
116
117 static void
118 drawmenu(void)
119 {
120         int curpos;
121         struct item *item;
122         int x = 0, y = 0, h = bh, w;
123
124         drw_setscheme(drw, &scheme[SchemeNorm]);
125         drw_rect(drw, 0, 0, mw, mh, 1, 1, 1);
126
127         if (prompt && *prompt) {
128                 drw_setscheme(drw, &scheme[SchemeSel]);
129                 drw_text(drw, x, 0, promptw, bh, prompt, 0);
130                 x += promptw;
131         }
132         /* draw input field */
133         w = (lines > 0 || !matches) ? mw - x : inputw;
134         drw_setscheme(drw, &scheme[SchemeNorm]);
135         drw_text(drw, x, 0, w, bh, text, 0);
136
137         if ((curpos = TEXTNW(text, cursor) + bh / 2 - 2) < w) {
138                 drw_setscheme(drw, &scheme[SchemeNorm]);
139                 drw_rect(drw, x + curpos + 2, 2, 1, bh - 4, 1, 1, 0);
140         }
141
142         if (lines > 0) {
143                 /* draw vertical list */
144                 w = mw - x;
145                 for (item = curr; item != next; item = item->right) {
146                         y += h;
147                         if (item == sel)
148                                 drw_setscheme(drw, &scheme[SchemeSel]);
149                         else if (item->out)
150                                 drw_setscheme(drw, &scheme[SchemeOut]);
151                         else
152                                 drw_setscheme(drw, &scheme[SchemeNorm]);
153
154                         drw_text(drw, x, y, w, bh, item->text, 0);
155                 }
156         } else if (matches) {
157                 /* draw horizontal list */
158                 x += inputw;
159                 w = TEXTW("<");
160                 if (curr->left) {
161                         drw_setscheme(drw, &scheme[SchemeNorm]);
162                         drw_text(drw, x, 0, w, bh, "<", 0);
163                 }
164                 for (item = curr; item != next; item = item->right) {
165                         x += w;
166                         w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
167
168                         if (item == sel)
169                                 drw_setscheme(drw, &scheme[SchemeSel]);
170                         else if (item->out)
171                                 drw_setscheme(drw, &scheme[SchemeOut]);
172                         else
173                                 drw_setscheme(drw, &scheme[SchemeNorm]);
174                         drw_text(drw, x, 0, w, bh, item->text, 0);
175                 }
176                 w = TEXTW(">");
177                 x = mw - w;
178                 if (next) {
179                         drw_setscheme(drw, &scheme[SchemeNorm]);
180                         drw_text(drw, x, 0, w, bh, ">", 0);
181                 }
182         }
183         drw_map(drw, win, 0, 0, mw, mh);
184 }
185
186 static void
187 grabkeyboard(void)
188 {
189         struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000  };
190         int i;
191
192         /* try to grab keyboard, we may have to wait for another process to ungrab */
193         for (i = 0; i < 1000; i++) {
194                 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True,
195                                  GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
196                         return;
197                 nanosleep(&ts, NULL);
198         }
199         die("cannot grab keyboard\n");
200 }
201
202 static void
203 match(void)
204 {
205         static char **tokv = NULL;
206         static int tokn = 0;
207
208         char buf[sizeof text], *s;
209         int i, tokc = 0;
210         size_t len, textsize;
211         struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
212
213         strcpy(buf, text);
214         /* separate input text into tokens to be matched individually */
215         for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
216                 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
217                         die("cannot realloc %u bytes\n", tokn * sizeof *tokv);
218         len = tokc ? strlen(tokv[0]) : 0;
219
220         matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
221         textsize = strlen(text);
222         for (item = items; item && item->text; item++) {
223                 for (i = 0; i < tokc; i++)
224                         if (!fstrstr(item->text, tokv[i]))
225                                 break;
226                 if (i != tokc) /* not all tokens match */
227                         continue;
228                 /* exact matches go first, then prefixes, then substrings */
229                 if (!tokc || !fstrncmp(text, item->text, textsize))
230                         appenditem(item, &matches, &matchend);
231                 else if (!fstrncmp(tokv[0], item->text, len))
232                         appenditem(item, &lprefix, &prefixend);
233                 else
234                         appenditem(item, &lsubstr, &substrend);
235         }
236         if (lprefix) {
237                 if (matches) {
238                         matchend->right = lprefix;
239                         lprefix->left = matchend;
240                 } else
241                         matches = lprefix;
242                 matchend = prefixend;
243         }
244         if (lsubstr) {
245                 if (matches) {
246                         matchend->right = lsubstr;
247                         lsubstr->left = matchend;
248                 } else
249                         matches = lsubstr;
250                 matchend = substrend;
251         }
252         curr = sel = matches;
253         calcoffsets();
254 }
255
256 static void
257 insert(const char *str, ssize_t n)
258 {
259         if (strlen(text) + n > sizeof text - 1)
260                 return;
261         /* move existing text out of the way, insert new text, and update cursor */
262         memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
263         if (n > 0)
264                 memcpy(&text[cursor], str, n);
265         cursor += n;
266         match();
267 }
268
269 static size_t
270 nextrune(int inc)
271 {
272         ssize_t n;
273
274         /* return location of next utf8 rune in the given direction (+1 or -1) */
275         for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
276                 ;
277         return n;
278 }
279
280 static void
281 keypress(XKeyEvent *ev)
282 {
283         char buf[32];
284         int len;
285         KeySym ksym = NoSymbol;
286         Status status;
287
288         len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
289         if (status == XBufferOverflow)
290                 return;
291         if (ev->state & ControlMask)
292                 switch(ksym) {
293                 case XK_a: ksym = XK_Home;      break;
294                 case XK_b: ksym = XK_Left;      break;
295                 case XK_c: ksym = XK_Escape;    break;
296                 case XK_d: ksym = XK_Delete;    break;
297                 case XK_e: ksym = XK_End;       break;
298                 case XK_f: ksym = XK_Right;     break;
299                 case XK_g: ksym = XK_Escape;    break;
300                 case XK_h: ksym = XK_BackSpace; break;
301                 case XK_i: ksym = XK_Tab;       break;
302                 case XK_j: /* fallthrough */
303                 case XK_J: /* fallthrough */
304                 case XK_m: /* fallthrough */
305                 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
306                 case XK_n: ksym = XK_Down;      break;
307                 case XK_p: ksym = XK_Up;        break;
308
309                 case XK_k: /* delete right */
310                         text[cursor] = '\0';
311                         match();
312                         break;
313                 case XK_u: /* delete left */
314                         insert(NULL, 0 - cursor);
315                         break;
316                 case XK_w: /* delete word */
317                         while (cursor > 0 && text[nextrune(-1)] == ' ')
318                                 insert(NULL, nextrune(-1) - cursor);
319                         while (cursor > 0 && text[nextrune(-1)] != ' ')
320                                 insert(NULL, nextrune(-1) - cursor);
321                         break;
322                 case XK_y: /* paste selection */
323                 case XK_Y:
324                         XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
325                                           utf8, utf8, win, CurrentTime);
326                         return;
327                 case XK_Return:
328                 case XK_KP_Enter:
329                         break;
330                 case XK_bracketleft:
331                         cleanup();
332                         exit(1);
333                 default:
334                         return;
335                 }
336         else if (ev->state & Mod1Mask)
337                 switch(ksym) {
338                 case XK_g: ksym = XK_Home;  break;
339                 case XK_G: ksym = XK_End;   break;
340                 case XK_h: ksym = XK_Up;    break;
341                 case XK_j: ksym = XK_Next;  break;
342                 case XK_k: ksym = XK_Prior; break;
343                 case XK_l: ksym = XK_Down;  break;
344                 default:
345                         return;
346                 }
347         switch(ksym) {
348         default:
349                 if (!iscntrl(*buf))
350                         insert(buf, len);
351                 break;
352         case XK_Delete:
353                 if (text[cursor] == '\0')
354                         return;
355                 cursor = nextrune(+1);
356                 /* fallthrough */
357         case XK_BackSpace:
358                 if (cursor == 0)
359                         return;
360                 insert(NULL, nextrune(-1) - cursor);
361                 break;
362         case XK_End:
363                 if (text[cursor] != '\0') {
364                         cursor = strlen(text);
365                         break;
366                 }
367                 if (next) {
368                         /* jump to end of list and position items in reverse */
369                         curr = matchend;
370                         calcoffsets();
371                         curr = prev;
372                         calcoffsets();
373                         while (next && (curr = curr->right))
374                                 calcoffsets();
375                 }
376                 sel = matchend;
377                 break;
378         case XK_Escape:
379                 cleanup();
380                 exit(1);
381         case XK_Home:
382                 if (sel == matches) {
383                         cursor = 0;
384                         break;
385                 }
386                 sel = curr = matches;
387                 calcoffsets();
388                 break;
389         case XK_Left:
390                 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
391                         cursor = nextrune(-1);
392                         break;
393                 }
394                 if (lines > 0)
395                         return;
396                 /* fallthrough */
397         case XK_Up:
398                 if (sel && sel->left && (sel = sel->left)->right == curr) {
399                         curr = prev;
400                         calcoffsets();
401                 }
402                 break;
403         case XK_Next:
404                 if (!next)
405                         return;
406                 sel = curr = next;
407                 calcoffsets();
408                 break;
409         case XK_Prior:
410                 if (!prev)
411                         return;
412                 sel = curr = prev;
413                 calcoffsets();
414                 break;
415         case XK_Return:
416         case XK_KP_Enter:
417                 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
418                 if (!(ev->state & ControlMask)) {
419                         cleanup();
420                         exit(0);
421                 }
422                 if (sel)
423                         sel->out = 1;
424                 break;
425         case XK_Right:
426                 if (text[cursor] != '\0') {
427                         cursor = nextrune(+1);
428                         break;
429                 }
430                 if (lines > 0)
431                         return;
432                 /* fallthrough */
433         case XK_Down:
434                 if (sel && sel->right && (sel = sel->right) == next) {
435                         curr = next;
436                         calcoffsets();
437                 }
438                 break;
439         case XK_Tab:
440                 if (!sel)
441                         return;
442                 strncpy(text, sel->text, sizeof text - 1);
443                 text[sizeof text - 1] = '\0';
444                 cursor = strlen(text);
445                 match();
446                 break;
447         }
448         drawmenu();
449 }
450
451 static void
452 paste(void)
453 {
454         char *p, *q;
455         int di;
456         unsigned long dl;
457         Atom da;
458
459         /* we have been given the current selection, now insert it into input */
460         XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
461                            utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
462         insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
463         XFree(p);
464         drawmenu();
465 }
466
467 static void
468 readstdin(void)
469 {
470         char buf[sizeof text], *p, *maxstr = NULL;
471         size_t i, max = 0, size = 0;
472
473         /* read each line from stdin and add it to the item list */
474         for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
475                 if (i + 1 >= size / sizeof *items)
476                         if (!(items = realloc(items, (size += BUFSIZ))))
477                                 die("cannot realloc %u bytes:", size);
478                 if ((p = strchr(buf, '\n')))
479                         *p = '\0';
480                 if (!(items[i].text = strdup(buf)))
481                         die("cannot strdup %u bytes:", strlen(buf) + 1);
482                 items[i].out = 0;
483                 if (strlen(items[i].text) > max)
484                         max = strlen(maxstr = items[i].text);
485         }
486         if (items)
487                 items[i].text = NULL;
488         inputw = maxstr ? TEXTW(maxstr) : 0;
489         lines = MIN(lines, i);
490 }
491
492 static void
493 run(void)
494 {
495         XEvent ev;
496
497         while (!XNextEvent(dpy, &ev)) {
498                 if (XFilterEvent(&ev, win))
499                         continue;
500                 switch(ev.type) {
501                 case Expose:
502                         if (ev.xexpose.count == 0)
503                                 drw_map(drw, win, 0, 0, mw, mh);
504                         break;
505                 case KeyPress:
506                         keypress(&ev.xkey);
507                         break;
508                 case SelectionNotify:
509                         if (ev.xselection.property == utf8)
510                                 paste();
511                         break;
512                 case VisibilityNotify:
513                         if (ev.xvisibility.state != VisibilityUnobscured)
514                                 XRaiseWindow(dpy, win);
515                         break;
516                 }
517         }
518 }
519
520 static void
521 setup(void)
522 {
523         int x, y;
524         XSetWindowAttributes swa;
525         XIM xim;
526 #ifdef XINERAMA
527         XineramaScreenInfo *info;
528         Window w, pw, dw, *dws;
529         XWindowAttributes wa;
530         int a, j, di, n, i = 0, area = 0;
531         unsigned int du;
532 #endif
533
534         /* init appearance */
535         scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
536         scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
537         scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
538         scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
539         scheme[SchemeOut].bg = drw_clr_create(drw, outbgcolor);
540         scheme[SchemeOut].fg = drw_clr_create(drw, outfgcolor);
541
542         clip = XInternAtom(dpy, "CLIPBOARD",   False);
543         utf8 = XInternAtom(dpy, "UTF8_STRING", False);
544
545         /* calculate menu geometry */
546         bh = drw->fonts[0]->h + 2;
547         lines = MAX(lines, 0);
548         mh = (lines + 1) * bh;
549 #ifdef XINERAMA
550         if ((info = XineramaQueryScreens(dpy, &n))) {
551                 XGetInputFocus(dpy, &w, &di);
552                 if (mon != -1 && mon < n)
553                         i = mon;
554                 else if (w != root && w != PointerRoot && w != None) {
555                         /* find top-level window containing current input focus */
556                         do {
557                                 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
558                                         XFree(dws);
559                         } while (w != root && w != pw);
560                         /* find xinerama screen with which the window intersects most */
561                         if (XGetWindowAttributes(dpy, pw, &wa))
562                                 for (j = 0; j < n; j++)
563                                         if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
564                                                 area = a;
565                                                 i = j;
566                                         }
567                 }
568                 /* no focused window is on screen, so use pointer location instead */
569                 if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
570                         for (i = 0; i < n; i++)
571                                 if (INTERSECT(x, y, 1, 1, info[i]))
572                                         break;
573
574                 x = info[i].x_org;
575                 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
576                 mw = info[i].width;
577                 XFree(info);
578         } else
579 #endif
580         {
581                 x = 0;
582                 y = topbar ? 0 : sh - mh;
583                 mw = sw;
584         }
585         promptw = (prompt && *prompt) ? TEXTW(prompt) : 0;
586         inputw = MIN(inputw, mw/3);
587         match();
588
589         /* create menu window */
590         swa.override_redirect = True;
591         swa.background_pixel = scheme[SchemeNorm].bg->pix;
592         swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
593         win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
594                             DefaultDepth(dpy, screen), CopyFromParent,
595                             DefaultVisual(dpy, screen),
596                             CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
597
598         /* open input methods */
599         xim = XOpenIM(dpy, NULL, NULL, NULL);
600         xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
601                         XNClientWindow, win, XNFocusWindow, win, NULL);
602
603         XMapRaised(dpy, win);
604         drw_resize(drw, mw, mh);
605         drawmenu();
606 }
607
608 static void
609 usage(void)
610 {
611         fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
612               "             [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
613         exit(1);
614 }
615
616 int
617 main(int argc, char *argv[])
618 {
619         int i, fast = 0;
620
621         for (i = 1; i < argc; i++)
622                 /* these options take no arguments */
623                 if (!strcmp(argv[i], "-v")) {      /* prints version information */
624                         puts("dmenu-"VERSION);
625                         exit(0);
626                 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
627                         topbar = 0;
628                 else if (!strcmp(argv[i], "-f"))   /* grabs keyboard before reading stdin */
629                         fast = 1;
630                 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
631                         fstrncmp = strncasecmp;
632                         fstrstr = cistrstr;
633                 } else if (i + 1 == argc)
634                         usage();
635                 /* these options take one argument */
636                 else if (!strcmp(argv[i], "-l"))   /* number of lines in vertical list */
637                         lines = atoi(argv[++i]);
638                 else if (!strcmp(argv[i], "-m"))
639                         mon = atoi(argv[++i]);
640                 else if (!strcmp(argv[i], "-p"))   /* adds prompt to left of input field */
641                         prompt = argv[++i];
642                 else if (!strcmp(argv[i], "-fn"))  /* font or font set */
643                         fonts[0] = argv[++i];
644                 else if (!strcmp(argv[i], "-nb"))  /* normal background color */
645                         normbgcolor = argv[++i];
646                 else if (!strcmp(argv[i], "-nf"))  /* normal foreground color */
647                         normfgcolor = argv[++i];
648                 else if (!strcmp(argv[i], "-sb"))  /* selected background color */
649                         selbgcolor = argv[++i];
650                 else if (!strcmp(argv[i], "-sf"))  /* selected foreground color */
651                         selfgcolor = argv[++i];
652                 else
653                         usage();
654
655         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
656                 fputs("warning: no locale support\n", stderr);
657         if (!(dpy = XOpenDisplay(NULL)))
658                 die("cannot open display\n");
659         screen = DefaultScreen(dpy);
660         root = RootWindow(dpy, screen);
661         sw = DisplayWidth(dpy, screen);
662         sh = DisplayHeight(dpy, screen);
663         drw = drw_create(dpy, screen, root, sw, sh);
664         drw_load_fonts(drw, fonts, LENGTH(fonts));
665         if (!drw->fontcount)
666                 die("no fonts could be loaded.\n");
667         drw_setscheme(drw, &scheme[SchemeNorm]);
668
669         if (fast) {
670                 grabkeyboard();
671                 readstdin();
672         } else {
673                 readstdin();
674                 grabkeyboard();
675         }
676         setup();
677         run();
678
679         return 1; /* unreachable */
680 }