testing is different project, check ctrlmenu
[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>
f472bfac 8#include <locale.h>
8902c43b 9#include <time.h>
a7732690 10#include <unistd.h>
11#include <X11/Xlib.h>
8902c43b 12#include <X11/Xatom.h>
a7732690 13#include <X11/Xutil.h>
f644b8bc 14#include <X11/Xresource.h>
858338d9 15#include <X11/XKBlib.h>
dbeb9940 16#include <X11/Xft/Xft.h>
237da982 17#include <X11/extensions/Xinerama.h>
33376f54 18#include <Imlib2.h>
45b2e22f 19
20/* macros */
523b3d5e 21#define MAXPATHS 128 /* maximal number of paths to look for icons */
22#define ICONPATH "ICONPATH" /* environment variable name */
45b2e22f 23#define CLASS "XMenu"
24#define LEN(x) (sizeof (x) / sizeof (x[0]))
45b2e22f 25#define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
26#define GETNUM(n, s) { \
27 unsigned long __TMP__; \
28 if ((__TMP__ = strtoul((s), NULL, 10)) < INT_MAX) \
29 (n) = __TMP__; \
30 }
31
32/* Actions for the main loop */
33enum {
34 ACTION_NOP = 0,
35 ACTION_CLEAR = 1<<0, /* clear text */
36 ACTION_SELECT = 1<<1, /* select item */
37 ACTION_MAP = 1<<2, /* remap menu windows */
38 ACTION_DRAW = 1<<3, /* redraw menu windows */
39 ACTION_WARP = 1<<4, /* warp the pointer */
40};
41
42/* enum for keyboard menu navigation */
43enum { ITEMPREV, ITEMNEXT, ITEMFIRST, ITEMLAST };
44
45/* enum for text alignment */
46enum {LeftAlignment, CenterAlignment, RightAlignment};
47
48/* color enum */
49enum {ColorFG, ColorBG, ColorLast};
50
51/* EWMH atoms */
52enum {NetWMName, NetWMWindowType, NetWMWindowTypePopupMenu, NetLast};
53
54/* configuration structure */
55struct Config {
56 /* the values below are set by config.h */
57 const char *font;
58 const char *background_color;
59 const char *foreground_color;
60 const char *selbackground_color;
61 const char *selforeground_color;
62 const char *separator_color;
63 const char *border_color;
64 int width_pixels;
65 int height_pixels;
66 int border_pixels;
523b3d5e 67 int max_items;
45b2e22f 68 int separator_pixels;
69 int gap_pixels;
70 int triangle_width;
71 int triangle_height;
72 int iconpadding;
73 int horzpadding;
74 int alignment;
75
76 /* the values below are set by options */
77 int monitor;
78 int posx, posy; /* rootmenu position */
79
80 /* the value below is computed by xmenu */
81 int iconsize;
82};
83
84/* draw context structure */
85struct DC {
86 XftColor normal[ColorLast];
87 XftColor selected[ColorLast];
88 XftColor border;
89 XftColor separator;
90
91 GC gc;
92
93 FcPattern *pattern;
94 XftFont **fonts;
95 size_t nfonts;
96};
97
98/* menu item structure */
99struct Item {
100 char *label; /* string to be drawed on menu */
101 char *output; /* string to be outputed when item is clicked */
102 char *file; /* filename of the icon */
103 int y; /* item y position relative to menu */
104 int h; /* item height */
105 int textw; /* text width */
106 struct Item *prev; /* previous item */
107 struct Item *next; /* next item */
108 struct Menu *submenu; /* submenu spawned by clicking on item */
109 Drawable sel, unsel; /* pixmap for selected and unselected item */
110 Imlib_Image icon;
111};
112
113/* monitor geometry structure */
114struct Monitor {
115 int x, y, w, h; /* monitor geometry */
116};
117
118/* menu structure */
119struct Menu {
120 struct Menu *parent; /* parent menu */
121 struct Item *caller; /* item that spawned the menu */
122 struct Item *list; /* list of items contained by the menu */
523b3d5e 123 struct Item *first; /* first item displayed on the menu */
45b2e22f 124 struct Item *selected; /* item currently selected in the menu */
125 int x, y, w, h; /* menu geometry */
126 int hasicon; /* whether the menu has item with icons */
127 int drawn; /* whether the menu was already drawn */
128 int maxtextw; /* maximum text width */
523b3d5e 129 int level; /* menu level relative to root */
130 int overflow; /* whether the menu is higher than the monitor */
45b2e22f 131 Window win; /* menu window to map on the screen */
132 XIC xic; /* input context */
133};
858338d9 134
738ed9d5 135/* X stuff */
a7732690 136static Display *dpy;
dbeb9940 137static Visual *visual;
a7732690 138static Window rootwin;
c6d9174e 139static Colormap colormap;
6abae763 140static XrmDatabase xdb;
45b2e22f 141static XClassHint classh;
6abae763 142static char *xrm;
a7732690 143static struct DC dc;
8902c43b 144static Atom utf8string;
3bec05ea 145static Atom wmdelete;
8902c43b 146static Atom netatom[NetLast];
523b3d5e 147static int screen;
148static int depth;
f472bfac 149static XIM xim;
3bec05ea 150
151/* flags */
45b2e22f 152static int iflag = 0; /* whether to disable icons */
153static int rflag = 0; /* whether to disable right-click */
154static int mflag = 0; /* whether the user specified a monitor with -p */
155static int pflag = 0; /* whether the user specified a position with -p */
156static int wflag = 0; /* whether to let the window manager control XMenu */
157static int rootmodeflag = 0; /* wheter to run in root mode */
158static int passclickflag = 0; /* whether to pass click to root window */
159static int firsttime = 1; /* set to 0 after first run */
160
161/* arguments */
162static unsigned int button = 0; /* button to trigger pmenu in root mode */
163static unsigned int modifier = 0; /* modifier to trigger pmenu */
a7732690 164
523b3d5e 165/* icons paths */
166static char *iconstring = NULL; /* string read from getenv */
167static char *iconpaths[MAXPATHS]; /* paths to icon directories */
168static int niconpaths = 0; /* number of paths to icon directories */
169
8902c43b 170/* include config variable */
a7732690 171#include "config.h"
172
73a2a23d 173/* show usage */
174static void
175usage(void)
a7732690 176{
1146fd81 177 (void)fprintf(stderr, "usage: xmenu [-irw] [-p position] [title]\n");
73a2a23d 178 exit(1);
21a9aaec 179}
180
523b3d5e 181/* maximum int */
182static int
183max(int x, int y)
184{
185 return x > y ? x : y;
186}
187
188/* minimum int */
189static int
190min(int x, int y)
191{
192 return x < y ? x : y;
193}
194
195/* call malloc checking for error */
196static void *
197emalloc(size_t size)
198{
199 void *p;
200
201 if ((p = malloc(size)) == NULL)
202 err(1, "malloc");
203 return p;
204}
205
206/* call strdup checking for error */
207static char *
208estrdup(const char *s)
209{
210 char *t;
211
212 if ((t = strdup(s)) == NULL)
213 err(1, "strdup");
214 return t;
215}
216
217/* parse position string from -p, put results on config.posx, config.posy, and config.monitor */
05cfe1a0 218static void
237da982 219parseposition(char *optarg)
05cfe1a0 220{
221 long n;
237da982 222 char *s = optarg;
05cfe1a0 223 char *endp;
224
225 n = strtol(s, &endp, 10);
226 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
227 goto error;
228 config.posx = n;
229 s = endp+1;
230 n = strtol(s, &endp, 10);
237da982 231 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s)
05cfe1a0 232 goto error;
233 config.posy = n;
237da982 234 if (*endp == ':') {
235 s = endp+1;
236 mflag = 1;
237 if (strncasecmp(s, "CUR", 3) == 0) {
238 config.monitor = -1;
239 endp = s+3;
240 } else {
241 n = strtol(s, &endp, 10);
242 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
243 goto error;
244 config.monitor = n;
245 }
246 } else if (*endp != '\0') {
247 goto error;
248 }
05cfe1a0 249
250 return;
251
252error:
253 errx(1, "improper position: %s", optarg);
254}
255
6abae763 256/* get configuration from X resources */
257static void
258getresources(void)
259{
260 char *type;
261 XrmValue xval;
262
263 if (xrm == NULL || xdb == NULL)
264 return;
265
266 if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
267 GETNUM(config.border_pixels, xval.addr)
268 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
269 GETNUM(config.separator_pixels, xval.addr)
270 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
271 GETNUM(config.height_pixels, xval.addr)
272 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
273 GETNUM(config.width_pixels, xval.addr)
274 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
275 GETNUM(config.gap_pixels, xval.addr)
523b3d5e 276 if (XrmGetResource(xdb, "xmenu.maxItems", "*", &type, &xval) == True)
277 GETNUM(config.max_items, xval.addr)
6abae763 278 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
279 config.background_color = xval.addr;
280 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
281 config.foreground_color = xval.addr;
282 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
283 config.selbackground_color = xval.addr;
284 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
285 config.selforeground_color = xval.addr;
286 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
287 config.separator_color = xval.addr;
288 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
289 config.border_color = xval.addr;
290 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
291 config.font = xval.addr;
292 if (XrmGetResource(xdb, "xmenu.alignment", "*", &type, &xval) == True) {
293 if (strcasecmp(xval.addr, "center") == 0)
294 config.alignment = CenterAlignment;
295 else if (strcasecmp(xval.addr, "left") == 0)
296 config.alignment = LeftAlignment;
297 else if (strcasecmp(xval.addr, "right") == 0)
298 config.alignment = RightAlignment;
299 }
300}
301
45b2e22f 302/* set button global variable */
303static void
304setbutton(char *s)
305{
306 size_t len;
307
308 if ((len = strlen(s)) < 1)
309 return;
310 switch (s[len-1]) {
311 case '1': button = Button1; break;
312 case '2': button = Button2; break;
313 case '3': button = Button3; break;
314 default: button = atoi(&s[len-1]); break;
315 }
316}
317
318/* set modifier global variable */
319static void
320setmodifier(char *s)
321{
322 size_t len;
323
324 if ((len = strlen(s)) < 1)
325 return;
326 switch (s[len-1]) {
327 case '1': modifier = Mod1Mask; break;
328 case '2': modifier = Mod2Mask; break;
329 case '3': modifier = Mod3Mask; break;
330 case '4': modifier = Mod4Mask; break;
331 case '5': modifier = Mod5Mask; break;
332 default:
333 if (strcasecmp(s, "Alt") == 0) {
334 modifier = Mod1Mask;
335 } else if (strcasecmp(s, "Super") == 0) {
336 modifier = Mod4Mask;
337 }
338 break;
339 }
340}
341
523b3d5e 342/* parse icon path string */
343static void
344parseiconpaths(char *s)
345{
346 if (s == NULL)
347 return;
348 free(iconstring);
349 iconstring = estrdup(s);
350 niconpaths = 0;
351 for (s = strtok(iconstring, ":"); s != NULL; s = strtok(NULL, ":")) {
352 if (niconpaths < MAXPATHS) {
353 iconpaths[niconpaths++] = s;
354 }
355 }
356}
357
6abae763 358/* get configuration from command-line options */
45b2e22f 359static void
6abae763 360getoptions(int argc, char *argv[])
361{
362 int ch;
45b2e22f 363 char *s, *t;
6abae763 364
45b2e22f 365 classh.res_class = CLASS;
366 classh.res_name = argv[0];
367 if ((s = strrchr(argv[0], '/')) != NULL)
368 classh.res_name = s + 1;
523b3d5e 369 parseiconpaths(getenv(ICONPATH));
45b2e22f 370 while ((ch = getopt(argc, argv, "ip:rwx:X:")) != -1) {
6abae763 371 switch (ch) {
372 case 'i':
373 iflag = 1;
374 break;
375 case 'p':
376 pflag = 1;
377 parseposition(optarg);
378 break;
379 case 'r':
380 rflag = 1;
381 break;
382 case 'w':
383 wflag = 1;
384 break;
45b2e22f 385 case 'X':
386 passclickflag = 1;
387 /* PASSTHROUGH */
388 case 'x':
389 rootmodeflag = 1;
390 s = optarg;
391 setbutton(s);
392 if ((t = strchr(s, '-')) == NULL)
393 return;
394 *t = '\0';
395 setmodifier(s);
396 break;
6abae763 397 default:
398 usage();
399 break;
400 }
401 }
523b3d5e 402 if (rootmodeflag)
403 wflag = 0;
6abae763 404 argc -= optind;
405 argv += optind;
45b2e22f 406 if (argc != 0)
6abae763 407 usage();
45b2e22f 408 return;
6abae763 409}
410
112e23c3 411/* parse font string */
cdeaefaa 412static void
413parsefonts(const char *s)
414{
415 const char *p;
416 char buf[1024];
417 size_t nfont = 0;
418
419 dc.nfonts = 1;
420 for (p = s; *p; p++)
421 if (*p == ',')
422 dc.nfonts++;
423
424 if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
425 err(1, "calloc");
426
427 p = s;
428 while (*p != '\0') {
429 size_t i;
430
431 i = 0;
432 while (isspace(*p))
433 p++;
70063f16 434 while (i < sizeof buf && *p != '\0' && *p != ',')
cdeaefaa 435 buf[i++] = *p++;
6d56f279 436 if (i >= sizeof buf)
437 errx(1, "font name too long");
cdeaefaa 438 if (*p == ',')
439 p++;
440 buf[i] = '\0';
6d56f279 441 if (nfont == 0)
442 if ((dc.pattern = FcNameParse((FcChar8 *)buf)) == NULL)
443 errx(1, "the first font in the cache must be loaded from a font string");
cdeaefaa 444 if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
8a7bfdf8 445 errx(1, "could not load font");
cdeaefaa 446 }
447}
448
8902c43b 449/* get color from color string */
450static void
451ealloccolor(const char *s, XftColor *color)
452{
453 if(!XftColorAllocName(dpy, visual, colormap, s, color))
8a7bfdf8 454 errx(1, "could not allocate color: %s", s);
8902c43b 455}
456
237da982 457/* query monitor information and cursor position */
458static void
45b2e22f 459getmonitor(struct Monitor *mon)
237da982 460{
461 XineramaScreenInfo *info = NULL;
462 Window dw; /* dummy variable */
463 int di; /* dummy variable */
464 unsigned du; /* dummy variable */
465 int cursx, cursy; /* cursor position */
466 int nmons;
467 int i;
468
469 XQueryPointer(dpy, rootwin, &dw, &dw, &cursx, &cursy, &di, &di, &du);
470
45b2e22f 471 mon->x = mon->y = 0;
472 mon->w = DisplayWidth(dpy, screen);
473 mon->h = DisplayHeight(dpy, screen);
237da982 474
475 if ((info = XineramaQueryScreens(dpy, &nmons)) != NULL) {
476 int selmon = 0;
477
70063f16 478 if (!mflag || config.monitor < 0 || config.monitor >= nmons) {
237da982 479 for (i = 0; i < nmons; i++) {
d2304ecf 480 if (BETWEEN(cursx, info[i].x_org, info[i].x_org + info[i].width) &&
481 BETWEEN(cursy, info[i].y_org, info[i].y_org + info[i].height)) {
237da982 482 selmon = i;
483 break;
484 }
485 }
486 } else {
487 selmon = config.monitor;
488 }
489
45b2e22f 490 mon->x = info[selmon].x_org;
491 mon->y = info[selmon].y_org;
492 mon->w = info[selmon].width;
493 mon->h = info[selmon].height;
883ec17f 494
495 XFree(info);
237da982 496 }
497
498 if (!pflag) {
499 config.posx = cursx;
500 config.posy = cursy;
501 } else if (mflag) {
45b2e22f 502 config.posx += mon->x;
503 config.posy += mon->y;
237da982 504 }
505}
506
a7732690 507/* init draw context */
508static void
8902c43b 509initdc(void)
a7732690 510{
511 /* get color pixels */
8902c43b 512 ealloccolor(config.background_color, &dc.normal[ColorBG]);
513 ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
514 ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
515 ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
516 ealloccolor(config.separator_color, &dc.separator);
517 ealloccolor(config.border_color, &dc.border);
a7732690 518
cdeaefaa 519 /* parse fonts */
520 parsefonts(config.font);
a7732690 521
fd530f3f 522 /* create common GC */
a7732690 523 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
a7732690 524}
525
b6cf4847 526/* calculate icon size */
a7732690 527static void
b6cf4847 528initiconsize(void)
a7732690 529{
71b4db92 530 config.iconsize = config.height_pixels - config.iconpadding * 2;
8902c43b 531}
532
533/* intern atoms */
534static void
535initatoms(void)
536{
537 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
538 wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
539 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
540 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
541 netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
a7732690 542}
543
a7732690 544/* allocate an item */
545static struct Item *
33376f54 546allocitem(const char *label, const char *output, char *file)
a7732690 547{
548 struct Item *item;
549
523b3d5e 550 item = emalloc(sizeof *item);
a5ddd2cd 551 if (label == NULL) {
7fbd1c5e 552 item->label = NULL;
553 item->output = NULL;
554 } else {
523b3d5e 555 item->label = estrdup(label);
15dfafdf 556 if (label == output) {
557 item->output = item->label;
558 } else {
523b3d5e 559 item->output = estrdup(output);
15dfafdf 560 }
7fbd1c5e 561 }
33376f54 562 if (file == NULL) {
563 item->file = NULL;
564 } else {
523b3d5e 565 item->file = estrdup(file);
33376f54 566 }
a80fee22 567 item->y = 0;
beae67a6 568 item->h = 0;
a7732690 569 item->next = NULL;
570 item->submenu = NULL;
3bec05ea 571 item->icon = NULL;
a7732690 572
573 return item;
574}
575
a3a73837 576/* allocate a menu and create its window */
a7732690 577static struct Menu *
523b3d5e 578allocmenu(struct Menu *parent, struct Item *list, int level)
a7732690 579{
580 XSetWindowAttributes swa;
581 struct Menu *menu;
582
523b3d5e 583 menu = emalloc(sizeof *menu);
584 *menu = (struct Menu){
585 .parent = parent,
586 .list = list,
587 .level = level,
588 .first = NULL,
589 };
a7732690 590
3bec05ea 591 swa.override_redirect = (wflag) ? False : True;
fd530f3f 592 swa.background_pixel = dc.normal[ColorBG].pixel;
593 swa.border_pixel = dc.border.pixel;
594 swa.save_under = True; /* pop-up windows should save_under*/
a7732690 595 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
f15fc339 596 | PointerMotionMask | LeaveWindowMask;
3bec05ea 597 if (wflag)
598 swa.event_mask |= StructureNotifyMask;
45b2e22f 599 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, config.border_pixels,
a7732690 600 CopyFromParent, CopyFromParent, CopyFromParent,
fd530f3f 601 CWOverrideRedirect | CWBackPixel |
602 CWBorderPixel | CWEventMask | CWSaveUnder,
a7732690 603 &swa);
604
f472bfac 605 menu->xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
606 XNClientWindow, menu->win, XNFocusWindow, menu->win, NULL);
607 if (menu->xic == NULL)
608 errx(1, "XCreateIC: could not obtain input method");
609
a7732690 610 return menu;
611}
612
a5ddd2cd 613/* build the menu tree */
614static struct Menu *
523b3d5e 615buildmenutree(int level, const char *label, const char *output, char *file)
a5ddd2cd 616{
617 static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
618 static struct Menu *rootmenu = NULL; /* menu to be returned */
619 struct Item *curritem = NULL; /* item currently being read */
620 struct Item *item; /* dummy item for loops */
621 struct Menu *menu; /* dummy menu for loops */
523b3d5e 622 int i;
a5ddd2cd 623
624 /* create the item */
33376f54 625 curritem = allocitem(label, output, file);
a5ddd2cd 626
627 /* put the item in the menu tree */
628 if (prevmenu == NULL) { /* there is no menu yet */
685ca30d 629 menu = allocmenu(NULL, curritem, level);
630 rootmenu = menu;
631 prevmenu = menu;
632 curritem->prev = NULL;
a5ddd2cd 633 } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
634 /* go up the menu tree until find the menu this item continues */
635 for (menu = prevmenu, i = level;
636 menu != NULL && i != prevmenu->level;
637 menu = menu->parent, i++)
638 ;
639 if (menu == NULL)
70f5db0f 640 errx(1, "improper indentation detected");
a5ddd2cd 641
642 /* find last item in the new menu */
643 for (item = menu->list; item->next != NULL; item = item->next)
644 ;
645
646 prevmenu = menu;
647 item->next = curritem;
648 curritem->prev = item;
649 } else if (level == prevmenu->level) { /* item is a continuation of current menu */
650 /* find last item in the previous menu */
651 for (item = prevmenu->list; item->next != NULL; item = item->next)
652 ;
653
654 item->next = curritem;
655 curritem->prev = item;
656 } else if (level > prevmenu->level) { /* item begins a new menu */
657 menu = allocmenu(prevmenu, curritem, level);
658
659 /* find last item in the previous menu */
660 for (item = prevmenu->list; item->next != NULL; item = item->next)
661 ;
662
78cdb02b
TH
663 /* a separator is no valid root for a submenu */
664 if (!item->label)
665 errx(1, "a separator is no valid root for a submenu");
666
a5ddd2cd 667 prevmenu = menu;
668 menu->caller = item;
669 item->submenu = menu;
670 curritem->prev = NULL;
671 }
672
a2ff706d 673 if (curritem->file)
674 prevmenu->hasicon = 1;
675
a5ddd2cd 676 return rootmenu;
677}
678
a7732690 679/* create menus and items from the stdin */
257e42cc 680static struct Menu *
a7732690 681parsestdin(void)
682{
a5ddd2cd 683 struct Menu *rootmenu;
a7732690 684 char *s, buf[BUFSIZ];
33376f54 685 char *file, *label, *output;
523b3d5e 686 int level = 0;
257e42cc 687
ddb15acf 688 rootmenu = NULL;
689
a7732690 690 while (fgets(buf, BUFSIZ, stdin) != NULL) {
a5ddd2cd 691 /* get the indentation level */
692 level = strspn(buf, "\t");
a7732690 693
a5ddd2cd 694 /* get the label */
695 s = level + buf;
696 label = strtok(s, "\t\n");
a7732690 697
33376f54 698 /* get the filename */
699 file = NULL;
700 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
701 file = label + 4;
702 label = strtok(NULL, "\t\n");
703 }
704
a5ddd2cd 705 /* get the output */
706 output = strtok(NULL, "\n");
707 if (output == NULL) {
708 output = label;
709 } else {
710 while (*output == '\t')
711 output++;
a7732690 712 }
a5ddd2cd 713
33376f54 714 rootmenu = buildmenutree(level, label, output, file);
a7732690 715 }
a7732690 716
257e42cc 717 return rootmenu;
a7732690 718}
719
3d853664 720/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
cdeaefaa 721static FcChar32
722getnextutf8char(const char *s, const char **next_ret)
723{
cdeaefaa 724 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
cdeaefaa 725 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
cdeaefaa 726 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
727 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
3d853664 728 /* 0xFFFD is the replacement character, used to represent unknown characters */
cdeaefaa 729 static const FcChar32 unknown = 0xFFFD;
730 FcChar32 ucode; /* FcChar32 type holds 32 bits */
731 size_t usize = 0; /* n' of bytes of the utf8 character */
732 size_t i;
733
734 *next_ret = s+1;
735
736 /* get code of first byte of utf8 character */
737 for (i = 0; i < sizeof utfmask; i++) {
738 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
739 usize = i;
740 ucode = (unsigned char)*s & ~utfmask[i];
741 break;
742 }
743 }
744
745 /* if first byte is a continuation byte or is not allowed, return unknown */
746 if (i == sizeof utfmask || usize == 0)
747 return unknown;
748
749 /* check the other usize-1 bytes */
750 s++;
751 for (i = 1; i < usize; i++) {
752 *next_ret = s+1;
237da982 753 /* if byte is nul or is not a continuation byte, return unknown */
cdeaefaa 754 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
755 return unknown;
756 /* 6 is the number of relevant bits in the continuation byte */
757 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
758 s++;
759 }
760
761 /* check if ucode is invalid or in utf-16 surrogate halves */
762 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
763 || BETWEEN (ucode, 0xD800, 0xDFFF))
764 return unknown;
765
766 return ucode;
767}
768
f8d55995 769/* get which font contains a given code point */
770static XftFont *
771getfontucode(FcChar32 ucode)
772{
a48473fd 773 FcCharSet *fccharset = NULL;
774 FcPattern *fcpattern = NULL;
775 FcPattern *match = NULL;
776 XftFont *retfont = NULL;
6d56f279 777 XftResult result;
f8d55995 778 size_t i;
779
780 for (i = 0; i < dc.nfonts; i++)
781 if (XftCharExists(dpy, dc.fonts[i], ucode) == FcTrue)
782 return dc.fonts[i];
6d56f279 783
784 /* create a charset containing our code point */
785 fccharset = FcCharSetCreate();
786 FcCharSetAddChar(fccharset, ucode);
787
a48473fd 788 /* create a pattern akin to the dc.pattern but containing our charset */
789 if (fccharset) {
790 fcpattern = FcPatternDuplicate(dc.pattern);
791 FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
792 }
6d56f279 793
794 /* find pattern matching fcpattern */
a48473fd 795 if (fcpattern) {
796 FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
797 FcDefaultSubstitute(fcpattern);
798 match = XftFontMatch(dpy, screen, fcpattern, &result);
799 }
6d56f279 800
801 /* if found a pattern, open its font */
802 if (match) {
803 retfont = XftFontOpenPattern(dpy, match);
804 if (retfont && XftCharExists(dpy, retfont, ucode) == FcTrue) {
805 if ((dc.fonts = realloc(dc.fonts, dc.nfonts+1)) == NULL)
806 err(1, "realloc");
a48473fd 807 dc.fonts[dc.nfonts] = retfont;
808 return dc.fonts[dc.nfonts++];
6d56f279 809 } else {
810 XftFontClose(dpy, retfont);
811 }
812 }
813
814 /* in case no fount was found, return the first one */
815 return dc.fonts[0];
f8d55995 816}
817
818/* draw text into XftDraw, return width of text glyphs */
cdeaefaa 819static int
820drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
821{
f8d55995 822 int textwidth = 0;
cdeaefaa 823
f8d55995 824 while (*text) {
825 XftFont *currfont;
cdeaefaa 826 XGlyphInfo ext;
f8d55995 827 FcChar32 ucode;
828 const char *next;
cdeaefaa 829 size_t len;
cdeaefaa 830
f8d55995 831 ucode = getnextutf8char(text, &next);
6d56f279 832 currfont = getfontucode(ucode);
cdeaefaa 833
f8d55995 834 len = next - text;
f8d55995 835 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)text, len, &ext);
836 textwidth += ext.xOff;
cdeaefaa 837
838 if (draw) {
a48473fd 839 int texty;
840
841 texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
f8d55995 842 XftDrawStringUtf8(draw, color, currfont, x, texty, (XftChar8 *)text, len);
cdeaefaa 843 x += ext.xOff;
844 }
845
f8d55995 846 text = next;
cdeaefaa 847 }
848
f8d55995 849 return textwidth;
cdeaefaa 850}
851
71b4db92 852/* setup the height, width and icon of the items of a menu */
a7732690 853static void
523b3d5e 854setupitems(struct Menu *menu, struct Monitor *mon)
a7732690 855{
523b3d5e 856 Pixmap pix;
a80fee22 857 struct Item *item;
27c03246 858 int itemwidth;
523b3d5e 859 int menuh;
860 int maxh;
a7732690 861
523b3d5e 862 menu->first = menu->list;
8902c43b 863 menu->w = config.width_pixels;
27c03246 864 menu->maxtextw = 0;
523b3d5e 865 menuh = 0;
866 maxh = config.max_items > 3 ? (2 + config.max_items) * config.height_pixels : mon->h;
a80fee22 867 for (item = menu->list; item != NULL; item = item->next) {
523b3d5e 868 item->y = menuh;
7fbd1c5e 869 if (item->label == NULL) /* height for separator item */
8902c43b 870 item->h = config.separator_pixels;
a80fee22 871 else
8902c43b 872 item->h = config.height_pixels;
523b3d5e 873 menuh += item->h;
874 if (!menu->overflow) {
875 if (menu->h + config.height_pixels * 2 < maxh - config.border_pixels * 2) {
876 menu->h = menuh;
877 } else {
878 menu->overflow = 1;
879 menu->h += config.height_pixels * 2;
880 }
881 }
15362de4 882 if (item->label)
27c03246 883 item->textw = drawtext(NULL, NULL, 0, 0, 0, item->label);
15362de4 884 else
27c03246 885 item->textw = 0;
685ca30d 886
71b4db92 887 /*
888 * set menu width
889 *
27c03246 890 * the item width depends on the size of its label (item->textw),
71b4db92 891 * and it is only used to calculate the width of the menu (which
892 * is equal to the width of the largest item).
893 *
894 * the horizontal padding appears 4 times through the width of a
15362de4 895 * item: before and after its icon, and before and after its triangle.
71b4db92 896 * if the iflag is set (icons are disabled) then the horizontal
15362de4 897 * padding appears 3 times: before the label and around the triangle.
71b4db92 898 */
27c03246 899 itemwidth = item->textw + config.triangle_width + config.horzpadding * 3;
a2ff706d 900 itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
523b3d5e 901 menu->w = max(menu->w, itemwidth);
902 menu->maxtextw = max(menu->maxtextw, item->textw);
903 }
904 if (!menu->overflow) {
905 XSetWindowBackground(dpy, menu->win, dc.normal[ColorBG].pixel);
906 } else {
907 pix = XCreatePixmap(dpy, menu->win, menu->w, menu->h, depth);
908 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
909 XFillRectangle(dpy, pix, dc.gc, 0, 0, menu->w, menu->h);
910 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
911 XFillPolygon(
912 dpy, pix, dc.gc,
913 (XPoint []){
914 {menu->w / 2 - 3, config.height_pixels / 2 + 2},
915 {3, -4},
916 {3, 4},
917 {-6, 0},
918 },
919 4, Convex, CoordModePrevious
920 );
921 XFillPolygon(
922 dpy, pix, dc.gc,
923 (XPoint []){
924 {menu->w / 2 - 3, menu->h - config.height_pixels / 2 - 2},
925 {3, 4},
926 {3, -4},
927 {-6, 0},
928 },
929 4, Convex, CoordModePrevious
930 );
931 XSetWindowBackgroundPixmap(dpy, menu->win, pix);
932 XFreePixmap(dpy, pix);
a80fee22 933 }
f8ffe0b2 934}
935
936/* setup the position of a menu */
937static void
45b2e22f 938setupmenupos(struct Menu *menu, struct Monitor *mon)
f8ffe0b2 939{
940 int width, height;
a7732690 941
8902c43b 942 width = menu->w + config.border_pixels * 2;
943 height = menu->h + config.border_pixels * 2;
a7732690 944 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
45b2e22f 945 if (pflag || (config.posx >= mon->x && mon->x + mon->w - config.posx >= width))
05cfe1a0 946 menu->x = config.posx;
947 else if (config.posx > width)
948 menu->x = config.posx - width;
8902c43b 949
45b2e22f 950 if (pflag || (config.posy >= mon->y && mon->y + mon->h - config.posy >= height))
05cfe1a0 951 menu->y = config.posy;
45b2e22f 952 else if (mon->y + mon->h > height)
953 menu->y = mon->y + mon->h - height;
a7732690 954 } else { /* else, calculate in respect to parent menu */
237da982 955 int parentwidth;
956
957 parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
958
45b2e22f 959 if (mon->x + mon->w - parentwidth >= width)
237da982 960 menu->x = parentwidth;
8902c43b 961 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
962 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
a7732690 963
45b2e22f 964 if (mon->y + mon->h - (menu->caller->y + menu->parent->y) >= height)
8455c369 965 menu->y = menu->caller->y + menu->parent->y;
45b2e22f 966 else if (mon->y + mon->h > height)
967 menu->y = mon->y + mon->h - height;
a7732690 968 }
f8ffe0b2 969}
970
971/* recursivelly setup menu configuration and its pixmap */
972static void
45b2e22f 973setupmenu(struct Menu *menu, struct Monitor *mon)
f8ffe0b2 974{
8902c43b 975 char *title;
f8ffe0b2 976 struct Item *item;
f8ffe0b2 977 XWindowChanges changes;
978 XSizeHints sizeh;
3bec05ea 979 XTextProperty wintitle;
f8ffe0b2 980
981 /* setup size and position of menus */
523b3d5e 982 setupitems(menu, mon);
45b2e22f 983 setupmenupos(menu, mon);
a7732690 984
985 /* update menu geometry */
986 changes.height = menu->h;
f1583285 987 changes.width = menu->w;
a7732690 988 changes.x = menu->x;
989 changes.y = menu->y;
45b2e22f 990 XConfigureWindow(dpy, menu->win, CWWidth | CWHeight | CWX | CWY, &changes);
991
992 if (firsttime) {
993 /* set window title (used if wflag is on) */
994 if (menu->parent == NULL) {
995 title = classh.res_name;
996 } else if (menu->caller->output) {
997 title = menu->caller->output;
998 } else {
999 title = "\0";
1000 }
1001 XStringListToTextProperty(&title, 1, &wintitle);
1002
1003 /* set window manager hints */
1004 sizeh.flags = USPosition | PMaxSize | PMinSize;
1005 sizeh.min_width = sizeh.max_width = menu->w;
1006 sizeh.min_height = sizeh.max_height = menu->h;
1007 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, &classh);
1008
1009 /* set WM protocols and ewmh window properties */
1010 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
1011 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
1012 PropModeReplace, (unsigned char *)title, strlen(title));
1013 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
1014 PropModeReplace,
1015 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
3bec05ea 1016 }
8902c43b 1017
a80fee22 1018 /* calculate positions of submenus */
a7732690 1019 for (item = menu->list; item != NULL; item = item->next) {
1020 if (item->submenu != NULL)
45b2e22f 1021 setupmenu(item->submenu, mon);
a7732690 1022 }
1023}
1024
85003546 1025/* try to grab pointer, we may have to wait for another process to ungrab */
1026static void
1027grabpointer(void)
1028{
1029 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
1030 int i;
1031
1032 for (i = 0; i < 1000; i++) {
1033 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
1034 GrabModeAsync, GrabModeAsync, None,
1035 None, CurrentTime) == GrabSuccess)
1036 return;
1037 nanosleep(&ts, NULL);
1038 }
70f5db0f 1039 errx(1, "could not grab pointer");
85003546 1040}
1041
1042/* try to grab keyboard, we may have to wait for another process to ungrab */
1043static void
1044grabkeyboard(void)
1045{
1046 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
1047 int i;
1048
1049 for (i = 0; i < 1000; i++) {
1050 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
1051 GrabModeAsync, CurrentTime) == GrabSuccess)
1052 return;
1053 nanosleep(&ts, NULL);
1054 }
8a7bfdf8 1055 errx(1, "could not grab keyboard");
85003546 1056}
1057
f472bfac 1058/* try to grab focus, we may have to wait for another process to ungrab */
1059static void
1060grabfocus(Window win)
1061{
1062 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
1063 Window focuswin;
1064 int i, revertwin;
1065
1066 for (i = 0; i < 100; ++i) {
1067 XGetInputFocus(dpy, &focuswin, &revertwin);
1068 if (focuswin == win)
1069 return;
1070 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
1071 nanosleep(&ts, NULL);
1072 }
1073 errx(1, "cannot grab focus");
1074}
1075
6abae763 1076/* ungrab pointer and keyboard */
1077static void
1078ungrab(void)
1079{
1080 XUngrabPointer(dpy, CurrentTime);
1081 XUngrabKeyboard(dpy, CurrentTime);
1082}
1083
523b3d5e 1084/* check if path is absolute or relative to current directory */
1085static int
1086isabsolute(const char *s)
1087{
1088 return s[0] == '/' || (s[0] == '.' && (s[1] == '/' || (s[1] == '.' && s[2] == '/')));
1089}
1090
3d853664 1091/* load and scale icon */
1092static Imlib_Image
1093loadicon(const char *file)
1094{
1095 Imlib_Image icon;
ed1650a7 1096 Imlib_Load_Error errcode;
523b3d5e 1097 char path[PATH_MAX];
ed1650a7 1098 const char *errstr;
3d853664 1099 int width;
1100 int height;
1101 int imgsize;
523b3d5e 1102 int i;
3d853664 1103
f66f4c18 1104 if (*file == '\0') {
1105 warnx("could not load icon (file name is blank)");
1106 return NULL;
523b3d5e 1107 }
1108 if (isabsolute(file))
1109 icon = imlib_load_image_with_error_return(file, &errcode);
1110 else {
1111 for (i = 0; i < niconpaths; i++) {
1112 snprintf(path, sizeof(path), "%s/%s", iconpaths[i], file);
1113 icon = imlib_load_image_with_error_return(path, &errcode);
1114 if (icon != NULL || errcode != IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST) {
1115 break;
1116 }
1117 }
1118 }
1119 if (icon == NULL) {
ed1650a7 1120 switch (errcode) {
1121 case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
1122 errstr = "file does not exist";
1123 break;
1124 case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
1125 errstr = "file is directory";
1126 break;
1127 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
1128 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
1129 errstr = "permission denied";
1130 break;
1131 case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
1132 errstr = "unknown file format";
1133 break;
1134 case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
1135 errstr = "path too long";
1136 break;
1137 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
1138 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
1139 case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
1140 errstr = "improper path";
1141 break;
1142 case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
1143 errstr = "too many symbolic links";
1144 break;
1145 case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
1146 errstr = "out of memory";
1147 break;
1148 case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
1149 errstr = "out of file descriptors";
1150 break;
1151 default:
1152 errstr = "unknown error";
1153 break;
1154 }
f66f4c18 1155 warnx("could not load icon (%s): %s", errstr, file);
1156 return NULL;
ed1650a7 1157 }
3d853664 1158
1159 imlib_context_set_image(icon);
1160
1161 width = imlib_image_get_width();
1162 height = imlib_image_get_height();
523b3d5e 1163 imgsize = min(width, height);
3d853664 1164
1165 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
1166 config.iconsize,
1167 config.iconsize);
1168
1169 return icon;
1170}
1171
1172/* draw pixmap for the selected and unselected version of each item on menu */
1173static void
1174drawitems(struct Menu *menu)
1175{
27c03246 1176 XftDraw *dsel, *dunsel;
3d853664 1177 struct Item *item;
27c03246 1178 int textx;
1179 int x, y;
3d853664 1180
1181 for (item = menu->list; item != NULL; item = item->next) {
523b3d5e 1182 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h, depth);
3d853664 1183
1184 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
1185 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
1186
1187 if (item->label == NULL) { /* item is separator */
523b3d5e 1188 y = item->h / 2;
3d853664 1189 XSetForeground(dpy, dc.gc, dc.separator.pixel);
1190 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
1191 menu->w - config.horzpadding, y);
1192
1193 item->sel = item->unsel;
1194 } else {
523b3d5e 1195 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h, depth);
3d853664 1196 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
1197 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
1198
1199 /* draw text */
27c03246 1200 textx = config.horzpadding;
1201 textx += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
1202 switch (config.alignment) {
1203 case CenterAlignment:
1204 textx += (menu->maxtextw - item->textw) / 2;
1205 break;
1206 case RightAlignment:
1207 textx += menu->maxtextw - item->textw;
1208 break;
1209 default:
1210 break;
1211 }
3d853664 1212 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
1213 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
1214 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
27c03246 1215 drawtext(dsel, &dc.selected[ColorFG], textx, 0, item->h, item->label);
3d853664 1216 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
27c03246 1217 drawtext(dunsel, &dc.normal[ColorFG], textx, 0, item->h, item->label);
3d853664 1218 XftDrawDestroy(dsel);
1219 XftDrawDestroy(dunsel);
1220
1221 /* draw triangle */
1222 if (item->submenu != NULL) {
1223 x = menu->w - config.triangle_width - config.horzpadding;
1224 y = (item->h - config.triangle_height + 1) / 2;
1225
1226 XPoint triangle[] = {
1227 {x, y},
1228 {x + config.triangle_width, y + config.triangle_height/2},
1229 {x, y + config.triangle_height},
1230 {x, y}
1231 };
1232
1233 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
1234 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
1235 Convex, CoordModeOrigin);
1236 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
1237 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
1238 Convex, CoordModeOrigin);
1239 }
1240
d3c21312 1241 /* try to load icon */
1242 if (item->file && !iflag) {
3d853664 1243 item->icon = loadicon(item->file);
d3c21312 1244 free(item->file);
1245 }
3d853664 1246
d3c21312 1247 /* draw icon if properly loaded */
f66f4c18 1248 if (item->icon) {
3d853664 1249 imlib_context_set_image(item->icon);
237da982 1250 imlib_context_set_drawable(item->sel);
3d853664 1251 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
1252 imlib_context_set_drawable(item->unsel);
1253 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
d3c21312 1254 imlib_context_set_image(item->icon);
1255 imlib_free_image();
3d853664 1256 }
1257 }
1258 }
1259}
1260
1261/* copy pixmaps of items of the current menu and of its ancestors into menu window */
1262static void
1263drawmenus(struct Menu *currmenu)
1264{
1265 struct Menu *menu;
1266 struct Item *item;
523b3d5e 1267 int y0, y;
1268 int maxh;
3d853664 1269
1270 for (menu = currmenu; menu != NULL; menu = menu->parent) {
1271 if (!menu->drawn) {
1272 drawitems(menu);
1273 menu->drawn = 1;
1274 }
523b3d5e 1275 if (menu->overflow && menu->selected != NULL) {
1276 maxh = menu->h - config.height_pixels * 2;
1277 while (menu->first->next != NULL &&
1278 menu->selected->y >= menu->first->y + maxh) {
1279 menu->first = menu->first->next;
1280 }
1281 while (menu->first->prev != NULL &&
1282 menu->selected->y < menu->first->y) {
1283 menu->first = menu->first->prev;
1284 }
1285 }
1286 y = menu->first->y;
1287 y0 = menu->overflow ? config.height_pixels : 0;
1288 for (item = menu->first; item != NULL; item = item->next) {
1289 if (menu->overflow && item->y - y + item->h > menu->h - config.height_pixels * 2)
1290 break;
1291 if (item == menu->selected) {
1292 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0, menu->w, item->h, 0, y0 + item->y - y);
1293 } else {
1294 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0, menu->w, item->h, 0, y0 + item->y - y);
1295 }
3d853664 1296 }
1297 }
1298}
1299
45b2e22f 1300/* unmap current menu and its parents */
a7732690 1301static void
45b2e22f 1302unmapmenu(struct Menu *currmenu)
1303{
1304 struct Menu *menu;
1305
1306 for (menu = currmenu; menu != NULL; menu = menu->parent) {
1307 menu->selected = NULL;
1308 XUnmapWindow(dpy, menu->win);
1309 }
1310}
1311
1312/* umap previous menus and map current menu and its parents */
1313static struct Menu *
1314mapmenu(struct Menu *currmenu, struct Menu *prevmenu, struct Monitor *mon)
a7732690 1315{
d8a7caf2 1316 struct Menu *menu, *menu_;
d8a7caf2 1317 struct Menu *lcamenu; /* lowest common ancestor menu */
523b3d5e 1318 int minlevel; /* level of the closest to root menu */
1319 int maxlevel; /* level of the closest to root menu */
a7732690 1320
257e42cc 1321 /* do not remap current menu if it wasn't updated*/
1322 if (prevmenu == currmenu)
45b2e22f 1323 goto done;
a7732690 1324
257e42cc 1325 /* if this is the first time mapping, skip calculations */
1326 if (prevmenu == NULL) {
fd530f3f 1327 XMapWindow(dpy, currmenu->win);
45b2e22f 1328 goto done;
27443900 1329 }
1330
d8a7caf2 1331 /* find lowest common ancestor menu */
523b3d5e 1332 minlevel = min(currmenu->level, prevmenu->level);
1333 maxlevel = max(currmenu->level, prevmenu->level);
257e42cc 1334 if (currmenu->level == maxlevel) {
27443900 1335 menu = currmenu;
257e42cc 1336 menu_ = prevmenu;
1337 } else {
1338 menu = prevmenu;
1339 menu_ = currmenu;
27443900 1340 }
1341 while (menu->level > minlevel)
1342 menu = menu->parent;
1343 while (menu != menu_) {
1344 menu = menu->parent;
1345 menu_ = menu_->parent;
d8a7caf2 1346 }
27443900 1347 lcamenu = menu;
d8a7caf2 1348
873c080c 1349 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
257e42cc 1350 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
8455c369 1351 menu->selected = NULL;
a7732690 1352 XUnmapWindow(dpy, menu->win);
1353 }
1354
873c080c 1355 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
d8a7caf2 1356 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
3bec05ea 1357 if (wflag) {
45b2e22f 1358 setupmenupos(menu, mon);
3bec05ea 1359 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1360 }
a7732690 1361 XMapWindow(dpy, menu->win);
fd530f3f 1362 }
257e42cc 1363
f472bfac 1364 grabfocus(currmenu->win);
45b2e22f 1365done:
1366 return currmenu;
fd530f3f 1367}
1368
8902c43b 1369/* get menu of given window */
1370static struct Menu *
1371getmenu(struct Menu *currmenu, Window win)
1372{
1373 struct Menu *menu;
1374
1375 for (menu = currmenu; menu != NULL; menu = menu->parent)
1376 if (menu->win == win)
1377 return menu;
1378
1379 return NULL;
1380}
1381
523b3d5e 1382/* get in *ret the item in given menu and position; return 1 if position is on a scroll triangle */
1383static int
1384getitem(struct Menu *menu, struct Item **ret, int y)
8902c43b 1385{
1386 struct Item *item;
523b3d5e 1387 int y0;
8902c43b 1388
523b3d5e 1389 *ret = NULL;
8902c43b 1390 if (menu == NULL)
523b3d5e 1391 return 0;
1392 if (menu->overflow) {
1393 if (y < config.height_pixels) {
1394 *ret = menu->first->prev;
1395 return 1;
1396 } else if (y > menu->h - config.height_pixels) {
1397 y0 = menu->overflow ? config.height_pixels : 0;
1398 y = menu->h - y0 + menu->first->y;
1399 for (item = menu->first; item != NULL; item = item->next)
1400 if (y >= item->y && y <= item->y + item->h)
1401 break;
1402 if (item != NULL)
1403 *ret = menu->first->next;
1404 return 1;
1405 }
1406 }
1407 y0 = menu->overflow ? config.height_pixels : 0;
1408 y -= y0 - menu->first->y;
1409 for (item = menu->first; item != NULL; item = item->next) {
1410 if (y >= item->y && y <= item->y + item->h) {
1411 *ret = item;
1412 break;
1413 }
1414 }
1415 return 0;
8902c43b 1416}
1417
858338d9 1418/* cycle through the items; non-zero direction is next, zero is prev */
1419static struct Item *
257e42cc 1420itemcycle(struct Menu *currmenu, int direction)
858338d9 1421{
006c94ce 1422 struct Item *item = NULL;
858338d9 1423 struct Item *lastitem;
1424
006c94ce 1425 for (lastitem = currmenu->list; lastitem && lastitem->next; lastitem = lastitem->next)
1426 ;
858338d9 1427
006c94ce 1428 /* select item (either separator or labeled item) in given direction */
1429 switch (direction) {
1430 case ITEMNEXT:
858338d9 1431 if (currmenu->selected == NULL)
1432 item = currmenu->list;
1433 else if (currmenu->selected->next != NULL)
1434 item = currmenu->selected->next;
006c94ce 1435 break;
1436 case ITEMPREV:
858338d9 1437 if (currmenu->selected == NULL)
1438 item = lastitem;
1439 else if (currmenu->selected->prev != NULL)
1440 item = currmenu->selected->prev;
006c94ce 1441 break;
1442 case ITEMFIRST:
1443 item = currmenu->list;
1444 break;
1445 case ITEMLAST:
1446 item = lastitem;
1447 break;
1448 }
858338d9 1449
006c94ce 1450 /*
1451 * the selected item can be a separator
1452 * let's select the closest labeled item (ie., one that isn't a separator)
1453 */
1454 switch (direction) {
1455 case ITEMNEXT:
1456 case ITEMFIRST:
1457 while (item != NULL && item->label == NULL)
1458 item = item->next;
1459 if (item == NULL)
1460 item = currmenu->list;
1461 break;
1462 case ITEMPREV:
1463 case ITEMLAST:
858338d9 1464 while (item != NULL && item->label == NULL)
1465 item = item->prev;
858338d9 1466 if (item == NULL)
1467 item = lastitem;
006c94ce 1468 break;
858338d9 1469 }
1470
1471 return item;
1472}
1473
60ddf397 1474/* check if button is used to scroll */
1475static int
1476isscrollbutton(unsigned int button)
1477{
1478 if (button == Button4 || button == Button5)
1479 return 1;
1480 return 0;
1481}
1482
1146fd81 1483/* check if button is used to open a item on click */
1484static int
1485isclickbutton(unsigned int button)
1486{
60ddf397 1487 if (button == Button1 || button == Button2)
1146fd81 1488 return 1;
1489 if (!rflag && button == Button3)
1490 return 1;
1491 return 0;
1492}
1493
60ddf397 1494/* warp pointer to center of selected item */
1495static void
1496warppointer(struct Menu *menu, struct Item *item)
1497{
1498 if (menu == NULL || item == NULL)
1499 return;
1500 if (menu->selected) {
1501 XWarpPointer(dpy, None, menu->win, 0, 0, 0, 0, menu->w / 2, item->y + item->h / 2);
1502 }
1503}
1504
b33886d7 1505/* append buf into text */
1506static int
1507append(char *text, char *buf, size_t textsize, size_t buflen)
1508{
1509 size_t textlen;
1510
1511 textlen = strlen(text);
1512 if (iscntrl(*buf))
1513 return 0;
1514 if (textlen + buflen > textsize - 1)
1515 return 0;
1516 if (buflen < 1)
1517 return 0;
1518 memcpy(text + textlen, buf, buflen);
1519 text[textlen + buflen] = '\0';
1520 return 1;
1521}
1522
693735f7 1523/* get item in menu matching text from given direction (or from beginning, if dir = 0) */
b33886d7 1524static struct Item *
693735f7 1525matchitem(struct Menu *menu, char *text, int dir)
b33886d7 1526{
693735f7 1527 struct Item *item, *lastitem;
b33886d7 1528 char *s;
1529 size_t textlen;
1530
693735f7 1531 for (lastitem = menu->list; lastitem && lastitem->next; lastitem = lastitem->next)
1532 ;
b33886d7 1533 textlen = strlen(text);
693735f7 1534 if (dir < 0) {
1535 if (menu->selected && menu->selected->prev)
1536 item = menu->selected->prev;
1537 else
1538 item = lastitem;
1539 } else if (dir > 0) {
1540 if (menu->selected && menu->selected->next)
1541 item = menu->selected->next;
1542 else
1543 item = menu->list;
1544 } else {
1545 item = menu->list;
1546 }
1547 /* find next item from selected item */
1548 for ( ; item; item = (dir < 0) ? item->prev : item->next)
b33886d7 1549 for (s = item->label; s && *s; s++)
1550 if (strncasecmp(s, text, textlen) == 0)
1551 return item;
693735f7 1552 /* if not found, try to find from the beginning/end of list */
1553 if (dir > 0) {
1554 for (item = menu->list ; item; item = item->next) {
1555 for (s = item->label; s && *s; s++) {
1556 if (strncasecmp(s, text, textlen) == 0) {
1557 return item;
1558 }
1559 }
1560 }
1561 } else {
1562 for (item = lastitem ; item; item = item->prev) {
1563 for (s = item->label; s && *s; s++) {
1564 if (strncasecmp(s, text, textlen) == 0) {
1565 return item;
1566 }
1567 }
1568 }
1569 }
b33886d7 1570 return NULL;
1571}
1572
8239f1f1 1573/* check keysyms defined on config.h */
1574static KeySym
1575normalizeksym(KeySym ksym)
1576{
1577 if (ksym == KSYMFIRST)
1578 return XK_Home;
1579 if (ksym == KSYMLAST)
1580 return XK_End;
1581 if (ksym == KSYMUP)
1582 return XK_Up;
1583 if (ksym == KSYMDOWN)
1584 return XK_Down;
1585 if (ksym == KSYMLEFT)
1586 return XK_Left;
1587 if (ksym == KSYMRIGHT)
1588 return XK_Right;
1589 return ksym;
1590}
1591
a7732690 1592/* run event loop */
1593static void
45b2e22f 1594run(struct Menu *currmenu, struct Monitor *mon)
a7732690 1595{
b33886d7 1596 char text[BUFSIZ];
1597 char buf[32];
45b2e22f 1598 struct Menu *menu, *prevmenu;
a7732690 1599 struct Item *item;
1600 struct Item *previtem = NULL;
b33886d7 1601 struct Item *lastitem, *select;
858338d9 1602 KeySym ksym;
b33886d7 1603 Status status;
a7732690 1604 XEvent ev;
60ddf397 1605 int warped = 0;
6bbc0e45 1606 int action;
b33886d7 1607 int len;
8239f1f1 1608 int i;
a7732690 1609
b33886d7 1610 text[0] = '\0';
45b2e22f 1611 prevmenu = currmenu;
a7732690 1612 while (!XNextEvent(dpy, &ev)) {
b33886d7 1613 if (XFilterEvent(&ev, None))
1614 continue;
6bbc0e45 1615 action = ACTION_NOP;
a7732690 1616 switch(ev.type) {
1617 case Expose:
858338d9 1618 if (ev.xexpose.count == 0)
6bbc0e45 1619 action = ACTION_DRAW;
a7732690 1620 break;
1621 case MotionNotify:
60ddf397 1622 if (!warped) {
1623 menu = getmenu(currmenu, ev.xbutton.window);
523b3d5e 1624 if (getitem(menu, &item, ev.xbutton.y))
1625 break;
60ddf397 1626 if (menu == NULL || item == NULL || previtem == item)
1627 break;
1628 previtem = item;
1629 select = menu->selected = item;
1630 if (item->submenu != NULL) {
1631 currmenu = item->submenu;
1632 select = NULL;
1633 } else {
1634 currmenu = menu;
1635 }
1636 action = ACTION_CLEAR | ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
a7732690 1637 }
60ddf397 1638 warped = 0;
a7732690 1639 break;
1640 case ButtonRelease:
60ddf397 1641 if (isscrollbutton(ev.xbutton.button)) {
1642 if (ev.xbutton.button == Button4)
1643 select = itemcycle(currmenu, ITEMPREV);
1644 else
1645 select = itemcycle(currmenu, ITEMNEXT);
1646 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW | ACTION_WARP;
1647 } else if (isclickbutton(ev.xbutton.button)) {
1648 menu = getmenu(currmenu, ev.xbutton.window);
523b3d5e 1649 if (getitem(menu, &item, ev.xbutton.y) && item != NULL) {
1650 select = NULL;
1651 menu->first = item;
1652 action = ACTION_CLEAR | ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
1653 break;
1654 }
60ddf397 1655 if (menu == NULL || item == NULL)
1656 break;
b33886d7 1657enteritem:
60ddf397 1658 if (item->label == NULL)
1659 break; /* ignore separators */
1660 if (item->submenu != NULL) {
1661 currmenu = item->submenu;
1662 } else {
1663 printf("%s\n", item->output);
45b2e22f 1664 goto done;
60ddf397 1665 }
1666 select = currmenu->list;
1667 action = ACTION_CLEAR | ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
1668 if (ev.xbutton.button == Button2) {
1669 action |= ACTION_WARP;
1670 }
a7732690 1671 }
fd530f3f 1672 break;
858338d9 1673 case ButtonPress:
257e42cc 1674 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1675 if (menu == NULL)
45b2e22f 1676 goto done;
858338d9 1677 break;
1678 case KeyPress:
b33886d7 1679 len = XmbLookupString(currmenu->xic, &ev.xkey, buf, sizeof buf, &ksym, &status);
1680 switch(status) {
1681 default: /* XLookupNone, XBufferOverflow */
1682 continue;
1683 case XLookupChars:
1684 goto append;
1685 case XLookupKeySym: /* FALLTHROUGH */
1686 case XLookupBoth:
1687 break;
1688 }
858338d9 1689
0c1a7864 1690 /* esc closes xmenu when current menu is the root menu */
257e42cc 1691 if (ksym == XK_Escape && currmenu->parent == NULL)
45b2e22f 1692 goto done;
858338d9 1693
1694 /* Shift-Tab = ISO_Left_Tab */
1695 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1696 ksym = XK_ISO_Left_Tab;
1697
1698 /* cycle through menu */
06d6acdb 1699 select = NULL;
8239f1f1 1700 ksym = normalizeksym(ksym);
1701 switch (ksym) {
1702 case XK_Home:
06d6acdb 1703 select = itemcycle(currmenu, ITEMFIRST);
0129fde4 1704 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1705 break;
1706 case XK_End:
06d6acdb 1707 select = itemcycle(currmenu, ITEMLAST);
0129fde4 1708 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1709 break;
1710 case XK_ISO_Left_Tab:
693735f7 1711 if (*text) {
06d6acdb 1712 select = matchitem(currmenu, text, -1);
e14d88b0 1713 action = ACTION_SELECT | ACTION_DRAW;
8239f1f1 1714 break;
693735f7 1715 }
8239f1f1 1716 /* FALLTHROUGH */
1717 case XK_Up:
06d6acdb 1718 select = itemcycle(currmenu, ITEMPREV);
0129fde4 1719 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1720 break;
1721 case XK_Tab:
693735f7 1722 if (*text) {
06d6acdb 1723 select = matchitem(currmenu, text, 1);
e14d88b0 1724 action = ACTION_SELECT | ACTION_DRAW;
8239f1f1 1725 break;
693735f7 1726 }
8239f1f1 1727 /* FALLTHROUGH */
1728 case XK_Down:
06d6acdb 1729 select = itemcycle(currmenu, ITEMNEXT);
0129fde4 1730 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1731 break;
1732 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:
02511d09 1733 item = itemcycle(currmenu, ITEMFIRST);
c2959cf4 1734 lastitem = itemcycle(currmenu, ITEMLAST);
1735 for (int i = ksym - XK_1; i > 0 && item != lastitem; i--) {
02511d09
R
1736 currmenu->selected = item;
1737 item = itemcycle(currmenu, ITEMNEXT);
02511d09 1738 }
06d6acdb 1739 select = item;
0129fde4 1740 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1741 break;
1742 case XK_Return: case XK_Right:
1743 if (currmenu->selected) {
1744 item = currmenu->selected;
1745 goto enteritem;
1746 }
1747 break;
1748 case XK_Escape: case XK_Left:
1749 if (currmenu->parent) {
06d6acdb 1750 select = currmenu->parent->selected;
8239f1f1 1751 currmenu = currmenu->parent;
06d6acdb 1752 action = ACTION_CLEAR | ACTION_MAP | ACTION_SELECT | ACTION_DRAW;
8239f1f1 1753 }
1754 break;
1755 case XK_BackSpace: case XK_Clear: case XK_Delete:
0129fde4 1756 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
693735f7 1757 break;
8239f1f1 1758 default:
b33886d7 1759append:
0129fde4 1760 if (*buf == '\0' || iscntrl(*buf))
1761 break;
8239f1f1 1762 for (i = 0; i < 2; i++) {
1763 append(text, buf, sizeof text, len);
06d6acdb 1764 if ((select = matchitem(currmenu, text, 0)))
8239f1f1 1765 break;
1766 text[0] = '\0';
b33886d7 1767 }
289de21f 1768 action = ACTION_SELECT | ACTION_DRAW;
8239f1f1 1769 break;
b33886d7 1770 }
a7732690 1771 break;
f15fc339 1772 case LeaveNotify:
fd530f3f 1773 previtem = NULL;
b33886d7 1774 select = NULL;
693735f7 1775 action = ACTION_CLEAR | ACTION_SELECT | ACTION_DRAW;
f15fc339 1776 break;
3bec05ea 1777 case ConfigureNotify:
1778 menu = getmenu(currmenu, ev.xconfigure.window);
1779 if (menu == NULL)
1780 break;
1781 menu->x = ev.xconfigure.x;
1782 menu->y = ev.xconfigure.y;
1783 break;
1784 case ClientMessage:
523b3d5e 1785 if ((unsigned long)ev.xclient.data.l[0] != wmdelete)
8902c43b 1786 break;
3bec05ea 1787 /* user closed window */
1788 menu = getmenu(currmenu, ev.xclient.window);
1789 if (menu->parent == NULL)
45b2e22f 1790 goto done; /* closing the root menu closes the program */
3bec05ea 1791 currmenu = menu->parent;
6bbc0e45 1792 action = ACTION_MAP;
3bec05ea 1793 break;
a7732690 1794 }
693735f7 1795 if (action & ACTION_CLEAR)
b33886d7 1796 text[0] = '\0';
693735f7 1797 if (action & ACTION_SELECT)
1798 currmenu->selected = select;
6bbc0e45 1799 if (action & ACTION_MAP)
45b2e22f 1800 prevmenu = mapmenu(currmenu, prevmenu, mon);
6bbc0e45 1801 if (action & ACTION_DRAW)
1802 drawmenus(currmenu);
60ddf397 1803 if (action & ACTION_WARP) {
1804 warppointer(currmenu, select);
1805 warped = 1;
1806 }
a7732690 1807 }
45b2e22f 1808done:
1809 unmapmenu(currmenu);
1810 ungrab();
a7732690 1811}
1812
fd530f3f 1813/* recursivelly free pixmaps and destroy windows */
f15fc339 1814static void
8902c43b 1815cleanmenu(struct Menu *menu)
f15fc339 1816{
1817 struct Item *item;
ec4ed1ac 1818 struct Item *tmp;
f15fc339 1819
ec4ed1ac 1820 item = menu->list;
1821 while (item != NULL) {
f15fc339 1822 if (item->submenu != NULL)
8902c43b 1823 cleanmenu(item->submenu);
ec4ed1ac 1824 tmp = item;
3d853664 1825 if (menu->drawn) {
1826 XFreePixmap(dpy, item->unsel);
1827 if (tmp->label != NULL)
1828 XFreePixmap(dpy, item->sel);
1829 }
15dfafdf 1830 if (tmp->label != tmp->output)
1831 free(tmp->label);
6b5123e7 1832 free(tmp->output);
33376f54 1833 item = item->next;
ec4ed1ac 1834 free(tmp);
1835 }
f15fc339 1836
f15fc339 1837 XDestroyWindow(dpy, menu->win);
ec4ed1ac 1838 free(menu);
f15fc339 1839}
1840
6abae763 1841/* cleanup draw context */
a7732690 1842static void
6abae763 1843cleandc(void)
a7732690 1844{
7539247b 1845 size_t i;
1846
dbeb9940 1847 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1848 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1849 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1850 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
fd530f3f 1851 XftColorFree(dpy, visual, colormap, &dc.separator);
1852 XftColorFree(dpy, visual, colormap, &dc.border);
7539247b 1853 for (i = 0; i < dc.nfonts; i++)
1854 XftFontClose(dpy, dc.fonts[i]);
f15fc339 1855 XFreeGC(dpy, dc.gc);
a7732690 1856}
1857
73a2a23d 1858/* xmenu: generate menu from stdin and print selected entry to stdout */
1859int
1860main(int argc, char *argv[])
a7732690 1861{
45b2e22f 1862 struct Monitor mon;
73a2a23d 1863 struct Menu *rootmenu;
45b2e22f 1864 XEvent ev;
73a2a23d 1865
1866 /* open connection to server and set X variables */
f472bfac 1867 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1868 warnx("warning: no locale support");
73a2a23d 1869 if ((dpy = XOpenDisplay(NULL)) == NULL)
1870 errx(1, "could not open display");
1871 screen = DefaultScreen(dpy);
1872 visual = DefaultVisual(dpy, screen);
1873 rootwin = RootWindow(dpy, screen);
1874 colormap = DefaultColormap(dpy, screen);
523b3d5e 1875 depth = DefaultDepth(dpy, screen);
6abae763 1876 XrmInitialize();
1877 if ((xrm = XResourceManagerString(dpy)) != NULL)
1878 xdb = XrmGetStringDatabase(xrm);
f472bfac 1879 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
1880 errx(1, "XOpenIM: could not open input device");
6abae763 1881
78fb523f 1882 /* process configuration and window class */
6abae763 1883 getresources();
45b2e22f 1884 getoptions(argc, argv);
73a2a23d 1885
1886 /* imlib2 stuff */
1887 if (!iflag) {
1888 imlib_set_cache_size(2048 * 1024);
1889 imlib_context_set_dither(1);
1890 imlib_context_set_display(dpy);
1891 imlib_context_set_visual(visual);
1892 imlib_context_set_colormap(colormap);
1893 }
1894
1895 /* initializers */
73a2a23d 1896 initdc();
1897 initiconsize();
1898 initatoms();
1899
45b2e22f 1900 /* if running in root mode, get button presses from root window */
1901 if (rootmodeflag)
1902 XGrabButton(dpy, button, AnyModifier, rootwin, False, ButtonPressMask, GrabModeSync, GrabModeSync, None, None);
1903
1904 /* generate menus */
73a2a23d 1905 rootmenu = parsestdin();
1906 if (rootmenu == NULL)
1907 errx(1, "no menu generated");
73a2a23d 1908
1909 /* run event loop */
45b2e22f 1910 do {
1911 if (rootmodeflag)
1912 XNextEvent(dpy, &ev);
1913 if (!rootmodeflag ||
1914 (ev.type == ButtonPress &&
1915 ((modifier != 0 && ev.xbutton.state == modifier) ||
1916 (ev.xbutton.subwindow == None)))) {
1917 if (rootmodeflag && passclickflag) {
1918 XAllowEvents(dpy, ReplayPointer, CurrentTime);
1919 }
1920 getmonitor(&mon);
1921 if (!wflag) {
1922 grabpointer();
1923 grabkeyboard();
1924 }
1925 setupmenu(rootmenu, &mon);
1926 mapmenu(rootmenu, NULL, &mon);
1927 XFlush(dpy);
1928 run(rootmenu, &mon);
1929 firsttime = 0;
1930 } else {
1931 XAllowEvents(dpy, ReplayPointer, CurrentTime);
1932 }
1933 } while (rootmodeflag);
73a2a23d 1934
6abae763 1935 /* clean stuff */
73a2a23d 1936 cleanmenu(rootmenu);
6abae763 1937 cleandc();
1938 XrmDestroyDatabase(xdb);
1939 XCloseDisplay(dpy);
73a2a23d 1940
1941 return 0;
a7732690 1942}