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