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. /* text drawer, and its helper routine */
  36. static FcChar32 getnextutf8char(const char *s, const char **end_ret);
  37. static int drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text);
  38. /* structure setters, and their helper routines */
  39. static void setupitems(struct Menu *menu);
  40. static void setupmenupos(struct Menu *menu);
  41. static void setupmenu(struct Menu *menu, XClassHint *classh);
  42. /* grabbers */
  43. static void grabpointer(void);
  44. static void grabkeyboard(void);
  45. /* item drawer, and its helper routine */
  46. static Imlib_Image loadicon(const char *file);
  47. static void drawitems(struct Menu *menu);
  48. /* menu drawers and mappers */
  49. static void drawmenus(struct Menu *currmenu);
  50. static void mapmenu(struct Menu *currmenu);
  51. /* getters */
  52. static struct Menu *getmenu(struct Menu *currmenu, Window win);
  53. static struct Item *getitem(struct Menu *menu, int y);
  54. /* cycle through items */
  55. static struct Item *itemcycle(struct Menu *currmenu, int direction);
  56. /* main event loop */
  57. static void run(struct Menu *currmenu);
  58. /* cleaners */
  59. static void cleanmenu(struct Menu *menu);
  60. static void cleanup(void);
  61. /* show usage */
  62. static void usage(void);
  63. /*
  64. * Variable declarations
  65. */
  66. /* X stuff */
  67. static Display *dpy;
  68. static int screen;
  69. static Visual *visual;
  70. static Window rootwin;
  71. static Colormap colormap;
  72. static struct DC dc;
  73. static Atom utf8string;
  74. static Atom wmdelete;
  75. static Atom netatom[NetLast];
  76. /* flags */
  77. static int iflag = 0; /* whether to disable icons */
  78. static int pflag = 0; /* whether the user specified a position */
  79. static int wflag = 0; /* whether to let the window manager control XMenu */
  80. /* include config variable */
  81. #include "config.h"
  82. /*
  83. * Function implementations
  84. */
  85. /* xmenu: generate menu from stdin and print selected entry to stdout */
  86. int
  87. main(int argc, char *argv[])
  88. {
  89. struct Menu *rootmenu;
  90. XClassHint classh;
  91. int ch;
  92. while ((ch = getopt(argc, argv, "ip:w")) != -1) {
  93. switch (ch) {
  94. case 'i':
  95. iflag = 1;
  96. break;
  97. case 'p':
  98. pflag = 1;
  99. parseposition(optarg);
  100. break;
  101. case 'w':
  102. wflag = 1;
  103. break;
  104. default:
  105. usage();
  106. break;
  107. }
  108. }
  109. argc -= optind;
  110. argv += optind;
  111. if (argc > 1)
  112. usage();
  113. /* open connection to server and set X variables */
  114. if ((dpy = XOpenDisplay(NULL)) == NULL)
  115. errx(1, "cannot open display");
  116. screen = DefaultScreen(dpy);
  117. visual = DefaultVisual(dpy, screen);
  118. rootwin = RootWindow(dpy, screen);
  119. colormap = DefaultColormap(dpy, screen);
  120. /* imlib2 stuff */
  121. if (!iflag) {
  122. imlib_set_cache_size(2048 * 1024);
  123. imlib_context_set_dither(1);
  124. imlib_context_set_display(dpy);
  125. imlib_context_set_visual(visual);
  126. imlib_context_set_colormap(colormap);
  127. }
  128. /* initializers */
  129. initresources();
  130. initdc();
  131. initconfig();
  132. initatoms();
  133. /* set window class */
  134. classh.res_class = PROGNAME;
  135. if (argc == 1)
  136. classh.res_name = *argv;
  137. else
  138. classh.res_name = PROGNAME;
  139. /* generate menus and set them up */
  140. rootmenu = parsestdin();
  141. if (rootmenu == NULL)
  142. errx(1, "no menu generated");
  143. setupmenu(rootmenu, &classh);
  144. /* grab mouse and keyboard */
  145. if (!wflag) {
  146. grabpointer();
  147. grabkeyboard();
  148. }
  149. /* run event loop */
  150. run(rootmenu);
  151. /* freeing stuff */
  152. cleanmenu(rootmenu);
  153. cleanup();
  154. return 0;
  155. }
  156. /* parse position string from -p, put results on config.x and config.y */
  157. static void
  158. parseposition(const char *optarg)
  159. {
  160. long n;
  161. const char *s = optarg;
  162. char *endp;
  163. n = strtol(s, &endp, 10);
  164. if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
  165. goto error;
  166. config.posx = n;
  167. s = endp+1;
  168. n = strtol(s, &endp, 10);
  169. if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
  170. goto error;
  171. config.posy = n;
  172. return;
  173. error:
  174. errx(1, "improper position: %s", optarg);
  175. }
  176. /* parse color string */
  177. static void
  178. parsefonts(const char *s)
  179. {
  180. const char *p;
  181. char buf[1024];
  182. size_t nfont = 0;
  183. dc.nfonts = 1;
  184. for (p = s; *p; p++)
  185. if (*p == ',')
  186. dc.nfonts++;
  187. if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
  188. err(1, "calloc");
  189. p = s;
  190. while (*p != '\0') {
  191. size_t i;
  192. i = 0;
  193. while (isspace(*p))
  194. p++;
  195. while (*p != '\0' && *p != ',') {
  196. buf[i++] = *p++;
  197. }
  198. if (*p == ',')
  199. p++;
  200. buf[i] = '\0';
  201. if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
  202. errx(1, "cannot load font");
  203. }
  204. }
  205. /* get color from color string */
  206. static void
  207. ealloccolor(const char *s, XftColor *color)
  208. {
  209. if(!XftColorAllocName(dpy, visual, colormap, s, color))
  210. errx(1, "cannot allocate color: %s", s);
  211. }
  212. /* read xrdb for configuration options */
  213. static void
  214. initresources(void)
  215. {
  216. char *xrm;
  217. long n;
  218. char *type;
  219. XrmDatabase xdb;
  220. XrmValue xval;
  221. XrmInitialize();
  222. if ((xrm = XResourceManagerString(dpy)) == NULL)
  223. return;
  224. xdb = XrmGetStringDatabase(xrm);
  225. if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
  226. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  227. config.border_pixels = n;
  228. if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
  229. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  230. config.separator_pixels = n;
  231. if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
  232. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  233. config.height_pixels = n;
  234. if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
  235. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  236. config.width_pixels = n;
  237. if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
  238. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  239. config.gap_pixels = n;
  240. if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
  241. config.background_color = strdup(xval.addr);
  242. if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
  243. config.foreground_color = strdup(xval.addr);
  244. if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
  245. config.selbackground_color = strdup(xval.addr);
  246. if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
  247. config.selforeground_color = strdup(xval.addr);
  248. if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
  249. config.separator_color = strdup(xval.addr);
  250. if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
  251. config.border_color = strdup(xval.addr);
  252. if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
  253. config.font = strdup(xval.addr);
  254. XrmDestroyDatabase(xdb);
  255. }
  256. /* init draw context */
  257. static void
  258. initdc(void)
  259. {
  260. /* get color pixels */
  261. ealloccolor(config.background_color, &dc.normal[ColorBG]);
  262. ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
  263. ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
  264. ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
  265. ealloccolor(config.separator_color, &dc.separator);
  266. ealloccolor(config.border_color, &dc.border);
  267. /* parse fonts */
  268. parsefonts(config.font);
  269. /* create common GC */
  270. dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
  271. }
  272. /* calculate configuration values that are not set manually */
  273. static void
  274. initconfig(void)
  275. {
  276. Window dw; /* dummy variable */
  277. int di; /* dummy variable */
  278. unsigned du; /* dummy variable */
  279. if (!pflag) /* if the user haven't specified a position, use cursor position*/
  280. XQueryPointer(dpy, rootwin, &dw, &dw, &config.posx, &config.posy, &di, &di, &du);
  281. config.screenw = DisplayWidth(dpy, screen);
  282. config.screenh = DisplayHeight(dpy, screen);
  283. config.iconsize = config.height_pixels - config.iconpadding * 2;
  284. }
  285. /* intern atoms */
  286. static void
  287. initatoms(void)
  288. {
  289. utf8string = XInternAtom(dpy, "UTF8_STRING", False);
  290. wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  291. netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
  292. netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
  293. netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
  294. }
  295. /* allocate an item */
  296. static struct Item *
  297. allocitem(const char *label, const char *output, char *file)
  298. {
  299. struct Item *item;
  300. if ((item = malloc(sizeof *item)) == NULL)
  301. err(1, "malloc");
  302. if (label == NULL) {
  303. item->label = NULL;
  304. item->output = NULL;
  305. } else {
  306. if ((item->label = strdup(label)) == NULL)
  307. err(1, "strdup");
  308. if (label == output) {
  309. item->output = item->label;
  310. } else {
  311. if ((item->output = strdup(output)) == NULL)
  312. err(1, "strdup");
  313. }
  314. }
  315. if (file == NULL) {
  316. item->file = NULL;
  317. } else {
  318. if ((item->file = strdup(file)) == NULL)
  319. err(1, "strdup");
  320. }
  321. item->y = 0;
  322. item->h = 0;
  323. if (item->label == NULL)
  324. item->labellen = 0;
  325. else
  326. item->labellen = strlen(item->label);
  327. item->next = NULL;
  328. item->submenu = NULL;
  329. item->icon = NULL;
  330. return item;
  331. }
  332. /* allocate a menu and create its window */
  333. static struct Menu *
  334. allocmenu(struct Menu *parent, struct Item *list, unsigned level)
  335. {
  336. XSetWindowAttributes swa;
  337. struct Menu *menu;
  338. if ((menu = malloc(sizeof *menu)) == NULL)
  339. err(1, "malloc");
  340. menu->parent = parent;
  341. menu->list = list;
  342. menu->caller = NULL;
  343. menu->selected = NULL;
  344. menu->w = 0; /* calculated by setupmenu() */
  345. menu->h = 0; /* calculated by setupmenu() */
  346. menu->x = 0; /* calculated by setupmenu() */
  347. menu->y = 0; /* calculated by setupmenu() */
  348. menu->level = level;
  349. menu->drawn = 0;
  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. /* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
  449. static FcChar32
  450. getnextutf8char(const char *s, const char **next_ret)
  451. {
  452. static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
  453. static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
  454. static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
  455. static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
  456. /* 0xFFFD is the replacement character, used to represent unknown characters */
  457. static const FcChar32 unknown = 0xFFFD;
  458. FcChar32 ucode; /* FcChar32 type holds 32 bits */
  459. size_t usize = 0; /* n' of bytes of the utf8 character */
  460. size_t i;
  461. *next_ret = s+1;
  462. /* get code of first byte of utf8 character */
  463. for (i = 0; i < sizeof utfmask; i++) {
  464. if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
  465. usize = i;
  466. ucode = (unsigned char)*s & ~utfmask[i];
  467. break;
  468. }
  469. }
  470. /* if first byte is a continuation byte or is not allowed, return unknown */
  471. if (i == sizeof utfmask || usize == 0)
  472. return unknown;
  473. /* check the other usize-1 bytes */
  474. s++;
  475. for (i = 1; i < usize; i++) {
  476. *next_ret = s+1;
  477. /* if byte is EOS or is not a continuation byte, return unknown */
  478. if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
  479. return unknown;
  480. /* 6 is the number of relevant bits in the continuation byte */
  481. ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
  482. s++;
  483. }
  484. /* check if ucode is invalid or in utf-16 surrogate halves */
  485. if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
  486. || BETWEEN (ucode, 0xD800, 0xDFFF))
  487. return unknown;
  488. return ucode;
  489. }
  490. /* draw text into XftDraw */
  491. static int
  492. drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
  493. {
  494. const char *s, *nexts;
  495. FcChar32 ucode;
  496. XftFont *currfont;
  497. int textlen = 0;
  498. s = text;
  499. while (*s) {
  500. XGlyphInfo ext;
  501. int charexists;
  502. size_t len;
  503. size_t i;
  504. charexists = 0;
  505. ucode = getnextutf8char(s, &nexts);
  506. for (i = 0; i < dc.nfonts; i++) {
  507. charexists = XftCharExists(dpy, dc.fonts[i], ucode);
  508. if (charexists)
  509. break;
  510. }
  511. if (charexists)
  512. currfont = dc.fonts[i];
  513. len = nexts - s;
  514. XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)s,
  515. len, &ext);
  516. textlen += ext.xOff;
  517. if (draw) {
  518. int texty;
  519. texty = y + (h + currfont->ascent) / 2;
  520. XftDrawStringUtf8(draw, color, currfont, x, texty,
  521. (XftChar8 *)s, len);
  522. x += ext.xOff;
  523. }
  524. s = nexts;
  525. }
  526. return textlen;
  527. }
  528. /* setup the height, width and icon of the items of a menu */
  529. static void
  530. setupitems(struct Menu *menu)
  531. {
  532. struct Item *item;
  533. menu->w = config.width_pixels;
  534. for (item = menu->list; item != NULL; item = item->next) {
  535. int itemwidth;
  536. int textwidth;
  537. item->y = menu->h;
  538. if (item->label == NULL) /* height for separator item */
  539. item->h = config.separator_pixels;
  540. else
  541. item->h = config.height_pixels;
  542. menu->h += item->h;
  543. if (item->label)
  544. textwidth = drawtext(NULL, NULL, 0, 0, item->h, item->label);
  545. else
  546. textwidth = 0;
  547. /*
  548. * set menu width
  549. *
  550. * the item width depends on the size of its label (textwidth),
  551. * and it is only used to calculate the width of the menu (which
  552. * is equal to the width of the largest item).
  553. *
  554. * the horizontal padding appears 4 times through the width of a
  555. * item: before and after its icon, and before and after its triangle.
  556. * if the iflag is set (icons are disabled) then the horizontal
  557. * padding appears 3 times: before the label and around the triangle.
  558. */
  559. itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
  560. itemwidth += (iflag) ? 0 : config.iconsize + config.horzpadding;
  561. menu->w = MAX(menu->w, itemwidth);
  562. }
  563. }
  564. /* setup the position of a menu */
  565. static void
  566. setupmenupos(struct Menu *menu)
  567. {
  568. int width, height;
  569. width = menu->w + config.border_pixels * 2;
  570. height = menu->h + config.border_pixels * 2;
  571. if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
  572. if (pflag || config.screenw - config.posx >= menu->w)
  573. menu->x = config.posx;
  574. else if (config.posx > width)
  575. menu->x = config.posx - width;
  576. if (pflag || config.screenh - config.posy >= height)
  577. menu->y = config.posy;
  578. else if (config.screenh > height)
  579. menu->y = config.screenh - height;
  580. } else { /* else, calculate in respect to parent menu */
  581. if (config.screenw - (menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels) >= width)
  582. menu->x = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
  583. else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
  584. menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
  585. if (config.screenh - (menu->caller->y + menu->parent->y) > height)
  586. menu->y = menu->caller->y + menu->parent->y;
  587. else if (config.screenh - menu->parent->y > height)
  588. menu->y = menu->parent->y;
  589. else if (config.screenh > height)
  590. menu->y = config.screenh - height;
  591. }
  592. }
  593. /* recursivelly setup menu configuration and its pixmap */
  594. static void
  595. setupmenu(struct Menu *menu, XClassHint *classh)
  596. {
  597. char *title;
  598. struct Item *item;
  599. XWindowChanges changes;
  600. XSizeHints sizeh;
  601. XTextProperty wintitle;
  602. /* setup size and position of menus */
  603. setupitems(menu);
  604. setupmenupos(menu);
  605. /* update menu geometry */
  606. changes.border_width = config.border_pixels;
  607. changes.height = menu->h;
  608. changes.width = menu->w;
  609. changes.x = menu->x;
  610. changes.y = menu->y;
  611. XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
  612. /* set window title (used if wflag is on) */
  613. if (menu->parent == NULL) {
  614. title = classh->res_name;
  615. } else {
  616. title = menu->caller->output;
  617. }
  618. XStringListToTextProperty(&title, 1, &wintitle);
  619. /* set window manager hints */
  620. sizeh.flags = PMaxSize | PMinSize;
  621. sizeh.min_width = sizeh.max_width = menu->w;
  622. sizeh.min_height = sizeh.max_height = menu->h;
  623. XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
  624. /* set WM protocols and ewmh window properties */
  625. XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
  626. XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
  627. PropModeReplace, (unsigned char *)title, strlen(title));
  628. XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
  629. PropModeReplace,
  630. (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
  631. /* calculate positions of submenus */
  632. for (item = menu->list; item != NULL; item = item->next) {
  633. if (item->submenu != NULL)
  634. setupmenu(item->submenu, classh);
  635. }
  636. }
  637. /* try to grab pointer, we may have to wait for another process to ungrab */
  638. static void
  639. grabpointer(void)
  640. {
  641. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  642. int i;
  643. for (i = 0; i < 1000; i++) {
  644. if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
  645. GrabModeAsync, GrabModeAsync, None,
  646. None, CurrentTime) == GrabSuccess)
  647. return;
  648. nanosleep(&ts, NULL);
  649. }
  650. errx(1, "cannot grab keyboard");
  651. }
  652. /* try to grab keyboard, we may have to wait for another process to ungrab */
  653. static void
  654. grabkeyboard(void)
  655. {
  656. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  657. int i;
  658. for (i = 0; i < 1000; i++) {
  659. if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
  660. GrabModeAsync, CurrentTime) == GrabSuccess)
  661. return;
  662. nanosleep(&ts, NULL);
  663. }
  664. errx(1, "cannot grab keyboard");
  665. }
  666. /* load and scale icon */
  667. static Imlib_Image
  668. loadicon(const char *file)
  669. {
  670. Imlib_Image icon;
  671. int width;
  672. int height;
  673. int imgsize;
  674. icon = imlib_load_image(file);
  675. if (icon == NULL)
  676. errx(1, "cannot load icon %s", file);
  677. imlib_context_set_image(icon);
  678. width = imlib_image_get_width();
  679. height = imlib_image_get_height();
  680. imgsize = MIN(width, height);
  681. icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
  682. config.iconsize,
  683. config.iconsize);
  684. return icon;
  685. }
  686. /* draw pixmap for the selected and unselected version of each item on menu */
  687. static void
  688. drawitems(struct Menu *menu)
  689. {
  690. struct Item *item;
  691. for (item = menu->list; item != NULL; item = item->next) {
  692. XftDraw *dsel, *dunsel;
  693. int x, y;
  694. item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  695. DefaultDepth(dpy, screen));
  696. XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
  697. XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
  698. if (item->label == NULL) { /* item is separator */
  699. y = item->h/2;
  700. XSetForeground(dpy, dc.gc, dc.separator.pixel);
  701. XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
  702. menu->w - config.horzpadding, y);
  703. item->sel = item->unsel;
  704. } else {
  705. item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  706. DefaultDepth(dpy, screen));
  707. XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
  708. XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
  709. /* draw text */
  710. x = config.horzpadding;
  711. x += (iflag) ? 0 : config.horzpadding + config.iconsize;
  712. dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
  713. dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
  714. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  715. drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
  716. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  717. drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
  718. XftDrawDestroy(dsel);
  719. XftDrawDestroy(dunsel);
  720. /* draw triangle */
  721. if (item->submenu != NULL) {
  722. x = menu->w - config.triangle_width - config.horzpadding;
  723. y = (item->h - config.triangle_height + 1) / 2;
  724. XPoint triangle[] = {
  725. {x, y},
  726. {x + config.triangle_width, y + config.triangle_height/2},
  727. {x, y + config.triangle_height},
  728. {x, y}
  729. };
  730. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  731. XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
  732. Convex, CoordModeOrigin);
  733. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  734. XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
  735. Convex, CoordModeOrigin);
  736. }
  737. /* draw icon */
  738. if (item->file != NULL && !iflag) {
  739. item->icon = loadicon(item->file);
  740. imlib_context_set_drawable(item->sel);
  741. imlib_context_set_image(item->icon);
  742. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  743. imlib_context_set_drawable(item->unsel);
  744. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  745. }
  746. }
  747. }
  748. }
  749. /* copy pixmaps of items of the current menu and of its ancestors into menu window */
  750. static void
  751. drawmenus(struct Menu *currmenu)
  752. {
  753. struct Menu *menu;
  754. struct Item *item;
  755. for (menu = currmenu; menu != NULL; menu = menu->parent) {
  756. if (!menu->drawn) {
  757. drawitems(menu);
  758. menu->drawn = 1;
  759. }
  760. for (item = menu->list; item != NULL; item = item->next) {
  761. if (item == menu->selected)
  762. XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
  763. menu->w, item->h, 0, item->y);
  764. else
  765. XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
  766. menu->w, item->h, 0, item->y);
  767. }
  768. }
  769. }
  770. /* umap previous menus and map current menu and its parents */
  771. static void
  772. mapmenu(struct Menu *currmenu)
  773. {
  774. static struct Menu *prevmenu = NULL;
  775. struct Menu *menu, *menu_;
  776. struct Menu *lcamenu; /* lowest common ancestor menu */
  777. unsigned minlevel; /* level of the closest to root menu */
  778. unsigned maxlevel; /* level of the closest to root menu */
  779. /* do not remap current menu if it wasn't updated*/
  780. if (prevmenu == currmenu)
  781. return;
  782. /* if this is the first time mapping, skip calculations */
  783. if (prevmenu == NULL) {
  784. XMapWindow(dpy, currmenu->win);
  785. prevmenu = currmenu;
  786. return;
  787. }
  788. /* find lowest common ancestor menu */
  789. minlevel = MIN(currmenu->level, prevmenu->level);
  790. maxlevel = MAX(currmenu->level, prevmenu->level);
  791. if (currmenu->level == maxlevel) {
  792. menu = currmenu;
  793. menu_ = prevmenu;
  794. } else {
  795. menu = prevmenu;
  796. menu_ = currmenu;
  797. }
  798. while (menu->level > minlevel)
  799. menu = menu->parent;
  800. while (menu != menu_) {
  801. menu = menu->parent;
  802. menu_ = menu_->parent;
  803. }
  804. lcamenu = menu;
  805. /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
  806. for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
  807. menu->selected = NULL;
  808. XUnmapWindow(dpy, menu->win);
  809. }
  810. /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
  811. for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
  812. if (wflag) {
  813. setupmenupos(menu);
  814. XMoveWindow(dpy, menu->win, menu->x, menu->y);
  815. }
  816. XMapWindow(dpy, menu->win);
  817. }
  818. prevmenu = currmenu;
  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. drawmenus(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. drawmenus(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. drawmenus(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. drawmenus(currmenu);
  956. break;
  957. case LeaveNotify:
  958. previtem = NULL;
  959. currmenu->selected = NULL;
  960. drawmenus(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. if (menu->drawn) {
  994. XFreePixmap(dpy, item->unsel);
  995. if (tmp->label != NULL)
  996. XFreePixmap(dpy, item->sel);
  997. }
  998. if (tmp->label != tmp->output)
  999. free(tmp->label);
  1000. free(tmp->output);
  1001. if (tmp->file != NULL) {
  1002. free(tmp->file);
  1003. if (tmp->icon != NULL) {
  1004. imlib_context_set_image(tmp->icon);
  1005. imlib_free_image();
  1006. }
  1007. }
  1008. item = item->next;
  1009. free(tmp);
  1010. }
  1011. XDestroyWindow(dpy, menu->win);
  1012. free(menu);
  1013. }
  1014. /* cleanup X and exit */
  1015. static void
  1016. cleanup(void)
  1017. {
  1018. XUngrabPointer(dpy, CurrentTime);
  1019. XUngrabKeyboard(dpy, CurrentTime);
  1020. XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
  1021. XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
  1022. XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
  1023. XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
  1024. XftColorFree(dpy, visual, colormap, &dc.separator);
  1025. XftColorFree(dpy, visual, colormap, &dc.border);
  1026. XFreeGC(dpy, dc.gc);
  1027. XCloseDisplay(dpy);
  1028. }
  1029. /* show usage */
  1030. static void
  1031. usage(void)
  1032. {
  1033. (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
  1034. exit(1);
  1035. }