README
[xmenu] / xmenu.c
... / ...
CommitLineData
1#include <ctype.h>
2#include <err.h>
3#include <errno.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <string.h>
7#include <limits.h>
8#include <locale.h>
9#include <time.h>
10#include <unistd.h>
11#include <X11/Xlib.h>
12#include <X11/Xatom.h>
13#include <X11/Xutil.h>
14#include <X11/Xresource.h>
15#include <X11/XKBlib.h>
16#include <X11/Xft/Xft.h>
17#include <X11/extensions/Xinerama.h>
18#include <Imlib2.h>
19
20/* macros */
21#define CLASS "XMenu"
22#define LEN(x) (sizeof (x) / sizeof (x[0]))
23#define MAX(x,y) ((x)>(y)?(x):(y))
24#define MIN(x,y) ((x)<(y)?(x):(y))
25#define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
26#define GETNUM(n, s) { \
27 unsigned long __TMP__; \
28 if ((__TMP__ = strtoul((s), NULL, 10)) < INT_MAX) \
29 (n) = __TMP__; \
30 }
31
32/* Actions for the main loop */
33enum {
34 ACTION_NOP = 0,
35 ACTION_CLEAR = 1<<0, /* clear text */
36 ACTION_SELECT = 1<<1, /* select item */
37 ACTION_MAP = 1<<2, /* remap menu windows */
38 ACTION_DRAW = 1<<3, /* redraw menu windows */
39 ACTION_WARP = 1<<4, /* warp the pointer */
40};
41
42/* enum for keyboard menu navigation */
43enum { ITEMPREV, ITEMNEXT, ITEMFIRST, ITEMLAST };
44
45/* enum for text alignment */
46enum {LeftAlignment, CenterAlignment, RightAlignment};
47
48/* color enum */
49enum {ColorFG, ColorBG, ColorLast};
50
51/* EWMH atoms */
52enum {NetWMName, NetWMWindowType, NetWMWindowTypePopupMenu, NetLast};
53
54/* configuration structure */
55struct Config {
56 /* the values below are set by config.h */
57 const char *font;
58 const char *background_color;
59 const char *foreground_color;
60 const char *selbackground_color;
61 const char *selforeground_color;
62 const char *separator_color;
63 const char *border_color;
64 int width_pixels;
65 int height_pixels;
66 int border_pixels;
67 int separator_pixels;
68 int gap_pixels;
69 int triangle_width;
70 int triangle_height;
71 int iconpadding;
72 int horzpadding;
73 int alignment;
74
75 /* the values below are set by options */
76 int monitor;
77 int posx, posy; /* rootmenu position */
78
79 /* the value below is computed by xmenu */
80 int iconsize;
81};
82
83/* draw context structure */
84struct DC {
85 XftColor normal[ColorLast];
86 XftColor selected[ColorLast];
87 XftColor border;
88 XftColor separator;
89
90 GC gc;
91
92 FcPattern *pattern;
93 XftFont **fonts;
94 size_t nfonts;
95};
96
97/* menu item structure */
98struct Item {
99 char *label; /* string to be drawed on menu */
100 char *output; /* string to be outputed when item is clicked */
101 char *file; /* filename of the icon */
102 int y; /* item y position relative to menu */
103 int h; /* item height */
104 int textw; /* text width */
105 struct Item *prev; /* previous item */
106 struct Item *next; /* next item */
107 struct Menu *submenu; /* submenu spawned by clicking on item */
108 Drawable sel, unsel; /* pixmap for selected and unselected item */
109 Imlib_Image icon;
110};
111
112/* monitor geometry structure */
113struct Monitor {
114 int x, y, w, h; /* monitor geometry */
115};
116
117/* menu structure */
118struct Menu {
119 struct Menu *parent; /* parent menu */
120 struct Item *caller; /* item that spawned the menu */
121 struct Item *list; /* list of items contained by the menu */
122 struct Item *selected; /* item currently selected in the menu */
123 int x, y, w, h; /* menu geometry */
124 int hasicon; /* whether the menu has item with icons */
125 int drawn; /* whether the menu was already drawn */
126 int maxtextw; /* maximum text width */
127 unsigned level; /* menu level relative to root */
128 Window win; /* menu window to map on the screen */
129 XIC xic; /* input context */
130};
131
132/* X stuff */
133static Display *dpy;
134static int screen;
135static Visual *visual;
136static Window rootwin;
137static Colormap colormap;
138static XrmDatabase xdb;
139static XClassHint classh;
140static char *xrm;
141static struct DC dc;
142static Atom utf8string;
143static Atom wmdelete;
144static Atom netatom[NetLast];
145static XIM xim;
146
147/* flags */
148static int iflag = 0; /* whether to disable icons */
149static int rflag = 0; /* whether to disable right-click */
150static int mflag = 0; /* whether the user specified a monitor with -p */
151static int pflag = 0; /* whether the user specified a position with -p */
152static int wflag = 0; /* whether to let the window manager control XMenu */
153static int rootmodeflag = 0; /* wheter to run in root mode */
154static int passclickflag = 0; /* whether to pass click to root window */
155static int firsttime = 1; /* set to 0 after first run */
156
157/* arguments */
158static unsigned int button = 0; /* button to trigger pmenu in root mode */
159static unsigned int modifier = 0; /* modifier to trigger pmenu */
160
161/* include config variable */
162#include "config.h"
163
164/* show usage */
165static void
166usage(void)
167{
168 (void)fprintf(stderr, "usage: xmenu [-irw] [-p position] [title]\n");
169 exit(1);
170}
171
172/* parse position string from -p,
173 * put results on config.posx, config.posy, and config.monitor */
174static void
175parseposition(char *optarg)
176{
177 long n;
178 char *s = optarg;
179 char *endp;
180
181 n = strtol(s, &endp, 10);
182 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
183 goto error;
184 config.posx = n;
185 s = endp+1;
186 n = strtol(s, &endp, 10);
187 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s)
188 goto error;
189 config.posy = n;
190 if (*endp == ':') {
191 s = endp+1;
192 mflag = 1;
193 if (strncasecmp(s, "CUR", 3) == 0) {
194 config.monitor = -1;
195 endp = s+3;
196 } else {
197 n = strtol(s, &endp, 10);
198 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
199 goto error;
200 config.monitor = n;
201 }
202 } else if (*endp != '\0') {
203 goto error;
204 }
205
206 return;
207
208error:
209 errx(1, "improper position: %s", optarg);
210}
211
212/* get configuration from X resources */
213static void
214getresources(void)
215{
216 char *type;
217 XrmValue xval;
218
219 if (xrm == NULL || xdb == NULL)
220 return;
221
222 if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
223 GETNUM(config.border_pixels, xval.addr)
224 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
225 GETNUM(config.separator_pixels, xval.addr)
226 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
227 GETNUM(config.height_pixels, xval.addr)
228 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
229 GETNUM(config.width_pixels, xval.addr)
230 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
231 GETNUM(config.gap_pixels, xval.addr)
232 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
233 config.background_color = xval.addr;
234 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
235 config.foreground_color = xval.addr;
236 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
237 config.selbackground_color = xval.addr;
238 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
239 config.selforeground_color = xval.addr;
240 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
241 config.separator_color = xval.addr;
242 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
243 config.border_color = xval.addr;
244 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
245 config.font = xval.addr;
246 if (XrmGetResource(xdb, "xmenu.alignment", "*", &type, &xval) == True) {
247 if (strcasecmp(xval.addr, "center") == 0)
248 config.alignment = CenterAlignment;
249 else if (strcasecmp(xval.addr, "left") == 0)
250 config.alignment = LeftAlignment;
251 else if (strcasecmp(xval.addr, "right") == 0)
252 config.alignment = RightAlignment;
253 }
254}
255
256/* set button global variable */
257static void
258setbutton(char *s)
259{
260 size_t len;
261
262 if ((len = strlen(s)) < 1)
263 return;
264 switch (s[len-1]) {
265 case '1': button = Button1; break;
266 case '2': button = Button2; break;
267 case '3': button = Button3; break;
268 default: button = atoi(&s[len-1]); break;
269 }
270}
271
272/* set modifier global variable */
273static void
274setmodifier(char *s)
275{
276 size_t len;
277
278 if ((len = strlen(s)) < 1)
279 return;
280 switch (s[len-1]) {
281 case '1': modifier = Mod1Mask; break;
282 case '2': modifier = Mod2Mask; break;
283 case '3': modifier = Mod3Mask; break;
284 case '4': modifier = Mod4Mask; break;
285 case '5': modifier = Mod5Mask; break;
286 default:
287 if (strcasecmp(s, "Alt") == 0) {
288 modifier = Mod1Mask;
289 } else if (strcasecmp(s, "Super") == 0) {
290 modifier = Mod4Mask;
291 }
292 break;
293 }
294}
295
296/* get configuration from command-line options */
297static void
298getoptions(int argc, char *argv[])
299{
300 int ch;
301 char *s, *t;
302
303 classh.res_class = CLASS;
304 classh.res_name = argv[0];
305 if ((s = strrchr(argv[0], '/')) != NULL)
306 classh.res_name = s + 1;
307 while ((ch = getopt(argc, argv, "ip:rwx:X:")) != -1) {
308 switch (ch) {
309 case 'i':
310 iflag = 1;
311 break;
312 case 'p':
313 pflag = 1;
314 parseposition(optarg);
315 break;
316 case 'r':
317 rflag = 1;
318 break;
319 case 'w':
320 wflag = 1;
321 break;
322 case 'X':
323 passclickflag = 1;
324 /* PASSTHROUGH */
325 case 'x':
326 rootmodeflag = 1;
327 s = optarg;
328 setbutton(s);
329 if ((t = strchr(s, '-')) == NULL)
330 return;
331 *t = '\0';
332 setmodifier(s);
333 break;
334 default:
335 usage();
336 break;
337 }
338 }
339 argc -= optind;
340 argv += optind;
341 if (argc != 0)
342 usage();
343 return;
344}
345
346/* parse font string */
347static void
348parsefonts(const char *s)
349{
350 const char *p;
351 char buf[1024];
352 size_t nfont = 0;
353
354 dc.nfonts = 1;
355 for (p = s; *p; p++)
356 if (*p == ',')
357 dc.nfonts++;
358
359 if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
360 err(1, "calloc");
361
362 p = s;
363 while (*p != '\0') {
364 size_t i;
365
366 i = 0;
367 while (isspace(*p))
368 p++;
369 while (i < sizeof buf && *p != '\0' && *p != ',')
370 buf[i++] = *p++;
371 if (i >= sizeof buf)
372 errx(1, "font name too long");
373 if (*p == ',')
374 p++;
375 buf[i] = '\0';
376 if (nfont == 0)
377 if ((dc.pattern = FcNameParse((FcChar8 *)buf)) == NULL)
378 errx(1, "the first font in the cache must be loaded from a font string");
379 if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
380 errx(1, "could not load font");
381 }
382}
383
384/* get color from color string */
385static void
386ealloccolor(const char *s, XftColor *color)
387{
388 if(!XftColorAllocName(dpy, visual, colormap, s, color))
389 errx(1, "could not allocate color: %s", s);
390}
391
392/* query monitor information and cursor position */
393static void
394getmonitor(struct Monitor *mon)
395{
396 XineramaScreenInfo *info = NULL;
397 Window dw; /* dummy variable */
398 int di; /* dummy variable */
399 unsigned du; /* dummy variable */
400 int cursx, cursy; /* cursor position */
401 int nmons;
402 int i;
403
404 XQueryPointer(dpy, rootwin, &dw, &dw, &cursx, &cursy, &di, &di, &du);
405
406 mon->x = mon->y = 0;
407 mon->w = DisplayWidth(dpy, screen);
408 mon->h = DisplayHeight(dpy, screen);
409
410 if ((info = XineramaQueryScreens(dpy, &nmons)) != NULL) {
411 int selmon = 0;
412
413 if (!mflag || config.monitor < 0 || config.monitor >= nmons) {
414 for (i = 0; i < nmons; i++) {
415 if (BETWEEN(cursx, info[i].x_org, info[i].x_org + info[i].width) &&
416 BETWEEN(cursy, info[i].y_org, info[i].y_org + info[i].height)) {
417 selmon = i;
418 break;
419 }
420 }
421 } else {
422 selmon = config.monitor;
423 }
424
425 mon->x = info[selmon].x_org;
426 mon->y = info[selmon].y_org;
427 mon->w = info[selmon].width;
428 mon->h = info[selmon].height;
429
430 XFree(info);
431 }
432
433 if (!pflag) {
434 config.posx = cursx;
435 config.posy = cursy;
436 } else if (mflag) {
437 config.posx += mon->x;
438 config.posy += mon->y;
439 }
440}
441
442/* init draw context */
443static void
444initdc(void)
445{
446 /* get color pixels */
447 ealloccolor(config.background_color, &dc.normal[ColorBG]);
448 ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
449 ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
450 ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
451 ealloccolor(config.separator_color, &dc.separator);
452 ealloccolor(config.border_color, &dc.border);
453
454 /* parse fonts */
455 parsefonts(config.font);
456
457 /* create common GC */
458 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
459}
460
461/* calculate icon size */
462static void
463initiconsize(void)
464{
465 config.iconsize = config.height_pixels - config.iconpadding * 2;
466}
467
468/* intern atoms */
469static void
470initatoms(void)
471{
472 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
473 wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
474 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
475 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
476 netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
477}
478
479/* allocate an item */
480static struct Item *
481allocitem(const char *label, const char *output, char *file)
482{
483 struct Item *item;
484
485 if ((item = malloc(sizeof *item)) == NULL)
486 err(1, "malloc");
487 if (label == NULL) {
488 item->label = NULL;
489 item->output = NULL;
490 } else {
491 if ((item->label = strdup(label)) == NULL)
492 err(1, "strdup");
493 if (label == output) {
494 item->output = item->label;
495 } else {
496 if ((item->output = strdup(output)) == NULL)
497 err(1, "strdup");
498 }
499 }
500 if (file == NULL) {
501 item->file = NULL;
502 } else {
503 if ((item->file = strdup(file)) == NULL)
504 err(1, "strdup");
505 }
506 item->y = 0;
507 item->h = 0;
508 item->next = NULL;
509 item->submenu = NULL;
510 item->icon = NULL;
511
512 return item;
513}
514
515/* allocate a menu and create its window */
516static struct Menu *
517allocmenu(struct Menu *parent, struct Item *list, unsigned level)
518{
519 XSetWindowAttributes swa;
520 struct Menu *menu;
521
522 if ((menu = malloc(sizeof *menu)) == NULL)
523 err(1, "malloc");
524 menu->parent = parent;
525 menu->list = list;
526 menu->caller = NULL;
527 menu->selected = NULL;
528 menu->w = 0; /* recalculated by setupmenu() */
529 menu->h = 0; /* recalculated by setupmenu() */
530 menu->x = 0; /* recalculated by setupmenu() */
531 menu->y = 0; /* recalculated by setupmenu() */
532 menu->level = level;
533 menu->drawn = 0;
534 menu->hasicon = 0;
535
536 swa.override_redirect = (wflag) ? False : True;
537 swa.background_pixel = dc.normal[ColorBG].pixel;
538 swa.border_pixel = dc.border.pixel;
539 swa.save_under = True; /* pop-up windows should save_under*/
540 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
541 | PointerMotionMask | LeaveWindowMask;
542 if (wflag)
543 swa.event_mask |= StructureNotifyMask;
544 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, config.border_pixels,
545 CopyFromParent, CopyFromParent, CopyFromParent,
546 CWOverrideRedirect | CWBackPixel |
547 CWBorderPixel | CWEventMask | CWSaveUnder,
548 &swa);
549
550 menu->xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
551 XNClientWindow, menu->win, XNFocusWindow, menu->win, NULL);
552 if (menu->xic == NULL)
553 errx(1, "XCreateIC: could not obtain input method");
554
555 return menu;
556}
557
558/* build the menu tree */
559static struct Menu *
560buildmenutree(unsigned level, const char *label, const char *output, char *file)
561{
562 static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
563 static struct Menu *rootmenu = NULL; /* menu to be returned */
564 struct Item *curritem = NULL; /* item currently being read */
565 struct Item *item; /* dummy item for loops */
566 struct Menu *menu; /* dummy menu for loops */
567 unsigned i;
568
569 /* create the item */
570 curritem = allocitem(label, output, file);
571
572 /* put the item in the menu tree */
573 if (prevmenu == NULL) { /* there is no menu yet */
574 menu = allocmenu(NULL, curritem, level);
575 rootmenu = menu;
576 prevmenu = menu;
577 curritem->prev = NULL;
578 } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
579 /* go up the menu tree until find the menu this item continues */
580 for (menu = prevmenu, i = level;
581 menu != NULL && i != prevmenu->level;
582 menu = menu->parent, i++)
583 ;
584 if (menu == NULL)
585 errx(1, "improper indentation detected");
586
587 /* find last item in the new menu */
588 for (item = menu->list; item->next != NULL; item = item->next)
589 ;
590
591 prevmenu = menu;
592 item->next = curritem;
593 curritem->prev = item;
594 } else if (level == prevmenu->level) { /* item is a continuation of current menu */
595 /* find last item in the previous menu */
596 for (item = prevmenu->list; item->next != NULL; item = item->next)
597 ;
598
599 item->next = curritem;
600 curritem->prev = item;
601 } else if (level > prevmenu->level) { /* item begins a new menu */
602 menu = allocmenu(prevmenu, curritem, level);
603
604 /* find last item in the previous menu */
605 for (item = prevmenu->list; item->next != NULL; item = item->next)
606 ;
607
608 /* a separator is no valid root for a submenu */
609 if (!item->label)
610 errx(1, "a separator is no valid root for a submenu");
611
612 prevmenu = menu;
613 menu->caller = item;
614 item->submenu = menu;
615 curritem->prev = NULL;
616 }
617
618 if (curritem->file)
619 prevmenu->hasicon = 1;
620
621 return rootmenu;
622}
623
624/* create menus and items from the stdin */
625static struct Menu *
626parsestdin(void)
627{
628 struct Menu *rootmenu;
629 char *s, buf[BUFSIZ];
630 char *file, *label, *output;
631 unsigned level = 0;
632
633 rootmenu = NULL;
634
635 while (fgets(buf, BUFSIZ, stdin) != NULL) {
636 /* get the indentation level */
637 level = strspn(buf, "\t");
638
639 /* get the label */
640 s = level + buf;
641 label = strtok(s, "\t\n");
642
643 /* get the filename */
644 file = NULL;
645 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
646 file = label + 4;
647 label = strtok(NULL, "\t\n");
648 }
649
650 /* get the output */
651 output = strtok(NULL, "\n");
652 if (output == NULL) {
653 output = label;
654 } else {
655 while (*output == '\t')
656 output++;
657 }
658
659 rootmenu = buildmenutree(level, label, output, file);
660 }
661
662 return rootmenu;
663}
664
665/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
666static FcChar32
667getnextutf8char(const char *s, const char **next_ret)
668{
669 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
670 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
671 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
672 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
673 /* 0xFFFD is the replacement character, used to represent unknown characters */
674 static const FcChar32 unknown = 0xFFFD;
675 FcChar32 ucode; /* FcChar32 type holds 32 bits */
676 size_t usize = 0; /* n' of bytes of the utf8 character */
677 size_t i;
678
679 *next_ret = s+1;
680
681 /* get code of first byte of utf8 character */
682 for (i = 0; i < sizeof utfmask; i++) {
683 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
684 usize = i;
685 ucode = (unsigned char)*s & ~utfmask[i];
686 break;
687 }
688 }
689
690 /* if first byte is a continuation byte or is not allowed, return unknown */
691 if (i == sizeof utfmask || usize == 0)
692 return unknown;
693
694 /* check the other usize-1 bytes */
695 s++;
696 for (i = 1; i < usize; i++) {
697 *next_ret = s+1;
698 /* if byte is nul or is not a continuation byte, return unknown */
699 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
700 return unknown;
701 /* 6 is the number of relevant bits in the continuation byte */
702 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
703 s++;
704 }
705
706 /* check if ucode is invalid or in utf-16 surrogate halves */
707 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
708 || BETWEEN (ucode, 0xD800, 0xDFFF))
709 return unknown;
710
711 return ucode;
712}
713
714/* get which font contains a given code point */
715static XftFont *
716getfontucode(FcChar32 ucode)
717{
718 FcCharSet *fccharset = NULL;
719 FcPattern *fcpattern = NULL;
720 FcPattern *match = NULL;
721 XftFont *retfont = NULL;
722 XftResult result;
723 size_t i;
724
725 for (i = 0; i < dc.nfonts; i++)
726 if (XftCharExists(dpy, dc.fonts[i], ucode) == FcTrue)
727 return dc.fonts[i];
728
729 /* create a charset containing our code point */
730 fccharset = FcCharSetCreate();
731 FcCharSetAddChar(fccharset, ucode);
732
733 /* create a pattern akin to the dc.pattern but containing our charset */
734 if (fccharset) {
735 fcpattern = FcPatternDuplicate(dc.pattern);
736 FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
737 }
738
739 /* find pattern matching fcpattern */
740 if (fcpattern) {
741 FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
742 FcDefaultSubstitute(fcpattern);
743 match = XftFontMatch(dpy, screen, fcpattern, &result);
744 }
745
746 /* if found a pattern, open its font */
747 if (match) {
748 retfont = XftFontOpenPattern(dpy, match);
749 if (retfont && XftCharExists(dpy, retfont, ucode) == FcTrue) {
750 if ((dc.fonts = realloc(dc.fonts, dc.nfonts+1)) == NULL)
751 err(1, "realloc");
752 dc.fonts[dc.nfonts] = retfont;
753 return dc.fonts[dc.nfonts++];
754 } else {
755 XftFontClose(dpy, retfont);
756 }
757 }
758
759 /* in case no fount was found, return the first one */
760 return dc.fonts[0];
761}
762
763/* draw text into XftDraw, return width of text glyphs */
764static int
765drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
766{
767 int textwidth = 0;
768
769 while (*text) {
770 XftFont *currfont;
771 XGlyphInfo ext;
772 FcChar32 ucode;
773 const char *next;
774 size_t len;
775
776 ucode = getnextutf8char(text, &next);
777 currfont = getfontucode(ucode);
778
779 len = next - text;
780 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)text, len, &ext);
781 textwidth += ext.xOff;
782
783 if (draw) {
784 int texty;
785
786 texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
787 XftDrawStringUtf8(draw, color, currfont, x, texty, (XftChar8 *)text, len);
788 x += ext.xOff;
789 }
790
791 text = next;
792 }
793
794 return textwidth;
795}
796
797/* setup the height, width and icon of the items of a menu */
798static void
799setupitems(struct Menu *menu)
800{
801 struct Item *item;
802 int itemwidth;
803
804 menu->w = config.width_pixels;
805 menu->maxtextw = 0;
806 for (item = menu->list; item != NULL; item = item->next) {
807 item->y = menu->h;
808 if (item->label == NULL) /* height for separator item */
809 item->h = config.separator_pixels;
810 else
811 item->h = config.height_pixels;
812 menu->h += item->h;
813 if (item->label)
814 item->textw = drawtext(NULL, NULL, 0, 0, 0, item->label);
815 else
816 item->textw = 0;
817
818 /*
819 * set menu width
820 *
821 * the item width depends on the size of its label (item->textw),
822 * and it is only used to calculate the width of the menu (which
823 * is equal to the width of the largest item).
824 *
825 * the horizontal padding appears 4 times through the width of a
826 * item: before and after its icon, and before and after its triangle.
827 * if the iflag is set (icons are disabled) then the horizontal
828 * padding appears 3 times: before the label and around the triangle.
829 */
830 itemwidth = item->textw + config.triangle_width + config.horzpadding * 3;
831 itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
832 menu->w = MAX(menu->w, itemwidth);
833 menu->maxtextw = MAX(menu->maxtextw, item->textw);
834 }
835}
836
837/* setup the position of a menu */
838static void
839setupmenupos(struct Menu *menu, struct Monitor *mon)
840{
841 int width, height;
842
843 width = menu->w + config.border_pixels * 2;
844 height = menu->h + config.border_pixels * 2;
845 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
846 if (pflag || (config.posx >= mon->x && mon->x + mon->w - config.posx >= width))
847 menu->x = config.posx;
848 else if (config.posx > width)
849 menu->x = config.posx - width;
850
851 if (pflag || (config.posy >= mon->y && mon->y + mon->h - config.posy >= height))
852 menu->y = config.posy;
853 else if (mon->y + mon->h > height)
854 menu->y = mon->y + mon->h - height;
855 } else { /* else, calculate in respect to parent menu */
856 int parentwidth;
857
858 parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
859
860 if (mon->x + mon->w - parentwidth >= width)
861 menu->x = parentwidth;
862 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
863 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
864
865 if (mon->y + mon->h - (menu->caller->y + menu->parent->y) >= height)
866 menu->y = menu->caller->y + menu->parent->y;
867 else if (mon->y + mon->h > height)
868 menu->y = mon->y + mon->h - height;
869 }
870}
871
872/* recursivelly setup menu configuration and its pixmap */
873static void
874setupmenu(struct Menu *menu, struct Monitor *mon)
875{
876 char *title;
877 struct Item *item;
878 XWindowChanges changes;
879 XSizeHints sizeh;
880 XTextProperty wintitle;
881
882 /* setup size and position of menus */
883 if (firsttime)
884 setupitems(menu);
885 setupmenupos(menu, mon);
886
887 /* update menu geometry */
888 changes.height = menu->h;
889 changes.width = menu->w;
890 changes.x = menu->x;
891 changes.y = menu->y;
892 XConfigureWindow(dpy, menu->win, CWWidth | CWHeight | CWX | CWY, &changes);
893
894 if (firsttime) {
895 /* set window title (used if wflag is on) */
896 if (menu->parent == NULL) {
897 title = classh.res_name;
898 } else if (menu->caller->output) {
899 title = menu->caller->output;
900 } else {
901 title = "\0";
902 }
903 XStringListToTextProperty(&title, 1, &wintitle);
904
905 /* set window manager hints */
906 sizeh.flags = USPosition | PMaxSize | PMinSize;
907 sizeh.min_width = sizeh.max_width = menu->w;
908 sizeh.min_height = sizeh.max_height = menu->h;
909 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, &classh);
910
911 /* set WM protocols and ewmh window properties */
912 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
913 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
914 PropModeReplace, (unsigned char *)title, strlen(title));
915 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
916 PropModeReplace,
917 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
918 }
919
920 /* calculate positions of submenus */
921 for (item = menu->list; item != NULL; item = item->next) {
922 if (item->submenu != NULL)
923 setupmenu(item->submenu, mon);
924 }
925}
926
927/* try to grab pointer, we may have to wait for another process to ungrab */
928static void
929grabpointer(void)
930{
931 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
932 int i;
933
934 for (i = 0; i < 1000; i++) {
935 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
936 GrabModeAsync, GrabModeAsync, None,
937 None, CurrentTime) == GrabSuccess)
938 return;
939 nanosleep(&ts, NULL);
940 }
941 errx(1, "could not grab pointer");
942}
943
944/* try to grab keyboard, we may have to wait for another process to ungrab */
945static void
946grabkeyboard(void)
947{
948 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
949 int i;
950
951 for (i = 0; i < 1000; i++) {
952 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
953 GrabModeAsync, CurrentTime) == GrabSuccess)
954 return;
955 nanosleep(&ts, NULL);
956 }
957 errx(1, "could not grab keyboard");
958}
959
960/* try to grab focus, we may have to wait for another process to ungrab */
961static void
962grabfocus(Window win)
963{
964 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
965 Window focuswin;
966 int i, revertwin;
967
968 for (i = 0; i < 100; ++i) {
969 XGetInputFocus(dpy, &focuswin, &revertwin);
970 if (focuswin == win)
971 return;
972 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
973 nanosleep(&ts, NULL);
974 }
975 errx(1, "cannot grab focus");
976}
977
978/* ungrab pointer and keyboard */
979static void
980ungrab(void)
981{
982 XUngrabPointer(dpy, CurrentTime);
983 XUngrabKeyboard(dpy, CurrentTime);
984}
985
986/* load and scale icon */
987static Imlib_Image
988loadicon(const char *file)
989{
990 Imlib_Image icon;
991 Imlib_Load_Error errcode;
992 const char *errstr;
993 int width;
994 int height;
995 int imgsize;
996
997 icon = imlib_load_image_with_error_return(file, &errcode);
998 if (*file == '\0') {
999 warnx("could not load icon (file name is blank)");
1000 return NULL;
1001 } else if (icon == NULL) {
1002 switch (errcode) {
1003 case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
1004 errstr = "file does not exist";
1005 break;
1006 case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
1007 errstr = "file is directory";
1008 break;
1009 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
1010 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
1011 errstr = "permission denied";
1012 break;
1013 case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
1014 errstr = "unknown file format";
1015 break;
1016 case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
1017 errstr = "path too long";
1018 break;
1019 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
1020 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
1021 case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
1022 errstr = "improper path";
1023 break;
1024 case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
1025 errstr = "too many symbolic links";
1026 break;
1027 case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
1028 errstr = "out of memory";
1029 break;
1030 case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
1031 errstr = "out of file descriptors";
1032 break;
1033 default:
1034 errstr = "unknown error";
1035 break;
1036 }
1037 warnx("could not load icon (%s): %s", errstr, file);
1038 return NULL;
1039 }
1040
1041 imlib_context_set_image(icon);
1042
1043 width = imlib_image_get_width();
1044 height = imlib_image_get_height();
1045 imgsize = MIN(width, height);
1046
1047 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
1048 config.iconsize,
1049 config.iconsize);
1050
1051 return icon;
1052}
1053
1054/* draw pixmap for the selected and unselected version of each item on menu */
1055static void
1056drawitems(struct Menu *menu)
1057{
1058 XftDraw *dsel, *dunsel;
1059 struct Item *item;
1060 int textx;
1061 int x, y;
1062
1063 for (item = menu->list; item != NULL; item = item->next) {
1064 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
1065 DefaultDepth(dpy, screen));
1066
1067 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
1068 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
1069
1070 if (item->label == NULL) { /* item is separator */
1071 y = item->h/2;
1072 XSetForeground(dpy, dc.gc, dc.separator.pixel);
1073 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
1074 menu->w - config.horzpadding, y);
1075
1076 item->sel = item->unsel;
1077 } else {
1078 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
1079 DefaultDepth(dpy, screen));
1080 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
1081 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
1082
1083 /* draw text */
1084 textx = config.horzpadding;
1085 textx += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
1086 switch (config.alignment) {
1087 case CenterAlignment:
1088 textx += (menu->maxtextw - item->textw) / 2;
1089 break;
1090 case RightAlignment:
1091 textx += menu->maxtextw - item->textw;
1092 break;
1093 default:
1094 break;
1095 }
1096 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
1097 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
1098 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
1099 drawtext(dsel, &dc.selected[ColorFG], textx, 0, item->h, item->label);
1100 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
1101 drawtext(dunsel, &dc.normal[ColorFG], textx, 0, item->h, item->label);
1102 XftDrawDestroy(dsel);
1103 XftDrawDestroy(dunsel);
1104
1105 /* draw triangle */
1106 if (item->submenu != NULL) {
1107 x = menu->w - config.triangle_width - config.horzpadding;
1108 y = (item->h - config.triangle_height + 1) / 2;
1109
1110 XPoint triangle[] = {
1111 {x, y},
1112 {x + config.triangle_width, y + config.triangle_height/2},
1113 {x, y + config.triangle_height},
1114 {x, y}
1115 };
1116
1117 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
1118 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
1119 Convex, CoordModeOrigin);
1120 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
1121 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
1122 Convex, CoordModeOrigin);
1123 }
1124
1125 /* try to load icon */
1126 if (item->file && !iflag) {
1127 item->icon = loadicon(item->file);
1128 free(item->file);
1129 }
1130
1131 /* draw icon if properly loaded */
1132 if (item->icon) {
1133 imlib_context_set_image(item->icon);
1134 imlib_context_set_drawable(item->sel);
1135 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
1136 imlib_context_set_drawable(item->unsel);
1137 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
1138 imlib_context_set_image(item->icon);
1139 imlib_free_image();
1140 }
1141 }
1142 }
1143}
1144
1145/* copy pixmaps of items of the current menu and of its ancestors into menu window */
1146static void
1147drawmenus(struct Menu *currmenu)
1148{
1149 struct Menu *menu;
1150 struct Item *item;
1151
1152 for (menu = currmenu; menu != NULL; menu = menu->parent) {
1153 if (!menu->drawn) {
1154 drawitems(menu);
1155 menu->drawn = 1;
1156 }
1157 for (item = menu->list; item != NULL; item = item->next) {
1158 if (item == menu->selected)
1159 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
1160 menu->w, item->h, 0, item->y);
1161 else
1162 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
1163 menu->w, item->h, 0, item->y);
1164 }
1165 }
1166}
1167
1168/* unmap current menu and its parents */
1169static void
1170unmapmenu(struct Menu *currmenu)
1171{
1172 struct Menu *menu;
1173
1174 for (menu = currmenu; menu != NULL; menu = menu->parent) {
1175 menu->selected = NULL;
1176 XUnmapWindow(dpy, menu->win);
1177 }
1178}
1179
1180/* umap previous menus and map current menu and its parents */
1181static struct Menu *
1182mapmenu(struct Menu *currmenu, struct Menu *prevmenu, struct Monitor *mon)
1183{
1184 struct Menu *menu, *menu_;
1185 struct Menu *lcamenu; /* lowest common ancestor menu */
1186 unsigned minlevel; /* level of the closest to root menu */
1187 unsigned maxlevel; /* level of the closest to root menu */
1188
1189 /* do not remap current menu if it wasn't updated*/
1190 if (prevmenu == currmenu)
1191 goto done;
1192
1193 /* if this is the first time mapping, skip calculations */
1194 if (prevmenu == NULL) {
1195 XMapWindow(dpy, currmenu->win);
1196 goto done;
1197 }
1198
1199 /* find lowest common ancestor menu */
1200 minlevel = MIN(currmenu->level, prevmenu->level);
1201 maxlevel = MAX(currmenu->level, prevmenu->level);
1202 if (currmenu->level == maxlevel) {
1203 menu = currmenu;
1204 menu_ = prevmenu;
1205 } else {
1206 menu = prevmenu;
1207 menu_ = currmenu;
1208 }
1209 while (menu->level > minlevel)
1210 menu = menu->parent;
1211 while (menu != menu_) {
1212 menu = menu->parent;
1213 menu_ = menu_->parent;
1214 }
1215 lcamenu = menu;
1216
1217 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
1218 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
1219 menu->selected = NULL;
1220 XUnmapWindow(dpy, menu->win);
1221 }
1222
1223 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
1224 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
1225 if (wflag) {
1226 setupmenupos(menu, mon);
1227 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1228 }
1229 XMapWindow(dpy, menu->win);
1230 }
1231
1232 grabfocus(currmenu->win);
1233done:
1234 return currmenu;
1235}
1236
1237/* get menu of given window */
1238static struct Menu *
1239getmenu(struct Menu *currmenu, Window win)
1240{
1241 struct Menu *menu;
1242
1243 for (menu = currmenu; menu != NULL; menu = menu->parent)
1244 if (menu->win == win)
1245 return menu;
1246
1247 return NULL;
1248}
1249
1250/* get item of given menu and position */
1251static struct Item *
1252getitem(struct Menu *menu, int y)
1253{
1254 struct Item *item;
1255
1256 if (menu == NULL)
1257 return NULL;
1258
1259 for (item = menu->list; item != NULL; item = item->next)
1260 if (y >= item->y && y <= item->y + item->h)
1261 return item;
1262
1263 return NULL;
1264}
1265
1266/* cycle through the items; non-zero direction is next, zero is prev */
1267static struct Item *
1268itemcycle(struct Menu *currmenu, int direction)
1269{
1270 struct Item *item = NULL;
1271 struct Item *lastitem;
1272
1273 for (lastitem = currmenu->list; lastitem && lastitem->next; lastitem = lastitem->next)
1274 ;
1275
1276 /* select item (either separator or labeled item) in given direction */
1277 switch (direction) {
1278 case ITEMNEXT:
1279 if (currmenu->selected == NULL)
1280 item = currmenu->list;
1281 else if (currmenu->selected->next != NULL)
1282 item = currmenu->selected->next;
1283 break;
1284 case ITEMPREV:
1285 if (currmenu->selected == NULL)
1286 item = lastitem;
1287 else if (currmenu->selected->prev != NULL)
1288 item = currmenu->selected->prev;
1289 break;
1290 case ITEMFIRST:
1291 item = currmenu->list;
1292 break;
1293 case ITEMLAST:
1294 item = lastitem;
1295 break;
1296 }
1297
1298 /*
1299 * the selected item can be a separator
1300 * let's select the closest labeled item (ie., one that isn't a separator)
1301 */
1302 switch (direction) {
1303 case ITEMNEXT:
1304 case ITEMFIRST:
1305 while (item != NULL && item->label == NULL)
1306 item = item->next;
1307 if (item == NULL)
1308 item = currmenu->list;
1309 break;
1310 case ITEMPREV:
1311 case ITEMLAST:
1312 while (item != NULL && item->label == NULL)
1313 item = item->prev;
1314 if (item == NULL)
1315 item = lastitem;
1316 break;
1317 }
1318
1319 return item;
1320}
1321
1322/* check if button is used to scroll */
1323static int
1324isscrollbutton(unsigned int button)
1325{
1326 if (button == Button4 || button == Button5)
1327 return 1;
1328 return 0;
1329}
1330
1331/* check if button is used to open a item on click */
1332static int
1333isclickbutton(unsigned int button)
1334{
1335 if (button == Button1 || button == Button2)
1336 return 1;
1337 if (!rflag && button == Button3)
1338 return 1;
1339 return 0;
1340}
1341
1342/* warp pointer to center of selected item */
1343static void
1344warppointer(struct Menu *menu, struct Item *item)
1345{
1346 if (menu == NULL || item == NULL)
1347 return;
1348 if (menu->selected) {
1349 XWarpPointer(dpy, None, menu->win, 0, 0, 0, 0, menu->w / 2, item->y + item->h / 2);
1350 }
1351}
1352
1353/* append buf into text */
1354static int
1355append(char *text, char *buf, size_t textsize, size_t buflen)
1356{
1357 size_t textlen;
1358
1359 textlen = strlen(text);
1360 if (iscntrl(*buf))
1361 return 0;
1362 if (textlen + buflen > textsize - 1)
1363 return 0;
1364 if (buflen < 1)
1365 return 0;
1366 memcpy(text + textlen, buf, buflen);
1367 text[textlen + buflen] = '\0';
1368 return 1;
1369}
1370
1371/* get item in menu matching text from given direction (or from beginning, if dir = 0) */
1372static struct Item *
1373matchitem(struct Menu *menu, char *text, int dir)
1374{
1375 struct Item *item, *lastitem;
1376 char *s;
1377 size_t textlen;
1378
1379 for (lastitem = menu->list; lastitem && lastitem->next; lastitem = lastitem->next)
1380 ;
1381 textlen = strlen(text);
1382 if (dir < 0) {
1383 if (menu->selected && menu->selected->prev)
1384 item = menu->selected->prev;
1385 else
1386 item = lastitem;
1387 } else if (dir > 0) {
1388 if (menu->selected && menu->selected->next)
1389 item = menu->selected->next;
1390 else
1391 item = menu->list;
1392 } else {
1393 item = menu->list;
1394 }
1395 /* find next item from selected item */
1396 for ( ; item; item = (dir < 0) ? item->prev : item->next)
1397 for (s = item->label; s && *s; s++)
1398 if (strncasecmp(s, text, textlen) == 0)
1399 return item;
1400 /* if not found, try to find from the beginning/end of list */
1401 if (dir > 0) {
1402 for (item = menu->list ; item; item = item->next) {
1403 for (s = item->label; s && *s; s++) {
1404 if (strncasecmp(s, text, textlen) == 0) {
1405 return item;
1406 }
1407 }
1408 }
1409 } else {
1410 for (item = lastitem ; item; item = item->prev) {
1411 for (s = item->label; s && *s; s++) {
1412 if (strncasecmp(s, text, textlen) == 0) {
1413 return item;
1414 }
1415 }
1416 }
1417 }
1418 return NULL;
1419}
1420
1421/* check keysyms defined on config.h */
1422static KeySym
1423normalizeksym(KeySym ksym)
1424{
1425 if (ksym == KSYMFIRST)
1426 return XK_Home;
1427 if (ksym == KSYMLAST)
1428 return XK_End;
1429 if (ksym == KSYMUP)
1430 return XK_Up;
1431 if (ksym == KSYMDOWN)
1432 return XK_Down;
1433 if (ksym == KSYMLEFT)
1434 return XK_Left;
1435 if (ksym == KSYMRIGHT)
1436 return XK_Right;
1437 return ksym;
1438}
1439
1440/* run event loop */
1441static void
1442run(struct Menu *currmenu, struct Monitor *mon)
1443{
1444 char text[BUFSIZ];
1445 char buf[32];
1446 struct Menu *menu, *prevmenu;
1447 struct Item *item;
1448 struct Item *previtem = NULL;
1449 struct Item *lastitem, *select;
1450 KeySym ksym;
1451 Status status;
1452 XEvent ev;
1453 int warped = 0;
1454 int action;
1455 int len;
1456 int i;
1457
1458 text[0] = '\0';
1459 prevmenu = currmenu;
1460 while (!XNextEvent(dpy, &ev)) {
1461 if (XFilterEvent(&ev, None))
1462 continue;
1463 action = ACTION_NOP;
1464 switch(ev.type) {
1465 case Expose:
1466 if (ev.xexpose.count == 0)
1467 action = ACTION_DRAW;
1468 break;
1469 case MotionNotify:
1470 if (!warped) {
1471 menu = getmenu(currmenu, ev.xbutton.window);
1472 item = getitem(menu, ev.xbutton.y);
1473 if (menu == NULL || item == NULL || previtem == item)
1474 break;
1475 previtem = item;
1476 select = menu->selected = item;
1477 if (item->submenu != NULL) {
1478 currmenu = item->submenu;
1479 select = NULL;
1480 } else {
1481 currmenu = menu;
1482 }
1483 action = ACTION_CLEAR | ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
1484 }
1485 warped = 0;
1486 break;
1487 case ButtonRelease:
1488 if (isscrollbutton(ev.xbutton.button)) {
1489 if (ev.xbutton.button == Button4)
1490 select = itemcycle(currmenu, ITEMPREV);
1491 else
1492 select = itemcycle(currmenu, ITEMNEXT);
1493 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW | ACTION_WARP;
1494 } else if (isclickbutton(ev.xbutton.button)) {
1495 menu = getmenu(currmenu, ev.xbutton.window);
1496 item = getitem(menu, ev.xbutton.y);
1497 if (menu == NULL || item == NULL)
1498 break;
1499enteritem:
1500 if (item->label == NULL)
1501 break; /* ignore separators */
1502 if (item->submenu != NULL) {
1503 currmenu = item->submenu;
1504 } else {
1505 printf("%s\n", item->output);
1506 goto done;
1507 }
1508 select = currmenu->list;
1509 action = ACTION_CLEAR | ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
1510 if (ev.xbutton.button == Button2) {
1511 action |= ACTION_WARP;
1512 }
1513 }
1514 break;
1515 case ButtonPress:
1516 menu = getmenu(currmenu, ev.xbutton.window);
1517 if (menu == NULL)
1518 goto done;
1519 break;
1520 case KeyPress:
1521 len = XmbLookupString(currmenu->xic, &ev.xkey, buf, sizeof buf, &ksym, &status);
1522 switch(status) {
1523 default: /* XLookupNone, XBufferOverflow */
1524 continue;
1525 case XLookupChars:
1526 goto append;
1527 case XLookupKeySym: /* FALLTHROUGH */
1528 case XLookupBoth:
1529 break;
1530 }
1531
1532 /* esc closes xmenu when current menu is the root menu */
1533 if (ksym == XK_Escape && currmenu->parent == NULL)
1534 goto done;
1535
1536 /* Shift-Tab = ISO_Left_Tab */
1537 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1538 ksym = XK_ISO_Left_Tab;
1539
1540 /* cycle through menu */
1541 select = NULL;
1542 ksym = normalizeksym(ksym);
1543 switch (ksym) {
1544 case XK_Home:
1545 select = itemcycle(currmenu, ITEMFIRST);
1546 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1547 break;
1548 case XK_End:
1549 select = itemcycle(currmenu, ITEMLAST);
1550 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1551 break;
1552 case XK_ISO_Left_Tab:
1553 if (*text) {
1554 select = matchitem(currmenu, text, -1);
1555 action = ACTION_SELECT | ACTION_DRAW;
1556 break;
1557 }
1558 /* FALLTHROUGH */
1559 case XK_Up:
1560 select = itemcycle(currmenu, ITEMPREV);
1561 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1562 break;
1563 case XK_Tab:
1564 if (*text) {
1565 select = matchitem(currmenu, text, 1);
1566 action = ACTION_SELECT | ACTION_DRAW;
1567 break;
1568 }
1569 /* FALLTHROUGH */
1570 case XK_Down:
1571 select = itemcycle(currmenu, ITEMNEXT);
1572 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1573 break;
1574 case XK_1: case XK_2: case XK_3: case XK_4: case XK_5: case XK_6: case XK_7: case XK_8: case XK_9:
1575 item = itemcycle(currmenu, ITEMFIRST);
1576 lastitem = itemcycle(currmenu, ITEMLAST);
1577 for (int i = ksym - XK_1; i > 0 && item != lastitem; i--) {
1578 currmenu->selected = item;
1579 item = itemcycle(currmenu, ITEMNEXT);
1580 }
1581 select = item;
1582 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1583 break;
1584 case XK_Return: case XK_Right:
1585 if (currmenu->selected) {
1586 item = currmenu->selected;
1587 goto enteritem;
1588 }
1589 break;
1590 case XK_Escape: case XK_Left:
1591 if (currmenu->parent) {
1592 select = currmenu->parent->selected;
1593 currmenu = currmenu->parent;
1594 action = ACTION_CLEAR | ACTION_MAP | ACTION_SELECT | ACTION_DRAW;
1595 }
1596 break;
1597 case XK_BackSpace: case XK_Clear: case XK_Delete:
1598 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1599 break;
1600 default:
1601append:
1602 if (*buf == '\0' || iscntrl(*buf))
1603 break;
1604 for (i = 0; i < 2; i++) {
1605 append(text, buf, sizeof text, len);
1606 if ((select = matchitem(currmenu, text, 0)))
1607 break;
1608 text[0] = '\0';
1609 }
1610 action = ACTION_SELECT | ACTION_DRAW;
1611 break;
1612 }
1613 break;
1614 case LeaveNotify:
1615 previtem = NULL;
1616 select = NULL;
1617 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
1618 break;
1619 case ConfigureNotify:
1620 menu = getmenu(currmenu, ev.xconfigure.window);
1621 if (menu == NULL)
1622 break;
1623 menu->x = ev.xconfigure.x;
1624 menu->y = ev.xconfigure.y;
1625 break;
1626 case ClientMessage:
1627 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1628 break;
1629 /* user closed window */
1630 menu = getmenu(currmenu, ev.xclient.window);
1631 if (menu->parent == NULL)
1632 goto done; /* closing the root menu closes the program */
1633 currmenu = menu->parent;
1634 action = ACTION_MAP;
1635 break;
1636 }
1637 if (action & ACTION_CLEAR)
1638 text[0] = '\0';
1639 if (action & ACTION_SELECT)
1640 currmenu->selected = select;
1641 if (action & ACTION_MAP)
1642 prevmenu = mapmenu(currmenu, prevmenu, mon);
1643 if (action & ACTION_DRAW)
1644 drawmenus(currmenu);
1645 if (action & ACTION_WARP) {
1646 warppointer(currmenu, select);
1647 warped = 1;
1648 }
1649 }
1650done:
1651 unmapmenu(currmenu);
1652 ungrab();
1653}
1654
1655/* recursivelly free pixmaps and destroy windows */
1656static void
1657cleanmenu(struct Menu *menu)
1658{
1659 struct Item *item;
1660 struct Item *tmp;
1661
1662 item = menu->list;
1663 while (item != NULL) {
1664 if (item->submenu != NULL)
1665 cleanmenu(item->submenu);
1666 tmp = item;
1667 if (menu->drawn) {
1668 XFreePixmap(dpy, item->unsel);
1669 if (tmp->label != NULL)
1670 XFreePixmap(dpy, item->sel);
1671 }
1672 if (tmp->label != tmp->output)
1673 free(tmp->label);
1674 free(tmp->output);
1675 item = item->next;
1676 free(tmp);
1677 }
1678
1679 XDestroyWindow(dpy, menu->win);
1680 free(menu);
1681}
1682
1683/* cleanup draw context */
1684static void
1685cleandc(void)
1686{
1687 size_t i;
1688
1689 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1690 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1691 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1692 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
1693 XftColorFree(dpy, visual, colormap, &dc.separator);
1694 XftColorFree(dpy, visual, colormap, &dc.border);
1695 for (i = 0; i < dc.nfonts; i++)
1696 XftFontClose(dpy, dc.fonts[i]);
1697 XFreeGC(dpy, dc.gc);
1698}
1699
1700/* xmenu: generate menu from stdin and print selected entry to stdout */
1701int
1702main(int argc, char *argv[])
1703{
1704 struct Monitor mon;
1705 struct Menu *rootmenu;
1706 XEvent ev;
1707
1708 /* open connection to server and set X variables */
1709 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1710 warnx("warning: no locale support");
1711 if ((dpy = XOpenDisplay(NULL)) == NULL)
1712 errx(1, "could not open display");
1713 screen = DefaultScreen(dpy);
1714 visual = DefaultVisual(dpy, screen);
1715 rootwin = RootWindow(dpy, screen);
1716 colormap = DefaultColormap(dpy, screen);
1717 XrmInitialize();
1718 if ((xrm = XResourceManagerString(dpy)) != NULL)
1719 xdb = XrmGetStringDatabase(xrm);
1720 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
1721 errx(1, "XOpenIM: could not open input device");
1722
1723 /* process configuration and window class */
1724 getresources();
1725 getoptions(argc, argv);
1726
1727 /* imlib2 stuff */
1728 if (!iflag) {
1729 imlib_set_cache_size(2048 * 1024);
1730 imlib_context_set_dither(1);
1731 imlib_context_set_display(dpy);
1732 imlib_context_set_visual(visual);
1733 imlib_context_set_colormap(colormap);
1734 }
1735
1736 /* initializers */
1737 initdc();
1738 initiconsize();
1739 initatoms();
1740
1741 /* if running in root mode, get button presses from root window */
1742 if (rootmodeflag)
1743 XGrabButton(dpy, button, AnyModifier, rootwin, False, ButtonPressMask, GrabModeSync, GrabModeSync, None, None);
1744
1745 /* generate menus */
1746 rootmenu = parsestdin();
1747 if (rootmenu == NULL)
1748 errx(1, "no menu generated");
1749
1750 /* run event loop */
1751 do {
1752 if (rootmodeflag)
1753 XNextEvent(dpy, &ev);
1754 if (!rootmodeflag ||
1755 (ev.type == ButtonPress &&
1756 ((modifier != 0 && ev.xbutton.state == modifier) ||
1757 (ev.xbutton.subwindow == None)))) {
1758 if (rootmodeflag && passclickflag) {
1759 XAllowEvents(dpy, ReplayPointer, CurrentTime);
1760 }
1761 getmonitor(&mon);
1762 if (!wflag) {
1763 grabpointer();
1764 grabkeyboard();
1765 }
1766 setupmenu(rootmenu, &mon);
1767 mapmenu(rootmenu, NULL, &mon);
1768 XFlush(dpy);
1769 run(rootmenu, &mon);
1770 firsttime = 0;
1771 } else {
1772 XAllowEvents(dpy, ReplayPointer, CurrentTime);
1773 }
1774 } while (rootmodeflag);
1775
1776 /* clean stuff */
1777 cleanmenu(rootmenu);
1778 cleandc();
1779 XrmDestroyDatabase(xdb);
1780 XCloseDisplay(dpy);
1781
1782 return 0;
1783}