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