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