computing textwidth with the function drawtext
[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>
8902c43b 8#include <time.h>
a7732690 9#include <unistd.h>
10#include <X11/Xlib.h>
8902c43b 11#include <X11/Xatom.h>
a7732690 12#include <X11/Xutil.h>
f644b8bc 13#include <X11/Xresource.h>
858338d9 14#include <X11/XKBlib.h>
dbeb9940 15#include <X11/Xft/Xft.h>
33376f54 16#include <Imlib2.h>
8902c43b 17#include "xmenu.h"
858338d9 18
8902c43b 19/*
20 * Function declarations
21 */
22
05cfe1a0 23/* argument parser */
24static void parseposition(const char *optarg);
25
8902c43b 26/* initializers, and their helper routines */
cdeaefaa 27static void parsefonts(const char *s);
8902c43b 28static void ealloccolor(const char *s, XftColor *color);
29static void initresources(void);
30static void initdc(void);
71b4db92 31static void initconfig(void);
8902c43b 32static void initatoms(void);
33
34/* structure builders, and their helper routines */
33376f54 35static struct Item *allocitem(const char *label, const char *output, char *file);
a7732690 36static struct Menu *allocmenu(struct Menu *parent, struct Item *list, unsigned level);
33376f54 37static struct Menu *buildmenutree(unsigned level, const char *label, const char *output, char *file);
257e42cc 38static struct Menu *parsestdin(void);
8902c43b 39
40/* image loader */
71b4db92 41static Imlib_Image loadicon(const char *file);
8902c43b 42
cdeaefaa 43/* utf8 utils */
44static FcChar32 getnextutf8char(const char *s, const char **end_ret);
45
46/* pixmap drawers */
47static int drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text);
48static void drawitems(struct Menu *menu);
49
8902c43b 50/* structure setters, and their helper routines */
71b4db92 51static void setupitems(struct Menu *menu);
8902c43b 52static void setupmenupos(struct Menu *menu);
53static void setupmenu(struct Menu *menu, XClassHint *classh);
54
55/* grabbers */
85003546 56static void grabpointer(void);
57static void grabkeyboard(void);
8902c43b 58
59/* window drawers and mappers */
257e42cc 60static void mapmenu(struct Menu *currmenu);
cdeaefaa 61static void copypixmaps(struct Menu *currmenu);
8902c43b 62
cdeaefaa 63/* getters */
8902c43b 64static struct Menu *getmenu(struct Menu *currmenu, Window win);
65static struct Item *getitem(struct Menu *menu, int y);
cdeaefaa 66
67/* cycle through items */
257e42cc 68static struct Item *itemcycle(struct Menu *currmenu, int direction);
cdeaefaa 69
70/* main event loop */
257e42cc 71static void run(struct Menu *currmenu);
8902c43b 72
73/* cleaners */
74static void cleanmenu(struct Menu *menu);
15dfafdf 75static void cleanup(void);
8902c43b 76
77/* show usage */
a7732690 78static void usage(void);
79
8902c43b 80
81/*
82 * Variable declarations
83 */
84
738ed9d5 85/* X stuff */
a7732690 86static Display *dpy;
c6d9174e 87static int screen;
dbeb9940 88static Visual *visual;
a7732690 89static Window rootwin;
c6d9174e 90static Colormap colormap;
a7732690 91static struct DC dc;
8902c43b 92static Atom utf8string;
3bec05ea 93static Atom wmdelete;
8902c43b 94static Atom netatom[NetLast];
3bec05ea 95
96/* flags */
71b4db92 97static int iflag = 0; /* whether to disable icons */
05cfe1a0 98static int pflag = 0; /* whether the user specified a position */
99static int wflag = 0; /* whether to let the window manager control XMenu */
a7732690 100
8902c43b 101/* include config variable */
a7732690 102#include "config.h"
103
8902c43b 104
105/*
106 * Function implementations
107 */
108
beae67a6 109/* xmenu: generate menu from stdin and print selected entry to stdout */
a7732690 110int
111main(int argc, char *argv[])
112{
257e42cc 113 struct Menu *rootmenu;
3bec05ea 114 XClassHint classh;
a7732690 115 int ch;
116
05cfe1a0 117 while ((ch = getopt(argc, argv, "ip:w")) != -1) {
a7732690 118 switch (ch) {
71b4db92 119 case 'i':
120 iflag = 1;
121 break;
05cfe1a0 122 case 'p':
123 pflag = 1;
124 parseposition(optarg);
05cfe1a0 125 break;
3bec05ea 126 case 'w':
127 wflag = 1;
128 break;
a7732690 129 default:
130 usage();
131 break;
132 }
133 }
134 argc -= optind;
135 argv += optind;
136
3bec05ea 137 if (argc > 1)
c6d9174e 138 usage();
139
a7732690 140 /* open connection to server and set X variables */
141 if ((dpy = XOpenDisplay(NULL)) == NULL)
142 errx(1, "cannot open display");
143 screen = DefaultScreen(dpy);
dbeb9940 144 visual = DefaultVisual(dpy, screen);
a7732690 145 rootwin = RootWindow(dpy, screen);
146 colormap = DefaultColormap(dpy, screen);
21a9aaec 147
33376f54 148 /* imlib2 stuff */
71b4db92 149 if (!iflag) {
150 imlib_set_cache_size(2048 * 1024);
151 imlib_context_set_dither(1);
152 imlib_context_set_display(dpy);
153 imlib_context_set_visual(visual);
154 imlib_context_set_colormap(colormap);
155 }
33376f54 156
8902c43b 157 /* initializers */
158 initresources();
159 initdc();
71b4db92 160 initconfig();
8902c43b 161 initatoms();
a7732690 162
3bec05ea 163 /* set window class */
164 classh.res_class = PROGNAME;
165 if (argc == 1)
166 classh.res_name = *argv;
167 else
168 classh.res_name = PROGNAME;
169
f8ffe0b2 170 /* generate menus and set them up */
257e42cc 171 rootmenu = parsestdin();
a7732690 172 if (rootmenu == NULL)
173 errx(1, "no menu generated");
8902c43b 174 setupmenu(rootmenu, &classh);
a7732690 175
465d07db 176 /* grab mouse and keyboard */
3bec05ea 177 if (!wflag) {
178 grabpointer();
179 grabkeyboard();
180 }
465d07db 181
a7732690 182 /* run event loop */
257e42cc 183 run(rootmenu);
a7732690 184
15dfafdf 185 /* freeing stuff */
8902c43b 186 cleanmenu(rootmenu);
15dfafdf 187 cleanup();
188
21a9aaec 189 return 0;
190}
191
05cfe1a0 192/* parse position string from -p, put results on config.x and config.y */
193static void
194parseposition(const char *optarg)
195{
196 long n;
197 const char *s = optarg;
198 char *endp;
199
200 n = strtol(s, &endp, 10);
201 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
202 goto error;
203 config.posx = n;
204 s = endp+1;
205 n = strtol(s, &endp, 10);
206 if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
207 goto error;
208 config.posy = n;
209
210 return;
211
212error:
213 errx(1, "improper position: %s", optarg);
214}
215
cdeaefaa 216/* parse color string */
217static void
218parsefonts(const char *s)
219{
220 const char *p;
221 char buf[1024];
222 size_t nfont = 0;
223
224 dc.nfonts = 1;
225 for (p = s; *p; p++)
226 if (*p == ',')
227 dc.nfonts++;
228
229 if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
230 err(1, "calloc");
231
232 p = s;
233 while (*p != '\0') {
234 size_t i;
235
236 i = 0;
237 while (isspace(*p))
238 p++;
239 while (*p != '\0' && *p != ',') {
240 buf[i++] = *p++;
241 }
242 if (*p == ',')
243 p++;
244 buf[i] = '\0';
245 if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
246 errx(1, "cannot load font");
247 }
248}
249
8902c43b 250/* get color from color string */
251static void
252ealloccolor(const char *s, XftColor *color)
253{
254 if(!XftColorAllocName(dpy, visual, colormap, s, color))
255 errx(1, "cannot allocate color: %s", s);
256}
257
f644b8bc 258/* read xrdb for configuration options */
259static void
8902c43b 260initresources(void)
f644b8bc 261{
262 char *xrm;
263 long n;
fd530f3f 264 char *type;
265 XrmDatabase xdb;
266 XrmValue xval;
f644b8bc 267
268 XrmInitialize();
fd530f3f 269 if ((xrm = XResourceManagerString(dpy)) == NULL)
270 return;
271
272 xdb = XrmGetStringDatabase(xrm);
273
274 if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
275 if ((n = strtol(xval.addr, NULL, 10)) > 0)
8902c43b 276 config.border_pixels = n;
fd530f3f 277 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
278 if ((n = strtol(xval.addr, NULL, 10)) > 0)
8902c43b 279 config.separator_pixels = n;
685ca30d 280 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
fd530f3f 281 if ((n = strtol(xval.addr, NULL, 10)) > 0)
8902c43b 282 config.height_pixels = n;
fd530f3f 283 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
284 if ((n = strtol(xval.addr, NULL, 10)) > 0)
8902c43b 285 config.width_pixels = n;
eecf9b25 286 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
287 if ((n = strtol(xval.addr, NULL, 10)) > 0)
288 config.gap_pixels = n;
fd530f3f 289 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
8902c43b 290 config.background_color = strdup(xval.addr);
fd530f3f 291 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
8902c43b 292 config.foreground_color = strdup(xval.addr);
fd530f3f 293 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
8902c43b 294 config.selbackground_color = strdup(xval.addr);
fd530f3f 295 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
8902c43b 296 config.selforeground_color = strdup(xval.addr);
fd530f3f 297 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
8902c43b 298 config.separator_color = strdup(xval.addr);
fd530f3f 299 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
8902c43b 300 config.border_color = strdup(xval.addr);
fd530f3f 301 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
8902c43b 302 config.font = strdup(xval.addr);
fd530f3f 303
304 XrmDestroyDatabase(xdb);
f644b8bc 305}
306
a7732690 307/* init draw context */
308static void
8902c43b 309initdc(void)
a7732690 310{
311 /* get color pixels */
8902c43b 312 ealloccolor(config.background_color, &dc.normal[ColorBG]);
313 ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
314 ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
315 ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
316 ealloccolor(config.separator_color, &dc.separator);
317 ealloccolor(config.border_color, &dc.border);
a7732690 318
cdeaefaa 319 /* parse fonts */
320 parsefonts(config.font);
a7732690 321
fd530f3f 322 /* create common GC */
a7732690 323 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
a7732690 324}
325
71b4db92 326/* calculate configuration values that are not set manually */
a7732690 327static void
71b4db92 328initconfig(void)
a7732690 329{
8902c43b 330 Window dw; /* dummy variable */
331 int di; /* dummy variable */
332 unsigned du; /* dummy variable */
333
05cfe1a0 334 if (!pflag) /* if the user haven't specified a position, use cursor position*/
335 XQueryPointer(dpy, rootwin, &dw, &dw, &config.posx, &config.posy, &di, &di, &du);
8902c43b 336 config.screenw = DisplayWidth(dpy, screen);
337 config.screenh = DisplayHeight(dpy, screen);
71b4db92 338 config.iconsize = config.height_pixels - config.iconpadding * 2;
8902c43b 339}
340
341/* intern atoms */
342static void
343initatoms(void)
344{
345 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
346 wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
347 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
348 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
349 netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
a7732690 350}
351
a7732690 352/* allocate an item */
353static struct Item *
33376f54 354allocitem(const char *label, const char *output, char *file)
a7732690 355{
356 struct Item *item;
357
358 if ((item = malloc(sizeof *item)) == NULL)
359 err(1, "malloc");
a5ddd2cd 360 if (label == NULL) {
7fbd1c5e 361 item->label = NULL;
362 item->output = NULL;
363 } else {
364 if ((item->label = strdup(label)) == NULL)
365 err(1, "strdup");
15dfafdf 366 if (label == output) {
367 item->output = item->label;
368 } else {
369 if ((item->output = strdup(output)) == NULL)
370 err(1, "strdup");
371 }
7fbd1c5e 372 }
33376f54 373 if (file == NULL) {
374 item->file = NULL;
375 } else {
376 if ((item->file = strdup(file)) == NULL)
377 err(1, "strdup");
378 }
a80fee22 379 item->y = 0;
beae67a6 380 item->h = 0;
f1583285 381 if (item->label == NULL)
382 item->labellen = 0;
383 else
384 item->labellen = strlen(item->label);
a7732690 385 item->next = NULL;
386 item->submenu = NULL;
3bec05ea 387 item->icon = NULL;
a7732690 388
389 return item;
390}
391
a3a73837 392/* allocate a menu and create its window */
a7732690 393static struct Menu *
394allocmenu(struct Menu *parent, struct Item *list, unsigned level)
395{
396 XSetWindowAttributes swa;
397 struct Menu *menu;
398
399 if ((menu = malloc(sizeof *menu)) == NULL)
400 err(1, "malloc");
401 menu->parent = parent;
402 menu->list = list;
d888f2ca 403 menu->caller = NULL;
a7732690 404 menu->selected = NULL;
f8ffe0b2 405 menu->w = 0; /* calculated by setupmenu() */
406 menu->h = 0; /* calculated by setupmenu() */
407 menu->x = 0; /* calculated by setupmenu() */
408 menu->y = 0; /* calculated by setupmenu() */
a7732690 409 menu->level = level;
a7732690 410
3bec05ea 411 swa.override_redirect = (wflag) ? False : True;
fd530f3f 412 swa.background_pixel = dc.normal[ColorBG].pixel;
413 swa.border_pixel = dc.border.pixel;
414 swa.save_under = True; /* pop-up windows should save_under*/
a7732690 415 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
f15fc339 416 | PointerMotionMask | LeaveWindowMask;
3bec05ea 417 if (wflag)
418 swa.event_mask |= StructureNotifyMask;
beae67a6 419 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
a7732690 420 CopyFromParent, CopyFromParent, CopyFromParent,
fd530f3f 421 CWOverrideRedirect | CWBackPixel |
422 CWBorderPixel | CWEventMask | CWSaveUnder,
a7732690 423 &swa);
424
425 return menu;
426}
427
a5ddd2cd 428/* build the menu tree */
429static struct Menu *
33376f54 430buildmenutree(unsigned level, const char *label, const char *output, char *file)
a5ddd2cd 431{
432 static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
433 static struct Menu *rootmenu = NULL; /* menu to be returned */
434 struct Item *curritem = NULL; /* item currently being read */
435 struct Item *item; /* dummy item for loops */
436 struct Menu *menu; /* dummy menu for loops */
437 unsigned i;
438
439 /* create the item */
33376f54 440 curritem = allocitem(label, output, file);
a5ddd2cd 441
442 /* put the item in the menu tree */
443 if (prevmenu == NULL) { /* there is no menu yet */
685ca30d 444 menu = allocmenu(NULL, curritem, level);
445 rootmenu = menu;
446 prevmenu = menu;
447 curritem->prev = NULL;
a5ddd2cd 448 } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
449 /* go up the menu tree until find the menu this item continues */
450 for (menu = prevmenu, i = level;
451 menu != NULL && i != prevmenu->level;
452 menu = menu->parent, i++)
453 ;
454 if (menu == NULL)
455 errx(1, "reached NULL menu");
456
457 /* find last item in the new menu */
458 for (item = menu->list; item->next != NULL; item = item->next)
459 ;
460
461 prevmenu = menu;
462 item->next = curritem;
463 curritem->prev = item;
464 } else if (level == prevmenu->level) { /* item is a continuation of current menu */
465 /* find last item in the previous menu */
466 for (item = prevmenu->list; item->next != NULL; item = item->next)
467 ;
468
469 item->next = curritem;
470 curritem->prev = item;
471 } else if (level > prevmenu->level) { /* item begins a new menu */
472 menu = allocmenu(prevmenu, curritem, level);
473
474 /* find last item in the previous menu */
475 for (item = prevmenu->list; item->next != NULL; item = item->next)
476 ;
477
478 prevmenu = menu;
479 menu->caller = item;
480 item->submenu = menu;
481 curritem->prev = NULL;
482 }
483
484 return rootmenu;
485}
486
a7732690 487/* create menus and items from the stdin */
257e42cc 488static struct Menu *
a7732690 489parsestdin(void)
490{
a5ddd2cd 491 struct Menu *rootmenu;
a7732690 492 char *s, buf[BUFSIZ];
33376f54 493 char *file, *label, *output;
a7732690 494 unsigned level = 0;
257e42cc 495
ddb15acf 496 rootmenu = NULL;
497
a7732690 498 while (fgets(buf, BUFSIZ, stdin) != NULL) {
a5ddd2cd 499 /* get the indentation level */
500 level = strspn(buf, "\t");
a7732690 501
a5ddd2cd 502 /* get the label */
503 s = level + buf;
504 label = strtok(s, "\t\n");
a7732690 505
33376f54 506 /* get the filename */
507 file = NULL;
508 if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
509 file = label + 4;
510 label = strtok(NULL, "\t\n");
511 }
512
a5ddd2cd 513 /* get the output */
514 output = strtok(NULL, "\n");
515 if (output == NULL) {
516 output = label;
517 } else {
518 while (*output == '\t')
519 output++;
a7732690 520 }
a5ddd2cd 521
33376f54 522 rootmenu = buildmenutree(level, label, output, file);
a7732690 523 }
a7732690 524
257e42cc 525 return rootmenu;
a7732690 526}
527
3bec05ea 528/* load and scale icon */
33376f54 529static Imlib_Image
71b4db92 530loadicon(const char *file)
33376f54 531{
3bec05ea 532 Imlib_Image icon;
33376f54 533 int width;
534 int height;
535 int imgsize;
536
3bec05ea 537 icon = imlib_load_image(file);
538 if (icon == NULL)
539 errx(1, "cannot load icon %s", file);
33376f54 540
3bec05ea 541 imlib_context_set_image(icon);
33376f54 542
543 width = imlib_image_get_width();
544 height = imlib_image_get_height();
545 imgsize = MIN(width, height);
546
71b4db92 547 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
548 config.iconsize,
549 config.iconsize);
33376f54 550
3bec05ea 551 return icon;
33376f54 552}
553
cdeaefaa 554/* get next utf8 char from s return its codepoint and set next_ret to pointer to next character */
555static FcChar32
556getnextutf8char(const char *s, const char **next_ret)
557{
558 /* */
559 static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
560 /* */
561 static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
562 /* 0xFFFD is the replacement character, used to represent unknown characters */
563 static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
564 static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
565 static const FcChar32 unknown = 0xFFFD;
566 FcChar32 ucode; /* FcChar32 type holds 32 bits */
567 size_t usize = 0; /* n' of bytes of the utf8 character */
568 size_t i;
569
570 *next_ret = s+1;
571
572 /* get code of first byte of utf8 character */
573 for (i = 0; i < sizeof utfmask; i++) {
574 if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
575 usize = i;
576 ucode = (unsigned char)*s & ~utfmask[i];
577 break;
578 }
579 }
580
581 /* if first byte is a continuation byte or is not allowed, return unknown */
582 if (i == sizeof utfmask || usize == 0)
583 return unknown;
584
585 /* check the other usize-1 bytes */
586 s++;
587 for (i = 1; i < usize; i++) {
588 *next_ret = s+1;
589 /* if byte is EOS or is not a continuation byte, return unknown */
590 if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
591 return unknown;
592 /* 6 is the number of relevant bits in the continuation byte */
593 ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
594 s++;
595 }
596
597 /* check if ucode is invalid or in utf-16 surrogate halves */
598 if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
599 || BETWEEN (ucode, 0xD800, 0xDFFF))
600 return unknown;
601
602 return ucode;
603}
604
605/* draw text into XftDraw */
606static int
607drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
608{
609 const char *s, *nexts;
610 FcChar32 ucode;
611 XftFont *currfont;
612 int textlen = 0;
613
614 s = text;
615 while (*s) {
616 XGlyphInfo ext;
617 int charexists;
618 size_t len;
619 size_t i;
620
621 charexists = 0;
622 ucode = getnextutf8char(s, &nexts);
623 for (i = 0; i < dc.nfonts; i++) {
624 charexists = XftCharExists(dpy, dc.fonts[i], ucode);
625 if (charexists)
626 break;
627 }
628 if (charexists)
629 currfont = dc.fonts[i];
630
631 len = nexts - s;
632
633 XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)s,
634 len, &ext);
635 textlen += ext.xOff;
636
637 if (draw) {
638 int texty;
639
640 texty = y + (h + currfont->ascent) / 2;
641 XftDrawStringUtf8(draw, color, currfont, x, texty,
642 (XftChar8 *)s, len);
643 x += ext.xOff;
644 }
645
646 s = nexts;
647 }
648
649 return textlen;
650}
651
652/* draw pixmap for the selected and unselected version of each item on menu */
653static void
654drawitems(struct Menu *menu)
655{
656 struct Item *item;
657
658 for (item = menu->list; item != NULL; item = item->next) {
659 XftDraw *dsel, *dunsel;
660 int x, y;
661
662 item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
663 DefaultDepth(dpy, screen));
664
665 XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
666 XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
667
668 if (item->label == NULL) { /* item is separator */
669 y = item->h/2;
670 XSetForeground(dpy, dc.gc, dc.separator.pixel);
671 XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
672 menu->w - config.horzpadding, y);
673
674 item->sel = item->unsel;
675 } else {
676
677 item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
678 DefaultDepth(dpy, screen));
679 XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
680 XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
681
682 /* draw text */
683 x = config.horzpadding;
684 x += (iflag) ? 0 : config.horzpadding + config.iconsize;
685 dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
686 dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
687 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
688 drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
689 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
690 drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
691 XftDrawDestroy(dsel);
692 XftDrawDestroy(dunsel);
693
694 /* draw triangle */
695 if (item->submenu != NULL) {
696 x = menu->w - config.triangle_width - config.horzpadding;
697 y = (item->h - config.triangle_height + 1) / 2;
698
699 XPoint triangle[] = {
700 {x, y},
701 {x + config.triangle_width, y + config.triangle_height/2},
702 {x, y + config.triangle_height},
703 {x, y}
704 };
705
706 XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
707 XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
708 Convex, CoordModeOrigin);
709 XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
710 XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
711 Convex, CoordModeOrigin);
712 }
713
714 /* draw icon */
715 if (item->file != NULL && !iflag) {
716 item->icon = loadicon(item->file);
717
718 imlib_context_set_drawable(item->sel);
719 imlib_context_set_image(item->icon);
720 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
721
722 imlib_context_set_drawable(item->unsel);
723 imlib_context_set_image(item->icon);
724 imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
725 }
726 }
727 }
728}
729
71b4db92 730/* setup the height, width and icon of the items of a menu */
a7732690 731static void
71b4db92 732setupitems(struct Menu *menu)
a7732690 733{
a80fee22 734 struct Item *item;
a7732690 735
8902c43b 736 menu->w = config.width_pixels;
a80fee22 737 for (item = menu->list; item != NULL; item = item->next) {
15362de4 738 int itemwidth;
739 int textwidth;
740
a80fee22 741 item->y = menu->h;
beae67a6 742
7fbd1c5e 743 if (item->label == NULL) /* height for separator item */
8902c43b 744 item->h = config.separator_pixels;
a80fee22 745 else
8902c43b 746 item->h = config.height_pixels;
beae67a6 747 menu->h += item->h;
f1583285 748
15362de4 749 if (item->label)
750 textwidth = drawtext(NULL, NULL, 0, 0, item->h, item->label);
751 else
752 textwidth = 0;
685ca30d 753
71b4db92 754 /*
755 * set menu width
756 *
15362de4 757 * the item width depends on the size of its label (textwidth),
71b4db92 758 * and it is only used to calculate the width of the menu (which
759 * is equal to the width of the largest item).
760 *
761 * the horizontal padding appears 4 times through the width of a
15362de4 762 * item: before and after its icon, and before and after its triangle.
71b4db92 763 * if the iflag is set (icons are disabled) then the horizontal
15362de4 764 * padding appears 3 times: before the label and around the triangle.
71b4db92 765 */
15362de4 766 itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
71b4db92 767 itemwidth += (iflag) ? 0 : config.iconsize + config.horzpadding;
768 menu->w = MAX(menu->w, itemwidth);
a80fee22 769 }
f8ffe0b2 770}
771
772/* setup the position of a menu */
773static void
8902c43b 774setupmenupos(struct Menu *menu)
f8ffe0b2 775{
776 int width, height;
a7732690 777
8902c43b 778 width = menu->w + config.border_pixels * 2;
779 height = menu->h + config.border_pixels * 2;
a7732690 780 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
05cfe1a0 781 if (pflag || config.screenw - config.posx >= menu->w)
782 menu->x = config.posx;
783 else if (config.posx > width)
784 menu->x = config.posx - width;
8902c43b 785
05cfe1a0 786 if (pflag || config.screenh - config.posy >= height)
787 menu->y = config.posy;
8902c43b 788 else if (config.screenh > height)
789 menu->y = config.screenh - height;
a7732690 790 } else { /* else, calculate in respect to parent menu */
8902c43b 791 if (config.screenw - (menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels) >= width)
792 menu->x = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
793 else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
794 menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
a7732690 795
8902c43b 796 if (config.screenh - (menu->caller->y + menu->parent->y) > height)
8455c369 797 menu->y = menu->caller->y + menu->parent->y;
8902c43b 798 else if (config.screenh - menu->parent->y > height)
a7732690 799 menu->y = menu->parent->y;
8902c43b 800 else if (config.screenh > height)
801 menu->y = config.screenh - height;
a7732690 802 }
f8ffe0b2 803}
804
805/* recursivelly setup menu configuration and its pixmap */
806static void
8902c43b 807setupmenu(struct Menu *menu, XClassHint *classh)
f8ffe0b2 808{
8902c43b 809 char *title;
f8ffe0b2 810 struct Item *item;
f8ffe0b2 811 XWindowChanges changes;
812 XSizeHints sizeh;
3bec05ea 813 XTextProperty wintitle;
f8ffe0b2 814
815 /* setup size and position of menus */
71b4db92 816 setupitems(menu);
cdeaefaa 817 drawitems(menu);
8902c43b 818 setupmenupos(menu);
a7732690 819
820 /* update menu geometry */
8902c43b 821 changes.border_width = config.border_pixels;
a7732690 822 changes.height = menu->h;
f1583285 823 changes.width = menu->w;
a7732690 824 changes.x = menu->x;
825 changes.y = menu->y;
beae67a6 826 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
a7732690 827
3bec05ea 828 /* set window title (used if wflag is on) */
829 if (menu->parent == NULL) {
8902c43b 830 title = classh->res_name;
3bec05ea 831 } else {
8902c43b 832 title = menu->caller->output;
3bec05ea 833 }
8902c43b 834 XStringListToTextProperty(&title, 1, &wintitle);
3bec05ea 835
d2435fcd 836 /* set window manager hints */
09c13122 837 sizeh.flags = PMaxSize | PMinSize;
838 sizeh.min_width = sizeh.max_width = menu->w;
839 sizeh.min_height = sizeh.max_height = menu->h;
3bec05ea 840 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
09c13122 841
a3a73837 842 /* set WM protocols and ewmh window properties */
843 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
8902c43b 844 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
a3a73837 845 PropModeReplace, (unsigned char *)title, strlen(title));
8902c43b 846 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
847 PropModeReplace,
848 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
849
a80fee22 850 /* calculate positions of submenus */
a7732690 851 for (item = menu->list; item != NULL; item = item->next) {
852 if (item->submenu != NULL)
8902c43b 853 setupmenu(item->submenu, classh);
a7732690 854 }
855}
856
85003546 857/* try to grab pointer, we may have to wait for another process to ungrab */
858static void
859grabpointer(void)
860{
861 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
862 int i;
863
864 for (i = 0; i < 1000; i++) {
865 if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
866 GrabModeAsync, GrabModeAsync, None,
867 None, CurrentTime) == GrabSuccess)
868 return;
869 nanosleep(&ts, NULL);
870 }
871 errx(1, "cannot grab keyboard");
872}
873
874/* try to grab keyboard, we may have to wait for another process to ungrab */
875static void
876grabkeyboard(void)
877{
878 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
879 int i;
880
881 for (i = 0; i < 1000; i++) {
882 if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
883 GrabModeAsync, CurrentTime) == GrabSuccess)
884 return;
885 nanosleep(&ts, NULL);
886 }
887 errx(1, "cannot grab keyboard");
888}
889
257e42cc 890/* umap previous menus and map current menu and its parents */
a7732690 891static void
257e42cc 892mapmenu(struct Menu *currmenu)
a7732690 893{
257e42cc 894 static struct Menu *prevmenu = NULL;
d8a7caf2 895 struct Menu *menu, *menu_;
d8a7caf2 896 struct Menu *lcamenu; /* lowest common ancestor menu */
897 unsigned minlevel; /* level of the closest to root menu */
898 unsigned maxlevel; /* level of the closest to root menu */
a7732690 899
257e42cc 900 /* do not remap current menu if it wasn't updated*/
901 if (prevmenu == currmenu)
a7732690 902 return;
903
257e42cc 904 /* if this is the first time mapping, skip calculations */
905 if (prevmenu == NULL) {
fd530f3f 906 XMapWindow(dpy, currmenu->win);
cdc4d51f 907 prevmenu = currmenu;
908 return;
27443900 909 }
910
d8a7caf2 911 /* find lowest common ancestor menu */
257e42cc 912 minlevel = MIN(currmenu->level, prevmenu->level);
913 maxlevel = MAX(currmenu->level, prevmenu->level);
914 if (currmenu->level == maxlevel) {
27443900 915 menu = currmenu;
257e42cc 916 menu_ = prevmenu;
917 } else {
918 menu = prevmenu;
919 menu_ = currmenu;
27443900 920 }
921 while (menu->level > minlevel)
922 menu = menu->parent;
923 while (menu != menu_) {
924 menu = menu->parent;
925 menu_ = menu_->parent;
d8a7caf2 926 }
27443900 927 lcamenu = menu;
d8a7caf2 928
873c080c 929 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
257e42cc 930 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
8455c369 931 menu->selected = NULL;
a7732690 932 XUnmapWindow(dpy, menu->win);
933 }
934
873c080c 935 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
d8a7caf2 936 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
3bec05ea 937
938 if (wflag) {
8902c43b 939 setupmenupos(menu);
3bec05ea 940 XMoveWindow(dpy, menu->win, menu->x, menu->y);
941 }
942
a7732690 943 XMapWindow(dpy, menu->win);
fd530f3f 944 }
257e42cc 945
257e42cc 946 prevmenu = currmenu;
fd530f3f 947}
948
cdeaefaa 949/* copy pixmaps of items of the current menu and of its ancestors into menu window */
a7732690 950static void
cdeaefaa 951copypixmaps(struct Menu *currmenu)
a7732690 952{
953 struct Menu *menu;
954 struct Item *item;
955
956 for (menu = currmenu; menu != NULL; menu = menu->parent) {
a7732690 957 for (item = menu->list; item != NULL; item = item->next) {
cdeaefaa 958 if (item == menu->selected)
959 XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
960 menu->w, item->h, 0, item->y);
a7732690 961 else
cdeaefaa 962 XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
963 menu->w, item->h, 0, item->y);
a7732690 964 }
965 }
966}
967
8902c43b 968/* get menu of given window */
969static struct Menu *
970getmenu(struct Menu *currmenu, Window win)
971{
972 struct Menu *menu;
973
974 for (menu = currmenu; menu != NULL; menu = menu->parent)
975 if (menu->win == win)
976 return menu;
977
978 return NULL;
979}
980
981/* get item of given menu and position */
982static struct Item *
983getitem(struct Menu *menu, int y)
984{
985 struct Item *item;
986
987 if (menu == NULL)
988 return NULL;
989
990 for (item = menu->list; item != NULL; item = item->next)
991 if (y >= item->y && y <= item->y + item->h)
992 return item;
993
994 return NULL;
995}
996
858338d9 997/* cycle through the items; non-zero direction is next, zero is prev */
998static struct Item *
257e42cc 999itemcycle(struct Menu *currmenu, int direction)
858338d9 1000{
1001 struct Item *item;
1002 struct Item *lastitem;
1003
1004 item = NULL;
1005
1006 if (direction == ITEMNEXT) {
1007 if (currmenu->selected == NULL)
1008 item = currmenu->list;
1009 else if (currmenu->selected->next != NULL)
1010 item = currmenu->selected->next;
1011
1012 while (item != NULL && item->label == NULL)
1013 item = item->next;
1014
1015 if (item == NULL)
1016 item = currmenu->list;
1017 } else {
1018 for (lastitem = currmenu->list;
1019 lastitem != NULL && lastitem->next != NULL;
1020 lastitem = lastitem->next)
1021 ;
1022
1023 if (currmenu->selected == NULL)
1024 item = lastitem;
1025 else if (currmenu->selected->prev != NULL)
1026 item = currmenu->selected->prev;
1027
1028 while (item != NULL && item->label == NULL)
1029 item = item->prev;
1030
1031 if (item == NULL)
1032 item = lastitem;
1033 }
1034
1035 return item;
1036}
1037
a7732690 1038/* run event loop */
1039static void
257e42cc 1040run(struct Menu *currmenu)
a7732690 1041{
1042 struct Menu *menu;
1043 struct Item *item;
1044 struct Item *previtem = NULL;
858338d9 1045 KeySym ksym;
a7732690 1046 XEvent ev;
1047
257e42cc 1048 mapmenu(currmenu);
fd530f3f 1049
a7732690 1050 while (!XNextEvent(dpy, &ev)) {
1051 switch(ev.type) {
1052 case Expose:
858338d9 1053 if (ev.xexpose.count == 0)
cdeaefaa 1054 copypixmaps(currmenu);
a7732690 1055 break;
1056 case MotionNotify:
257e42cc 1057 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1058 item = getitem(menu, ev.xbutton.y);
c6d9174e 1059 if (menu == NULL || item == NULL || previtem == item)
fd530f3f 1060 break;
c6d9174e 1061 previtem = item;
1062 menu->selected = item;
1063 if (item->submenu != NULL) {
1064 currmenu = item->submenu;
1065 currmenu->selected = NULL;
1066 } else {
1067 currmenu = menu;
a7732690 1068 }
c6d9174e 1069 mapmenu(currmenu);
cdeaefaa 1070 copypixmaps(currmenu);
a7732690 1071 break;
1072 case ButtonRelease:
257e42cc 1073 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1074 item = getitem(menu, ev.xbutton.y);
fd530f3f 1075 if (menu == NULL || item == NULL)
858338d9 1076 break;
fd530f3f 1077selectitem:
1078 if (item->label == NULL)
1079 break; /* ignore separators */
1080 if (item->submenu != NULL) {
257e42cc 1081 currmenu = item->submenu;
a7732690 1082 } else {
fd530f3f 1083 printf("%s\n", item->output);
08f16589 1084 return;
a7732690 1085 }
257e42cc 1086 mapmenu(currmenu);
fd530f3f 1087 currmenu->selected = currmenu->list;
cdeaefaa 1088 copypixmaps(currmenu);
fd530f3f 1089 break;
858338d9 1090 case ButtonPress:
257e42cc 1091 menu = getmenu(currmenu, ev.xbutton.window);
0c1a7864 1092 if (menu == NULL)
858338d9 1093 return;
1094 break;
1095 case KeyPress:
1096 ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
1097
0c1a7864 1098 /* esc closes xmenu when current menu is the root menu */
257e42cc 1099 if (ksym == XK_Escape && currmenu->parent == NULL)
858338d9 1100 return;
1101
1102 /* Shift-Tab = ISO_Left_Tab */
1103 if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
1104 ksym = XK_ISO_Left_Tab;
1105
1106 /* cycle through menu */
1107 item = NULL;
1108 if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
257e42cc 1109 item = itemcycle(currmenu, ITEMPREV);
858338d9 1110 } else if (ksym == XK_Tab || ksym == XK_Down) {
257e42cc 1111 item = itemcycle(currmenu, ITEMNEXT);
858338d9 1112 } else if ((ksym == XK_Return || ksym == XK_Right) &&
1113 currmenu->selected != NULL) {
1114 item = currmenu->selected;
1115 goto selectitem;
1116 } else if ((ksym == XK_Escape || ksym == XK_Left) &&
1117 currmenu->parent != NULL) {
1118 item = currmenu->parent->selected;
257e42cc 1119 currmenu = currmenu->parent;
1120 mapmenu(currmenu);
858338d9 1121 } else
1122 break;
1123 currmenu->selected = item;
cdeaefaa 1124 copypixmaps(currmenu);
a7732690 1125 break;
f15fc339 1126 case LeaveNotify:
fd530f3f 1127 previtem = NULL;
f15fc339 1128 currmenu->selected = NULL;
cdeaefaa 1129 copypixmaps(currmenu);
f15fc339 1130 break;
3bec05ea 1131 case ConfigureNotify:
1132 menu = getmenu(currmenu, ev.xconfigure.window);
1133 if (menu == NULL)
1134 break;
1135 menu->x = ev.xconfigure.x;
1136 menu->y = ev.xconfigure.y;
1137 break;
1138 case ClientMessage:
8902c43b 1139 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
1140 break;
3bec05ea 1141 /* user closed window */
1142 menu = getmenu(currmenu, ev.xclient.window);
1143 if (menu->parent == NULL)
1144 return; /* closing the root menu closes the program */
1145 currmenu = menu->parent;
1146 mapmenu(currmenu);
1147 break;
a7732690 1148 }
1149 }
1150}
1151
fd530f3f 1152/* recursivelly free pixmaps and destroy windows */
f15fc339 1153static void
8902c43b 1154cleanmenu(struct Menu *menu)
f15fc339 1155{
1156 struct Item *item;
ec4ed1ac 1157 struct Item *tmp;
f15fc339 1158
ec4ed1ac 1159 item = menu->list;
1160 while (item != NULL) {
f15fc339 1161 if (item->submenu != NULL)
8902c43b 1162 cleanmenu(item->submenu);
ec4ed1ac 1163 tmp = item;
cdeaefaa 1164 XFreePixmap(dpy, item->unsel);
1165 if (tmp->label != NULL)
1166 XFreePixmap(dpy, item->sel);
15dfafdf 1167 if (tmp->label != tmp->output)
1168 free(tmp->label);
6b5123e7 1169 free(tmp->output);
33376f54 1170 if (tmp->file != NULL) {
1171 free(tmp->file);
3bec05ea 1172 if (tmp->icon != NULL) {
1173 imlib_context_set_image(tmp->icon);
33376f54 1174 imlib_free_image();
1175 }
1176 }
1177 item = item->next;
ec4ed1ac 1178 free(tmp);
1179 }
f15fc339 1180
f15fc339 1181 XDestroyWindow(dpy, menu->win);
ec4ed1ac 1182 free(menu);
f15fc339 1183}
1184
8902c43b 1185/* cleanup X and exit */
a7732690 1186static void
15dfafdf 1187cleanup(void)
a7732690 1188{
257e42cc 1189 XUngrabPointer(dpy, CurrentTime);
1190 XUngrabKeyboard(dpy, CurrentTime);
1191
dbeb9940 1192 XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
1193 XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
1194 XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
1195 XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
fd530f3f 1196 XftColorFree(dpy, visual, colormap, &dc.separator);
1197 XftColorFree(dpy, visual, colormap, &dc.border);
dbeb9940 1198
f15fc339 1199 XFreeGC(dpy, dc.gc);
a7732690 1200 XCloseDisplay(dpy);
a7732690 1201}
1202
1203/* show usage */
1204static void
1205usage(void)
1206{
05cfe1a0 1207 (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
a7732690 1208 exit(1);
1209}