changing the computation of the text y position
[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 initconfig(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 initconfig();
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 configuration values that are not set manually */
394static void
395initconfig(void)
396{
397 config.screenw = DisplayWidth(dpy, screen);
398 config.screenh = DisplayHeight(dpy, screen);
399 config.iconsize = config.height_pixels - config.iconpadding * 2;
400}
401
402/* intern atoms */
403static void
404initatoms(void)
405{
406 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
407 wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
408 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
409 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
410 netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
411}
412
413/* allocate an item */
414static struct Item *
415allocitem(const char *label, const char *output, char *file)
416{
417 struct Item *item;
418
419 if ((item = malloc(sizeof *item)) == NULL)
420 err(1, "malloc");
421 if (label == NULL) {
422 item->label = NULL;
423 item->output = NULL;
424 } else {
425 if ((item->label = strdup(label)) == NULL)
426 err(1, "strdup");
427 if (label == output) {
428 item->output = item->label;
429 } else {
430 if ((item->output = strdup(output)) == NULL)
431 err(1, "strdup");
432 }
433 }
434 if (file == NULL) {
435 item->file = NULL;
436 } else {
437 if ((item->file = strdup(file)) == NULL)
438 err(1, "strdup");
439 }
440 item->y = 0;
441 item->h = 0;
442 if (item->label == NULL)
443 item->labellen = 0;
444 else
445 item->labellen = strlen(item->label);
446 item->next = NULL;
447 item->submenu = NULL;
448 item->icon = NULL;
449
450 return item;
451}
452
453/* allocate a menu and create its window */
454static struct Menu *
455allocmenu(struct Menu *parent, struct Item *list, unsigned level)
456{
457 XSetWindowAttributes swa;
458 struct Menu *menu;
459
460 if ((menu = malloc(sizeof *menu)) == NULL)
461 err(1, "malloc");
462 menu->parent = parent;
463 menu->list = list;
464 menu->caller = NULL;
465 menu->selected = NULL;
466 menu->w = 0; /* calculated by setupmenu() */
467 menu->h = 0; /* calculated by setupmenu() */
468 menu->x = 0; /* calculated by setupmenu() */
469 menu->y = 0; /* calculated by setupmenu() */
470 menu->level = level;
471 menu->drawn = 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 return rootmenu;
547}
548
549/* create menus and items from the stdin */
550static struct Menu *
551parsestdin(void)
552{
553 struct Menu *rootmenu;
554 char *s, buf[BUFSIZ];
555 char *file, *label, *output;
556 unsigned level = 0;
557
558 rootmenu = NULL;
559
560 while (fgets(buf, BUFSIZ, stdin) != NULL) {
561 /* get the indentation level */
562 level = strspn(buf, "\t");
563
564 /* get the label */
565 s = level + buf;
566 label = strtok(s, "\t\n");
567
568 /* get the filename */
569 file = NULL;
570 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
571 file = label + 4;
572 label = strtok(NULL, "\t\n");
573 }
574
575 /* get the output */
576 output = strtok(NULL, "\n");
577 if (output == NULL) {
578 output = label;
579 } else {
580 while (*output == '\t')
581 output++;
582 }
583
584 rootmenu = buildmenutree(level, label, output, file);
585 }
586
587 return rootmenu;
588}
589
590/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
591static FcChar32
592getnextutf8char(const char *s, const char **next_ret)
593{
594 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
595 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
596 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
597 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
598 /* 0xFFFD is the replacement character, used to represent unknown characters */
599 static const FcChar32 unknown = 0xFFFD;
600 FcChar32 ucode; /* FcChar32 type holds 32 bits */
601 size_t usize = 0; /* n' of bytes of the utf8 character */
602 size_t i;
603
604 *next_ret = s+1;
605
606 /* get code of first byte of utf8 character */
607 for (i = 0; i < sizeof utfmask; i++) {
608 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
609 usize = i;
610 ucode = (unsigned char)*s & ~utfmask[i];
611 break;
612 }
613 }
614
615 /* if first byte is a continuation byte or is not allowed, return unknown */
616 if (i == sizeof utfmask || usize == 0)
617 return unknown;
618
619 /* check the other usize-1 bytes */
620 s++;
621 for (i = 1; i < usize; i++) {
622 *next_ret = s+1;
623 /* if byte is nul or is not a continuation byte, return unknown */
624 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
625 return unknown;
626 /* 6 is the number of relevant bits in the continuation byte */
627 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
628 s++;
629 }
630
631 /* check if ucode is invalid or in utf-16 surrogate halves */
632 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
633 || BETWEEN (ucode, 0xD800, 0xDFFF))
634 return unknown;
635
636 return ucode;
637}
638
639/* draw text into XftDraw */
640static int
641drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
642{
643 const char *s, *nexts;
644 FcChar32 ucode;
645 XftFont *currfont;
646 int textlen = 0;
647
648 s = text;
649 while (*s) {
650 XGlyphInfo ext;
651 int charexists;
652 size_t len;
653 size_t i;
654
655 charexists = 0;
656 ucode = getnextutf8char(s, &nexts);
657 for (i = 0; i < dc.nfonts; i++) {
658 charexists = XftCharExists(dpy, dc.fonts[i], ucode);
659 if (charexists)
660 break;
661 }
662 if (charexists)
663 currfont = dc.fonts[i];
664
665 len = nexts - s;
666
667 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)s,
668 len, &ext);
669 textlen += ext.xOff;
670
671 if (draw) {
672 int texty;
673
674 texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
675 XftDrawStringUtf8(draw, color, currfont, x, texty,
676 (XftChar8 *)s, len);
677 x += ext.xOff;
678 }
679
680 s = nexts;
681 }
682
683 return textlen;
684}
685
686/* setup the height, width and icon of the items of a menu */
687static void
688setupitems(struct Menu *menu)
689{
690 struct Item *item;
691
692 menu->w = config.width_pixels;
693 for (item = menu->list; item != NULL; item = item->next) {
694 int itemwidth;
695 int textwidth;
696
697 item->y = menu->h;
698
699 if (item->label == NULL) /* height for separator item */
700 item->h = config.separator_pixels;
701 else
702 item->h = config.height_pixels;
703 menu->h += item->h;
704
705 if (item->label)
706 textwidth = drawtext(NULL, NULL, 0, 0, item->h, item->label);
707 else
708 textwidth = 0;
709
710 /*
711 * set menu width
712 *
713 * the item width depends on the size of its label (textwidth),
714 * and it is only used to calculate the width of the menu (which
715 * is equal to the width of the largest item).
716 *
717 * the horizontal padding appears 4 times through the width of a
718 * item: before and after its icon, and before and after its triangle.
719 * if the iflag is set (icons are disabled) then the horizontal
720 * padding appears 3 times: before the label and around the triangle.
721 */
722 itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
723 itemwidth += (iflag) ? 0 : config.iconsize + config.horzpadding;
724 menu->w = MAX(menu->w, itemwidth);
725 }
726}
727
728/* setup the position of a menu */
729static void
730setupmenupos(struct Menu *menu)
731{
732 int width, height;
733
734 width = menu->w + config.border_pixels * 2;
735 height = menu->h + config.border_pixels * 2;
736 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
737 if (pflag || (config.posx > mon.x && mon.x + mon.w - config.posx >= width))
738 menu->x = config.posx;
739 else if (config.posx > width)
740 menu->x = config.posx - width;
741
742 if (pflag || (config.posy > mon.y && mon.y + mon.h - config.posy >= height))
743 menu->y = config.posy;
744 else if (config.screenh > height)
745 menu->y = mon.y + mon.h - height;
746 } else { /* else, calculate in respect to parent menu */
747 int parentwidth;
748
749 parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
750
751 if (mon.x + mon.w - parentwidth >= width)
752 menu->x = parentwidth;
753 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
754 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
755
756 if (mon.y + mon.h - (menu->caller->y + menu->parent->y) > height)
757 menu->y = menu->caller->y + menu->parent->y;
758 else if (mon.y + mon.h - menu->parent->y > height)
759 menu->y = menu->parent->y;
760 else if (mon.y + mon.h > height)
761 menu->y = mon.y + mon.h - height;
762 }
763}
764
765/* recursivelly setup menu configuration and its pixmap */
766static void
767setupmenu(struct Menu *menu, XClassHint *classh)
768{
769 char *title;
770 struct Item *item;
771 XWindowChanges changes;
772 XSizeHints sizeh;
773 XTextProperty wintitle;
774
775 /* setup size and position of menus */
776 setupitems(menu);
777 setupmenupos(menu);
778
779 /* update menu geometry */
780 changes.border_width = config.border_pixels;
781 changes.height = menu->h;
782 changes.width = menu->w;
783 changes.x = menu->x;
784 changes.y = menu->y;
785 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
786
787 /* set window title (used if wflag is on) */
788 if (menu->parent == NULL) {
789 title = classh->res_name;
790 } else {
791 title = menu->caller->output;
792 }
793 XStringListToTextProperty(&title, 1, &wintitle);
794
795 /* set window manager hints */
796 sizeh.flags = PMaxSize | PMinSize;
797 sizeh.min_width = sizeh.max_width = menu->w;
798 sizeh.min_height = sizeh.max_height = menu->h;
799 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
800
801 /* set WM protocols and ewmh window properties */
802 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
803 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
804 PropModeReplace, (unsigned char *)title, strlen(title));
805 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
806 PropModeReplace,
807 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
808
809 /* calculate positions of submenus */
810 for (item = menu->list; item != NULL; item = item->next) {
811 if (item->submenu != NULL)
812 setupmenu(item->submenu, classh);
813 }
814}
815
816/* try to grab pointer, we may have to wait for another process to ungrab */
817static void
818grabpointer(void)
819{
820 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
821 int i;
822
823 for (i = 0; i < 1000; i++) {
824 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
825 GrabModeAsync, GrabModeAsync, None,
826 None, CurrentTime) == GrabSuccess)
827 return;
828 nanosleep(&ts, NULL);
829 }
830 errx(1, "cannot grab keyboard");
831}
832
833/* try to grab keyboard, we may have to wait for another process to ungrab */
834static void
835grabkeyboard(void)
836{
837 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
838 int i;
839
840 for (i = 0; i < 1000; i++) {
841 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
842 GrabModeAsync, CurrentTime) == GrabSuccess)
843 return;
844 nanosleep(&ts, NULL);
845 }
846 errx(1, "cannot grab keyboard");
847}
848
849/* load and scale icon */
850static Imlib_Image
851loadicon(const char *file)
852{
853 Imlib_Image icon;
854 int width;
855 int height;
856 int imgsize;
857
858 icon = imlib_load_image(file);
859 if (icon == NULL)
860 errx(1, "cannot load icon %s", file);
861
862 imlib_context_set_image(icon);
863
864 width = imlib_image_get_width();
865 height = imlib_image_get_height();
866 imgsize = MIN(width, height);
867
868 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
869 config.iconsize,
870 config.iconsize);
871
872 return icon;
873}
874
875/* draw pixmap for the selected and unselected version of each item on menu */
876static void
877drawitems(struct Menu *menu)
878{
879 struct Item *item;
880
881 for (item = menu->list; item != NULL; item = item->next) {
882 XftDraw *dsel, *dunsel;
883 int x, y;
884
885 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
886 DefaultDepth(dpy, screen));
887
888 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
889 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
890
891 if (item->label == NULL) { /* item is separator */
892 y = item->h/2;
893 XSetForeground(dpy, dc.gc, dc.separator.pixel);
894 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
895 menu->w - config.horzpadding, y);
896
897 item->sel = item->unsel;
898 } else {
899
900 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
901 DefaultDepth(dpy, screen));
902 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
903 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
904
905 /* draw text */
906 x = config.horzpadding;
907 x += (iflag) ? 0 : config.horzpadding + config.iconsize;
908 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
909 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
910 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
911 drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
912 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
913 drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
914 XftDrawDestroy(dsel);
915 XftDrawDestroy(dunsel);
916
917 /* draw triangle */
918 if (item->submenu != NULL) {
919 x = menu->w - config.triangle_width - config.horzpadding;
920 y = (item->h - config.triangle_height + 1) / 2;
921
922 XPoint triangle[] = {
923 {x, y},
924 {x + config.triangle_width, y + config.triangle_height/2},
925 {x, y + config.triangle_height},
926 {x, y}
927 };
928
929 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
930 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
931 Convex, CoordModeOrigin);
932 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
933 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
934 Convex, CoordModeOrigin);
935 }
936
937 /* draw icon */
938 if (item->file != NULL && !iflag) {
939 item->icon = loadicon(item->file);
940
941 imlib_context_set_image(item->icon);
942 imlib_context_set_drawable(item->sel);
943 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
944 imlib_context_set_drawable(item->unsel);
945 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
946 }
947 }
948 }
949}
950
951/* copy pixmaps of items of the current menu and of its ancestors into menu window */
952static void
953drawmenus(struct Menu *currmenu)
954{
955 struct Menu *menu;
956 struct Item *item;
957
958 for (menu = currmenu; menu != NULL; menu = menu->parent) {
959 if (!menu->drawn) {
960 drawitems(menu);
961 menu->drawn = 1;
962 }
963 for (item = menu->list; item != NULL; item = item->next) {
964 if (item == menu->selected)
965 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
966 menu->w, item->h, 0, item->y);
967 else
968 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
969 menu->w, item->h, 0, item->y);
970 }
971 }
972}
973
974/* umap previous menus and map current menu and its parents */
975static void
976mapmenu(struct Menu *currmenu)
977{
978 static struct Menu *prevmenu = NULL;
979 struct Menu *menu, *menu_;
980 struct Menu *lcamenu; /* lowest common ancestor menu */
981 unsigned minlevel; /* level of the closest to root menu */
982 unsigned maxlevel; /* level of the closest to root menu */
983
984 /* do not remap current menu if it wasn't updated*/
985 if (prevmenu == currmenu)
986 return;
987
988 /* if this is the first time mapping, skip calculations */
989 if (prevmenu == NULL) {
990 XMapWindow(dpy, currmenu->win);
991 prevmenu = currmenu;
992 return;
993 }
994
995 /* find lowest common ancestor menu */
996 minlevel = MIN(currmenu->level, prevmenu->level);
997 maxlevel = MAX(currmenu->level, prevmenu->level);
998 if (currmenu->level == maxlevel) {
999 menu = currmenu;
1000 menu_ = prevmenu;
1001 } else {
1002 menu = prevmenu;
1003 menu_ = currmenu;
1004 }
1005 while (menu->level > minlevel)
1006 menu = menu->parent;
1007 while (menu != menu_) {
1008 menu = menu->parent;
1009 menu_ = menu_->parent;
1010 }
1011 lcamenu = menu;
1012
1013 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
1014 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
1015 menu->selected = NULL;
1016 XUnmapWindow(dpy, menu->win);
1017 }
1018
1019 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
1020 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
1021
1022 if (wflag) {
1023 setupmenupos(menu);
1024 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1025 }
1026
1027 XMapWindow(dpy, menu->win);
1028 }
1029
1030 prevmenu = currmenu;
1031}
1032
1033/* get menu of given window */
1034static struct Menu *
1035getmenu(struct Menu *currmenu, Window win)
1036{
1037 struct Menu *menu;
1038
1039 for (menu = currmenu; menu != NULL; menu = menu->parent)
1040 if (menu->win == win)
1041 return menu;
1042
1043 return NULL;
1044}
1045
1046/* get item of given menu and position */
1047static struct Item *
1048getitem(struct Menu *menu, int y)
1049{
1050 struct Item *item;
1051
1052 if (menu == NULL)
1053 return NULL;
1054
1055 for (item = menu->list; item != NULL; item = item->next)
1056 if (y >= item->y && y <= item->y + item->h)
1057 return item;
1058
1059 return NULL;
1060}
1061
1062/* cycle through the items; non-zero direction is next, zero is prev */
1063static struct Item *
1064itemcycle(struct Menu *currmenu, int direction)
1065{
1066 struct Item *item;
1067 struct Item *lastitem;
1068
1069 item = NULL;
1070
1071 if (direction == ITEMNEXT) {
1072 if (currmenu->selected == NULL)
1073 item = currmenu->list;
1074 else if (currmenu->selected->next != NULL)
1075 item = currmenu->selected->next;
1076
1077 while (item != NULL && item->label == NULL)
1078 item = item->next;
1079
1080 if (item == NULL)
1081 item = currmenu->list;
1082 } else {
1083 for (lastitem = currmenu->list;
1084 lastitem != NULL && lastitem->next != NULL;
1085 lastitem = lastitem->next)
1086 ;
1087
1088 if (currmenu->selected == NULL)
1089 item = lastitem;
1090 else if (currmenu->selected->prev != NULL)
1091 item = currmenu->selected->prev;
1092
1093 while (item != NULL && item->label == NULL)
1094 item = item->prev;
1095
1096 if (item == NULL)
1097 item = lastitem;
1098 }
1099
1100 return item;
1101}
1102
1103/* run event loop */
1104static void
1105run(struct Menu *currmenu)
1106{
1107 struct Menu *menu;
1108 struct Item *item;
1109 struct Item *previtem = NULL;
1110 KeySym ksym;
1111 XEvent ev;
1112
1113 mapmenu(currmenu);
1114
1115 while (!XNextEvent(dpy, &ev)) {
1116 switch(ev.type) {
1117 case Expose:
1118 if (ev.xexpose.count == 0)
1119 drawmenus(currmenu);
1120 break;
1121 case MotionNotify:
1122 menu = getmenu(currmenu, ev.xbutton.window);
1123 item = getitem(menu, ev.xbutton.y);
1124 if (menu == NULL || item == NULL || previtem == item)
1125 break;
1126 previtem = item;
1127 menu->selected = item;
1128 if (item->submenu != NULL) {
1129 currmenu = item->submenu;
1130 currmenu->selected = NULL;
1131 } else {
1132 currmenu = menu;
1133 }
1134 mapmenu(currmenu);
1135 drawmenus(currmenu);
1136 break;
1137 case ButtonRelease:
1138 menu = getmenu(currmenu, ev.xbutton.window);
1139 item = getitem(menu, ev.xbutton.y);
1140 if (menu == NULL || item == NULL)
1141 break;
1142selectitem:
1143 if (item->label == NULL)
1144 break; /* ignore separators */
1145 if (item->submenu != NULL) {
1146 currmenu = item->submenu;
1147 } else {
1148 printf("%s\n", item->output);
1149 return;
1150 }
1151 mapmenu(currmenu);
1152 currmenu->selected = currmenu->list;
1153 drawmenus(currmenu);
1154 break;
1155 case ButtonPress:
1156 menu = getmenu(currmenu, ev.xbutton.window);
1157 if (menu == NULL)
1158 return;
1159 break;
1160 case KeyPress:
1161 ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
1162
1163 /* esc closes xmenu when current menu is the root menu */
1164 if (ksym == XK_Escape && currmenu->parent == NULL)
1165 return;
1166
1167 /* Shift-Tab = ISO_Left_Tab */
1168 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1169 ksym = XK_ISO_Left_Tab;
1170
1171 /* cycle through menu */
1172 item = NULL;
1173 if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
1174 item = itemcycle(currmenu, ITEMPREV);
1175 } else if (ksym == XK_Tab || ksym == XK_Down) {
1176 item = itemcycle(currmenu, ITEMNEXT);
1177 } else if ((ksym == XK_Return || ksym == XK_Right) &&
1178 currmenu->selected != NULL) {
1179 item = currmenu->selected;
1180 goto selectitem;
1181 } else if ((ksym == XK_Escape || ksym == XK_Left) &&
1182 currmenu->parent != NULL) {
1183 item = currmenu->parent->selected;
1184 currmenu = currmenu->parent;
1185 mapmenu(currmenu);
1186 } else
1187 break;
1188 currmenu->selected = item;
1189 drawmenus(currmenu);
1190 break;
1191 case LeaveNotify:
1192 previtem = NULL;
1193 currmenu->selected = NULL;
1194 drawmenus(currmenu);
1195 break;
1196 case ConfigureNotify:
1197 menu = getmenu(currmenu, ev.xconfigure.window);
1198 if (menu == NULL)
1199 break;
1200 menu->x = ev.xconfigure.x;
1201 menu->y = ev.xconfigure.y;
1202 break;
1203 case ClientMessage:
1204 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1205 break;
1206 /* user closed window */
1207 menu = getmenu(currmenu, ev.xclient.window);
1208 if (menu->parent == NULL)
1209 return; /* closing the root menu closes the program */
1210 currmenu = menu->parent;
1211 mapmenu(currmenu);
1212 break;
1213 }
1214 }
1215}
1216
1217/* recursivelly free pixmaps and destroy windows */
1218static void
1219cleanmenu(struct Menu *menu)
1220{
1221 struct Item *item;
1222 struct Item *tmp;
1223
1224 item = menu->list;
1225 while (item != NULL) {
1226 if (item->submenu != NULL)
1227 cleanmenu(item->submenu);
1228 tmp = item;
1229 if (menu->drawn) {
1230 XFreePixmap(dpy, item->unsel);
1231 if (tmp->label != NULL)
1232 XFreePixmap(dpy, item->sel);
1233 }
1234 if (tmp->label != tmp->output)
1235 free(tmp->label);
1236 free(tmp->output);
1237 if (tmp->file != NULL) {
1238 free(tmp->file);
1239 if (tmp->icon != NULL) {
1240 imlib_context_set_image(tmp->icon);
1241 imlib_free_image();
1242 }
1243 }
1244 item = item->next;
1245 free(tmp);
1246 }
1247
1248 XDestroyWindow(dpy, menu->win);
1249 free(menu);
1250}
1251
1252/* cleanup X and exit */
1253static void
1254cleanup(void)
1255{
1256 XUngrabPointer(dpy, CurrentTime);
1257 XUngrabKeyboard(dpy, CurrentTime);
1258
1259 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1260 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1261 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1262 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
1263 XftColorFree(dpy, visual, colormap, &dc.separator);
1264 XftColorFree(dpy, visual, colormap, &dc.border);
1265
1266 XFreeGC(dpy, dc.gc);
1267 XCloseDisplay(dpy);
1268}
1269
1270/* show usage */
1271static void
1272usage(void)
1273{
1274 (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
1275 exit(1);
1276}