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