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