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