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