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