d54b1b3312fdf063999eaf82cf546b48094ca4ef
[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 *s, ssize_t n);
31 static void keypress(XKeyEvent *ev);
32 static void match(void);
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 *s, 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], s, n);
227         cursor += n;
228         match();
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();
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();
379                 break;
380         }
381         drawmenu();
382 }
383
384 void
385 match(void) {
386         size_t len = strlen(text);
387         Item *item, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
388
389         matches = lexact = lprefix = lsubstr = matchend = exactend = prefixend = substrend = NULL;
390         for(item = items; item && item->text; item++)
391                 if(!fstrncmp(text, item->text, len + 1))
392                         appenditem(item, &lexact, &exactend);
393                 else if(!fstrncmp(text, item->text, len))
394                         appenditem(item, &lprefix, &prefixend);
395                 else if(fstrstr(item->text, text))
396                         appenditem(item, &lsubstr, &substrend);
397
398         if(lexact) {
399                 matches = lexact;
400                 matchend = exactend;
401         }
402         if(lprefix) {
403                 if(matchend) {
404                         matchend->right = lprefix;
405                         lprefix->left = matchend;
406                 }
407                 else
408                         matches = lprefix;
409                 matchend = prefixend;
410         }
411         if(lsubstr) {
412                 if(matchend) {
413                         matchend->right = lsubstr;
414                         lsubstr->left = matchend;
415                 }
416                 else
417                         matches = lsubstr;
418                 matchend = substrend;
419         }
420         curr = sel = matches;
421         calcoffsets();
422 }
423
424 size_t
425 nextrune(int incr) {
426         size_t n, len = strlen(text);
427
428         for(n = cursor + incr; n >= 0 && n < len && (text[n] & 0xc0) == 0x80; n += incr);
429         return n;
430 }
431
432 void
433 paste(void) {
434         char *p, *q;
435         int di;
436         unsigned long dl;
437         Atom da;
438
439         XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
440                            utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
441         insert(p, (q = strchr(p, '\n')) ? q-p : strlen(p));
442         XFree(p);
443         drawmenu();
444 }
445
446 void
447 readstdin(void) {
448         char buf[sizeof text], *p, *maxstr = NULL;
449         size_t i, max = 0, size = 0;
450
451         for(i = 0; fgets(buf, sizeof buf, stdin); items[++i].text = NULL) {
452                 if(i+1 >= size / sizeof *items)
453                         if(!(items = realloc(items, (size += BUFSIZ))))
454                                 eprintf("cannot realloc %u bytes:", size);
455                 if((p = strchr(buf, '\n')))
456                         *p = '\0';
457                 if(!(items[i].text = strdup(buf)))
458                         eprintf("cannot strdup %u bytes:", strlen(buf)+1);
459                 if(strlen(items[i].text) > max)
460                         max = strlen(maxstr = items[i].text);
461         }
462         inputw = maxstr ? textw(dc, maxstr) : 0;
463 }
464
465 void
466 run(void) {
467         XEvent ev;
468
469         while(!XNextEvent(dc->dpy, &ev))
470                 switch(ev.type) {
471                 case Expose:
472                         if(ev.xexpose.count == 0)
473                                 drawmenu();
474                         break;
475                 case KeyPress:
476                         keypress(&ev.xkey);
477                         break;
478                 case SelectionNotify:
479                         if(ev.xselection.property == utf8)
480                                 paste();
481                         break;
482                 case VisibilityNotify:
483                         if(ev.xvisibility.state != VisibilityUnobscured)
484                                 XRaiseWindow(dc->dpy, win);
485                         break;
486                 }
487 }
488
489 void
490 setup(void) {
491         int x, y, screen = DefaultScreen(dc->dpy);
492         Window root = RootWindow(dc->dpy, screen);
493         XSetWindowAttributes wa;
494 #ifdef XINERAMA
495         int n;
496         XineramaScreenInfo *info;
497 #endif
498
499         normcol[ColBG] = getcolor(dc, normbgcolor);
500         normcol[ColFG] = getcolor(dc, normfgcolor);
501         selcol[ColBG] = getcolor(dc, selbgcolor);
502         selcol[ColFG] = getcolor(dc, selfgcolor);
503
504         utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
505
506         /* menu geometry */
507         bh = dc->font.height + 2;
508         lines = MAX(lines, 0);
509         mh = (lines + 1) * bh;
510 #ifdef XINERAMA
511         if((info = XineramaQueryScreens(dc->dpy, &n))) {
512                 int i, di;
513                 unsigned int du;
514                 Window dw;
515
516                 XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
517                 for(i = 0; i < n-1; i++)
518                         if((monitor == info[i].screen_number)
519                         || (monitor < 0 && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)))
520                                 break;
521                 x = info[i].x_org;
522                 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
523                 mw = info[i].width;
524                 XFree(info);
525         }
526         else
527 #endif
528         {
529                 x = 0;
530                 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
531                 mw = DisplayWidth(dc->dpy, screen);
532         }
533         /* menu window */
534         wa.override_redirect = True;
535         wa.background_pixmap = ParentRelative;
536         wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
537         win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
538                             DefaultDepth(dc->dpy, screen), CopyFromParent,
539                             DefaultVisual(dc->dpy, screen),
540                             CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
541
542         resizedc(dc, mw, mh);
543         inputw = MIN(inputw, mw/3);
544         promptw = prompt ? textw(dc, prompt) : 0;
545         XMapRaised(dc->dpy, win);
546         drawmenu();
547         match();
548 }