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