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.
 
 
 
 
 

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