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