A mirror of phillbush's xmenu.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

1277 lines
33 KiB

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