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