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