Xinqi Bao's Git

Added tag 4.0 for changeset 78f9f72cc9c6
[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 #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;
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 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
284 if(missing)
285 XFreeStringList(missing);
286 if(dc.font.set) {
287 XFontSetExtents *font_extents;
288 XFontStruct **xfonts;
289 char **font_names;
290 dc.font.ascent = dc.font.descent = 0;
291 font_extents = XExtentsOfFontSet(dc.font.set);
292 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
293 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
294 if(dc.font.ascent < (*xfonts)->ascent)
295 dc.font.ascent = (*xfonts)->ascent;
296 if(dc.font.descent < (*xfonts)->descent)
297 dc.font.descent = (*xfonts)->descent;
298 xfonts++;
299 }
300 }
301 else {
302 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
303 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
304 eprint("error, cannot load font: '%s'\n", fontstr);
305 dc.font.ascent = dc.font.xfont->ascent;
306 dc.font.descent = dc.font.xfont->descent;
307 }
308 dc.font.height = dc.font.ascent + dc.font.descent;
309 }
310
311 void
312 kpress(XKeyEvent * e) {
313 char buf[32];
314 int i, num;
315 unsigned int len;
316 KeySym ksym;
317
318 len = strlen(text);
319 buf[0] = 0;
320 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
321 if(IsKeypadKey(ksym)) {
322 if(ksym == XK_KP_Enter)
323 ksym = XK_Return;
324 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
325 ksym = (ksym - XK_KP_0) + XK_0;
326 }
327 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
328 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
329 || IsPrivateKeypadKey(ksym))
330 return;
331 /* first check if a control mask is omitted */
332 if(e->state & ControlMask) {
333 switch (ksym) {
334 default: /* ignore other control sequences */
335 return;
336 case XK_bracketleft:
337 ksym = XK_Escape;
338 break;
339 case XK_h:
340 case XK_H:
341 ksym = XK_BackSpace;
342 break;
343 case XK_i:
344 case XK_I:
345 ksym = XK_Tab;
346 break;
347 case XK_j:
348 case XK_J:
349 ksym = XK_Return;
350 break;
351 case XK_u:
352 case XK_U:
353 text[0] = 0;
354 match(text);
355 drawmenu();
356 return;
357 case XK_w:
358 case XK_W:
359 if(len) {
360 i = len - 1;
361 while(i >= 0 && text[i] == ' ')
362 text[i--] = 0;
363 while(i >= 0 && text[i] != ' ')
364 text[i--] = 0;
365 match(text);
366 drawmenu();
367 }
368 return;
369 }
370 }
371 if(CLEANMASK(e->state) & Mod1Mask) {
372 switch(ksym) {
373 default: return;
374 case XK_h:
375 ksym = XK_Left;
376 break;
377 case XK_l:
378 ksym = XK_Right;
379 break;
380 case XK_j:
381 ksym = XK_Next;
382 break;
383 case XK_k:
384 ksym = XK_Prior;
385 break;
386 case XK_g:
387 ksym = XK_Home;
388 break;
389 case XK_G:
390 ksym = XK_End;
391 break;
392 }
393 }
394 switch(ksym) {
395 default:
396 if(num && !iscntrl((int) buf[0])) {
397 buf[num] = 0;
398 strncpy(text + len, buf, sizeof text - len);
399 match(text);
400 }
401 break;
402 case XK_BackSpace:
403 if(len) {
404 text[--len] = 0;
405 match(text);
406 }
407 break;
408 case XK_End:
409 if(!item)
410 return;
411 while(next) {
412 sel = curr = next;
413 calcoffsets();
414 }
415 while(sel && sel->right)
416 sel = sel->right;
417 break;
418 case XK_Escape:
419 ret = 1;
420 running = False;
421 break;
422 case XK_Home:
423 if(!item)
424 return;
425 sel = curr = item;
426 calcoffsets();
427 break;
428 case XK_Left:
429 if(!(sel && sel->left))
430 return;
431 sel=sel->left;
432 if(sel->right == curr) {
433 curr = prev;
434 calcoffsets();
435 }
436 break;
437 case XK_Next:
438 if(!next)
439 return;
440 sel = curr = next;
441 calcoffsets();
442 break;
443 case XK_Prior:
444 if(!prev)
445 return;
446 sel = curr = prev;
447 calcoffsets();
448 break;
449 case XK_Return:
450 if((e->state & ShiftMask) && *text)
451 fprintf(stdout, "%s", text);
452 else if(sel)
453 fprintf(stdout, "%s", sel->text);
454 else if(*text)
455 fprintf(stdout, "%s", text);
456 fflush(stdout);
457 running = False;
458 break;
459 case XK_Right:
460 if(!(sel && sel->right))
461 return;
462 sel=sel->right;
463 if(sel == next) {
464 curr = next;
465 calcoffsets();
466 }
467 break;
468 case XK_Tab:
469 if(!sel)
470 return;
471 strncpy(text, sel->text, sizeof text);
472 match(text);
473 break;
474 }
475 drawmenu();
476 }
477
478 void
479 match(char *pattern) {
480 unsigned int plen;
481 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
482
483 if(!pattern)
484 return;
485 plen = strlen(pattern);
486 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
487 for(i = allitems; i; i = i->next)
488 if(!fstrncmp(pattern, i->text, plen + 1))
489 appenditem(i, &lexact, &exactend);
490 else if(!fstrncmp(pattern, i->text, plen))
491 appenditem(i, &lprefix, &prefixend);
492 else if(fstrstr(i->text, pattern))
493 appenditem(i, &lsubstr, &substrend);
494 if(lexact) {
495 item = lexact;
496 itemend = exactend;
497 }
498 if(lprefix) {
499 if(itemend) {
500 itemend->right = lprefix;
501 lprefix->left = itemend;
502 }
503 else
504 item = lprefix;
505 itemend = prefixend;
506 }
507 if(lsubstr) {
508 if(itemend) {
509 itemend->right = lsubstr;
510 lsubstr->left = itemend;
511 }
512 else
513 item = lsubstr;
514 }
515 curr = prev = next = sel = item;
516 calcoffsets();
517 }
518
519 void
520 readstdin(void) {
521 char *p, buf[1024];
522 unsigned int len = 0, max = 0;
523 Item *i, *new;
524
525 i = 0;
526 while(fgets(buf, sizeof buf, stdin)) {
527 len = strlen(buf);
528 if (buf[len - 1] == '\n')
529 buf[len - 1] = 0;
530 if(!(p = strdup(buf)))
531 eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
532 if(max < len) {
533 maxname = p;
534 max = len;
535 }
536 if(!(new = (Item *)malloc(sizeof(Item))))
537 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
538 new->next = new->left = new->right = NULL;
539 new->text = p;
540 if(!i)
541 allitems = new;
542 else
543 i->next = new;
544 i = new;
545 }
546 }
547
548 void
549 run(void) {
550 XEvent ev;
551
552 /* main event loop */
553 while(running && !XNextEvent(dpy, &ev))
554 switch (ev.type) {
555 default: /* ignore all crap */
556 break;
557 case KeyPress:
558 kpress(&ev.xkey);
559 break;
560 case Expose:
561 if(ev.xexpose.count == 0)
562 drawmenu();
563 break;
564 }
565 }
566
567 void
568 setup(Bool topbar) {
569 int i, j, x, y;
570 #if XINERAMA
571 int n;
572 XineramaScreenInfo *info = NULL;
573 #endif
574 XModifierKeymap *modmap;
575 XSetWindowAttributes wa;
576
577 /* init modifier map */
578 modmap = XGetModifierMapping(dpy);
579 for(i = 0; i < 8; i++)
580 for(j = 0; j < modmap->max_keypermod; j++) {
581 if(modmap->modifiermap[i * modmap->max_keypermod + j]
582 == XKeysymToKeycode(dpy, XK_Num_Lock))
583 numlockmask = (1 << i);
584 }
585 XFreeModifiermap(modmap);
586
587 /* style */
588 dc.norm[ColBG] = getcolor(normbgcolor);
589 dc.norm[ColFG] = getcolor(normfgcolor);
590 dc.sel[ColBG] = getcolor(selbgcolor);
591 dc.sel[ColFG] = getcolor(selfgcolor);
592 initfont(font);
593
594 /* menu window */
595 wa.override_redirect = True;
596 wa.background_pixmap = ParentRelative;
597 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
598
599 /* menu window geometry */
600 mh = dc.font.height + 2;
601 #if XINERAMA
602 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
603 i = 0;
604 if(n > 1) {
605 int di;
606 unsigned int dui;
607 Window dummy;
608 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
609 for(i = 0; i < n; i++)
610 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
611 break;
612 }
613 x = info[i].x_org;
614 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
615 mw = info[i].width;
616 XFree(info);
617 }
618 else
619 #endif
620 {
621 x = 0;
622 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
623 mw = DisplayWidth(dpy, screen);
624 }
625
626 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
627 DefaultDepth(dpy, screen), CopyFromParent,
628 DefaultVisual(dpy, screen),
629 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
630
631 /* pixmap */
632 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
633 dc.gc = XCreateGC(dpy, root, 0, NULL);
634 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
635 if(!dc.font.set)
636 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
637 if(maxname)
638 cmdw = textw(maxname);
639 if(cmdw > mw / 3)
640 cmdw = mw / 3;
641 if(prompt)
642 promptw = textw(prompt);
643 if(promptw > mw / 5)
644 promptw = mw / 5;
645 text[0] = 0;
646 match(text);
647 XMapRaised(dpy, win);
648 }
649
650 int
651 textnw(const char *text, unsigned int len) {
652 XRectangle r;
653
654 if(dc.font.set) {
655 XmbTextExtents(dc.font.set, text, len, NULL, &r);
656 return r.width;
657 }
658 return XTextWidth(dc.font.xfont, text, len);
659 }
660
661 int
662 textw(const char *text) {
663 return textnw(text, strlen(text)) + dc.font.height;
664 }
665
666 int
667 main(int argc, char *argv[]) {
668 unsigned int i;
669 Bool topbar = True;
670
671 /* command line args */
672 for(i = 1; i < argc; i++)
673 if(!strcmp(argv[i], "-i")) {
674 fstrncmp = strncasecmp;
675 fstrstr = cistrstr;
676 }
677 else if(!strcmp(argv[i], "-b"))
678 topbar = False;
679 else if(!strcmp(argv[i], "-fn")) {
680 if(++i < argc) font = argv[i];
681 }
682 else if(!strcmp(argv[i], "-nb")) {
683 if(++i < argc) normbgcolor = argv[i];
684 }
685 else if(!strcmp(argv[i], "-nf")) {
686 if(++i < argc) normfgcolor = argv[i];
687 }
688 else if(!strcmp(argv[i], "-p")) {
689 if(++i < argc) prompt = argv[i];
690 }
691 else if(!strcmp(argv[i], "-sb")) {
692 if(++i < argc) selbgcolor = argv[i];
693 }
694 else if(!strcmp(argv[i], "-sf")) {
695 if(++i < argc) selfgcolor = argv[i];
696 }
697 else if(!strcmp(argv[i], "-v"))
698 eprint("dmenu-"VERSION", © 2006-2008 dmenu engineers, see LICENSE for details\n");
699 else
700 eprint("usage: dmenu [-i] [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
701 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
702 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
703 fprintf(stderr, "warning: no locale support\n");
704 if(!(dpy = XOpenDisplay(NULL)))
705 eprint("dmenu: cannot open display\n");
706 screen = DefaultScreen(dpy);
707 root = RootWindow(dpy, screen);
708
709 if(isatty(STDIN_FILENO)) {
710 readstdin();
711 running = grabkeyboard();
712 }
713 else { /* prevent keypress loss */
714 running = grabkeyboard();
715 readstdin();
716 }
717
718 setup(topbar);
719 drawmenu();
720 XSync(dpy, False);
721 run();
722 cleanup();
723 XCloseDisplay(dpy);
724 return ret;
725 }