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