Fixing position in some wms when using -w
[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 (cursx >= info[i].x_org && cursx <= info[i].x_org + info[i].width &&
301 cursy >= info[i].y_org && cursy <= info[i].y_org + info[i].height) {
302 selmon = i;
303 break;
304 }
305 }
306 } else {
307 selmon = config.monitor;
308 }
309
310 mon.x = info[selmon].x_org;
311 mon.y = info[selmon].y_org;
312 mon.w = info[selmon].width;
313 mon.h = info[selmon].height;
314 }
315
316 if (!pflag) {
317 config.posx = cursx;
318 config.posy = cursy;
319 } else if (mflag) {
320 config.posx += mon.x;
321 config.posy += mon.y;
322 }
323}
324
325/* read xrdb for configuration options */
326static void
327initresources(void)
328{
329 char *xrm;
330 long n;
331 char *type;
332 XrmDatabase xdb;
333 XrmValue xval;
334
335 XrmInitialize();
336 if ((xrm = XResourceManagerString(dpy)) == NULL)
337 return;
338
339 xdb = XrmGetStringDatabase(xrm);
340
341 if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
342 if ((n = strtol(xval.addr, NULL, 10)) > 0)
343 config.border_pixels = n;
344 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
345 if ((n = strtol(xval.addr, NULL, 10)) > 0)
346 config.separator_pixels = n;
347 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
348 if ((n = strtol(xval.addr, NULL, 10)) > 0)
349 config.height_pixels = n;
350 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
351 if ((n = strtol(xval.addr, NULL, 10)) > 0)
352 config.width_pixels = n;
353 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
354 if ((n = strtol(xval.addr, NULL, 10)) > 0)
355 config.gap_pixels = n;
356 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
357 config.background_color = strdup(xval.addr);
358 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
359 config.foreground_color = strdup(xval.addr);
360 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
361 config.selbackground_color = strdup(xval.addr);
362 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
363 config.selforeground_color = strdup(xval.addr);
364 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
365 config.separator_color = strdup(xval.addr);
366 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
367 config.border_color = strdup(xval.addr);
368 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
369 config.font = strdup(xval.addr);
370
371 XrmDestroyDatabase(xdb);
372}
373
374/* init draw context */
375static void
376initdc(void)
377{
378 /* get color pixels */
379 ealloccolor(config.background_color, &dc.normal[ColorBG]);
380 ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
381 ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
382 ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
383 ealloccolor(config.separator_color, &dc.separator);
384 ealloccolor(config.border_color, &dc.border);
385
386 /* parse fonts */
387 parsefonts(config.font);
388
389 /* create common GC */
390 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
391}
392
393/* calculate 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 if (item->label == NULL)
441 item->labellen = 0;
442 else
443 item->labellen = strlen(item->label);
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; /* calculated by setupmenu() */
465 menu->h = 0; /* calculated by setupmenu() */
466 menu->x = 0; /* calculated by setupmenu() */
467 menu->y = 0; /* calculated by setupmenu() */
468 menu->level = level;
469 menu->drawn = 0;
470
471 swa.override_redirect = (wflag) ? False : True;
472 swa.background_pixel = dc.normal[ColorBG].pixel;
473 swa.border_pixel = dc.border.pixel;
474 swa.save_under = True; /* pop-up windows should save_under*/
475 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
476 | PointerMotionMask | LeaveWindowMask;
477 if (wflag)
478 swa.event_mask |= StructureNotifyMask;
479 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
480 CopyFromParent, CopyFromParent, CopyFromParent,
481 CWOverrideRedirect | CWBackPixel |
482 CWBorderPixel | CWEventMask | CWSaveUnder,
483 &swa);
484
485 return menu;
486}
487
488/* build the menu tree */
489static struct Menu *
490buildmenutree(unsigned level, const char *label, const char *output, char *file)
491{
492 static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
493 static struct Menu *rootmenu = NULL; /* menu to be returned */
494 struct Item *curritem = NULL; /* item currently being read */
495 struct Item *item; /* dummy item for loops */
496 struct Menu *menu; /* dummy menu for loops */
497 unsigned i;
498
499 /* create the item */
500 curritem = allocitem(label, output, file);
501
502 /* put the item in the menu tree */
503 if (prevmenu == NULL) { /* there is no menu yet */
504 menu = allocmenu(NULL, curritem, level);
505 rootmenu = menu;
506 prevmenu = menu;
507 curritem->prev = NULL;
508 } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
509 /* go up the menu tree until find the menu this item continues */
510 for (menu = prevmenu, i = level;
511 menu != NULL && i != prevmenu->level;
512 menu = menu->parent, i++)
513 ;
514 if (menu == NULL)
515 errx(1, "reached NULL menu");
516
517 /* find last item in the new menu */
518 for (item = menu->list; item->next != NULL; item = item->next)
519 ;
520
521 prevmenu = menu;
522 item->next = curritem;
523 curritem->prev = item;
524 } else if (level == prevmenu->level) { /* item is a continuation of current menu */
525 /* find last item in the previous menu */
526 for (item = prevmenu->list; item->next != NULL; item = item->next)
527 ;
528
529 item->next = curritem;
530 curritem->prev = item;
531 } else if (level > prevmenu->level) { /* item begins a new menu */
532 menu = allocmenu(prevmenu, curritem, level);
533
534 /* find last item in the previous menu */
535 for (item = prevmenu->list; item->next != NULL; item = item->next)
536 ;
537
538 prevmenu = menu;
539 menu->caller = item;
540 item->submenu = menu;
541 curritem->prev = NULL;
542 }
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, item->h, 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) ? 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 - menu->parent->y > height)
757 menu->y = menu->parent->y;
758 else if (mon.y + mon.h > height)
759 menu->y = mon.y + mon.h - height;
760 }
761}
762
763/* recursivelly setup menu configuration and its pixmap */
764static void
765setupmenu(struct Menu *menu, XClassHint *classh)
766{
767 char *title;
768 struct Item *item;
769 XWindowChanges changes;
770 XSizeHints sizeh;
771 XTextProperty wintitle;
772
773 /* setup size and position of menus */
774 setupitems(menu);
775 setupmenupos(menu);
776
777 /* update menu geometry */
778 changes.border_width = config.border_pixels;
779 changes.height = menu->h;
780 changes.width = menu->w;
781 changes.x = menu->x;
782 changes.y = menu->y;
783 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
784
785 /* set window title (used if wflag is on) */
786 if (menu->parent == NULL) {
787 title = classh->res_name;
788 } else {
789 title = menu->caller->output;
790 }
791 XStringListToTextProperty(&title, 1, &wintitle);
792
793 /* set window manager hints */
794 sizeh.flags = USPosition | PMaxSize | PMinSize;
795 sizeh.min_width = sizeh.max_width = menu->w;
796 sizeh.min_height = sizeh.max_height = menu->h;
797 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
798
799 /* set WM protocols and ewmh window properties */
800 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
801 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
802 PropModeReplace, (unsigned char *)title, strlen(title));
803 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
804 PropModeReplace,
805 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
806
807 /* calculate positions of submenus */
808 for (item = menu->list; item != NULL; item = item->next) {
809 if (item->submenu != NULL)
810 setupmenu(item->submenu, classh);
811 }
812}
813
814/* try to grab pointer, we may have to wait for another process to ungrab */
815static void
816grabpointer(void)
817{
818 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
819 int i;
820
821 for (i = 0; i < 1000; i++) {
822 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
823 GrabModeAsync, GrabModeAsync, None,
824 None, CurrentTime) == GrabSuccess)
825 return;
826 nanosleep(&ts, NULL);
827 }
828 errx(1, "cannot grab keyboard");
829}
830
831/* try to grab keyboard, we may have to wait for another process to ungrab */
832static void
833grabkeyboard(void)
834{
835 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
836 int i;
837
838 for (i = 0; i < 1000; i++) {
839 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
840 GrabModeAsync, CurrentTime) == GrabSuccess)
841 return;
842 nanosleep(&ts, NULL);
843 }
844 errx(1, "cannot grab keyboard");
845}
846
847/* load and scale icon */
848static Imlib_Image
849loadicon(const char *file)
850{
851 Imlib_Image icon;
852 int width;
853 int height;
854 int imgsize;
855
856 icon = imlib_load_image(file);
857 if (icon == NULL)
858 errx(1, "cannot load icon %s", file);
859
860 imlib_context_set_image(icon);
861
862 width = imlib_image_get_width();
863 height = imlib_image_get_height();
864 imgsize = MIN(width, height);
865
866 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
867 config.iconsize,
868 config.iconsize);
869
870 return icon;
871}
872
873/* draw pixmap for the selected and unselected version of each item on menu */
874static void
875drawitems(struct Menu *menu)
876{
877 struct Item *item;
878
879 for (item = menu->list; item != NULL; item = item->next) {
880 XftDraw *dsel, *dunsel;
881 int x, y;
882
883 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
884 DefaultDepth(dpy, screen));
885
886 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
887 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
888
889 if (item->label == NULL) { /* item is separator */
890 y = item->h/2;
891 XSetForeground(dpy, dc.gc, dc.separator.pixel);
892 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
893 menu->w - config.horzpadding, y);
894
895 item->sel = item->unsel;
896 } else {
897
898 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
899 DefaultDepth(dpy, screen));
900 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
901 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
902
903 /* draw text */
904 x = config.horzpadding;
905 x += (iflag) ? 0 : config.horzpadding + config.iconsize;
906 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
907 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
908 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
909 drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
910 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
911 drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
912 XftDrawDestroy(dsel);
913 XftDrawDestroy(dunsel);
914
915 /* draw triangle */
916 if (item->submenu != NULL) {
917 x = menu->w - config.triangle_width - config.horzpadding;
918 y = (item->h - config.triangle_height + 1) / 2;
919
920 XPoint triangle[] = {
921 {x, y},
922 {x + config.triangle_width, y + config.triangle_height/2},
923 {x, y + config.triangle_height},
924 {x, y}
925 };
926
927 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
928 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
929 Convex, CoordModeOrigin);
930 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
931 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
932 Convex, CoordModeOrigin);
933 }
934
935 /* draw icon */
936 if (item->file != NULL && !iflag) {
937 item->icon = loadicon(item->file);
938
939 imlib_context_set_image(item->icon);
940 imlib_context_set_drawable(item->sel);
941 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
942 imlib_context_set_drawable(item->unsel);
943 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
944 }
945 }
946 }
947}
948
949/* copy pixmaps of items of the current menu and of its ancestors into menu window */
950static void
951drawmenus(struct Menu *currmenu)
952{
953 struct Menu *menu;
954 struct Item *item;
955
956 for (menu = currmenu; menu != NULL; menu = menu->parent) {
957 if (!menu->drawn) {
958 drawitems(menu);
959 menu->drawn = 1;
960 }
961 for (item = menu->list; item != NULL; item = item->next) {
962 if (item == menu->selected)
963 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
964 menu->w, item->h, 0, item->y);
965 else
966 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
967 menu->w, item->h, 0, item->y);
968 }
969 }
970}
971
972/* umap previous menus and map current menu and its parents */
973static void
974mapmenu(struct Menu *currmenu)
975{
976 static struct Menu *prevmenu = NULL;
977 struct Menu *menu, *menu_;
978 struct Menu *lcamenu; /* lowest common ancestor menu */
979 unsigned minlevel; /* level of the closest to root menu */
980 unsigned maxlevel; /* level of the closest to root menu */
981
982 /* do not remap current menu if it wasn't updated*/
983 if (prevmenu == currmenu)
984 return;
985
986 /* if this is the first time mapping, skip calculations */
987 if (prevmenu == NULL) {
988 XMapWindow(dpy, currmenu->win);
989 prevmenu = currmenu;
990 return;
991 }
992
993 /* find lowest common ancestor menu */
994 minlevel = MIN(currmenu->level, prevmenu->level);
995 maxlevel = MAX(currmenu->level, prevmenu->level);
996 if (currmenu->level == maxlevel) {
997 menu = currmenu;
998 menu_ = prevmenu;
999 } else {
1000 menu = prevmenu;
1001 menu_ = currmenu;
1002 }
1003 while (menu->level > minlevel)
1004 menu = menu->parent;
1005 while (menu != menu_) {
1006 menu = menu->parent;
1007 menu_ = menu_->parent;
1008 }
1009 lcamenu = menu;
1010
1011 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
1012 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
1013 menu->selected = NULL;
1014 XUnmapWindow(dpy, menu->win);
1015 }
1016
1017 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
1018 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
1019
1020 if (wflag) {
1021 setupmenupos(menu);
1022 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1023 }
1024
1025 XMapWindow(dpy, menu->win);
1026 }
1027
1028 prevmenu = currmenu;
1029}
1030
1031/* get menu of given window */
1032static struct Menu *
1033getmenu(struct Menu *currmenu, Window win)
1034{
1035 struct Menu *menu;
1036
1037 for (menu = currmenu; menu != NULL; menu = menu->parent)
1038 if (menu->win == win)
1039 return menu;
1040
1041 return NULL;
1042}
1043
1044/* get item of given menu and position */
1045static struct Item *
1046getitem(struct Menu *menu, int y)
1047{
1048 struct Item *item;
1049
1050 if (menu == NULL)
1051 return NULL;
1052
1053 for (item = menu->list; item != NULL; item = item->next)
1054 if (y >= item->y && y <= item->y + item->h)
1055 return item;
1056
1057 return NULL;
1058}
1059
1060/* cycle through the items; non-zero direction is next, zero is prev */
1061static struct Item *
1062itemcycle(struct Menu *currmenu, int direction)
1063{
1064 struct Item *item;
1065 struct Item *lastitem;
1066
1067 item = NULL;
1068
1069 if (direction == ITEMNEXT) {
1070 if (currmenu->selected == NULL)
1071 item = currmenu->list;
1072 else if (currmenu->selected->next != NULL)
1073 item = currmenu->selected->next;
1074
1075 while (item != NULL && item->label == NULL)
1076 item = item->next;
1077
1078 if (item == NULL)
1079 item = currmenu->list;
1080 } else {
1081 for (lastitem = currmenu->list;
1082 lastitem != NULL && lastitem->next != NULL;
1083 lastitem = lastitem->next)
1084 ;
1085
1086 if (currmenu->selected == NULL)
1087 item = lastitem;
1088 else if (currmenu->selected->prev != NULL)
1089 item = currmenu->selected->prev;
1090
1091 while (item != NULL && item->label == NULL)
1092 item = item->prev;
1093
1094 if (item == NULL)
1095 item = lastitem;
1096 }
1097
1098 return item;
1099}
1100
1101/* run event loop */
1102static void
1103run(struct Menu *currmenu)
1104{
1105 struct Menu *menu;
1106 struct Item *item;
1107 struct Item *previtem = NULL;
1108 KeySym ksym;
1109 XEvent ev;
1110
1111 mapmenu(currmenu);
1112
1113 while (!XNextEvent(dpy, &ev)) {
1114 switch(ev.type) {
1115 case Expose:
1116 if (ev.xexpose.count == 0)
1117 drawmenus(currmenu);
1118 break;
1119 case MotionNotify:
1120 menu = getmenu(currmenu, ev.xbutton.window);
1121 item = getitem(menu, ev.xbutton.y);
1122 if (menu == NULL || item == NULL || previtem == item)
1123 break;
1124 previtem = item;
1125 menu->selected = item;
1126 if (item->submenu != NULL) {
1127 currmenu = item->submenu;
1128 currmenu->selected = NULL;
1129 } else {
1130 currmenu = menu;
1131 }
1132 mapmenu(currmenu);
1133 drawmenus(currmenu);
1134 break;
1135 case ButtonRelease:
1136 menu = getmenu(currmenu, ev.xbutton.window);
1137 item = getitem(menu, ev.xbutton.y);
1138 if (menu == NULL || item == NULL)
1139 break;
1140selectitem:
1141 if (item->label == NULL)
1142 break; /* ignore separators */
1143 if (item->submenu != NULL) {
1144 currmenu = item->submenu;
1145 } else {
1146 printf("%s\n", item->output);
1147 return;
1148 }
1149 mapmenu(currmenu);
1150 currmenu->selected = currmenu->list;
1151 drawmenus(currmenu);
1152 break;
1153 case ButtonPress:
1154 menu = getmenu(currmenu, ev.xbutton.window);
1155 if (menu == NULL)
1156 return;
1157 break;
1158 case KeyPress:
1159 ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
1160
1161 /* esc closes xmenu when current menu is the root menu */
1162 if (ksym == XK_Escape && currmenu->parent == NULL)
1163 return;
1164
1165 /* Shift-Tab = ISO_Left_Tab */
1166 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1167 ksym = XK_ISO_Left_Tab;
1168
1169 /* cycle through menu */
1170 item = NULL;
1171 if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
1172 item = itemcycle(currmenu, ITEMPREV);
1173 } else if (ksym == XK_Tab || ksym == XK_Down) {
1174 item = itemcycle(currmenu, ITEMNEXT);
1175 } else if ((ksym == XK_Return || ksym == XK_Right) &&
1176 currmenu->selected != NULL) {
1177 item = currmenu->selected;
1178 goto selectitem;
1179 } else if ((ksym == XK_Escape || ksym == XK_Left) &&
1180 currmenu->parent != NULL) {
1181 item = currmenu->parent->selected;
1182 currmenu = currmenu->parent;
1183 mapmenu(currmenu);
1184 } else
1185 break;
1186 currmenu->selected = item;
1187 drawmenus(currmenu);
1188 break;
1189 case LeaveNotify:
1190 previtem = NULL;
1191 currmenu->selected = NULL;
1192 drawmenus(currmenu);
1193 break;
1194 case ConfigureNotify:
1195 menu = getmenu(currmenu, ev.xconfigure.window);
1196 if (menu == NULL)
1197 break;
1198 menu->x = ev.xconfigure.x;
1199 menu->y = ev.xconfigure.y;
1200 break;
1201 case ClientMessage:
1202 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1203 break;
1204 /* user closed window */
1205 menu = getmenu(currmenu, ev.xclient.window);
1206 if (menu->parent == NULL)
1207 return; /* closing the root menu closes the program */
1208 currmenu = menu->parent;
1209 mapmenu(currmenu);
1210 break;
1211 }
1212 }
1213}
1214
1215/* recursivelly free pixmaps and destroy windows */
1216static void
1217cleanmenu(struct Menu *menu)
1218{
1219 struct Item *item;
1220 struct Item *tmp;
1221
1222 item = menu->list;
1223 while (item != NULL) {
1224 if (item->submenu != NULL)
1225 cleanmenu(item->submenu);
1226 tmp = item;
1227 if (menu->drawn) {
1228 XFreePixmap(dpy, item->unsel);
1229 if (tmp->label != NULL)
1230 XFreePixmap(dpy, item->sel);
1231 }
1232 if (tmp->label != tmp->output)
1233 free(tmp->label);
1234 free(tmp->output);
1235 if (tmp->file != NULL) {
1236 free(tmp->file);
1237 if (tmp->icon != NULL) {
1238 imlib_context_set_image(tmp->icon);
1239 imlib_free_image();
1240 }
1241 }
1242 item = item->next;
1243 free(tmp);
1244 }
1245
1246 XDestroyWindow(dpy, menu->win);
1247 free(menu);
1248}
1249
1250/* cleanup X and exit */
1251static void
1252cleanup(void)
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 XFreeGC(dpy, dc.gc);
1265 XCloseDisplay(dpy);
1266}
1267
1268/* show usage */
1269static void
1270usage(void)
1271{
1272 (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
1273 exit(1);
1274}