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