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