A mirror of phillbush's xmenu.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 

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