rub out text when no item matches it
[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
144 while ((ch = getopt(argc, argv, "ip:rw")) != -1) {
145 switch (ch) {
146 case 'i':
147 iflag = 1;
148 break;
149 case 'p':
150 pflag = 1;
151 parseposition(optarg);
152 break;
153 case 'r':
154 rflag = 1;
155 break;
156 case '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
435 prevmenu = menu;
436 menu->caller = item;
437 item->submenu = menu;
438 curritem->prev = NULL;
439 }
440
a2ff706d 441 if (curritem->file)
442 prevmenu->hasicon = 1;
443
a5ddd2cd 444 return rootmenu;
445}
446
a7732690 447/* create menus and items from the stdin */
257e42cc 448static struct Menu *
a7732690 449parsestdin(void)
450{
a5ddd2cd 451 struct Menu *rootmenu;
a7732690 452 char *s, buf[BUFSIZ];
33376f54 453 char *file, *label, *output;
a7732690 454 unsigned level = 0;
257e42cc 455
ddb15acf 456 rootmenu = NULL;
457
a7732690 458 while (fgets(buf, BUFSIZ, stdin) != NULL) {
a5ddd2cd 459 /* get the indentation level */
460 level = strspn(buf, "\t");
a7732690 461
a5ddd2cd 462 /* get the label */
463 s = level + buf;
464 label = strtok(s, "\t\n");
a7732690 465
33376f54 466 /* get the filename */
467 file = NULL;
468 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
469 file = label + 4;
470 label = strtok(NULL, "\t\n");
471 }
472
a5ddd2cd 473 /* get the output */
474 output = strtok(NULL, "\n");
475 if (output == NULL) {
476 output = label;
477 } else {
478 while (*output == '\t')
479 output++;
a7732690 480 }
a5ddd2cd 481
33376f54 482 rootmenu = buildmenutree(level, label, output, file);
a7732690 483 }
a7732690 484
257e42cc 485 return rootmenu;
a7732690 486}
487
3d853664 488/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
cdeaefaa 489static FcChar32
490getnextutf8char(const char *s, const char **next_ret)
491{
cdeaefaa 492 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
cdeaefaa 493 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
cdeaefaa 494 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
495 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
3d853664 496 /* 0xFFFD is the replacement character, used to represent unknown characters */
cdeaefaa 497 static const FcChar32 unknown = 0xFFFD;
498 FcChar32 ucode; /* FcChar32 type holds 32 bits */
499 size_t usize = 0; /* n' of bytes of the utf8 character */
500 size_t i;
501
502 *next_ret = s+1;
503
504 /* get code of first byte of utf8 character */
505 for (i = 0; i < sizeof utfmask; i++) {
506 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
507 usize = i;
508 ucode = (unsigned char)*s & ~utfmask[i];
509 break;
510 }
511 }
512
513 /* if first byte is a continuation byte or is not allowed, return unknown */
514 if (i == sizeof utfmask || usize == 0)
515 return unknown;
516
517 /* check the other usize-1 bytes */
518 s++;
519 for (i = 1; i < usize; i++) {
520 *next_ret = s+1;
237da982 521 /* if byte is nul or is not a continuation byte, return unknown */
cdeaefaa 522 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
523 return unknown;
524 /* 6 is the number of relevant bits in the continuation byte */
525 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
526 s++;
527 }
528
529 /* check if ucode is invalid or in utf-16 surrogate halves */
530 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
531 || BETWEEN (ucode, 0xD800, 0xDFFF))
532 return unknown;
533
534 return ucode;
535}
536
f8d55995 537/* get which font contains a given code point */
538static XftFont *
539getfontucode(FcChar32 ucode)
540{
a48473fd 541 FcCharSet *fccharset = NULL;
542 FcPattern *fcpattern = NULL;
543 FcPattern *match = NULL;
544 XftFont *retfont = NULL;
6d56f279 545 XftResult result;
f8d55995 546 size_t i;
547
548 for (i = 0; i < dc.nfonts; i++)
549 if (XftCharExists(dpy, dc.fonts[i], ucode) == FcTrue)
550 return dc.fonts[i];
6d56f279 551
552 /* create a charset containing our code point */
553 fccharset = FcCharSetCreate();
554 FcCharSetAddChar(fccharset, ucode);
555
a48473fd 556 /* create a pattern akin to the dc.pattern but containing our charset */
557 if (fccharset) {
558 fcpattern = FcPatternDuplicate(dc.pattern);
559 FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
560 }
6d56f279 561
562 /* find pattern matching fcpattern */
a48473fd 563 if (fcpattern) {
564 FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
565 FcDefaultSubstitute(fcpattern);
566 match = XftFontMatch(dpy, screen, fcpattern, &result);
567 }
6d56f279 568
569 /* if found a pattern, open its font */
570 if (match) {
571 retfont = XftFontOpenPattern(dpy, match);
572 if (retfont && XftCharExists(dpy, retfont, ucode) == FcTrue) {
573 if ((dc.fonts = realloc(dc.fonts, dc.nfonts+1)) == NULL)
574 err(1, "realloc");
a48473fd 575 dc.fonts[dc.nfonts] = retfont;
576 return dc.fonts[dc.nfonts++];
6d56f279 577 } else {
578 XftFontClose(dpy, retfont);
579 }
580 }
581
582 /* in case no fount was found, return the first one */
583 return dc.fonts[0];
f8d55995 584}
585
586/* draw text into XftDraw, return width of text glyphs */
cdeaefaa 587static int
588drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
589{
f8d55995 590 int textwidth = 0;
cdeaefaa 591
f8d55995 592 while (*text) {
593 XftFont *currfont;
cdeaefaa 594 XGlyphInfo ext;
f8d55995 595 FcChar32 ucode;
596 const char *next;
cdeaefaa 597 size_t len;
cdeaefaa 598
f8d55995 599 ucode = getnextutf8char(text, &next);
6d56f279 600 currfont = getfontucode(ucode);
cdeaefaa 601
f8d55995 602 len = next - text;
f8d55995 603 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)text, len, &ext);
604 textwidth += ext.xOff;
cdeaefaa 605
606 if (draw) {
a48473fd 607 int texty;
608
609 texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
f8d55995 610 XftDrawStringUtf8(draw, color, currfont, x, texty, (XftChar8 *)text, len);
cdeaefaa 611 x += ext.xOff;
612 }
613
f8d55995 614 text = next;
cdeaefaa 615 }
616
f8d55995 617 return textwidth;
cdeaefaa 618}
619
71b4db92 620/* setup the height, width and icon of the items of a menu */
a7732690 621static void
71b4db92 622setupitems(struct Menu *menu)
a7732690 623{
a80fee22 624 struct Item *item;
27c03246 625 int itemwidth;
a7732690 626
8902c43b 627 menu->w = config.width_pixels;
27c03246 628 menu->maxtextw = 0;
a80fee22 629 for (item = menu->list; item != NULL; item = item->next) {
630 item->y = menu->h;
7fbd1c5e 631 if (item->label == NULL) /* height for separator item */
8902c43b 632 item->h = config.separator_pixels;
a80fee22 633 else
8902c43b 634 item->h = config.height_pixels;
beae67a6 635 menu->h += item->h;
15362de4 636 if (item->label)
27c03246 637 item->textw = drawtext(NULL, NULL, 0, 0, 0, item->label);
15362de4 638 else
27c03246 639 item->textw = 0;
685ca30d 640
71b4db92 641 /*
642 * set menu width
643 *
27c03246 644 * the item width depends on the size of its label (item->textw),
71b4db92 645 * and it is only used to calculate the width of the menu (which
646 * is equal to the width of the largest item).
647 *
648 * the horizontal padding appears 4 times through the width of a
15362de4 649 * item: before and after its icon, and before and after its triangle.
71b4db92 650 * if the iflag is set (icons are disabled) then the horizontal
15362de4 651 * padding appears 3 times: before the label and around the triangle.
71b4db92 652 */
27c03246 653 itemwidth = item->textw + config.triangle_width + config.horzpadding * 3;
a2ff706d 654 itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
71b4db92 655 menu->w = MAX(menu->w, itemwidth);
27c03246 656 menu->maxtextw = MAX(menu->maxtextw, item->textw);
a80fee22 657 }
f8ffe0b2 658}
659
660/* setup the position of a menu */
661static void
8902c43b 662setupmenupos(struct Menu *menu)
f8ffe0b2 663{
664 int width, height;
a7732690 665
8902c43b 666 width = menu->w + config.border_pixels * 2;
667 height = menu->h + config.border_pixels * 2;
a7732690 668 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
ef667106 669 if (pflag || (config.posx >= mon.x && mon.x + mon.w - config.posx >= width))
05cfe1a0 670 menu->x = config.posx;
671 else if (config.posx > width)
672 menu->x = config.posx - width;
8902c43b 673
ef667106 674 if (pflag || (config.posy >= mon.y && mon.y + mon.h - config.posy >= height))
05cfe1a0 675 menu->y = config.posy;
b6cf4847 676 else if (mon.y + mon.h > height)
237da982 677 menu->y = mon.y + mon.h - height;
a7732690 678 } else { /* else, calculate in respect to parent menu */
237da982 679 int parentwidth;
680
681 parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
682
683 if (mon.x + mon.w - parentwidth >= width)
684 menu->x = parentwidth;
8902c43b 685 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
686 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
a7732690 687
8e799bb4 688 if (mon.y + mon.h - (menu->caller->y + menu->parent->y) >= height)
8455c369 689 menu->y = menu->caller->y + menu->parent->y;
237da982 690 else if (mon.y + mon.h > height)
691 menu->y = mon.y + mon.h - height;
a7732690 692 }
f8ffe0b2 693}
694
695/* recursivelly setup menu configuration and its pixmap */
696static void
8902c43b 697setupmenu(struct Menu *menu, XClassHint *classh)
f8ffe0b2 698{
8902c43b 699 char *title;
f8ffe0b2 700 struct Item *item;
f8ffe0b2 701 XWindowChanges changes;
702 XSizeHints sizeh;
3bec05ea 703 XTextProperty wintitle;
f8ffe0b2 704
705 /* setup size and position of menus */
71b4db92 706 setupitems(menu);
8902c43b 707 setupmenupos(menu);
a7732690 708
709 /* update menu geometry */
8902c43b 710 changes.border_width = config.border_pixels;
a7732690 711 changes.height = menu->h;
f1583285 712 changes.width = menu->w;
a7732690 713 changes.x = menu->x;
714 changes.y = menu->y;
beae67a6 715 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
a7732690 716
3bec05ea 717 /* set window title (used if wflag is on) */
718 if (menu->parent == NULL) {
8902c43b 719 title = classh->res_name;
3bec05ea 720 } else {
8902c43b 721 title = menu->caller->output;
3bec05ea 722 }
8902c43b 723 XStringListToTextProperty(&title, 1, &wintitle);
3bec05ea 724
d2435fcd 725 /* set window manager hints */
c15958bd 726 sizeh.flags = USPosition | PMaxSize | PMinSize;
09c13122 727 sizeh.min_width = sizeh.max_width = menu->w;
728 sizeh.min_height = sizeh.max_height = menu->h;
3bec05ea 729 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
09c13122 730
a3a73837 731 /* set WM protocols and ewmh window properties */
732 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
8902c43b 733 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
a3a73837 734 PropModeReplace, (unsigned char *)title, strlen(title));
8902c43b 735 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
736 PropModeReplace,
737 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
738
a80fee22 739 /* calculate positions of submenus */
a7732690 740 for (item = menu->list; item != NULL; item = item->next) {
741 if (item->submenu != NULL)
8902c43b 742 setupmenu(item->submenu, classh);
a7732690 743 }
744}
745
85003546 746/* try to grab pointer, we may have to wait for another process to ungrab */
747static void
748grabpointer(void)
749{
750 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
751 int i;
752
753 for (i = 0; i < 1000; i++) {
754 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
755 GrabModeAsync, GrabModeAsync, None,
756 None, CurrentTime) == GrabSuccess)
757 return;
758 nanosleep(&ts, NULL);
759 }
70f5db0f 760 errx(1, "could not grab pointer");
85003546 761}
762
763/* try to grab keyboard, we may have to wait for another process to ungrab */
764static void
765grabkeyboard(void)
766{
767 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
768 int i;
769
770 for (i = 0; i < 1000; i++) {
771 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
772 GrabModeAsync, CurrentTime) == GrabSuccess)
773 return;
774 nanosleep(&ts, NULL);
775 }
8a7bfdf8 776 errx(1, "could not grab keyboard");
85003546 777}
778
f472bfac 779/* try to grab focus, we may have to wait for another process to ungrab */
780static void
781grabfocus(Window win)
782{
783 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
784 Window focuswin;
785 int i, revertwin;
786
787 for (i = 0; i < 100; ++i) {
788 XGetInputFocus(dpy, &focuswin, &revertwin);
789 if (focuswin == win)
790 return;
791 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
792 nanosleep(&ts, NULL);
793 }
794 errx(1, "cannot grab focus");
795}
796
6abae763 797/* ungrab pointer and keyboard */
798static void
799ungrab(void)
800{
801 XUngrabPointer(dpy, CurrentTime);
802 XUngrabKeyboard(dpy, CurrentTime);
803}
804
3d853664 805/* load and scale icon */
806static Imlib_Image
807loadicon(const char *file)
808{
809 Imlib_Image icon;
ed1650a7 810 Imlib_Load_Error errcode;
811 const char *errstr;
3d853664 812 int width;
813 int height;
814 int imgsize;
815
ed1650a7 816 icon = imlib_load_image_with_error_return(file, &errcode);
f66f4c18 817 if (*file == '\0') {
818 warnx("could not load icon (file name is blank)");
819 return NULL;
820 } else if (icon == NULL) {
ed1650a7 821 switch (errcode) {
822 case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
823 errstr = "file does not exist";
824 break;
825 case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
826 errstr = "file is directory";
827 break;
828 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
829 case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
830 errstr = "permission denied";
831 break;
832 case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
833 errstr = "unknown file format";
834 break;
835 case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
836 errstr = "path too long";
837 break;
838 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
839 case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
840 case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
841 errstr = "improper path";
842 break;
843 case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
844 errstr = "too many symbolic links";
845 break;
846 case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
847 errstr = "out of memory";
848 break;
849 case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
850 errstr = "out of file descriptors";
851 break;
852 default:
853 errstr = "unknown error";
854 break;
855 }
f66f4c18 856 warnx("could not load icon (%s): %s", errstr, file);
857 return NULL;
ed1650a7 858 }
3d853664 859
860 imlib_context_set_image(icon);
861
862 width = imlib_image_get_width();
863 height = imlib_image_get_height();
864 imgsize = MIN(width, height);
865
866 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
867 config.iconsize,
868 config.iconsize);
869
870 return icon;
871}
872
873/* draw pixmap for the selected and unselected version of each item on menu */
874static void
875drawitems(struct Menu *menu)
876{
27c03246 877 XftDraw *dsel, *dunsel;
3d853664 878 struct Item *item;
27c03246 879 int textx;
880 int x, y;
3d853664 881
882 for (item = menu->list; item != NULL; item = item->next) {
3d853664 883 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
884 DefaultDepth(dpy, screen));
885
886 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
887 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
888
889 if (item->label == NULL) { /* item is separator */
890 y = item->h/2;
891 XSetForeground(dpy, dc.gc, dc.separator.pixel);
892 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
893 menu->w - config.horzpadding, y);
894
895 item->sel = item->unsel;
896 } else {
3d853664 897 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
898 DefaultDepth(dpy, screen));
899 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
900 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
901
902 /* draw text */
27c03246 903 textx = config.horzpadding;
904 textx += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
905 switch (config.alignment) {
906 case CenterAlignment:
907 textx += (menu->maxtextw - item->textw) / 2;
908 break;
909 case RightAlignment:
910 textx += menu->maxtextw - item->textw;
911 break;
912 default:
913 break;
914 }
3d853664 915 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
916 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
917 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
27c03246 918 drawtext(dsel, &dc.selected[ColorFG], textx, 0, item->h, item->label);
3d853664 919 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
27c03246 920 drawtext(dunsel, &dc.normal[ColorFG], textx, 0, item->h, item->label);
3d853664 921 XftDrawDestroy(dsel);
922 XftDrawDestroy(dunsel);
923
924 /* draw triangle */
925 if (item->submenu != NULL) {
926 x = menu->w - config.triangle_width - config.horzpadding;
927 y = (item->h - config.triangle_height + 1) / 2;
928
929 XPoint triangle[] = {
930 {x, y},
931 {x + config.triangle_width, y + config.triangle_height/2},
932 {x, y + config.triangle_height},
933 {x, y}
934 };
935
936 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
937 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
938 Convex, CoordModeOrigin);
939 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
940 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
941 Convex, CoordModeOrigin);
942 }
943
d3c21312 944 /* try to load icon */
945 if (item->file && !iflag) {
3d853664 946 item->icon = loadicon(item->file);
d3c21312 947 free(item->file);
948 }
3d853664 949
d3c21312 950 /* draw icon if properly loaded */
f66f4c18 951 if (item->icon) {
3d853664 952 imlib_context_set_image(item->icon);
237da982 953 imlib_context_set_drawable(item->sel);
3d853664 954 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
955 imlib_context_set_drawable(item->unsel);
956 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
d3c21312 957 imlib_context_set_image(item->icon);
958 imlib_free_image();
3d853664 959 }
960 }
961 }
962}
963
964/* copy pixmaps of items of the current menu and of its ancestors into menu window */
965static void
966drawmenus(struct Menu *currmenu)
967{
968 struct Menu *menu;
969 struct Item *item;
970
971 for (menu = currmenu; menu != NULL; menu = menu->parent) {
972 if (!menu->drawn) {
973 drawitems(menu);
974 menu->drawn = 1;
975 }
976 for (item = menu->list; item != NULL; item = item->next) {
977 if (item == menu->selected)
978 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
979 menu->w, item->h, 0, item->y);
980 else
981 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
982 menu->w, item->h, 0, item->y);
983 }
984 }
985}
986
257e42cc 987/* umap previous menus and map current menu and its parents */
a7732690 988static void
257e42cc 989mapmenu(struct Menu *currmenu)
a7732690 990{
257e42cc 991 static struct Menu *prevmenu = NULL;
d8a7caf2 992 struct Menu *menu, *menu_;
d8a7caf2 993 struct Menu *lcamenu; /* lowest common ancestor menu */
994 unsigned minlevel; /* level of the closest to root menu */
995 unsigned maxlevel; /* level of the closest to root menu */
a7732690 996
257e42cc 997 /* do not remap current menu if it wasn't updated*/
998 if (prevmenu == currmenu)
a7732690 999 return;
1000
257e42cc 1001 /* if this is the first time mapping, skip calculations */
1002 if (prevmenu == NULL) {
fd530f3f 1003 XMapWindow(dpy, currmenu->win);
cdc4d51f 1004 prevmenu = currmenu;
1005 return;
27443900 1006 }
1007
d8a7caf2 1008 /* find lowest common ancestor menu */
257e42cc 1009 minlevel = MIN(currmenu->level, prevmenu->level);
1010 maxlevel = MAX(currmenu->level, prevmenu->level);
1011 if (currmenu->level == maxlevel) {
27443900 1012 menu = currmenu;
257e42cc 1013 menu_ = prevmenu;
1014 } else {
1015 menu = prevmenu;
1016 menu_ = currmenu;
27443900 1017 }
1018 while (menu->level > minlevel)
1019 menu = menu->parent;
1020 while (menu != menu_) {
1021 menu = menu->parent;
1022 menu_ = menu_->parent;
d8a7caf2 1023 }
27443900 1024 lcamenu = menu;
d8a7caf2 1025
873c080c 1026 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
257e42cc 1027 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
8455c369 1028 menu->selected = NULL;
a7732690 1029 XUnmapWindow(dpy, menu->win);
1030 }
1031
873c080c 1032 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
d8a7caf2 1033 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
3bec05ea 1034
1035 if (wflag) {
8902c43b 1036 setupmenupos(menu);
3bec05ea 1037 XMoveWindow(dpy, menu->win, menu->x, menu->y);
1038 }
1039
a7732690 1040 XMapWindow(dpy, menu->win);
fd530f3f 1041 }
257e42cc 1042
257e42cc 1043 prevmenu = currmenu;
f472bfac 1044 grabfocus(currmenu->win);
fd530f3f 1045}
1046
8902c43b 1047/* get menu of given window */
1048static struct Menu *
1049getmenu(struct Menu *currmenu, Window win)
1050{
1051 struct Menu *menu;
1052
1053 for (menu = currmenu; menu != NULL; menu = menu->parent)
1054 if (menu->win == win)
1055 return menu;
1056
1057 return NULL;
1058}
1059
1060/* get item of given menu and position */
1061static struct Item *
1062getitem(struct Menu *menu, int y)
1063{
1064 struct Item *item;
1065
1066 if (menu == NULL)
1067 return NULL;
1068
1069 for (item = menu->list; item != NULL; item = item->next)
1070 if (y >= item->y && y <= item->y + item->h)
1071 return item;
1072
1073 return NULL;
1074}
1075
858338d9 1076/* cycle through the items; non-zero direction is next, zero is prev */
1077static struct Item *
257e42cc 1078itemcycle(struct Menu *currmenu, int direction)
858338d9 1079{
006c94ce 1080 struct Item *item = NULL;
858338d9 1081 struct Item *lastitem;
1082
006c94ce 1083 for (lastitem = currmenu->list; lastitem && lastitem->next; lastitem = lastitem->next)
1084 ;
858338d9 1085
006c94ce 1086 /* select item (either separator or labeled item) in given direction */
1087 switch (direction) {
1088 case ITEMNEXT:
858338d9 1089 if (currmenu->selected == NULL)
1090 item = currmenu->list;
1091 else if (currmenu->selected->next != NULL)
1092 item = currmenu->selected->next;
006c94ce 1093 break;
1094 case ITEMPREV:
858338d9 1095 if (currmenu->selected == NULL)
1096 item = lastitem;
1097 else if (currmenu->selected->prev != NULL)
1098 item = currmenu->selected->prev;
006c94ce 1099 break;
1100 case ITEMFIRST:
1101 item = currmenu->list;
1102 break;
1103 case ITEMLAST:
1104 item = lastitem;
1105 break;
1106 }
858338d9 1107
006c94ce 1108 /*
1109 * the selected item can be a separator
1110 * let's select the closest labeled item (ie., one that isn't a separator)
1111 */
1112 switch (direction) {
1113 case ITEMNEXT:
1114 case ITEMFIRST:
1115 while (item != NULL && item->label == NULL)
1116 item = item->next;
1117 if (item == NULL)
1118 item = currmenu->list;
1119 break;
1120 case ITEMPREV:
1121 case ITEMLAST:
858338d9 1122 while (item != NULL && item->label == NULL)
1123 item = item->prev;
858338d9 1124 if (item == NULL)
1125 item = lastitem;
006c94ce 1126 break;
858338d9 1127 }
1128
1129 return item;
1130}
1131
1146fd81 1132/* check if button is used to open a item on click */
1133static int
1134isclickbutton(unsigned int button)
1135{
1136 if (button == Button1)
1137 return 1;
1138 if (!rflag && button == Button3)
1139 return 1;
1140 return 0;
1141}
1142
b33886d7 1143/* append buf into text */
1144static int
1145append(char *text, char *buf, size_t textsize, size_t buflen)
1146{
1147 size_t textlen;
1148
1149 textlen = strlen(text);
1150 if (iscntrl(*buf))
1151 return 0;
1152 if (textlen + buflen > textsize - 1)
1153 return 0;
1154 if (buflen < 1)
1155 return 0;
1156 memcpy(text + textlen, buf, buflen);
1157 text[textlen + buflen] = '\0';
1158 return 1;
1159}
1160
1161/* get item in menu matching text */
1162static struct Item *
1163matchitem(struct Menu *menu, char *text)
1164{
1165 struct Item *item;
1166 char *s;
1167 size_t textlen;
1168
1169 textlen = strlen(text);
1170 for (item = menu->list; item; item = item->next)
1171 for (s = item->label; s && *s; s++)
1172 if (strncasecmp(s, text, textlen) == 0)
1173 return item;
1174 return NULL;
1175}
1176
a7732690 1177/* run event loop */
1178static void
257e42cc 1179run(struct Menu *currmenu)
a7732690 1180{
b33886d7 1181 char text[BUFSIZ];
1182 char buf[32];
a7732690 1183 struct Menu *menu;
1184 struct Item *item;
1185 struct Item *previtem = NULL;
b33886d7 1186 struct Item *lastitem, *select;
858338d9 1187 KeySym ksym;
b33886d7 1188 Status status;
a7732690 1189 XEvent ev;
6bbc0e45 1190 int action;
b33886d7 1191 int len;
a7732690 1192
b33886d7 1193 text[0] = '\0';
257e42cc 1194 mapmenu(currmenu);
a7732690 1195 while (!XNextEvent(dpy, &ev)) {
b33886d7 1196 if (XFilterEvent(&ev, None))
1197 continue;
6bbc0e45 1198 action = ACTION_NOP;
a7732690 1199 switch(ev.type) {
1200 case Expose:
858338d9 1201 if (ev.xexpose.count == 0)
6bbc0e45 1202 action = ACTION_DRAW;
a7732690 1203 break;
1204 case MotionNotify:
257e42cc 1205 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1206 item = getitem(menu, ev.xbutton.y);
c6d9174e 1207 if (menu == NULL || item == NULL || previtem == item)
fd530f3f 1208 break;
c6d9174e 1209 previtem = item;
b33886d7 1210 select = menu->selected = item;
c6d9174e 1211 if (item->submenu != NULL) {
1212 currmenu = item->submenu;
b33886d7 1213 select = NULL;
c6d9174e 1214 } else {
1215 currmenu = menu;
a7732690 1216 }
b33886d7 1217 action = ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
a7732690 1218 break;
1219 case ButtonRelease:
1146fd81 1220 if (!isclickbutton(ev.xbutton.button))
1221 break;
257e42cc 1222 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1223 item = getitem(menu, ev.xbutton.y);
fd530f3f 1224 if (menu == NULL || item == NULL)
858338d9 1225 break;
b33886d7 1226enteritem:
fd530f3f 1227 if (item->label == NULL)
1228 break; /* ignore separators */
1229 if (item->submenu != NULL) {
257e42cc 1230 currmenu = item->submenu;
a7732690 1231 } else {
fd530f3f 1232 printf("%s\n", item->output);
08f16589 1233 return;
a7732690 1234 }
b33886d7 1235 select = currmenu->list;
1236 action = ACTION_SELECT | ACTION_MAP | ACTION_DRAW;
fd530f3f 1237 break;
858338d9 1238 case ButtonPress:
257e42cc 1239 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1240 if (menu == NULL)
858338d9 1241 return;
1242 break;
1243 case KeyPress:
b33886d7 1244 len = XmbLookupString(currmenu->xic, &ev.xkey, buf, sizeof buf, &ksym, &status);
1245 switch(status) {
1246 default: /* XLookupNone, XBufferOverflow */
1247 continue;
1248 case XLookupChars:
1249 goto append;
1250 case XLookupKeySym: /* FALLTHROUGH */
1251 case XLookupBoth:
1252 break;
1253 }
858338d9 1254
0c1a7864 1255 /* esc closes xmenu when current menu is the root menu */
257e42cc 1256 if (ksym == XK_Escape && currmenu->parent == NULL)
858338d9 1257 return;
1258
1259 /* Shift-Tab = ISO_Left_Tab */
1260 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1261 ksym = XK_ISO_Left_Tab;
1262
1263 /* cycle through menu */
1264 item = NULL;
7b166488 1265 if (ksym == XK_Home || ksym == KSYMFIRST) {
006c94ce 1266 item = itemcycle(currmenu, ITEMFIRST);
7b166488 1267 } else if (ksym == XK_End || ksym == KSYMLAST) {
006c94ce 1268 item = itemcycle(currmenu, ITEMLAST);
7b166488 1269 } else if (ksym == XK_ISO_Left_Tab || ksym == XK_Up || ksym == KSYMUP) {
257e42cc 1270 item = itemcycle(currmenu, ITEMPREV);
7b166488 1271 } else if (ksym == XK_Tab || ksym == XK_Down || ksym == KSYMDOWN) {
257e42cc 1272 item = itemcycle(currmenu, ITEMNEXT);
2b0484b1 1273 } else if (ksym >= XK_1 && ksym <= XK_9){
02511d09 1274 item = itemcycle(currmenu, ITEMFIRST);
c2959cf4 1275 lastitem = itemcycle(currmenu, ITEMLAST);
1276 for (int i = ksym - XK_1; i > 0 && item != lastitem; i--) {
02511d09
R
1277 currmenu->selected = item;
1278 item = itemcycle(currmenu, ITEMNEXT);
02511d09
R
1279 }
1280 } else if ((ksym == XK_Return || ksym == XK_Right || ksym == KSYMRIGHT) &&
1281 currmenu->selected != NULL) {
858338d9 1282 item = currmenu->selected;
b33886d7 1283 goto enteritem;
7b166488 1284 } else if ((ksym == XK_Escape || ksym == XK_Left || ksym == KSYMLEFT) &&
858338d9 1285 currmenu->parent != NULL) {
1286 item = currmenu->parent->selected;
257e42cc 1287 currmenu = currmenu->parent;
6bbc0e45 1288 action = ACTION_MAP;
b33886d7 1289 } else {
1290append:
1291 if (append(text, buf, sizeof text, len)) {
7bdb3b0b 1292 if ((currmenu->selected = matchitem(currmenu, text))) {
1293 action = ACTION_DRAW;
1294 break;
1295 }
b33886d7 1296 }
7bdb3b0b 1297 select = NULL;
1298 action = ACTION_SELECT | ACTION_DRAW;
858338d9 1299 break;
b33886d7 1300 }
1301 select = item;
1302 action |= ACTION_SELECT | ACTION_DRAW;
a7732690 1303 break;
f15fc339 1304 case LeaveNotify:
fd530f3f 1305 previtem = NULL;
b33886d7 1306 select = NULL;
1307 action = ACTION_SELECT | ACTION_DRAW;
f15fc339 1308 break;
3bec05ea 1309 case ConfigureNotify:
1310 menu = getmenu(currmenu, ev.xconfigure.window);
1311 if (menu == NULL)
1312 break;
1313 menu->x = ev.xconfigure.x;
1314 menu->y = ev.xconfigure.y;
1315 break;
1316 case ClientMessage:
8902c43b 1317 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1318 break;
3bec05ea 1319 /* user closed window */
1320 menu = getmenu(currmenu, ev.xclient.window);
1321 if (menu->parent == NULL)
1322 return; /* closing the root menu closes the program */
1323 currmenu = menu->parent;
6bbc0e45 1324 action = ACTION_MAP;
3bec05ea 1325 break;
a7732690 1326 }
b33886d7 1327 if (action & ACTION_SELECT) {
1328 currmenu->selected = select;
1329 text[0] = '\0';
1330 }
6bbc0e45 1331 if (action & ACTION_MAP)
1332 mapmenu(currmenu);
1333 if (action & ACTION_DRAW)
1334 drawmenus(currmenu);
a7732690 1335 }
1336}
1337
fd530f3f 1338/* recursivelly free pixmaps and destroy windows */
f15fc339 1339static void
8902c43b 1340cleanmenu(struct Menu *menu)
f15fc339 1341{
1342 struct Item *item;
ec4ed1ac 1343 struct Item *tmp;
f15fc339 1344
ec4ed1ac 1345 item = menu->list;
1346 while (item != NULL) {
f15fc339 1347 if (item->submenu != NULL)
8902c43b 1348 cleanmenu(item->submenu);
ec4ed1ac 1349 tmp = item;
3d853664 1350 if (menu->drawn) {
1351 XFreePixmap(dpy, item->unsel);
1352 if (tmp->label != NULL)
1353 XFreePixmap(dpy, item->sel);
1354 }
15dfafdf 1355 if (tmp->label != tmp->output)
1356 free(tmp->label);
6b5123e7 1357 free(tmp->output);
33376f54 1358 item = item->next;
ec4ed1ac 1359 free(tmp);
1360 }
f15fc339 1361
f15fc339 1362 XDestroyWindow(dpy, menu->win);
ec4ed1ac 1363 free(menu);
f15fc339 1364}
1365
6abae763 1366/* cleanup draw context */
a7732690 1367static void
6abae763 1368cleandc(void)
a7732690 1369{
7539247b 1370 size_t i;
1371
dbeb9940 1372 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1373 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1374 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1375 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
fd530f3f 1376 XftColorFree(dpy, visual, colormap, &dc.separator);
1377 XftColorFree(dpy, visual, colormap, &dc.border);
7539247b 1378 for (i = 0; i < dc.nfonts; i++)
1379 XftFontClose(dpy, dc.fonts[i]);
f15fc339 1380 XFreeGC(dpy, dc.gc);
a7732690 1381}
1382
73a2a23d 1383/* xmenu: generate menu from stdin and print selected entry to stdout */
1384int
1385main(int argc, char *argv[])
a7732690 1386{
73a2a23d 1387 struct Menu *rootmenu;
1388 XClassHint classh;
73a2a23d 1389
1390 /* open connection to server and set X variables */
f472bfac 1391 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1392 warnx("warning: no locale support");
73a2a23d 1393 if ((dpy = XOpenDisplay(NULL)) == NULL)
1394 errx(1, "could not open display");
1395 screen = DefaultScreen(dpy);
1396 visual = DefaultVisual(dpy, screen);
1397 rootwin = RootWindow(dpy, screen);
1398 colormap = DefaultColormap(dpy, screen);
6abae763 1399 XrmInitialize();
1400 if ((xrm = XResourceManagerString(dpy)) != NULL)
1401 xdb = XrmGetStringDatabase(xrm);
f472bfac 1402 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
1403 errx(1, "XOpenIM: could not open input device");
6abae763 1404
1405 /* get configuration */
1406 getresources();
1407 classh.res_class = PROGNAME;
1408 classh.res_name = getoptions(argc, argv);
73a2a23d 1409
1410 /* imlib2 stuff */
1411 if (!iflag) {
1412 imlib_set_cache_size(2048 * 1024);
1413 imlib_context_set_dither(1);
1414 imlib_context_set_display(dpy);
1415 imlib_context_set_visual(visual);
1416 imlib_context_set_colormap(colormap);
1417 }
1418
1419 /* initializers */
1420 initmonitor();
73a2a23d 1421 initdc();
1422 initiconsize();
1423 initatoms();
1424
73a2a23d 1425 /* generate menus and set them up */
1426 rootmenu = parsestdin();
1427 if (rootmenu == NULL)
1428 errx(1, "no menu generated");
1429 setupmenu(rootmenu, &classh);
1430
1431 /* grab mouse and keyboard */
1432 if (!wflag) {
1433 grabpointer();
1434 grabkeyboard();
1435 }
1436
1437 /* run event loop */
1438 run(rootmenu);
1439
6abae763 1440 /* clean stuff */
1441 ungrab();
73a2a23d 1442 cleanmenu(rootmenu);
6abae763 1443 cleandc();
1444 XrmDestroyDatabase(xdb);
1445 XCloseDisplay(dpy);
73a2a23d 1446
1447 return 0;
a7732690 1448}