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