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