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