]> git.armaanb.net Git - dmenu.git/blob - dmenu.c
b56f3a899ebdf1ae177ef819d04c3661a69f37cd
[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-2014 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                 if(sel)
374                         sel->out = True;
375                 break;
376         case XK_Right:
377                 if(text[cursor] != '\0') {
378                         cursor = nextrune(+1);
379                         break;
380                 }
381                 if(lines > 0)
382                         return;
383                 /* fallthrough */
384         case XK_Down:
385                 if(sel && sel->right && (sel = sel->right) == next) {
386                         curr = next;
387                         calcoffsets();
388                 }
389                 break;
390         case XK_Tab:
391                 if(!sel)
392                         return;
393                 strncpy(text, sel->text, sizeof text - 1);
394                 text[sizeof text - 1] = '\0';
395                 cursor = strlen(text);
396                 match();
397                 break;
398         }
399         drawmenu();
400 }
401
402 void
403 match(void) {
404         static char **tokv = NULL;
405         static int tokn = 0;
406
407         char buf[sizeof text], *s;
408         int i, tokc = 0;
409         size_t len;
410         Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
411
412         strcpy(buf, text);
413         /* separate input text into tokens to be matched individually */
414         for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
415                 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
416                         eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
417         len = tokc ? strlen(tokv[0]) : 0;
418
419         matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
420         for(item = items; item && item->text; item++) {
421                 for(i = 0; i < tokc; i++)
422                         if(!fstrstr(item->text, tokv[i]))
423                                 break;
424                 if(i != tokc) /* not all tokens match */
425                         continue;
426                 /* exact matches go first, then prefixes, then substrings */
427                 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
428                         appenditem(item, &matches, &matchend);
429                 else if(!fstrncmp(tokv[0], item->text, len))
430                         appenditem(item, &lprefix, &prefixend);
431                 else
432                         appenditem(item, &lsubstr, &substrend);
433         }
434         if(lprefix) {
435                 if(matches) {
436                         matchend->right = lprefix;
437                         lprefix->left = matchend;
438                 }
439                 else
440                         matches = lprefix;
441                 matchend = prefixend;
442         }
443         if(lsubstr) {
444                 if(matches) {
445                         matchend->right = lsubstr;
446                         lsubstr->left = matchend;
447                 }
448                 else
449                         matches = lsubstr;
450                 matchend = substrend;
451         }
452         curr = sel = matches;
453         calcoffsets();
454 }
455
456 size_t
457 nextrune(int inc) {
458         ssize_t n;
459
460         /* return location of next utf8 rune in the given direction (+1 or -1) */
461         for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
462         return n;
463 }
464
465 void
466 paste(void) {
467         char *p, *q;
468         int di;
469         unsigned long dl;
470         Atom da;
471
472         /* we have been given the current selection, now insert it into input */
473         XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
474                            utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
475         insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
476         XFree(p);
477         drawmenu();
478 }
479
480 void
481 readstdin(void) {
482         char buf[sizeof text], *p, *maxstr = NULL;
483         size_t i, max = 0, size = 0;
484
485         /* read each line from stdin and add it to the item list */
486         for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
487                 if(i+1 >= size / sizeof *items)
488                         if(!(items = realloc(items, (size += BUFSIZ))))
489                                 eprintf("cannot realloc %u bytes:", size);
490                 if((p = strchr(buf, '\n')))
491                         *p = '\0';
492                 if(!(items[i].text = strdup(buf)))
493                         eprintf("cannot strdup %u bytes:", strlen(buf)+1);
494                 items[i].out = False;
495                 if(strlen(items[i].text) > max)
496                         max = strlen(maxstr = items[i].text);
497         }
498         if(items)
499                 items[i].text = NULL;
500         inputw = maxstr ? textw(dc, maxstr) : 0;
501         lines = MIN(lines, i);
502 }
503
504 void
505 run(void) {
506         XEvent ev;
507
508         while(!XNextEvent(dc->dpy, &ev)) {
509                 if(XFilterEvent(&ev, win))
510                         continue;
511                 switch(ev.type) {
512                 case Expose:
513                         if(ev.xexpose.count == 0)
514                                 mapdc(dc, win, mw, mh);
515                         break;
516                 case KeyPress:
517                         keypress(&ev.xkey);
518                         break;
519                 case SelectionNotify:
520                         if(ev.xselection.property == utf8)
521                                 paste();
522                         break;
523                 case VisibilityNotify:
524                         if(ev.xvisibility.state != VisibilityUnobscured)
525                                 XRaiseWindow(dc->dpy, win);
526                         break;
527                 }
528         }
529 }
530
531 void
532 setup(void) {
533         int x, y, screen = DefaultScreen(dc->dpy);
534         Window root = RootWindow(dc->dpy, screen);
535         XSetWindowAttributes swa;
536         XIM xim;
537 #ifdef XINERAMA
538         int n;
539         XineramaScreenInfo *info;
540 #endif
541
542         normcol[ColBG] = getcolor(dc, normbgcolor);
543         normcol[ColFG] = getcolor(dc, normfgcolor);
544         selcol[ColBG]  = getcolor(dc, selbgcolor);
545         selcol[ColFG]  = getcolor(dc, selfgcolor);
546         outcol[ColBG]  = getcolor(dc, outbgcolor);
547         outcol[ColFG]  = getcolor(dc, outfgcolor);
548
549         clip = XInternAtom(dc->dpy, "CLIPBOARD",   False);
550         utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
551
552         /* calculate menu geometry */
553         bh = dc->font.height + 2;
554         lines = MAX(lines, 0);
555         mh = (lines + 1) * bh;
556 #ifdef XINERAMA
557         if((info = XineramaQueryScreens(dc->dpy, &n))) {
558                 int a, j, di, i = 0, area = 0;
559                 unsigned int du;
560                 Window w, pw, dw, *dws;
561                 XWindowAttributes wa;
562
563                 XGetInputFocus(dc->dpy, &w, &di);
564                 if(mon != -1 && mon < n)
565                         i = mon;
566                 if(!i && w != root && w != PointerRoot && w != None) {
567                         /* find top-level window containing current input focus */
568                         do {
569                                 if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
570                                         XFree(dws);
571                         } while(w != root && w != pw);
572                         /* find xinerama screen with which the window intersects most */
573                         if(XGetWindowAttributes(dc->dpy, pw, &wa))
574                                 for(j = 0; j < n; j++)
575                                         if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
576                                                 area = a;
577                                                 i = j;
578                                         }
579                 }
580                 /* no focused window is on screen, so use pointer location instead */
581                 if(mon == -1 && !area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
582                         for(i = 0; i < n; i++)
583                                 if(INTERSECT(x, y, 1, 1, info[i]))
584                                         break;
585
586                 x = info[i].x_org;
587                 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
588                 mw = info[i].width;
589                 XFree(info);
590         }
591         else
592 #endif
593         {
594                 x = 0;
595                 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
596                 mw = DisplayWidth(dc->dpy, screen);
597         }
598         promptw = (prompt && *prompt) ? textw(dc, prompt) : 0;
599         inputw = MIN(inputw, mw/3);
600         match();
601
602         /* create menu window */
603         swa.override_redirect = True;
604         swa.background_pixel = normcol[ColBG];
605         swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
606         win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
607                             DefaultDepth(dc->dpy, screen), CopyFromParent,
608                             DefaultVisual(dc->dpy, screen),
609                             CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
610
611         /* open input methods */
612         xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
613         xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
614                         XNClientWindow, win, XNFocusWindow, win, NULL);
615
616         XMapRaised(dc->dpy, win);
617         resizedc(dc, mw, mh);
618         drawmenu();
619 }
620
621 void
622 usage(void) {
623         fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
624               "             [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
625         exit(EXIT_FAILURE);
626 }