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