]> git.armaanb.net Git - dmenu.git/blob - dmenu.c
fixed a problem when backporting dwm's drawtext()
[dmenu.git] / dmenu.c
1 /* See LICENSE file for copyright and license details. */
2 #define _BSD_SOURCE
3 #include <ctype.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <strings.h>
9 #include <unistd.h>
10 #include <X11/keysym.h>
11 #include <X11/Xlib.h>
12 #include <X11/Xutil.h>
13 #ifdef XINERAMA
14 #include <X11/extensions/Xinerama.h>
15 #endif
16
17 /* macros */
18 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
19 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
20 #define MIN(a, b)               ((a) < (b) ? (a) : (b))
21
22 /* enums */
23 enum { ColFG, ColBG, ColLast };
24
25 /* typedefs */
26 typedef struct {
27         int x, y, w, h;
28         unsigned long norm[ColLast];
29         unsigned long sel[ColLast];
30         Drawable drawable;
31         GC gc;
32         struct {
33                 XFontStruct *xfont;
34                 XFontSet set;
35                 int ascent;
36                 int descent;
37                 int height;
38         } font;
39 } DC; /* draw context */
40
41 typedef struct Item Item;
42 struct Item {
43         char *text;
44         Item *next;             /* traverses all items */
45         Item *left, *right;     /* traverses items matching current search pattern */
46 };
47
48 /* forward declarations */
49 static void appenditem(Item *i, Item **list, Item **last);
50 static void calcoffsets(void);
51 static char *cistrstr(const char *s, const char *sub);
52 static void cleanup(void);
53 static void drawmenu(void);
54 static void drawtext(const char *text, unsigned long col[ColLast]);
55 static void eprint(const char *errstr, ...);
56 static unsigned long getcolor(const char *colstr);
57 static Bool grabkeyboard(void);
58 static void initfont(const char *fontstr);
59 static void kpress(XKeyEvent * e);
60 static void match(char *pattern);
61 static void readstdin(void);
62 static void run(void);
63 static void setup(Bool topbar);
64 static int textnw(const char *text, unsigned int len);
65 static int textw(const char *text);
66
67 #include "config.h"
68
69 /* variables */
70 static char *maxname = NULL;
71 static char *prompt = NULL;
72 static char text[4096];
73 static int cmdw = 0;
74 static int promptw = 0;
75 static int ret = 0;
76 static int screen;
77 static unsigned int mw, mh;
78 static unsigned int numlockmask = 0;
79 static Bool running = True;
80 static Display *dpy;
81 static DC dc = {0};
82 static Item *allitems = NULL;   /* first of all items */
83 static Item *item = NULL;       /* first of pattern matching items */
84 static Item *sel = NULL;
85 static Item *next = NULL;
86 static Item *prev = NULL;
87 static Item *curr = NULL;
88 static Window root, win;
89 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
90 static char *(*fstrstr)(const char *, const char *) = strstr;
91
92 void
93 appenditem(Item *i, Item **list, Item **last) {
94         if(!(*last))
95                 *list = i;
96         else
97                 (*last)->right = i;
98         i->left = *last;
99         i->right = NULL;
100         *last = i;
101 }
102
103 void
104 calcoffsets(void) {
105         int tw;
106         unsigned int w;
107
108         if(!curr)
109                 return;
110         w = promptw + cmdw + 2 * spaceitem;
111         for(next = curr; next; next=next->right) {
112                 tw = textw(next->text);
113                 if(tw > mw / 3)
114                         tw = mw / 3;
115                 w += tw;
116                 if(w > mw)
117                         break;
118         }
119         w = promptw + cmdw + 2 * spaceitem;
120         for(prev = curr; prev && prev->left; prev=prev->left) {
121                 tw = textw(prev->left->text);
122                 if(tw > mw / 3)
123                         tw = mw / 3;
124                 w += tw;
125                 if(w > mw)
126                         break;
127         }
128 }
129
130 char *
131 cistrstr(const char *s, const char *sub) {
132         int c, csub;
133         unsigned int len;
134
135         if(!sub)
136                 return (char *)s;
137         if((c = *sub++) != 0) {
138                 c = tolower(c);
139                 len = strlen(sub);
140                 do {
141                         do {
142                                 if((csub = *s++) == 0)
143                                         return (NULL);
144                         }
145                         while(tolower(csub) != c);
146                 }
147                 while(strncasecmp(s, sub, len) != 0);
148                 s--;
149         }
150         return (char *)s;
151 }
152
153 void
154 cleanup(void) {
155         Item *itm;
156
157         while(allitems) {
158                 itm = allitems->next;
159                 free(allitems->text);
160                 free(allitems);
161                 allitems = itm;
162         }
163         if(dc.font.set)
164                 XFreeFontSet(dpy, dc.font.set);
165         else
166                 XFreeFont(dpy, dc.font.xfont);
167         XFreePixmap(dpy, dc.drawable);
168         XFreeGC(dpy, dc.gc);
169         XDestroyWindow(dpy, win);
170         XUngrabKeyboard(dpy, CurrentTime);
171 }
172
173 void
174 drawmenu(void) {
175         Item *i;
176
177         dc.x = 0;
178         dc.y = 0;
179         dc.w = mw;
180         dc.h = mh;
181         drawtext(NULL, dc.norm);
182         /* print prompt? */
183         if(promptw) {
184                 dc.w = promptw;
185                 drawtext(prompt, dc.sel);
186         }
187         dc.x += promptw;
188         dc.w = mw - promptw;
189         /* print command */
190         if(cmdw && item)
191                 dc.w = cmdw;
192         drawtext(text[0] ? text : NULL, dc.norm);
193         dc.x += cmdw;
194         if(curr) {
195                 dc.w = spaceitem;
196                 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
197                 dc.x += dc.w;
198                 /* determine maximum items */
199                 for(i = curr; i != next; i=i->right) {
200                         dc.w = textw(i->text);
201                         if(dc.w > mw / 3)
202                                 dc.w = mw / 3;
203                         drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
204                         dc.x += dc.w;
205                 }
206                 dc.x = mw - spaceitem;
207                 dc.w = spaceitem;
208                 drawtext(next ? ">" : NULL, dc.norm);
209         }
210         XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
211         XFlush(dpy);
212 }
213
214 void
215 drawtext(const char *text, unsigned long col[ColLast]) {
216         char buf[256];
217         int i, x, y, h, len, olen;
218         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
219
220         XSetForeground(dpy, dc.gc, col[ColBG]);
221         XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
222         if(!text)
223                 return;
224         olen = strlen(text);
225         h = dc.font.ascent + dc.font.descent;
226         y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
227         x = dc.x + (h / 2);
228         /* shorten text if necessary */
229         for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
230         if(!len)
231                 return;
232         memcpy(buf, text, len);
233         if(len < olen)
234                 for(i = len; i && i > len - 3; buf[--i] = '.');
235         XSetForeground(dpy, dc.gc, col[ColFG]);
236         if(dc.font.set)
237                 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
238         else
239                 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
240 }
241
242 void
243 eprint(const char *errstr, ...) {
244         va_list ap;
245
246         va_start(ap, errstr);
247         vfprintf(stderr, errstr, ap);
248         va_end(ap);
249         exit(EXIT_FAILURE);
250 }
251
252 unsigned long
253 getcolor(const char *colstr) {
254         Colormap cmap = DefaultColormap(dpy, screen);
255         XColor color;
256
257         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
258                 eprint("error, cannot allocate color '%s'\n", colstr);
259         return color.pixel;
260 }
261
262 Bool
263 grabkeyboard(void) {
264         unsigned int len;
265
266         for(len = 1000; len; len--) {
267                 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
268                 == GrabSuccess)
269                         break;
270                 usleep(1000);
271         }
272         return len > 0;
273 }
274
275 void
276 initfont(const char *fontstr) {
277         char *def, **missing;
278         int i, n;
279
280         if(!fontstr || fontstr[0] == '\0')
281                 eprint("error, cannot load font: '%s'\n", fontstr);
282         missing = NULL;
283         if(dc.font.set)
284                 XFreeFontSet(dpy, dc.font.set);
285         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
286         if(missing)
287                 XFreeStringList(missing);
288         if(dc.font.set) {
289                 XFontSetExtents *font_extents;
290                 XFontStruct **xfonts;
291                 char **font_names;
292                 dc.font.ascent = dc.font.descent = 0;
293                 font_extents = XExtentsOfFontSet(dc.font.set);
294                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
295                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
296                         if(dc.font.ascent < (*xfonts)->ascent)
297                                 dc.font.ascent = (*xfonts)->ascent;
298                         if(dc.font.descent < (*xfonts)->descent)
299                                 dc.font.descent = (*xfonts)->descent;
300                         xfonts++;
301                 }
302         }
303         else {
304                 if(dc.font.xfont)
305                         XFreeFont(dpy, dc.font.xfont);
306                 dc.font.xfont = NULL;
307                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
308                 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
309                         eprint("error, cannot load font: '%s'\n", fontstr);
310                 dc.font.ascent = dc.font.xfont->ascent;
311                 dc.font.descent = dc.font.xfont->descent;
312         }
313         dc.font.height = dc.font.ascent + dc.font.descent;
314 }
315
316 void
317 kpress(XKeyEvent * e) {
318         char buf[32];
319         int i, num;
320         unsigned int len;
321         KeySym ksym;
322
323         len = strlen(text);
324         buf[0] = 0;
325         num = XLookupString(e, buf, sizeof buf, &ksym, 0);
326         if(IsKeypadKey(ksym)) {
327                 if(ksym == XK_KP_Enter)
328                         ksym = XK_Return;
329                 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
330                         ksym = (ksym - XK_KP_0) + XK_0;
331         }
332         if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
333            || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
334            || IsPrivateKeypadKey(ksym))
335                 return;
336         /* first check if a control mask is omitted */
337         if(e->state & ControlMask) {
338                 switch (ksym) {
339                 default:        /* ignore other control sequences */
340                         return;
341                 case XK_bracketleft:
342                         ksym = XK_Escape;
343                         break;
344                 case XK_h:
345                 case XK_H:
346                         ksym = XK_BackSpace;
347                         break;
348                 case XK_i:
349                 case XK_I:
350                         ksym = XK_Tab;
351                         break;
352                 case XK_j:
353                 case XK_J:
354                         ksym = XK_Return;
355                         break;
356                 case XK_u:
357                 case XK_U:
358                         text[0] = 0;
359                         match(text);
360                         drawmenu();
361                         return;
362                 case XK_w:
363                 case XK_W:
364                         if(len) {
365                                 i = len - 1;
366                                 while(i >= 0 && text[i] == ' ')
367                                         text[i--] = 0;
368                                 while(i >= 0 && text[i] != ' ')
369                                         text[i--] = 0;
370                                 match(text);
371                                 drawmenu();
372                         }
373                         return;
374                 }
375         }
376         if(CLEANMASK(e->state) & Mod1Mask) {
377                 switch(ksym) {
378                 default: return;
379                 case XK_h:
380                         ksym = XK_Left;
381                         break;
382                 case XK_l:
383                         ksym = XK_Right;
384                         break;
385                 case XK_j:
386                         ksym = XK_Next;
387                         break;
388                 case XK_k:
389                         ksym = XK_Prior;
390                         break;
391                 case XK_g:
392                         ksym = XK_Home;
393                         break;
394                 case XK_G:
395                         ksym = XK_End;
396                         break;
397                 }
398         }
399         switch(ksym) {
400         default:
401                 if(num && !iscntrl((int) buf[0])) {
402                         buf[num] = 0;
403                         if(len > 0)
404                                 strncat(text, buf, sizeof text);
405                         else
406                                 strncpy(text, buf, sizeof text);
407                         match(text);
408                 }
409                 break;
410         case XK_BackSpace:
411                 if(len) {
412                         text[--len] = 0;
413                         match(text);
414                 }
415                 break;
416         case XK_End:
417                 if(!item)
418                         return;
419                 while(next) {
420                         sel = curr = next;
421                         calcoffsets();
422                 }
423                 while(sel && sel->right)
424                         sel = sel->right;
425                 break;
426         case XK_Escape:
427                 ret = 1;
428                 running = False;
429                 break;
430         case XK_Home:
431                 if(!item)
432                         return;
433                 sel = curr = item;
434                 calcoffsets();
435                 break;
436         case XK_Left:
437                 if(!(sel && sel->left))
438                         return;
439                 sel=sel->left;
440                 if(sel->right == curr) {
441                         curr = prev;
442                         calcoffsets();
443                 }
444                 break;
445         case XK_Next:
446                 if(!next)
447                         return;
448                 sel = curr = next;
449                 calcoffsets();
450                 break;
451         case XK_Prior:
452                 if(!prev)
453                         return;
454                 sel = curr = prev;
455                 calcoffsets();
456                 break;
457         case XK_Return:
458                 if((e->state & ShiftMask) && *text)
459                         fprintf(stdout, "%s", text);
460                 else if(sel)
461                         fprintf(stdout, "%s", sel->text);
462                 else if(*text)
463                         fprintf(stdout, "%s", text);
464                 fflush(stdout);
465                 running = False;
466                 break;
467         case XK_Right:
468                 if(!(sel && sel->right))
469                         return;
470                 sel=sel->right;
471                 if(sel == next) {
472                         curr = next;
473                         calcoffsets();
474                 }
475                 break;
476         case XK_Tab:
477                 if(!sel)
478                         return;
479                 strncpy(text, sel->text, sizeof text);
480                 match(text);
481                 break;
482         }
483         drawmenu();
484 }
485
486 void
487 match(char *pattern) {
488         unsigned int plen;
489         Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
490
491         if(!pattern)
492                 return;
493         plen = strlen(pattern);
494         item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
495         for(i = allitems; i; i = i->next)
496                 if(!fstrncmp(pattern, i->text, plen + 1))
497                         appenditem(i, &lexact, &exactend);
498                 else if(!fstrncmp(pattern, i->text, plen))
499                         appenditem(i, &lprefix, &prefixend);
500                 else if(fstrstr(i->text, pattern))
501                         appenditem(i, &lsubstr, &substrend);
502         if(lexact) {
503                 item = lexact;
504                 itemend = exactend;
505         }
506         if(lprefix) {
507                 if(itemend) {
508                         itemend->right = lprefix;
509                         lprefix->left = itemend;
510                 }
511                 else
512                         item = lprefix;
513                 itemend = prefixend;
514         }
515         if(lsubstr) {
516                 if(itemend) {
517                         itemend->right = lsubstr;
518                         lsubstr->left = itemend;
519                 }
520                 else
521                         item = lsubstr;
522         }
523         curr = prev = next = sel = item;
524         calcoffsets();
525 }
526
527 void
528 readstdin(void) {
529         char *p, buf[1024];
530         unsigned int len = 0, max = 0;
531         Item *i, *new;
532
533         i = 0;
534         while(fgets(buf, sizeof buf, stdin)) {
535                 len = strlen(buf);
536                 if (buf[len - 1] == '\n')
537                         buf[len - 1] = 0;
538                 if(!(p = strdup(buf)))
539                         eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
540                 if(max < len) {
541                         maxname = p;
542                         max = len;
543                 }
544                 if((new = (Item *)malloc(sizeof(Item))) == NULL)
545                         eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
546                 new->next = new->left = new->right = NULL;
547                 new->text = p;
548                 if(!i)
549                         allitems = new;
550                 else 
551                         i->next = new;
552                 i = new;
553         }
554 }
555
556 void
557 run(void) {
558         XEvent ev;
559
560         /* main event loop */
561         while(running && !XNextEvent(dpy, &ev))
562                 switch (ev.type) {
563                 default:        /* ignore all crap */
564                         break;
565                 case KeyPress:
566                         kpress(&ev.xkey);
567                         break;
568                 case Expose:
569                         if(ev.xexpose.count == 0)
570                                 drawmenu();
571                         break;
572                 }
573 }
574
575 void
576 setup(Bool topbar) {
577         int i, j, x, y;
578 #if XINERAMA
579         int n;
580         XineramaScreenInfo *info = NULL;
581 #endif
582         XModifierKeymap *modmap;
583         XSetWindowAttributes wa;
584
585         /* init modifier map */
586         modmap = XGetModifierMapping(dpy);
587         for(i = 0; i < 8; i++)
588                 for(j = 0; j < modmap->max_keypermod; j++) {
589                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
590                         == XKeysymToKeycode(dpy, XK_Num_Lock))
591                                 numlockmask = (1 << i);
592                 }
593         XFreeModifiermap(modmap);
594
595         /* style */
596         dc.norm[ColBG] = getcolor(normbgcolor);
597         dc.norm[ColFG] = getcolor(normfgcolor);
598         dc.sel[ColBG] = getcolor(selbgcolor);
599         dc.sel[ColFG] = getcolor(selfgcolor);
600         initfont(font);
601
602         /* menu window */
603         wa.override_redirect = 1;
604         wa.background_pixmap = ParentRelative;
605         wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
606
607         /* menu window geometry */
608         mh = dc.font.height + 2;
609 #if XINERAMA
610         if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
611                 i = 0;
612                 if(n > 1) {
613                         int di;
614                         unsigned int dui;
615                         Window dummy;
616                         if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
617                                 for(i = 0; i < n; i++)
618                                         if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
619                                                 break;
620                 }
621                 x = info[i].x_org;
622                 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
623                 mw = info[i].width;
624                 XFree(info);
625         }
626         else
627 #endif
628         {
629                 x = 0;
630                 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
631                 mw = DisplayWidth(dpy, screen);
632         }
633
634         win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
635                         DefaultDepth(dpy, screen), CopyFromParent,
636                         DefaultVisual(dpy, screen),
637                         CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
638
639         /* pixmap */
640         dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
641         dc.gc = XCreateGC(dpy, root, 0, 0);
642         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
643         if(!dc.font.set)
644                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
645         if(maxname)
646                 cmdw = textw(maxname);
647         if(cmdw > mw / 3)
648                 cmdw = mw / 3;
649         if(prompt)
650                 promptw = textw(prompt);
651         if(promptw > mw / 5)
652                 promptw = mw / 5;
653         text[0] = 0;
654         match(text);
655         XMapRaised(dpy, win);
656 }
657
658 int
659 textnw(const char *text, unsigned int len) {
660         XRectangle r;
661
662         if(dc.font.set) {
663                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
664                 return r.width;
665         }
666         return XTextWidth(dc.font.xfont, text, len);
667 }
668
669 int
670 textw(const char *text) {
671         return textnw(text, strlen(text)) + dc.font.height;
672 }
673
674 int
675 main(int argc, char *argv[]) {
676         unsigned int i;
677         Bool topbar = True;
678
679         /* command line args */
680         for(i = 1; i < argc; i++)
681                 if(!strcmp(argv[i], "-i")) {
682                         fstrncmp = strncasecmp;
683                         fstrstr = cistrstr;
684                 }
685                 else if(!strcmp(argv[i], "-b"))
686                         topbar = False;
687                 else if(!strcmp(argv[i], "-fn")) {
688                         if(++i < argc) font = argv[i];
689                 }
690                 else if(!strcmp(argv[i], "-nb")) {
691                         if(++i < argc) normbgcolor = argv[i];
692                 }
693                 else if(!strcmp(argv[i], "-nf")) {
694                         if(++i < argc) normfgcolor = argv[i];
695                 }
696                 else if(!strcmp(argv[i], "-p")) {
697                         if(++i < argc) prompt = argv[i];
698                 }
699                 else if(!strcmp(argv[i], "-sb")) {
700                         if(++i < argc) selbgcolor = argv[i];
701                 }
702                 else if(!strcmp(argv[i], "-sf")) {
703                         if(++i < argc) selfgcolor = argv[i];
704                 }
705                 else if(!strcmp(argv[i], "-v"))
706                         eprint("dmenu-"VERSION", © 2006-2008 dmenu engineers, see LICENSE for details\n");
707                 else
708                         eprint("usage: dmenu [-i] [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
709                                "             [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
710         if(!XSupportsLocale())
711                 fprintf(stderr, "warning: no locale support\n");
712         if(!(dpy = XOpenDisplay(0)))
713                 eprint("dmenu: cannot open display\n");
714         screen = DefaultScreen(dpy);
715         root = RootWindow(dpy, screen);
716
717         if(isatty(STDIN_FILENO)) {
718                 readstdin();
719                 running = grabkeyboard();
720         }
721         else { /* prevent keypress loss */
722                 running = grabkeyboard();
723                 readstdin();
724         }
725
726         setup(topbar);
727         drawmenu();
728         XSync(dpy, False);
729         run();
730         cleanup();
731         XCloseDisplay(dpy);
732         return ret;
733 }