removed -t, now using isatty() instead of select() to prevent execution from an inter...
[dmenu.git] / main.c
1 /* (C)opyright MMVI-MMVII Anselm R. Garbe <garbeam at gmail dot com>
2  * (C)opyright MMVI-MMVII Sander van Dijk <a dot h dot vandijk at gmail dot com>
3  * See LICENSE file for license details.
4  */
5 #include "dmenu.h"
6
7 #include <ctype.h>
8 #include <locale.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <X11/Xutil.h>
14 #include <X11/keysym.h>
15
16 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
17
18 typedef struct Item Item;
19 struct Item {
20         Item *next;             /* traverses all items */
21         Item *left, *right;     /* traverses items matching current search pattern */
22         char *text;
23 };
24
25 /* static */
26
27 static char text[4096];
28 static char *prompt = NULL;
29 static int mw, mh;
30 static int ret = 0;
31 static int nitem = 0;
32 static unsigned int cmdw = 0;
33 static unsigned int promptw = 0;
34 static unsigned int numlockmask = 0;
35 static Bool running = True;
36 static Item *allitems = NULL;   /* first of all items */
37 static Item *item = NULL;       /* first of pattern matching items */
38 static Item *sel = NULL;
39 static Item *next = NULL;
40 static Item *prev = NULL;
41 static Item *curr = NULL;
42 static Window root;
43 static Window win;
44
45 static unsigned int
46 textnw(const char *text, unsigned int len) {
47         XRectangle r;
48
49         if(dc.font.set) {
50                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
51                 return r.width;
52         }
53         return XTextWidth(dc.font.xfont, text, len);
54 }
55
56 static unsigned int
57 textw(const char *text) {
58         return textnw(text, strlen(text)) + dc.font.height;
59 }
60
61 static void
62 calcoffsets(void) {
63         unsigned int tw, w;
64
65         if(!curr)
66                 return;
67         w = promptw + cmdw + 2 * SPACE;
68         for(next = curr; next; next=next->right) {
69                 tw = textw(next->text);
70                 if(tw > mw / 3)
71                         tw = mw / 3;
72                 w += tw;
73                 if(w > mw)
74                         break;
75         }
76         w = promptw + cmdw + 2 * SPACE;
77         for(prev = curr; prev && prev->left; prev=prev->left) {
78                 tw = textw(prev->left->text);
79                 if(tw > mw / 3)
80                         tw = mw / 3;
81                 w += tw;
82                 if(w > mw)
83                         break;
84         }
85 }
86
87 static void
88 drawtext(const char *text, unsigned long col[ColLast]) {
89         int x, y, w, h;
90         static char buf[256];
91         unsigned int len, olen;
92         XGCValues gcv;
93         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
94
95         XSetForeground(dpy, dc.gc, col[ColBG]);
96         XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
97         if(!text)
98                 return;
99         w = 0;
100         olen = len = strlen(text);
101         if(len >= sizeof buf)
102                 len = sizeof buf - 1;
103         memcpy(buf, text, len);
104         buf[len] = 0;
105         h = dc.font.ascent + dc.font.descent;
106         y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
107         x = dc.x + (h / 2);
108         /* shorten text if necessary */
109         while(len && (w = textnw(buf, len)) > dc.w - h)
110                 buf[--len] = 0;
111         if(len < olen) {
112                 if(len > 1)
113                         buf[len - 1] = '.';
114                 if(len > 2)
115                         buf[len - 2] = '.';
116                 if(len > 3)
117                         buf[len - 3] = '.';
118         }
119         if(w > dc.w)
120                 return; /* too long */
121         gcv.foreground = col[ColFG];
122         if(dc.font.set) {
123                 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
124                 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc,
125                                 x, y, buf, len);
126         }
127         else {
128                 gcv.font = dc.font.xfont->fid;
129                 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
130                 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
131         }
132 }
133
134 static void
135 drawmenu(void) {
136         Item *i;
137
138         dc.x = 0;
139         dc.y = 0;
140         dc.w = mw;
141         dc.h = mh;
142         drawtext(NULL, dc.norm);
143         /* print prompt? */
144         if(promptw) {
145                 dc.w = promptw;
146                 drawtext(prompt, dc.sel);
147         }
148         dc.x += promptw;
149         dc.w = mw - promptw;
150         /* print command */
151         if(cmdw && item)
152                 dc.w = cmdw;
153         drawtext(text[0] ? text : NULL, dc.norm);
154         dc.x += cmdw;
155         if(curr) {
156                 dc.w = SPACE;
157                 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
158                 dc.x += dc.w;
159                 /* determine maximum items */
160                 for(i = curr; i != next; i=i->right) {
161                         dc.w = textw(i->text);
162                         if(dc.w > mw / 3)
163                                 dc.w = mw / 3;
164                         drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
165                         dc.x += dc.w;
166                 }
167                 dc.x = mw - SPACE;
168                 dc.w = SPACE;
169                 drawtext(next ? ">" : NULL, dc.norm);
170         }
171         XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
172         XFlush(dpy);
173 }
174
175 static unsigned long
176 getcolor(const char *colstr) {
177         Colormap cmap = DefaultColormap(dpy, screen);
178         XColor color;
179
180         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
181                 eprint("error, cannot allocate color '%s'\n", colstr);
182         return color.pixel;
183 }
184
185 static void
186 setfont(const char *fontstr) {
187         char *def, **missing;
188         int i, n;
189
190         missing = NULL;
191         if(dc.font.set)
192                 XFreeFontSet(dpy, dc.font.set);
193         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
194         if(missing)
195                 XFreeStringList(missing);
196         if(dc.font.set) {
197                 XFontSetExtents *font_extents;
198                 XFontStruct **xfonts;
199                 char **font_names;
200                 dc.font.ascent = dc.font.descent = 0;
201                 font_extents = XExtentsOfFontSet(dc.font.set);
202                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
203                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
204                         if(dc.font.ascent < (*xfonts)->ascent)
205                                 dc.font.ascent = (*xfonts)->ascent;
206                         if(dc.font.descent < (*xfonts)->descent)
207                                 dc.font.descent = (*xfonts)->descent;
208                         xfonts++;
209                 }
210         }
211         else {
212                 if(dc.font.xfont)
213                         XFreeFont(dpy, dc.font.xfont);
214                 dc.font.xfont = NULL;
215                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
216                         eprint("error, cannot load font: '%s'\n", fontstr);
217                 dc.font.ascent = dc.font.xfont->ascent;
218                 dc.font.descent = dc.font.xfont->descent;
219         }
220         dc.font.height = dc.font.ascent + dc.font.descent;
221 }
222
223 static void
224 match(char *pattern) {
225         unsigned int plen;
226         Item *i, *j;
227
228         if(!pattern)
229                 return;
230         plen = strlen(pattern);
231         item = j = NULL;
232         nitem = 0;
233         for(i = allitems; i; i=i->next)
234                 if(!plen || !strncmp(pattern, i->text, plen)) {
235                         if(!j)
236                                 item = i;
237                         else
238                                 j->right = i;
239                         i->left = j;
240                         i->right = NULL;
241                         j = i;
242                         nitem++;
243                 }
244         for(i = allitems; i; i=i->next)
245                 if(plen && strncmp(pattern, i->text, plen)
246                                 && strstr(i->text, pattern)) {
247                         if(!j)
248                                 item = i;
249                         else
250                                 j->right = i;
251                         i->left = j;
252                         i->right = NULL;
253                         j = i;
254                         nitem++;
255                 }
256         curr = prev = next = sel = item;
257         calcoffsets();
258 }
259
260 static void
261 kpress(XKeyEvent * e) {
262         char buf[32];
263         int i, num, prev_nitem;
264         unsigned int len;
265         KeySym ksym;
266
267         len = strlen(text);
268         buf[0] = 0;
269         num = XLookupString(e, buf, sizeof buf, &ksym, 0);
270         if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
271                         || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
272                         || IsPrivateKeypadKey(ksym))
273                 return;
274         /* first check if a control mask is omitted */
275         if(e->state & ControlMask) {
276                 switch (ksym) {
277                 default:        /* ignore other control sequences */
278                         return;
279                 case XK_bracketleft:
280                         ksym = XK_Escape;
281                         break;
282                 case XK_h:
283                 case XK_H:
284                         ksym = XK_BackSpace;
285                         break;
286                 case XK_i:
287                 case XK_I:
288                         ksym = XK_Tab;
289                         break;
290                 case XK_j:
291                 case XK_J:
292                         ksym = XK_Return;
293                         break;
294                 case XK_u:
295                 case XK_U:
296                         text[0] = 0;
297                         match(text);
298                         drawmenu();
299                         return;
300                 case XK_w:
301                 case XK_W:
302                         if(len) {
303                                 i = len - 1;
304                                 while(i >= 0 && text[i] == ' ')
305                                         text[i--] = 0;
306                                 while(i >= 0 && text[i] != ' ')
307                                         text[i--] = 0;
308                                 match(text);
309                                 drawmenu();
310                         }
311                         return;
312                 }
313         }
314         if(CLEANMASK(e->state) & Mod1Mask) {
315                 switch(ksym) {
316                 default: return;
317                 case XK_h:
318                         ksym = XK_Left;
319                         break;
320                 case XK_l:
321                         ksym = XK_Right;
322                         break;
323                 case XK_j:
324                         ksym = XK_Next;
325                         break;
326                 case XK_k:
327                         ksym = XK_Prior;
328                         break;
329                 case XK_g:
330                         ksym = XK_Home;
331                         break;
332                 case XK_G:
333                         ksym = XK_End;
334                         break;
335                 }
336         }
337         switch(ksym) {
338         default:
339                 if(num && !iscntrl((int) buf[0])) {
340                         buf[num] = 0;
341                         if(len > 0)
342                                 strncat(text, buf, sizeof text);
343                         else
344                                 strncpy(text, buf, sizeof text);
345                         match(text);
346                 }
347                 break;
348         case XK_BackSpace:
349                 if((i = len)) {
350                         prev_nitem = nitem;
351                         do {
352                                 text[--i] = 0;
353                                 match(text);
354                         } while(i && nitem && prev_nitem == nitem);
355                         match(text);
356                 }
357                 break;
358         case XK_End:
359                 if(!item)
360                         return;
361                 while(next) {
362                         sel = curr = next;
363                         calcoffsets();
364                 }
365                 while(sel && sel->right)
366                         sel = sel->right;
367                 break;
368         case XK_Escape:
369                 ret = 1;
370                 running = False;
371                 break;
372         case XK_Home:
373                 if(!item)
374                         return;
375                 sel = curr = item;
376                 calcoffsets();
377                 break;
378         case XK_Left:
379                 if(!(sel && sel->left))
380                         return;
381                 sel=sel->left;
382                 if(sel->right == curr) {
383                         curr = prev;
384                         calcoffsets();
385                 }
386                 break;
387         case XK_Next:
388                 if(!next)
389                         return;
390                 sel = curr = next;
391                 calcoffsets();
392                 break;
393         case XK_Prior:
394                 if(!prev)
395                         return;
396                 sel = curr = prev;
397                 calcoffsets();
398                 break;
399         case XK_Return:
400                 if((e->state & ShiftMask) && text)
401                         fprintf(stdout, "%s", text);
402                 else if(sel)
403                         fprintf(stdout, "%s", sel->text);
404                 else if(text)
405                         fprintf(stdout, "%s", text);
406                 fflush(stdout);
407                 running = False;
408                 break;
409         case XK_Right:
410                 if(!(sel && sel->right))
411                         return;
412                 sel=sel->right;
413                 if(sel == next) {
414                         curr = next;
415                         calcoffsets();
416                 }
417                 break;
418         case XK_Tab:
419                 if(!sel)
420                         return;
421                 strncpy(text, sel->text, sizeof text);
422                 match(text);
423                 break;
424         }
425         drawmenu();
426 }
427
428 static char *
429 readstdin(void) {
430         static char *maxname = NULL;
431         char *p, buf[1024];
432         unsigned int len = 0, max = 0;
433         Item *i, *new;
434
435         i = 0;
436         while(fgets(buf, sizeof buf, stdin)) {
437                 len = strlen(buf);
438                 if (buf[len - 1] == '\n')
439                         buf[len - 1] = 0;
440                 p = estrdup(buf);
441                 if(max < len) {
442                         maxname = p;
443                         max = len;
444                 }
445                 new = emalloc(sizeof(Item));
446                 new->next = new->left = new->right = NULL;
447                 new->text = p;
448                 if(!i)
449                         allitems = new;
450                 else 
451                         i->next = new;
452                 i = new;
453         }
454
455         return maxname;
456 }
457
458 static void
459 usage(void) {
460         eprint("usage: dmenu [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
461                 "             [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
462 }
463
464 /* extern */
465
466 int screen;
467 Display *dpy;
468 DC dc = {0};
469
470 int
471 main(int argc, char *argv[]) {
472         Bool bottom = False;
473         char *font = FONT;
474         char *maxname;
475         char *normbg = NORMBGCOLOR;
476         char *normfg = NORMFGCOLOR;
477         char *selbg = SELBGCOLOR;
478         char *selfg = SELFGCOLOR;
479         int i, j;
480         Item *itm;
481         XEvent ev;
482         XModifierKeymap *modmap;
483         XSetWindowAttributes wa;
484
485         if(isatty(STDIN_FILENO)) {
486                 fputs("error: dmenu can't run in an interactive shell\n", stdout);
487                 usage();
488         }
489         /* command line args */
490         for(i = 1; i < argc; i++)
491                 if(!strncmp(argv[i], "-b", 3)) {
492                         bottom = True;
493                 }
494                 else if(!strncmp(argv[i], "-fn", 4)) {
495                         if(++i < argc) font = argv[i];
496                 }
497                 else if(!strncmp(argv[i], "-nb", 4)) {
498                         if(++i < argc) normbg = argv[i];
499                 }
500                 else if(!strncmp(argv[i], "-nf", 4)) {
501                         if(++i < argc) normfg = argv[i];
502                 }
503                 else if(!strncmp(argv[i], "-p", 3)) {
504                         if(++i < argc) prompt = argv[i];
505                 }
506                 else if(!strncmp(argv[i], "-sb", 4)) {
507                         if(++i < argc) selbg = argv[i];
508                 }
509                 else if(!strncmp(argv[i], "-sf", 4)) {
510                         if(++i < argc) selfg = argv[i];
511                 }
512                 else if(!strncmp(argv[i], "-v", 3))
513                         eprint("dmenu-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n");
514                 else
515                         usage();
516         setlocale(LC_CTYPE, "");
517         dpy = XOpenDisplay(0);
518         if(!dpy)
519                 eprint("dmenu: cannot open display\n");
520         screen = DefaultScreen(dpy);
521         root = RootWindow(dpy, screen);
522         while(XGrabKeyboard(dpy, root, True, GrabModeAsync,
523                          GrabModeAsync, CurrentTime) != GrabSuccess)
524                 usleep(1000);
525         maxname = readstdin();
526         /* init modifier map */
527         modmap = XGetModifierMapping(dpy);
528         for (i = 0; i < 8; i++) {
529                 for (j = 0; j < modmap->max_keypermod; j++) {
530                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
531                         == XKeysymToKeycode(dpy, XK_Num_Lock))
532                                 numlockmask = (1 << i);
533                 }
534         }
535         XFreeModifiermap(modmap);
536         /* style */
537         dc.norm[ColBG] = getcolor(normbg);
538         dc.norm[ColFG] = getcolor(normfg);
539         dc.sel[ColBG] = getcolor(selbg);
540         dc.sel[ColFG] = getcolor(selfg);
541         setfont(font);
542         /* menu window */
543         wa.override_redirect = 1;
544         wa.background_pixmap = ParentRelative;
545         wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
546         mw = DisplayWidth(dpy, screen);
547         mh = dc.font.height + 2;
548         win = XCreateWindow(dpy, root, 0,
549                         bottom ? DisplayHeight(dpy, screen) - mh : 0, mw, mh, 0,
550                         DefaultDepth(dpy, screen), CopyFromParent,
551                         DefaultVisual(dpy, screen),
552                         CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
553         /* pixmap */
554         dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
555         dc.gc = XCreateGC(dpy, root, 0, 0);
556         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
557         if(maxname)
558                 cmdw = textw(maxname);
559         if(cmdw > mw / 3)
560                 cmdw = mw / 3;
561         if(prompt)
562                 promptw = textw(prompt);
563         if(promptw > mw / 5)
564                 promptw = mw / 5;
565         text[0] = 0;
566         match(text);
567         XMapRaised(dpy, win);
568         drawmenu();
569         XSync(dpy, False);
570
571         /* main event loop */
572         while(running && !XNextEvent(dpy, &ev))
573                 switch (ev.type) {
574                 default:        /* ignore all crap */
575                         break;
576                 case KeyPress:
577                         kpress(&ev.xkey);
578                         break;
579                 case Expose:
580                         if(ev.xexpose.count == 0)
581                                 drawmenu();
582                         break;
583                 }
584
585         /* cleanup */
586         while(allitems) {
587                 itm = allitems->next;
588                 free(allitems->text);
589                 free(allitems);
590                 allitems = itm;
591         }
592         if(dc.font.set)
593                 XFreeFontSet(dpy, dc.font.set);
594         else
595                 XFreeFont(dpy, dc.font.xfont);
596         XFreePixmap(dpy, dc.drawable);
597         XFreeGC(dpy, dc.gc);
598         XDestroyWindow(dpy, win);
599         XUngrabKeyboard(dpy, CurrentTime);
600         XCloseDisplay(dpy);
601         return ret;
602 }