No more needed to use -i to disable icon padding
[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 <time.h>
9#include <unistd.h>
10#include <X11/Xlib.h>
11#include <X11/Xatom.h>
12#include <X11/Xutil.h>
13#include <X11/Xresource.h>
14#include <X11/XKBlib.h>
15#include <X11/Xft/Xft.h>
16#include <X11/extensions/Xinerama.h>
17#include <Imlib2.h>
18#include "xmenu.h"
19
20/*
21 * Function declarations
22 */
23
24/* argument parser */
25static void parseposition(char *optarg);
26
27/* initializers, and their helper routines */
28static void parsefonts(const char *s);
29static void ealloccolor(const char *s, XftColor *color);
30static void initmonitor(void);
31static void initresources(void);
32static void initdc(void);
33static void initiconsize(void);
34static void initatoms(void);
35
36/* structure builders, and their helper routines */
37static struct Item *allocitem(const char *label, const char *output, char *file);
38static struct Menu *allocmenu(struct Menu *parent, struct Item *list, unsigned level);
39static struct Menu *buildmenutree(unsigned level, const char *label, const char *output, char *file);
40static struct Menu *parsestdin(void);
41
42/* text drawer, and its helper routine */
43static FcChar32 getnextutf8char(const char *s, const char **end_ret);
44static int drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text);
45
46/* structure setters, and their helper routines */
47static void setupitems(struct Menu *menu);
48static void setupmenupos(struct Menu *menu);
49static void setupmenu(struct Menu *menu, XClassHint *classh);
50
51/* grabbers */
52static void grabpointer(void);
53static void grabkeyboard(void);
54
55/* item drawer, and its helper routine */
56static Imlib_Image loadicon(const char *file);
57static void drawitems(struct Menu *menu);
58
59/* menu drawers and mappers */
60static void drawmenus(struct Menu *currmenu);
61static void mapmenu(struct Menu *currmenu);
62
63/* getters */
64static struct Menu *getmenu(struct Menu *currmenu, Window win);
65static struct Item *getitem(struct Menu *menu, int y);
66
67/* cycle through items */
68static struct Item *itemcycle(struct Menu *currmenu, int direction);
69
70/* main event loop */
71static void run(struct Menu *currmenu);
72
73/* cleaners */
74static void cleanmenu(struct Menu *menu);
75static void cleanup(void);
76
77/* show usage */
78static void usage(void);
79
80
81/*
82 * Variable declarations
83 */
84
85/* X stuff */
86static Display *dpy;
87static int screen;
88static Visual *visual;
89static Window rootwin;
90static Colormap colormap;
91static struct DC dc;
92static struct Monitor mon;
93static Atom utf8string;
94static Atom wmdelete;
95static Atom netatom[NetLast];
96
97/* flags */
98static int iflag = 0; /* whether to disable icons */
99static int mflag = 0; /* whether the user specified a monitor with -p */
100static int pflag = 0; /* whether the user specified a position with -p */
101static int wflag = 0; /* whether to let the window manager control XMenu */
102
103/* include config variable */
104#include "config.h"
105
106
107/*
108 * Function implementations
109 */
110
111/* xmenu: generate menu from stdin and print selected entry to stdout */
112int
113main(int argc, char *argv[])
114{
115 struct Menu *rootmenu;
116 XClassHint classh;
117 int ch;
118
119 while ((ch = getopt(argc, argv, "ip:w")) != -1) {
120 switch (ch) {
121 case 'i':
122 iflag = 1;
123 break;
124 case 'p':
125 pflag = 1;
126 parseposition(optarg);
127 break;
128 case 'w':
129 wflag = 1;
130 break;
131 default:
132 usage();
133 break;
134 }
135 }
136 argc -= optind;
137 argv += optind;
138
139 if (argc > 1)
140 usage();
141
142 /* open connection to server and set X variables */
143 if ((dpy = XOpenDisplay(NULL)) == NULL)
144 errx(1, "cannot open display");
145 screen = DefaultScreen(dpy);
146 visual = DefaultVisual(dpy, screen);
147 rootwin = RootWindow(dpy, screen);
148 colormap = DefaultColormap(dpy, screen);
149
150 /* imlib2 stuff */
151 if (!iflag) {
152 imlib_set_cache_size(2048 * 1024);
153 imlib_context_set_dither(1);
154 imlib_context_set_display(dpy);
155 imlib_context_set_visual(visual);
156 imlib_context_set_colormap(colormap);
157 }
158
159 /* initializers */
160 initmonitor();
161 initresources();
162 initdc();
163 initiconsize();
164 initatoms();
165
166 /* set window class */
167 classh.res_class = PROGNAME;
168 if (argc == 1)
169 classh.res_name = *argv;
170 else
171 classh.res_name = PROGNAME;
172
173 /* generate menus and set them up */
174 rootmenu = parsestdin();
175 if (rootmenu == NULL)
176 errx(1, "no menu generated");
177 setupmenu(rootmenu, &classh);
178
179 /* grab mouse and keyboard */
180 if (!wflag) {
181 grabpointer();
182 grabkeyboard();
183 }
184
185 /* run event loop */
186 run(rootmenu);
187
188 /* freeing stuff */
189 cleanmenu(rootmenu);
190 cleanup();
191
192 return 0;
193}
194
195/* parse position string from -p,
196 * put results on config.posx, config.posy, and config.monitor */
197static void
198parseposition(char *optarg)
199{
200 long n;
201 char *s = optarg;
202 char *endp;
203
204 n = strtol(s, &endp, 10);
205 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
206 goto error;
207 config.posx = n;
208 s = endp+1;
209 n = strtol(s, &endp, 10);
210 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s)
211 goto error;
212 config.posy = n;
213 if (*endp == ':') {
214 s = endp+1;
215 mflag = 1;
216 if (strncasecmp(s, "CUR", 3) == 0) {
217 config.monitor = -1;
218 endp = s+3;
219 } else {
220 n = strtol(s, &endp, 10);
221 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
222 goto error;
223 config.monitor = n;
224 }
225 } else if (*endp != '\0') {
226 goto error;
227 }
228
229 return;
230
231error:
232 errx(1, "improper position: %s", optarg);
233}
234
235/* parse color string */
236static void
237parsefonts(const char *s)
238{
239 const char *p;
240 char buf[1024];
241 size_t nfont = 0;
242
243 dc.nfonts = 1;
244 for (p = s; *p; p++)
245 if (*p == ',')
246 dc.nfonts++;
247
248 if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
249 err(1, "calloc");
250
251 p = s;
252 while (*p != '\0') {
253 size_t i;
254
255 i = 0;
256 while (isspace(*p))
257 p++;
258 while (*p != '\0' && *p != ',') {
259 buf[i++] = *p++;
260 }
261 if (*p == ',')
262 p++;
263 buf[i] = '\0';
264 if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
265 errx(1, "cannot load font");
266 }
267}
268
269/* get color from color string */
270static void
271ealloccolor(const char *s, XftColor *color)
272{
273 if(!XftColorAllocName(dpy, visual, colormap, s, color))
274 errx(1, "cannot allocate color: %s", s);
275}
276
277/* query monitor information and cursor position */
278static void
279initmonitor(void)
280{
281 XineramaScreenInfo *info = NULL;
282 Window dw; /* dummy variable */
283 int di; /* dummy variable */
284 unsigned du; /* dummy variable */
285 int cursx, cursy; /* cursor position */
286 int nmons;
287 int i;
288
289 XQueryPointer(dpy, rootwin, &dw, &dw, &cursx, &cursy, &di, &di, &du);
290
291 mon.x = mon.y = 0;
292 mon.w = DisplayWidth(dpy, screen);
293 mon.h = DisplayHeight(dpy, screen);
294
295 if ((info = XineramaQueryScreens(dpy, &nmons)) != NULL) {
296 int selmon = 0;
297
298 if (!mflag || (mflag && (config.monitor < 0 || config.monitor >= nmons))) {
299 for (i = 0; i < nmons; i++) {
300 if (cursx >= info[i].x_org && cursx <= info[i].x_org + info[i].width &&
301 cursy >= info[i].y_org && cursy <= info[i].y_org + info[i].height) {
302 selmon = i;
303 break;
304 }
305 }
306 } else {
307 selmon = config.monitor;
308 }
309
310 mon.x = info[selmon].x_org;
311 mon.y = info[selmon].y_org;
312 mon.w = info[selmon].width;
313 mon.h = info[selmon].height;
314 }
315
316 if (!pflag) {
317 config.posx = cursx;
318 config.posy = cursy;
319 } else if (mflag) {
320 config.posx += mon.x;
321 config.posy += mon.y;
322 }
323}
324
325/* read xrdb for configuration options */
326static void
327initresources(void)
328{
329 char *xrm;
330 long n;
331 char *type;
332 XrmDatabase xdb;
333 XrmValue xval;
334
335 XrmInitialize();
336 if ((xrm = XResourceManagerString(dpy)) == NULL)
337 return;
338
339 xdb = XrmGetStringDatabase(xrm);
340
341 if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
342 if ((n = strtol(xval.addr, NULL, 10)) > 0)
343 config.border_pixels = n;
344 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
345 if ((n = strtol(xval.addr, NULL, 10)) > 0)
346 config.separator_pixels = n;
347 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
348 if ((n = strtol(xval.addr, NULL, 10)) > 0)
349 config.height_pixels = n;
350 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
351 if ((n = strtol(xval.addr, NULL, 10)) > 0)
352 config.width_pixels = n;
353 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
354 if ((n = strtol(xval.addr, NULL, 10)) > 0)
355 config.gap_pixels = n;
356 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
357 config.background_color = strdup(xval.addr);
358 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
359 config.foreground_color = strdup(xval.addr);
360 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
361 config.selbackground_color = strdup(xval.addr);
362 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
363 config.selforeground_color = strdup(xval.addr);
364 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
365 config.separator_color = strdup(xval.addr);
366 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
367 config.border_color = strdup(xval.addr);
368 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
369 config.font = strdup(xval.addr);
370
371 XrmDestroyDatabase(xdb);
372}
373
374/* init draw context */
375static void
376initdc(void)
377{
378 /* get color pixels */
379 ealloccolor(config.background_color, &dc.normal[ColorBG]);
380 ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
381 ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
382 ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
383 ealloccolor(config.separator_color, &dc.separator);
384 ealloccolor(config.border_color, &dc.border);
385
386 /* parse fonts */
387 parsefonts(config.font);
388
389 /* create common GC */
390 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
391}
392
393/* calculate icon size */
394static void
395initiconsize(void)
396{
397 config.iconsize = config.height_pixels - config.iconpadding * 2;
398}
399
400/* intern atoms */
401static void
402initatoms(void)
403{
404 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
405 wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
406 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
407 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
408 netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
409}
410
411/* allocate an item */
412static struct Item *
413allocitem(const char *label, const char *output, char *file)
414{
415 struct Item *item;
416
417 if ((item = malloc(sizeof *item)) == NULL)
418 err(1, "malloc");
419 if (label == NULL) {
420 item->label = NULL;
421 item->output = NULL;
422 } else {
423 if ((item->label = strdup(label)) == NULL)
424 err(1, "strdup");
425 if (label == output) {
426 item->output = item->label;
427 } else {
428 if ((item->output = strdup(output)) == NULL)
429 err(1, "strdup");
430 }
431 }
432 if (file == NULL) {
433 item->file = NULL;
434 } else {
435 if ((item->file = strdup(file)) == NULL)
436 err(1, "strdup");
437 }
438 item->y = 0;
439 item->h = 0;
440 if (item->label == NULL)
441 item->labellen = 0;
442 else
443 item->labellen = strlen(item->label);
444 item->next = NULL;
445 item->submenu = NULL;
446 item->icon = NULL;
447
448 return item;
449}
450
451/* allocate a menu and create its window */
452static struct Menu *
453allocmenu(struct Menu *parent, struct Item *list, unsigned level)
454{
455 XSetWindowAttributes swa;
456 struct Menu *menu;
457
458 if ((menu = malloc(sizeof *menu)) == NULL)
459 err(1, "malloc");
460 menu->parent = parent;
461 menu->list = list;
462 menu->caller = NULL;
463 menu->selected = NULL;
464 menu->w = 0; /* calculated by setupmenu() */
465 menu->h = 0; /* calculated by setupmenu() */
466 menu->x = 0; /* calculated by setupmenu() */
467 menu->y = 0; /* calculated by setupmenu() */
468 menu->level = level;
469 menu->drawn = 0;
470 menu->hasicon = 0;
471
472 swa.override_redirect = (wflag) ? False : True;
473 swa.background_pixel = dc.normal[ColorBG].pixel;
474 swa.border_pixel = dc.border.pixel;
475 swa.save_under = True; /* pop-up windows should save_under*/
476 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
477 | PointerMotionMask | LeaveWindowMask;
478 if (wflag)
479 swa.event_mask |= StructureNotifyMask;
480 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
481 CopyFromParent, CopyFromParent, CopyFromParent,
482 CWOverrideRedirect | CWBackPixel |
483 CWBorderPixel | CWEventMask | CWSaveUnder,
484 &swa);
485
486 return menu;
487}
488
489/* build the menu tree */
490static struct Menu *
491buildmenutree(unsigned level, const char *label, const char *output, char *file)
492{
493 static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
494 static struct Menu *rootmenu = NULL; /* menu to be returned */
495 struct Item *curritem = NULL; /* item currently being read */
496 struct Item *item; /* dummy item for loops */
497 struct Menu *menu; /* dummy menu for loops */
498 unsigned i;
499
500 /* create the item */
501 curritem = allocitem(label, output, file);
502
503 /* put the item in the menu tree */
504 if (prevmenu == NULL) { /* there is no menu yet */
505 menu = allocmenu(NULL, curritem, level);
506 rootmenu = menu;
507 prevmenu = menu;
508 curritem->prev = NULL;
509 } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
510 /* go up the menu tree until find the menu this item continues */
511 for (menu = prevmenu, i = level;
512 menu != NULL && i != prevmenu->level;
513 menu = menu->parent, i++)
514 ;
515 if (menu == NULL)
516 errx(1, "reached NULL menu");
517
518 /* find last item in the new menu */
519 for (item = menu->list; item->next != NULL; item = item->next)
520 ;
521
522 prevmenu = menu;
523 item->next = curritem;
524 curritem->prev = item;
525 } else if (level == prevmenu->level) { /* item is a continuation of current menu */
526 /* find last item in the previous menu */
527 for (item = prevmenu->list; item->next != NULL; item = item->next)
528 ;
529
530 item->next = curritem;
531 curritem->prev = item;
532 } else if (level > prevmenu->level) { /* item begins a new menu */
533 menu = allocmenu(prevmenu, curritem, level);
534
535 /* find last item in the previous menu */
536 for (item = prevmenu->list; item->next != NULL; item = item->next)
537 ;
538
539 prevmenu = menu;
540 menu->caller = item;
541 item->submenu = menu;
542 curritem->prev = NULL;
543 }
544
545 if (curritem->file)
546 prevmenu->hasicon = 1;
547
548 return rootmenu;
549}
550
551/* create menus and items from the stdin */
552static struct Menu *
553parsestdin(void)
554{
555 struct Menu *rootmenu;
556 char *s, buf[BUFSIZ];
557 char *file, *label, *output;
558 unsigned level = 0;
559
560 rootmenu = NULL;
561
562 while (fgets(buf, BUFSIZ, stdin) != NULL) {
563 /* get the indentation level */
564 level = strspn(buf, "\t");
565
566 /* get the label */
567 s = level + buf;
568 label = strtok(s, "\t\n");
569
570 /* get the filename */
571 file = NULL;
572 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
573 file = label + 4;
574 label = strtok(NULL, "\t\n");
575 }
576
577 /* get the output */
578 output = strtok(NULL, "\n");
579 if (output == NULL) {
580 output = label;
581 } else {
582 while (*output == '\t')
583 output++;
584 }
585
586 rootmenu = buildmenutree(level, label, output, file);
587 }
588
589 return rootmenu;
590}
591
592/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
593static FcChar32
594getnextutf8char(const char *s, const char **next_ret)
595{
596 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
597 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
598 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
599 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
600 /* 0xFFFD is the replacement character, used to represent unknown characters */
601 static const FcChar32 unknown = 0xFFFD;
602 FcChar32 ucode; /* FcChar32 type holds 32 bits */
603 size_t usize = 0; /* n' of bytes of the utf8 character */
604 size_t i;
605
606 *next_ret = s+1;
607
608 /* get code of first byte of utf8 character */
609 for (i = 0; i < sizeof utfmask; i++) {
610 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
611 usize = i;
612 ucode = (unsigned char)*s & ~utfmask[i];
613 break;
614 }
615 }
616
617 /* if first byte is a continuation byte or is not allowed, return unknown */
618 if (i == sizeof utfmask || usize == 0)
619 return unknown;
620
621 /* check the other usize-1 bytes */
622 s++;
623 for (i = 1; i < usize; i++) {
624 *next_ret = s+1;
625 /* if byte is nul or is not a continuation byte, return unknown */
626 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
627 return unknown;
628 /* 6 is the number of relevant bits in the continuation byte */
629 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
630 s++;
631 }
632
633 /* check if ucode is invalid or in utf-16 surrogate halves */
634 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
635 || BETWEEN (ucode, 0xD800, 0xDFFF))
636 return unknown;
637
638 return ucode;
639}
640
641/* draw text into XftDraw */
642static int
643drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
644{
645 const char *s, *nexts;
646 FcChar32 ucode;
647 XftFont *currfont;
648 int textlen = 0;
649
650 s = text;
651 while (*s) {
652 XGlyphInfo ext;
653 int charexists;
654 size_t len;
655 size_t i;
656
657 charexists = 0;
658 ucode = getnextutf8char(s, &nexts);
659 for (i = 0; i < dc.nfonts; i++) {
660 charexists = XftCharExists(dpy, dc.fonts[i], ucode);
661 if (charexists)
662 break;
663 }
664 if (charexists)
665 currfont = dc.fonts[i];
666
667 len = nexts - s;
668
669 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)s,
670 len, &ext);
671 textlen += ext.xOff;
672
673 if (draw) {
674 int texty;
675
676 texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
677 XftDrawStringUtf8(draw, color, currfont, x, texty,
678 (XftChar8 *)s, len);
679 x += ext.xOff;
680 }
681
682 s = nexts;
683 }
684
685 return textlen;
686}
687
688/* setup the height, width and icon of the items of a menu */
689static void
690setupitems(struct Menu *menu)
691{
692 struct Item *item;
693
694 menu->w = config.width_pixels;
695 for (item = menu->list; item != NULL; item = item->next) {
696 int itemwidth;
697 int textwidth;
698
699 item->y = menu->h;
700
701 if (item->label == NULL) /* height for separator item */
702 item->h = config.separator_pixels;
703 else
704 item->h = config.height_pixels;
705 menu->h += item->h;
706
707 if (item->label)
708 textwidth = drawtext(NULL, NULL, 0, 0, item->h, item->label);
709 else
710 textwidth = 0;
711
712 /*
713 * set menu width
714 *
715 * the item width depends on the size of its label (textwidth),
716 * and it is only used to calculate the width of the menu (which
717 * is equal to the width of the largest item).
718 *
719 * the horizontal padding appears 4 times through the width of a
720 * item: before and after its icon, and before and after its triangle.
721 * if the iflag is set (icons are disabled) then the horizontal
722 * padding appears 3 times: before the label and around the triangle.
723 */
724 itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
725 itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
726 menu->w = MAX(menu->w, itemwidth);
727 }
728}
729
730/* setup the position of a menu */
731static void
732setupmenupos(struct Menu *menu)
733{
734 int width, height;
735
736 width = menu->w + config.border_pixels * 2;
737 height = menu->h + config.border_pixels * 2;
738 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
739 if (pflag || (config.posx > mon.x && mon.x + mon.w - config.posx >= width))
740 menu->x = config.posx;
741 else if (config.posx > width)
742 menu->x = config.posx - width;
743
744 if (pflag || (config.posy > mon.y && mon.y + mon.h - config.posy >= height))
745 menu->y = config.posy;
746 else if (mon.y + mon.h > height)
747 menu->y = mon.y + mon.h - height;
748 } else { /* else, calculate in respect to parent menu */
749 int parentwidth;
750
751 parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
752
753 if (mon.x + mon.w - parentwidth >= width)
754 menu->x = parentwidth;
755 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
756 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
757
758 if (mon.y + mon.h - (menu->caller->y + menu->parent->y) > height)
759 menu->y = menu->caller->y + menu->parent->y;
760 else if (mon.y + mon.h - menu->parent->y > height)
761 menu->y = menu->parent->y;
762 else if (mon.y + mon.h > height)
763 menu->y = mon.y + mon.h - height;
764 }
765}
766
767/* recursivelly setup menu configuration and its pixmap */
768static void
769setupmenu(struct Menu *menu, XClassHint *classh)
770{
771 char *title;
772 struct Item *item;
773 XWindowChanges changes;
774 XSizeHints sizeh;
775 XTextProperty wintitle;
776
777 /* setup size and position of menus */
778 setupitems(menu);
779 setupmenupos(menu);
780
781 /* update menu geometry */
782 changes.border_width = config.border_pixels;
783 changes.height = menu->h;
784 changes.width = menu->w;
785 changes.x = menu->x;
786 changes.y = menu->y;
787 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
788
789 /* set window title (used if wflag is on) */
790 if (menu->parent == NULL) {
791 title = classh->res_name;
792 } else {
793 title = menu->caller->output;
794 }
795 XStringListToTextProperty(&title, 1, &wintitle);
796
797 /* set window manager hints */
798 sizeh.flags = USPosition | PMaxSize | PMinSize;
799 sizeh.min_width = sizeh.max_width = menu->w;
800 sizeh.min_height = sizeh.max_height = menu->h;
801 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
802
803 /* set WM protocols and ewmh window properties */
804 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
805 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
806 PropModeReplace, (unsigned char *)title, strlen(title));
807 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
808 PropModeReplace,
809 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
810
811 /* calculate positions of submenus */
812 for (item = menu->list; item != NULL; item = item->next) {
813 if (item->submenu != NULL)
814 setupmenu(item->submenu, classh);
815 }
816}
817
818/* try to grab pointer, we may have to wait for another process to ungrab */
819static void
820grabpointer(void)
821{
822 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
823 int i;
824
825 for (i = 0; i < 1000; i++) {
826 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
827 GrabModeAsync, GrabModeAsync, None,
828 None, CurrentTime) == GrabSuccess)
829 return;
830 nanosleep(&ts, NULL);
831 }
832 errx(1, "cannot grab keyboard");
833}
834
835/* try to grab keyboard, we may have to wait for another process to ungrab */
836static void
837grabkeyboard(void)
838{
839 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
840 int i;
841
842 for (i = 0; i < 1000; i++) {
843 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
844 GrabModeAsync, CurrentTime) == GrabSuccess)
845 return;
846 nanosleep(&ts, NULL);
847 }
848 errx(1, "cannot grab keyboard");
849}
850
851/* load and scale icon */
852static Imlib_Image
853loadicon(const char *file)
854{
855 Imlib_Image icon;
856 int width;
857 int height;
858 int imgsize;
859
860 icon = imlib_load_image(file);
861 if (icon == NULL)
862 errx(1, "cannot load icon %s", file);
863
864 imlib_context_set_image(icon);
865
866 width = imlib_image_get_width();
867 height = imlib_image_get_height();
868 imgsize = MIN(width, height);
869
870 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
871 config.iconsize,
872 config.iconsize);
873
874 return icon;
875}
876
877/* draw pixmap for the selected and unselected version of each item on menu */
878static void
879drawitems(struct Menu *menu)
880{
881 struct Item *item;
882
883 for (item = menu->list; item != NULL; item = item->next) {
884 XftDraw *dsel, *dunsel;
885 int x, y;
886
887 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
888 DefaultDepth(dpy, screen));
889
890 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
891 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
892
893 if (item->label == NULL) { /* item is separator */
894 y = item->h/2;
895 XSetForeground(dpy, dc.gc, dc.separator.pixel);
896 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
897 menu->w - config.horzpadding, y);
898
899 item->sel = item->unsel;
900 } else {
901
902 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
903 DefaultDepth(dpy, screen));
904 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
905 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
906
907 /* draw text */
908 x = config.horzpadding;
909 x += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
910 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
911 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
912 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
913 drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
914 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
915 drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
916 XftDrawDestroy(dsel);
917 XftDrawDestroy(dunsel);
918
919 /* draw triangle */
920 if (item->submenu != NULL) {
921 x = menu->w - config.triangle_width - config.horzpadding;
922 y = (item->h - config.triangle_height + 1) / 2;
923
924 XPoint triangle[] = {
925 {x, y},
926 {x + config.triangle_width, y + config.triangle_height/2},
927 {x, y + config.triangle_height},
928 {x, y}
929 };
930
931 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
932 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
933 Convex, CoordModeOrigin);
934 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
935 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
936 Convex, CoordModeOrigin);
937 }
938
939 /* draw icon */
940 if (item->file != NULL && !iflag) {
941 item->icon = loadicon(item->file);
942
943 imlib_context_set_image(item->icon);
944 imlib_context_set_drawable(item->sel);
945 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
946 imlib_context_set_drawable(item->unsel);
947 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
948 }
949 }
950 }
951}
952
953/* copy pixmaps of items of the current menu and of its ancestors into menu window */
954static void
955drawmenus(struct Menu *currmenu)
956{
957 struct Menu *menu;
958 struct Item *item;
959
960 for (menu = currmenu; menu != NULL; menu = menu->parent) {
961 if (!menu->drawn) {
962 drawitems(menu);
963 menu->drawn = 1;
964 }
965 for (item = menu->list; item != NULL; item = item->next) {
966 if (item == menu->selected)
967 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
968 menu->w, item->h, 0, item->y);
969 else
970 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
971 menu->w, item->h, 0, item->y);
972 }
973 }
974}
975
976/* umap previous menus and map current menu and its parents */
977static void
978mapmenu(struct Menu *currmenu)
979{
980 static struct Menu *prevmenu = NULL;
981 struct Menu *menu, *menu_;
982 struct Menu *lcamenu; /* lowest common ancestor menu */
983 unsigned minlevel; /* level of the closest to root menu */
984 unsigned maxlevel; /* level of the closest to root menu */
985
986 /* do not remap current menu if it wasn't updated*/
987 if (prevmenu == currmenu)
988 return;
989
990 /* if this is the first time mapping, skip calculations */
991 if (prevmenu == NULL) {
992 XMapWindow(dpy, currmenu->win);
993 prevmenu = currmenu;
994 return;
995 }
996
997 /* find lowest common ancestor menu */
998 minlevel = MIN(currmenu->level, prevmenu->level);
999 maxlevel = MAX(currmenu->level, prevmenu->level);
1000 if (currmenu->level == maxlevel) {
1001 menu = currmenu;
1002 menu_ = prevmenu;
1003 } else {
1004 menu = prevmenu;
1005 menu_ = currmenu;
1006 }
1007 while (menu->level > minlevel)
1008 menu = menu->parent;
1009 while (menu != menu_) {
1010 menu = menu->parent;
1011 menu_ = menu_->parent;
1012 }
1013 lcamenu = menu;
1014
1015 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
1016 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
1017 menu->selected = NULL;
1018 XUnmapWindow(dpy, menu->win);
1019 }
1020
1021 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
1022 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
1023
1024 if (wflag) {
1025 setupmenupos(menu);
1026 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1027 }
1028
1029 XMapWindow(dpy, menu->win);
1030 }
1031
1032 prevmenu = currmenu;
1033}
1034
1035/* get menu of given window */
1036static struct Menu *
1037getmenu(struct Menu *currmenu, Window win)
1038{
1039 struct Menu *menu;
1040
1041 for (menu = currmenu; menu != NULL; menu = menu->parent)
1042 if (menu->win == win)
1043 return menu;
1044
1045 return NULL;
1046}
1047
1048/* get item of given menu and position */
1049static struct Item *
1050getitem(struct Menu *menu, int y)
1051{
1052 struct Item *item;
1053
1054 if (menu == NULL)
1055 return NULL;
1056
1057 for (item = menu->list; item != NULL; item = item->next)
1058 if (y >= item->y && y <= item->y + item->h)
1059 return item;
1060
1061 return NULL;
1062}
1063
1064/* cycle through the items; non-zero direction is next, zero is prev */
1065static struct Item *
1066itemcycle(struct Menu *currmenu, int direction)
1067{
1068 struct Item *item;
1069 struct Item *lastitem;
1070
1071 item = NULL;
1072
1073 if (direction == ITEMNEXT) {
1074 if (currmenu->selected == NULL)
1075 item = currmenu->list;
1076 else if (currmenu->selected->next != NULL)
1077 item = currmenu->selected->next;
1078
1079 while (item != NULL && item->label == NULL)
1080 item = item->next;
1081
1082 if (item == NULL)
1083 item = currmenu->list;
1084 } else {
1085 for (lastitem = currmenu->list;
1086 lastitem != NULL && lastitem->next != NULL;
1087 lastitem = lastitem->next)
1088 ;
1089
1090 if (currmenu->selected == NULL)
1091 item = lastitem;
1092 else if (currmenu->selected->prev != NULL)
1093 item = currmenu->selected->prev;
1094
1095 while (item != NULL && item->label == NULL)
1096 item = item->prev;
1097
1098 if (item == NULL)
1099 item = lastitem;
1100 }
1101
1102 return item;
1103}
1104
1105/* run event loop */
1106static void
1107run(struct Menu *currmenu)
1108{
1109 struct Menu *menu;
1110 struct Item *item;
1111 struct Item *previtem = NULL;
1112 KeySym ksym;
1113 XEvent ev;
1114
1115 mapmenu(currmenu);
1116
1117 while (!XNextEvent(dpy, &ev)) {
1118 switch(ev.type) {
1119 case Expose:
1120 if (ev.xexpose.count == 0)
1121 drawmenus(currmenu);
1122 break;
1123 case MotionNotify:
1124 menu = getmenu(currmenu, ev.xbutton.window);
1125 item = getitem(menu, ev.xbutton.y);
1126 if (menu == NULL || item == NULL || previtem == item)
1127 break;
1128 previtem = item;
1129 menu->selected = item;
1130 if (item->submenu != NULL) {
1131 currmenu = item->submenu;
1132 currmenu->selected = NULL;
1133 } else {
1134 currmenu = menu;
1135 }
1136 mapmenu(currmenu);
1137 drawmenus(currmenu);
1138 break;
1139 case ButtonRelease:
1140 menu = getmenu(currmenu, ev.xbutton.window);
1141 item = getitem(menu, ev.xbutton.y);
1142 if (menu == NULL || item == NULL)
1143 break;
1144selectitem:
1145 if (item->label == NULL)
1146 break; /* ignore separators */
1147 if (item->submenu != NULL) {
1148 currmenu = item->submenu;
1149 } else {
1150 printf("%s\n", item->output);
1151 return;
1152 }
1153 mapmenu(currmenu);
1154 currmenu->selected = currmenu->list;
1155 drawmenus(currmenu);
1156 break;
1157 case ButtonPress:
1158 menu = getmenu(currmenu, ev.xbutton.window);
1159 if (menu == NULL)
1160 return;
1161 break;
1162 case KeyPress:
1163 ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
1164
1165 /* esc closes xmenu when current menu is the root menu */
1166 if (ksym == XK_Escape && currmenu->parent == NULL)
1167 return;
1168
1169 /* Shift-Tab = ISO_Left_Tab */
1170 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1171 ksym = XK_ISO_Left_Tab;
1172
1173 /* cycle through menu */
1174 item = NULL;
1175 if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
1176 item = itemcycle(currmenu, ITEMPREV);
1177 } else if (ksym == XK_Tab || ksym == XK_Down) {
1178 item = itemcycle(currmenu, ITEMNEXT);
1179 } else if ((ksym == XK_Return || ksym == XK_Right) &&
1180 currmenu->selected != NULL) {
1181 item = currmenu->selected;
1182 goto selectitem;
1183 } else if ((ksym == XK_Escape || ksym == XK_Left) &&
1184 currmenu->parent != NULL) {
1185 item = currmenu->parent->selected;
1186 currmenu = currmenu->parent;
1187 mapmenu(currmenu);
1188 } else
1189 break;
1190 currmenu->selected = item;
1191 drawmenus(currmenu);
1192 break;
1193 case LeaveNotify:
1194 previtem = NULL;
1195 currmenu->selected = NULL;
1196 drawmenus(currmenu);
1197 break;
1198 case ConfigureNotify:
1199 menu = getmenu(currmenu, ev.xconfigure.window);
1200 if (menu == NULL)
1201 break;
1202 menu->x = ev.xconfigure.x;
1203 menu->y = ev.xconfigure.y;
1204 break;
1205 case ClientMessage:
1206 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1207 break;
1208 /* user closed window */
1209 menu = getmenu(currmenu, ev.xclient.window);
1210 if (menu->parent == NULL)
1211 return; /* closing the root menu closes the program */
1212 currmenu = menu->parent;
1213 mapmenu(currmenu);
1214 break;
1215 }
1216 }
1217}
1218
1219/* recursivelly free pixmaps and destroy windows */
1220static void
1221cleanmenu(struct Menu *menu)
1222{
1223 struct Item *item;
1224 struct Item *tmp;
1225
1226 item = menu->list;
1227 while (item != NULL) {
1228 if (item->submenu != NULL)
1229 cleanmenu(item->submenu);
1230 tmp = item;
1231 if (menu->drawn) {
1232 XFreePixmap(dpy, item->unsel);
1233 if (tmp->label != NULL)
1234 XFreePixmap(dpy, item->sel);
1235 }
1236 if (tmp->label != tmp->output)
1237 free(tmp->label);
1238 free(tmp->output);
1239 if (tmp->file != NULL) {
1240 free(tmp->file);
1241 if (tmp->icon != NULL) {
1242 imlib_context_set_image(tmp->icon);
1243 imlib_free_image();
1244 }
1245 }
1246 item = item->next;
1247 free(tmp);
1248 }
1249
1250 XDestroyWindow(dpy, menu->win);
1251 free(menu);
1252}
1253
1254/* cleanup X and exit */
1255static void
1256cleanup(void)
1257{
1258 XUngrabPointer(dpy, CurrentTime);
1259 XUngrabKeyboard(dpy, CurrentTime);
1260
1261 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1262 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1263 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1264 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
1265 XftColorFree(dpy, visual, colormap, &dc.separator);
1266 XftColorFree(dpy, visual, colormap, &dc.border);
1267
1268 XFreeGC(dpy, dc.gc);
1269 XCloseDisplay(dpy);
1270}
1271
1272/* show usage */
1273static void
1274usage(void)
1275{
1276 (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
1277 exit(1);
1278}