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