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