Xinqi Bao's Git

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