Adding the -p option.
[xmenu] / xmenu.c
... / ...
CommitLineData
1#include <err.h>
2#include <errno.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6#include <limits.h>
7#include <time.h>
8#include <unistd.h>
9#include <X11/Xlib.h>
10#include <X11/Xatom.h>
11#include <X11/Xutil.h>
12#include <X11/Xresource.h>
13#include <X11/XKBlib.h>
14#include <X11/Xft/Xft.h>
15#include <Imlib2.h>
16#include "xmenu.h"
17
18/*
19 * Function declarations
20 */
21
22/* argument parser */
23static void parseposition(const char *optarg);
24
25/* initializers, and their helper routines */
26static void ealloccolor(const char *s, XftColor *color);
27static void initresources(void);
28static void initdc(void);
29static void initconfig(void);
30static void initatoms(void);
31
32/* structure builders, and their helper routines */
33static struct Item *allocitem(const char *label, const char *output, char *file);
34static struct Menu *allocmenu(struct Menu *parent, struct Item *list, unsigned level);
35static struct Menu *buildmenutree(unsigned level, const char *label, const char *output, char *file);
36static struct Menu *parsestdin(void);
37
38/* image loader */
39static Imlib_Image loadicon(const char *file);
40
41/* structure setters, and their helper routines */
42static void setupitems(struct Menu *menu);
43static void setupmenupos(struct Menu *menu);
44static void setupmenu(struct Menu *menu, XClassHint *classh);
45
46/* grabbers */
47static void grabpointer(void);
48static void grabkeyboard(void);
49
50/* window drawers and mappers */
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);
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);
59static struct Item *itemcycle(struct Menu *currmenu, int direction);
60static void run(struct Menu *currmenu);
61
62/* cleaners */
63static void cleanmenu(struct Menu *menu);
64static void cleanup(void);
65
66/* show usage */
67static void usage(void);
68
69
70/*
71 * Variable declarations
72 */
73
74/* X stuff */
75static Display *dpy;
76static int screen;
77static Visual *visual;
78static Window rootwin;
79static Colormap colormap;
80static struct DC dc;
81static Atom utf8string;
82static Atom wmdelete;
83static Atom netatom[NetLast];
84
85/* flags */
86static int iflag = 0; /* whether to disable icons */
87static int pflag = 0; /* whether the user specified a position */
88static int wflag = 0; /* whether to let the window manager control XMenu */
89
90/* include config variable */
91#include "config.h"
92
93
94/*
95 * Function implementations
96 */
97
98/* xmenu: generate menu from stdin and print selected entry to stdout */
99int
100main(int argc, char *argv[])
101{
102 struct Menu *rootmenu;
103 XClassHint classh;
104 int ch;
105
106 while ((ch = getopt(argc, argv, "ip:w")) != -1) {
107 switch (ch) {
108 case 'i':
109 iflag = 1;
110 break;
111 case 'p':
112 pflag = 1;
113 parseposition(optarg);
114 printf("%dx%d\n", config.posx, config.posy);
115 break;
116 case 'w':
117 wflag = 1;
118 break;
119 default:
120 usage();
121 break;
122 }
123 }
124 argc -= optind;
125 argv += optind;
126
127 if (argc > 1)
128 usage();
129
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);
134 visual = DefaultVisual(dpy, screen);
135 rootwin = RootWindow(dpy, screen);
136 colormap = DefaultColormap(dpy, screen);
137
138 /* imlib2 stuff */
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 }
146
147 /* initializers */
148 initresources();
149 initdc();
150 initconfig();
151 initatoms();
152
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
160 /* generate menus and set them up */
161 rootmenu = parsestdin();
162 if (rootmenu == NULL)
163 errx(1, "no menu generated");
164 setupmenu(rootmenu, &classh);
165
166 /* grab mouse and keyboard */
167 if (!wflag) {
168 grabpointer();
169 grabkeyboard();
170 }
171
172 /* run event loop */
173 run(rootmenu);
174
175 /* freeing stuff */
176 cleanmenu(rootmenu);
177 cleanup();
178
179 return 0;
180}
181
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
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
214/* read xrdb for configuration options */
215static void
216initresources(void)
217{
218 char *xrm;
219 long n;
220 char *type;
221 XrmDatabase xdb;
222 XrmValue xval;
223
224 XrmInitialize();
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)
232 config.border_pixels = n;
233 if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
234 if ((n = strtol(xval.addr, NULL, 10)) > 0)
235 config.separator_pixels = n;
236 if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
237 if ((n = strtol(xval.addr, NULL, 10)) > 0)
238 config.height_pixels = n;
239 if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
240 if ((n = strtol(xval.addr, NULL, 10)) > 0)
241 config.width_pixels = n;
242 if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
243 if ((n = strtol(xval.addr, NULL, 10)) > 0)
244 config.gap_pixels = n;
245 if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
246 config.background_color = strdup(xval.addr);
247 if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
248 config.foreground_color = strdup(xval.addr);
249 if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
250 config.selbackground_color = strdup(xval.addr);
251 if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
252 config.selforeground_color = strdup(xval.addr);
253 if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
254 config.separator_color = strdup(xval.addr);
255 if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
256 config.border_color = strdup(xval.addr);
257 if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
258 config.font = strdup(xval.addr);
259
260 XrmDestroyDatabase(xdb);
261}
262
263/* init draw context */
264static void
265initdc(void)
266{
267 /* get color pixels */
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);
274
275 /* try to get font */
276 if ((dc.font = XftFontOpenName(dpy, screen, config.font)) == NULL)
277 errx(1, "cannot load font");
278
279 /* create common GC */
280 dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
281}
282
283/* calculate configuration values that are not set manually */
284static void
285initconfig(void)
286{
287 Window dw; /* dummy variable */
288 int di; /* dummy variable */
289 unsigned du; /* dummy variable */
290
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);
293 config.screenw = DisplayWidth(dpy, screen);
294 config.screenh = DisplayHeight(dpy, screen);
295 config.iconsize = config.height_pixels - config.iconpadding * 2;
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);
307}
308
309/* allocate an item */
310static struct Item *
311allocitem(const char *label, const char *output, char *file)
312{
313 struct Item *item;
314
315 if ((item = malloc(sizeof *item)) == NULL)
316 err(1, "malloc");
317 if (label == NULL) {
318 item->label = NULL;
319 item->output = NULL;
320 } else {
321 if ((item->label = strdup(label)) == NULL)
322 err(1, "strdup");
323 if (label == output) {
324 item->output = item->label;
325 } else {
326 if ((item->output = strdup(output)) == NULL)
327 err(1, "strdup");
328 }
329 }
330 if (file == NULL) {
331 item->file = NULL;
332 } else {
333 if ((item->file = strdup(file)) == NULL)
334 err(1, "strdup");
335 }
336 item->y = 0;
337 item->h = 0;
338 if (item->label == NULL)
339 item->labellen = 0;
340 else
341 item->labellen = strlen(item->label);
342 item->next = NULL;
343 item->submenu = NULL;
344 item->icon = NULL;
345
346 return item;
347}
348
349/* allocate a menu and create its window */
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;
360 menu->caller = NULL;
361 menu->selected = NULL;
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() */
366 menu->level = level;
367
368 swa.override_redirect = (wflag) ? False : True;
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*/
372 swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
373 | PointerMotionMask | LeaveWindowMask;
374 if (wflag)
375 swa.event_mask |= StructureNotifyMask;
376 menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
377 CopyFromParent, CopyFromParent, CopyFromParent,
378 CWOverrideRedirect | CWBackPixel |
379 CWBorderPixel | CWEventMask | CWSaveUnder,
380 &swa);
381
382 return menu;
383}
384
385/* build the menu tree */
386static struct Menu *
387buildmenutree(unsigned level, const char *label, const char *output, char *file)
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 */
397 curritem = allocitem(label, output, file);
398
399 /* put the item in the menu tree */
400 if (prevmenu == NULL) { /* there is no menu yet */
401 menu = allocmenu(NULL, curritem, level);
402 rootmenu = menu;
403 prevmenu = menu;
404 curritem->prev = NULL;
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
444/* create menus and items from the stdin */
445static struct Menu *
446parsestdin(void)
447{
448 struct Menu *rootmenu;
449 char *s, buf[BUFSIZ];
450 char *file, *label, *output;
451 unsigned level = 0;
452
453 rootmenu = NULL;
454
455 while (fgets(buf, BUFSIZ, stdin) != NULL) {
456 /* get the indentation level */
457 level = strspn(buf, "\t");
458
459 /* get the label */
460 s = level + buf;
461 label = strtok(s, "\t\n");
462
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
470 /* get the output */
471 output = strtok(NULL, "\n");
472 if (output == NULL) {
473 output = label;
474 } else {
475 while (*output == '\t')
476 output++;
477 }
478
479 rootmenu = buildmenutree(level, label, output, file);
480 }
481
482 return rootmenu;
483}
484
485/* load and scale icon */
486static Imlib_Image
487loadicon(const char *file)
488{
489 Imlib_Image icon;
490 int width;
491 int height;
492 int imgsize;
493
494 icon = imlib_load_image(file);
495 if (icon == NULL)
496 errx(1, "cannot load icon %s", file);
497
498 imlib_context_set_image(icon);
499
500 width = imlib_image_get_width();
501 height = imlib_image_get_height();
502 imgsize = MIN(width, height);
503
504 icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
505 config.iconsize,
506 config.iconsize);
507
508 return icon;
509}
510
511/* setup the height, width and icon of the items of a menu */
512static void
513setupitems(struct Menu *menu)
514{
515 XGlyphInfo ext;
516 struct Item *item;
517 int itemwidth;
518
519 menu->w = config.width_pixels;
520 for (item = menu->list; item != NULL; item = item->next) {
521 item->y = menu->h;
522
523 if (item->label == NULL) /* height for separator item */
524 item->h = config.separator_pixels;
525 else
526 item->h = config.height_pixels;
527 menu->h += item->h;
528
529 /* get length of item->label rendered in the font */
530 XftTextExtentsUtf8(dpy, dc.font, (XftChar8 *)item->label,
531 item->labellen, &ext);
532
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);
548
549 /* create icon */
550 if (item->file != NULL && !iflag)
551 item->icon = loadicon(item->file);
552 }
553}
554
555/* setup the position of a menu */
556static void
557setupmenupos(struct Menu *menu)
558{
559 int width, height;
560
561 width = menu->w + config.border_pixels * 2;
562 height = menu->h + config.border_pixels * 2;
563 if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
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;
568
569 if (pflag || config.screenh - config.posy >= height)
570 menu->y = config.posy;
571 else if (config.screenh > height)
572 menu->y = config.screenh - height;
573 } else { /* else, calculate in respect to parent menu */
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;
578
579 if (config.screenh - (menu->caller->y + menu->parent->y) > height)
580 menu->y = menu->caller->y + menu->parent->y;
581 else if (config.screenh - menu->parent->y > height)
582 menu->y = menu->parent->y;
583 else if (config.screenh > height)
584 menu->y = config.screenh - height;
585 }
586}
587
588/* recursivelly setup menu configuration and its pixmap */
589static void
590setupmenu(struct Menu *menu, XClassHint *classh)
591{
592 char *title;
593 struct Item *item;
594 XWindowChanges changes;
595 XSizeHints sizeh;
596 XTextProperty wintitle;
597
598 /* setup size and position of menus */
599 setupitems(menu);
600 setupmenupos(menu);
601
602 /* update menu geometry */
603 changes.border_width = config.border_pixels;
604 changes.height = menu->h;
605 changes.width = menu->w;
606 changes.x = menu->x;
607 changes.y = menu->y;
608 XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
609
610 /* set window title (used if wflag is on) */
611 if (menu->parent == NULL) {
612 title = classh->res_name;
613 } else {
614 title = menu->caller->output;
615 }
616 XStringListToTextProperty(&title, 1, &wintitle);
617
618 /* set window manager hints */
619 sizeh.flags = PMaxSize | PMinSize;
620 sizeh.min_width = sizeh.max_width = menu->w;
621 sizeh.min_height = sizeh.max_height = menu->h;
622 XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
623
624 /* create pixmap and XftDraw */
625 menu->pixmap = XCreatePixmap(dpy, menu->win, menu->w, menu->h,
626 DefaultDepth(dpy, screen));
627 menu->draw = XftDrawCreate(dpy, menu->pixmap, visual, colormap);
628
629 /* set WM protocols and ewmh window properties */
630 XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
631 XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
632 PropModeReplace, (unsigned char *)title, strlen(title));
633 XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
634 PropModeReplace,
635 (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
636
637 /* calculate positions of submenus */
638 for (item = menu->list; item != NULL; item = item->next) {
639 if (item->submenu != NULL)
640 setupmenu(item->submenu, classh);
641 }
642}
643
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
677/* umap previous menus and map current menu and its parents */
678static void
679mapmenu(struct Menu *currmenu)
680{
681 static struct Menu *prevmenu = NULL;
682 struct Menu *menu, *menu_;
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 */
686
687 /* do not remap current menu if it wasn't updated*/
688 if (prevmenu == currmenu)
689 return;
690
691 /* if this is the first time mapping, skip calculations */
692 if (prevmenu == NULL) {
693 XMapWindow(dpy, currmenu->win);
694 prevmenu = currmenu;
695 return;
696 }
697
698 /* find lowest common ancestor menu */
699 minlevel = MIN(currmenu->level, prevmenu->level);
700 maxlevel = MAX(currmenu->level, prevmenu->level);
701 if (currmenu->level == maxlevel) {
702 menu = currmenu;
703 menu_ = prevmenu;
704 } else {
705 menu = prevmenu;
706 menu_ = currmenu;
707 }
708 while (menu->level > minlevel)
709 menu = menu->parent;
710 while (menu != menu_) {
711 menu = menu->parent;
712 menu_ = menu_->parent;
713 }
714 lcamenu = menu;
715
716 /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
717 for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
718 menu->selected = NULL;
719 XUnmapWindow(dpy, menu->win);
720 }
721
722 /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
723 for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
724
725 if (wflag) {
726 setupmenupos(menu);
727 XMoveWindow(dpy, menu->win, menu->x, menu->y);
728 }
729
730 XMapWindow(dpy, menu->win);
731 }
732
733 prevmenu = currmenu;
734}
735
736/* draw separator item */
737static void
738drawseparator(struct Menu *menu, struct Item *item)
739{
740 int y;
741
742 y = item->y + item->h/2;
743
744 XSetForeground(dpy, dc.gc, dc.separator.pixel);
745 XDrawLine(dpy, menu->pixmap, dc.gc, config.horzpadding, y,
746 menu->w - config.horzpadding, y);
747}
748
749/* draw regular item */
750static void
751drawitem(struct Menu *menu, struct Item *item, XftColor *color)
752{
753 int x, y;
754
755 x = config.horzpadding;
756 x += (iflag) ? 0 : config.horzpadding + config.iconsize;
757 y = item->y + (item->h + dc.font->ascent) / 2;
758 XSetForeground(dpy, dc.gc, color[ColorFG].pixel);
759 XftDrawStringUtf8(menu->draw, &color[ColorFG], dc.font,
760 x, y, (XftChar8 *)item->label, item->labellen);
761
762 /* draw triangle, if item contains a submenu */
763 if (item->submenu != NULL) {
764 x = menu->w - config.triangle_width - config.horzpadding;
765 y = item->y + (item->h - config.triangle_height + 1) / 2;
766
767 XPoint triangle[] = {
768 {x, y},
769 {x + config.triangle_width, y + config.triangle_height/2},
770 {x, y + config.triangle_height},
771 {x, y}
772 };
773
774 XFillPolygon(dpy, menu->pixmap, dc.gc, triangle, LEN(triangle),
775 Convex, CoordModeOrigin);
776 }
777
778 /* draw icon */
779 if (item->icon != NULL) {
780 x = config.horzpadding;
781 y = item->y + config.iconpadding;
782 imlib_context_set_drawable(menu->pixmap);
783 imlib_context_set_image(item->icon);
784 imlib_render_image_on_drawable(x, y);
785 }
786}
787
788/* draw items of the current menu and of its ancestors */
789static void
790drawmenu(struct Menu *currmenu)
791{
792 struct Menu *menu;
793 struct Item *item;
794
795 for (menu = currmenu; menu != NULL; menu = menu->parent) {
796 for (item = menu->list; item != NULL; item = item->next) {
797 XftColor *color;
798
799 /* determine item color */
800 if (item == menu->selected && item->label != NULL)
801 color = dc.selected;
802 else
803 color = dc.normal;
804
805 /* draw item box */
806 XSetForeground(dpy, dc.gc, color[ColorBG].pixel);
807 XFillRectangle(dpy, menu->pixmap, dc.gc, 0, item->y,
808 menu->w, item->h);
809
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);
814 }
815
816 XCopyArea(dpy, menu->pixmap, menu->win, dc.gc, 0, 0,
817 menu->w, menu->h, 0, 0);
818 }
819}
820
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
850/* cycle through the items; non-zero direction is next, zero is prev */
851static struct Item *
852itemcycle(struct Menu *currmenu, int direction)
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
891/* run event loop */
892static void
893run(struct Menu *currmenu)
894{
895 struct Menu *menu;
896 struct Item *item;
897 struct Item *previtem = NULL;
898 KeySym ksym;
899 XEvent ev;
900
901 mapmenu(currmenu);
902
903 while (!XNextEvent(dpy, &ev)) {
904 switch(ev.type) {
905 case Expose:
906 if (ev.xexpose.count == 0)
907 drawmenu(currmenu);
908 break;
909 case MotionNotify:
910 menu = getmenu(currmenu, ev.xbutton.window);
911 item = getitem(menu, ev.xbutton.y);
912 if (menu == NULL || item == NULL || previtem == item)
913 break;
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;
921 }
922 mapmenu(currmenu);
923 drawmenu(currmenu);
924 break;
925 case ButtonRelease:
926 menu = getmenu(currmenu, ev.xbutton.window);
927 item = getitem(menu, ev.xbutton.y);
928 if (menu == NULL || item == NULL)
929 break;
930selectitem:
931 if (item->label == NULL)
932 break; /* ignore separators */
933 if (item->submenu != NULL) {
934 currmenu = item->submenu;
935 } else {
936 printf("%s\n", item->output);
937 return;
938 }
939 mapmenu(currmenu);
940 currmenu->selected = currmenu->list;
941 drawmenu(currmenu);
942 break;
943 case ButtonPress:
944 menu = getmenu(currmenu, ev.xbutton.window);
945 if (menu == NULL)
946 return;
947 break;
948 case KeyPress:
949 ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
950
951 /* esc closes xmenu when current menu is the root menu */
952 if (ksym == XK_Escape && currmenu->parent == NULL)
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) {
962 item = itemcycle(currmenu, ITEMPREV);
963 } else if (ksym == XK_Tab || ksym == XK_Down) {
964 item = itemcycle(currmenu, ITEMNEXT);
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;
972 currmenu = currmenu->parent;
973 mapmenu(currmenu);
974 } else
975 break;
976 currmenu->selected = item;
977 drawmenu(currmenu);
978 break;
979 case LeaveNotify:
980 previtem = NULL;
981 currmenu->selected = NULL;
982 drawmenu(currmenu);
983 break;
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:
992 if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
993 break;
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;
1001 }
1002 }
1003}
1004
1005/* recursivelly free pixmaps and destroy windows */
1006static void
1007cleanmenu(struct Menu *menu)
1008{
1009 struct Item *item;
1010 struct Item *tmp;
1011
1012 item = menu->list;
1013 while (item != NULL) {
1014 if (item->submenu != NULL)
1015 cleanmenu(item->submenu);
1016 tmp = item;
1017 if (tmp->label != tmp->output)
1018 free(tmp->label);
1019 free(tmp->output);
1020 if (tmp->file != NULL) {
1021 free(tmp->file);
1022 if (tmp->icon != NULL) {
1023 imlib_context_set_image(tmp->icon);
1024 imlib_free_image();
1025 }
1026 }
1027 item = item->next;
1028 free(tmp);
1029 }
1030
1031 XFreePixmap(dpy, menu->pixmap);
1032 XftDrawDestroy(menu->draw);
1033 XDestroyWindow(dpy, menu->win);
1034 free(menu);
1035}
1036
1037/* cleanup X and exit */
1038static void
1039cleanup(void)
1040{
1041 XUngrabPointer(dpy, CurrentTime);
1042 XUngrabKeyboard(dpy, CurrentTime);
1043
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]);
1048 XftColorFree(dpy, visual, colormap, &dc.separator);
1049 XftColorFree(dpy, visual, colormap, &dc.border);
1050
1051 XFreeGC(dpy, dc.gc);
1052 XCloseDisplay(dpy);
1053}
1054
1055/* show usage */
1056static void
1057usage(void)
1058{
1059 (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
1060 exit(1);
1061}