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