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