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