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