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