]> git.armaanb.net Git - dmenu.git/blob - dmenu.c
efficient incremental search
[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 <unistd.h>
7 #include <X11/Xlib.h>
8 #include <X11/Xatom.h>
9 #include <X11/Xutil.h>
10 #ifdef XINERAMA
11 #include <X11/extensions/Xinerama.h>
12 #endif
13 #include "draw.h"
14
15 #define INRECT(x,y,rx,ry,rw,rh) ((x) >= (rx) && (x) < (rx)+(rw) && (y) >= (ry) && (y) < (ry)+(rh))
16 #define MIN(a,b)                ((a) < (b) ? (a) : (b))
17 #define MAX(a,b)                ((a) > (b) ? (a) : (b))
18
19 typedef struct Item Item;
20 struct Item {
21         char *text;
22         Item *left, *right;
23 };
24
25 static void appenditem(Item *item, Item **list, Item **last);
26 static void calcoffsets(void);
27 static void drawmenu(void);
28 static char *fstrstr(const char *s, const char *sub);
29 static void grabkeyboard(void);
30 static void insert(const char *str, ssize_t n);
31 static void keypress(XKeyEvent *ev);
32 static void match(Bool sub);
33 static size_t nextrune(int incr);
34 static void paste(void);
35 static void readstdin(void);
36 static void run(void);
37 static void setup(void);
38
39 static char text[BUFSIZ] = "";
40 static int bh, mw, mh;
41 static int inputw;
42 static int lines = 0;
43 static int monitor = -1;
44 static int promptw;
45 static size_t cursor = 0;
46 static const char *font = NULL;
47 static const char *prompt = NULL;
48 static const char *normbgcolor = "#cccccc";
49 static const char *normfgcolor = "#000000";
50 static const char *selbgcolor  = "#0066ff";
51 static const char *selfgcolor  = "#ffffff";
52 static unsigned long normcol[ColLast];
53 static unsigned long selcol[ColLast];
54 static Atom utf8;
55 static Bool topbar = True;
56 static DC *dc;
57 static Item *items = NULL;
58 static Item *matches, *matchend;
59 static Item *prev, *curr, *next, *sel;
60 static Window win;
61
62 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
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                 /* single flags */
71                 if(!strcmp(argv[i], "-v")) {
72                         fputs("dmenu-"VERSION", © 2006-2011 dmenu engineers, see LICENSE for details\n", stdout);
73                         exit(EXIT_SUCCESS);
74                 }
75                 else if(!strcmp(argv[i], "-b"))
76                         topbar = False;
77                 else if(!strcmp(argv[i], "-f"))
78                         fast = True;
79                 else if(!strcmp(argv[i], "-i"))
80                         fstrncmp = strncasecmp;
81                 else if(i+1 == argc)
82                         goto usage;
83                 /* double flags */
84                 else if(!strcmp(argv[i], "-l"))
85                         lines = atoi(argv[++i]);
86                 else if(!strcmp(argv[i], "-m"))
87                         monitor = atoi(argv[++i]);
88                 else if(!strcmp(argv[i], "-p"))
89                         prompt = argv[++i];
90                 else if(!strcmp(argv[i], "-fn"))
91                         font = argv[++i];
92                 else if(!strcmp(argv[i], "-nb"))
93                         normbgcolor = argv[++i];
94                 else if(!strcmp(argv[i], "-nf"))
95                         normfgcolor = argv[++i];
96                 else if(!strcmp(argv[i], "-sb"))
97                         selbgcolor = argv[++i];
98                 else if(!strcmp(argv[i], "-sf"))
99                         selfgcolor = argv[++i];
100                 else
101                         goto usage;
102
103         dc = initdc();
104         initfont(dc, font);
105
106         if(fast) {
107                 grabkeyboard();
108                 readstdin();
109         }
110         else {
111                 readstdin();
112                 grabkeyboard();
113         }
114         setup();
115         run();
116         return EXIT_FAILURE;
117
118 usage:
119         fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-m monitor] [-p prompt] [-fn font]\n"
120               "             [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
121         return EXIT_FAILURE;
122 }
123
124 void
125 appenditem(Item *item, Item **list, Item **last) {
126         if(!*last)
127                 *list = item;
128         else
129                 (*last)->right = item;
130         item->left = *last;
131         item->right = NULL;
132         *last = item;
133 }
134
135 void
136 calcoffsets(void) {
137         unsigned int i, n;
138
139         if(lines > 0)
140                 n = lines * bh;
141         else
142                 n = mw - (promptw + inputw + textw(dc, "<") + textw(dc, ">"));
143
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 void
153 drawmenu(void) {
154         int curpos;
155         Item *item;
156
157         dc->x = 0;
158         dc->y = 0;
159         dc->h = bh;
160         drawrect(dc, 0, 0, mw, mh, True, BG(dc, normcol));
161
162         if(prompt) {
163                 dc->w = promptw;
164                 drawtext(dc, prompt, selcol);
165                 dc->x = dc->w;
166         }
167         dc->w = (lines > 0 || !matches) ? mw - dc->x : inputw;
168         drawtext(dc, text, normcol);
169         if((curpos = textnw(dc, text, cursor) + dc->h/2 - 2) < dc->w)
170                 drawrect(dc, curpos, 2, 1, dc->h - 4, True, FG(dc, normcol));
171
172         if(lines > 0) {
173                 dc->w = mw - dc->x;
174                 for(item = curr; item != next; item = item->right) {
175                         dc->y += dc->h;
176                         drawtext(dc, item->text, (item == sel) ? selcol : normcol);
177                 }
178         }
179         else if(matches) {
180                 dc->x += inputw;
181                 dc->w = textw(dc, "<");
182                 if(curr->left)
183                         drawtext(dc, "<", normcol);
184                 for(item = curr; item != next; item = item->right) {
185                         dc->x += dc->w;
186                         dc->w = MIN(textw(dc, item->text), mw - dc->x - textw(dc, ">"));
187                         drawtext(dc, item->text, (item == sel) ? selcol : normcol);
188                 }
189                 dc->w = textw(dc, ">");
190                 dc->x = mw - dc->w;
191                 if(next)
192                         drawtext(dc, ">", normcol);
193         }
194         mapdc(dc, win, mw, mh);
195 }
196
197 char *
198 fstrstr(const char *s, const char *sub) {
199         size_t len;
200
201         for(len = strlen(sub); *s; s++)
202                 if(!fstrncmp(s, sub, len))
203                         return (char *)s;
204         return NULL;
205 }
206
207 void
208 grabkeyboard(void) {
209         int i;
210
211         for(i = 0; i < 1000; i++) {
212                 if(XGrabKeyboard(dc->dpy, DefaultRootWindow(dc->dpy), True,
213                                  GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
214                         return;
215                 usleep(1000);
216         }
217         eprintf("cannot grab keyboard\n");
218 }
219
220 void
221 insert(const char *str, ssize_t n) {
222         if(strlen(text) + n > sizeof text - 1)
223                 return;
224         memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
225         if(n > 0)
226                 memcpy(&text[cursor], str, n);
227         cursor += n;
228         match(n > 0);
229 }
230
231 void
232 keypress(XKeyEvent *ev) {
233         char buf[32];
234         size_t len;
235         KeySym ksym;
236
237         len = strlen(text);
238         XLookupString(ev, buf, sizeof buf, &ksym, NULL);
239         if(ev->state & ControlMask)
240                 switch(tolower(ksym)) {
241                 default:
242                         return;
243                 case XK_a:
244                         ksym = XK_Home;
245                         break;
246                 case XK_b:
247                         ksym = XK_Left;
248                         break;
249                 case XK_c:
250                         ksym = XK_Escape;
251                         break;
252                 case XK_d:
253                         ksym = XK_Delete;
254                         break;
255                 case XK_e:
256                         ksym = XK_End;
257                         break;
258                 case XK_f:
259                         ksym = XK_Right;
260                         break;
261                 case XK_h:
262                         ksym = XK_BackSpace;
263                         break;
264                 case XK_i:
265                         ksym = XK_Tab;
266                         break;
267                 case XK_j:
268                         ksym = XK_Return;
269                         break;
270                 case XK_k:  /* delete right */
271                         text[cursor] = '\0';
272                         match(False);
273                         break;
274                 case XK_n:
275                         ksym = XK_Down;
276                         break;
277                 case XK_p:
278                         ksym = XK_Up;
279                         break;
280                 case XK_u:  /* delete left */
281                         insert(NULL, 0 - cursor);
282                         break;
283                 case XK_w:  /* delete word */
284                         while(cursor > 0 && text[nextrune(-1)] == ' ')
285                                 insert(NULL, nextrune(-1) - cursor);
286                         while(cursor > 0 && text[nextrune(-1)] != ' ')
287                                 insert(NULL, nextrune(-1) - cursor);
288                         break;
289                 case XK_y:  /* paste selection */
290                         XConvertSelection(dc->dpy, XA_PRIMARY, utf8, utf8, win, CurrentTime);
291                         return;
292                 }
293         switch(ksym) {
294         default:
295                 if(!iscntrl(*buf))
296                         insert(buf, strlen(buf));
297                 break;
298         case XK_Delete:
299                 if(cursor == len)
300                         return;
301                 cursor = nextrune(+1);
302         case XK_BackSpace:
303                 if(cursor > 0)
304                         insert(NULL, nextrune(-1) - cursor);
305                 break;
306         case XK_End:
307                 if(cursor < len) {
308                         cursor = len;
309                         break;
310                 }
311                 if(next) {
312                         curr = matchend;
313                         calcoffsets();
314                         curr = prev;
315                         calcoffsets();
316                         while(next && (curr = curr->right))
317                                 calcoffsets();
318                 }
319                 sel = matchend;
320                 break;
321         case XK_Escape:
322                 exit(EXIT_FAILURE);
323         case XK_Home:
324                 if(sel == matches) {
325                         cursor = 0;
326                         break;
327                 }
328                 sel = curr = matches;
329                 calcoffsets();
330                 break;
331         case XK_Left:
332                 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
333                         cursor = nextrune(-1);
334                         break;
335                 }
336                 else if(lines > 0)
337                         return;
338         case XK_Up:
339                 if(sel && sel->left && (sel = sel->left)->right == curr) {
340                         curr = prev;
341                         calcoffsets();
342                 }
343                 break;
344         case XK_Next:
345                 if(!next)
346                         return;
347                 sel = curr = next;
348                 calcoffsets();
349                 break;
350         case XK_Prior:
351                 if(!prev)
352                         return;
353                 sel = curr = prev;
354                 calcoffsets();
355                 break;
356         case XK_Return:
357         case XK_KP_Enter:
358                 fputs((sel && !(ev->state & ShiftMask)) ? sel->text : text, stdout);
359                 exit(EXIT_SUCCESS);
360         case XK_Right:
361                 if(cursor < len) {
362                         cursor = nextrune(+1);
363                         break;
364                 }
365                 else if(lines > 0)
366                         return;
367         case XK_Down:
368                 if(sel && sel->right && (sel = sel->right) == next) {
369                         curr = next;
370                         calcoffsets();
371                 }
372                 break;
373         case XK_Tab:
374                 if(!sel)
375                         return;
376                 strncpy(text, sel->text, sizeof text);
377                 cursor = strlen(text);
378                 match(True);
379                 break;
380         }
381         drawmenu();
382 }
383
384 void
385 match(Bool sub) {
386         size_t len = strlen(text);
387         Item *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
388         Item *item, *next = NULL;
389
390         lexact = lprefix = lsubstr = exactend = prefixend = substrend = NULL;
391         for(item = sub ? matches : items; item && item->text; item = next) {
392                 next = sub ? item->right : item + 1;
393                 if(!fstrncmp(text, item->text, len + 1))
394                         appenditem(item, &lexact, &exactend);
395                 else if(!fstrncmp(text, item->text, len))
396                         appenditem(item, &lprefix, &prefixend);
397                 else if(fstrstr(item->text, text))
398                         appenditem(item, &lsubstr, &substrend);
399         }
400         matches = lexact;
401         matchend = exactend;
402
403         if(lprefix) {
404                 if(matchend) {
405                         matchend->right = lprefix;
406                         lprefix->left = matchend;
407                 }
408                 else
409                         matches = lprefix;
410                 matchend = prefixend;
411         }
412         if(lsubstr) {
413                 if(matchend) {
414                         matchend->right = lsubstr;
415                         lsubstr->left = matchend;
416                 }
417                 else
418                         matches = lsubstr;
419                 matchend = substrend;
420         }
421         curr = sel = matches;
422         calcoffsets();
423 }
424
425 size_t
426 nextrune(int incr) {
427         size_t n, len = strlen(text);
428
429         for(n = cursor + incr; n >= 0 && n < len && (text[n] & 0xc0) == 0x80; n += incr);
430         return n;
431 }
432
433 void
434 paste(void) {
435         char *p, *q;
436         int di;
437         unsigned long dl;
438         Atom da;
439
440         XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
441                            utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
442         insert(p, (q = strchr(p, '\n')) ? q-p : strlen(p));
443         XFree(p);
444         drawmenu();
445 }
446
447 void
448 readstdin(void) {
449         char buf[sizeof text], *p, *maxstr = NULL;
450         size_t i, max = 0, size = 0;
451
452         for(i = 0; fgets(buf, sizeof buf, stdin); items[++i].text = NULL) {
453                 if(i+1 >= size / sizeof *items)
454                         if(!(items = realloc(items, (size += BUFSIZ))))
455                                 eprintf("cannot realloc %u bytes:", size);
456                 if((p = strchr(buf, '\n')))
457                         *p = '\0';
458                 if(!(items[i].text = strdup(buf)))
459                         eprintf("cannot strdup %u bytes:", strlen(buf)+1);
460                 if(strlen(items[i].text) > max)
461                         max = strlen(maxstr = items[i].text);
462         }
463         inputw = maxstr ? textw(dc, maxstr) : 0;
464 }
465
466 void
467 run(void) {
468         XEvent ev;
469
470         while(!XNextEvent(dc->dpy, &ev))
471                 switch(ev.type) {
472                 case Expose:
473                         if(ev.xexpose.count == 0)
474                                 drawmenu();
475                         break;
476                 case KeyPress:
477                         keypress(&ev.xkey);
478                         break;
479                 case SelectionNotify:
480                         if(ev.xselection.property == utf8)
481                                 paste();
482                         break;
483                 case VisibilityNotify:
484                         if(ev.xvisibility.state != VisibilityUnobscured)
485                                 XRaiseWindow(dc->dpy, win);
486                         break;
487                 }
488 }
489
490 void
491 setup(void) {
492         int x, y, screen = DefaultScreen(dc->dpy);
493         Window root = RootWindow(dc->dpy, screen);
494         XSetWindowAttributes wa;
495 #ifdef XINERAMA
496         int n;
497         XineramaScreenInfo *info;
498 #endif
499
500         normcol[ColBG] = getcolor(dc, normbgcolor);
501         normcol[ColFG] = getcolor(dc, normfgcolor);
502         selcol[ColBG]  = getcolor(dc, selbgcolor);
503         selcol[ColFG]  = getcolor(dc, selfgcolor);
504
505         utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
506
507         /* menu geometry */
508         bh = dc->font.height + 2;
509         lines = MAX(lines, 0);
510         mh = (lines + 1) * bh;
511 #ifdef XINERAMA
512         if((info = XineramaQueryScreens(dc->dpy, &n))) {
513                 int i, di;
514                 unsigned int du;
515                 Window dw;
516
517                 XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
518                 for(i = 0; i < n-1; i++)
519                         if((monitor == info[i].screen_number)
520                         || (monitor < 0 && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)))
521                                 break;
522                 x = info[i].x_org;
523                 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
524                 mw = info[i].width;
525                 XFree(info);
526         }
527         else
528 #endif
529         {
530                 x = 0;
531                 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
532                 mw = DisplayWidth(dc->dpy, screen);
533         }
534         inputw = MIN(inputw, mw/3);
535         promptw = prompt ? textw(dc, prompt) : 0;
536         match(False);
537
538         /* menu window */
539         wa.override_redirect = True;
540         wa.background_pixmap = ParentRelative;
541         wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
542         win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
543                             DefaultDepth(dc->dpy, screen), CopyFromParent,
544                             DefaultVisual(dc->dpy, screen),
545                             CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
546
547         XMapRaised(dc->dpy, win);
548         resizedc(dc, mw, mh);
549         drawmenu();
550 }