My dmenu build
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

702 lines
15 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <ctype.h>
  3. #include <locale.h>
  4. #include <stdarg.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include <X11/Xlib.h>
  10. #include <X11/Xutil.h>
  11. #include <X11/keysym.h>
  12. /* macros */
  13. #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
  14. /* enums */
  15. enum { ColFG, ColBG, ColLast };
  16. /* typedefs */
  17. typedef struct {
  18. int x, y, w, h;
  19. unsigned long norm[ColLast];
  20. unsigned long sel[ColLast];
  21. Drawable drawable;
  22. GC gc;
  23. struct {
  24. XFontStruct *xfont;
  25. XFontSet set;
  26. int ascent;
  27. int descent;
  28. int height;
  29. } font;
  30. } DC; /* draw context */
  31. typedef struct Item Item;
  32. struct Item {
  33. Item *next; /* traverses all items */
  34. Item *left, *right; /* traverses items matching current search pattern */
  35. char *text;
  36. };
  37. /* forward declarations */
  38. static void *emalloc(unsigned int size);
  39. static void eprint(const char *errstr, ...);
  40. static char *estrdup(const char *str);
  41. static void drawtext(const char *text, unsigned long col[ColLast]);
  42. static unsigned int textw(const char *text);
  43. static unsigned int textnw(const char *text, unsigned int len);
  44. static void calcoffsets(void);
  45. static void drawmenu(void);
  46. static Bool grabkeyboard(void);
  47. static unsigned long getcolor(const char *colstr);
  48. static void initfont(const char *fontstr);
  49. static int strido(const char *text, const char *pattern);
  50. static void match(char *pattern);
  51. static void kpress(XKeyEvent * e);
  52. static char *readstdin(void);
  53. static void usage(void);
  54. /* variables */
  55. static int screen;
  56. static Display *dpy;
  57. static DC dc = {0};
  58. static char text[4096];
  59. static char *prompt = NULL;
  60. static int mw, mh;
  61. static int ret = 0;
  62. static int nitem = 0;
  63. static unsigned int cmdw = 0;
  64. static unsigned int promptw = 0;
  65. static unsigned int numlockmask = 0;
  66. static Bool running = True;
  67. static Item *allitems = NULL; /* first of all items */
  68. static Item *item = NULL; /* first of pattern matching items */
  69. static Item *sel = NULL;
  70. static Item *next = NULL;
  71. static Item *prev = NULL;
  72. static Item *curr = NULL;
  73. static Window root;
  74. static Window win;
  75. #include "config.h"
  76. static void *
  77. emalloc(unsigned int size) {
  78. void *res = malloc(size);
  79. if(!res)
  80. eprint("fatal: could not malloc() %u bytes\n", size);
  81. return res;
  82. }
  83. static void
  84. eprint(const char *errstr, ...) {
  85. va_list ap;
  86. va_start(ap, errstr);
  87. vfprintf(stderr, errstr, ap);
  88. va_end(ap);
  89. exit(EXIT_FAILURE);
  90. }
  91. static char *
  92. estrdup(const char *str) {
  93. void *res = strdup(str);
  94. if(!res)
  95. eprint("fatal: could not malloc() %u bytes\n", strlen(str));
  96. return res;
  97. }
  98. static void
  99. drawtext(const char *text, unsigned long col[ColLast]) {
  100. int x, y, w, h;
  101. static char buf[256];
  102. unsigned int len, olen;
  103. XRectangle r = { dc.x, dc.y, dc.w, dc.h };
  104. XSetForeground(dpy, dc.gc, col[ColBG]);
  105. XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
  106. if(!text)
  107. return;
  108. w = 0;
  109. olen = len = strlen(text);
  110. if(len >= sizeof buf)
  111. len = sizeof buf - 1;
  112. memcpy(buf, text, len);
  113. buf[len] = 0;
  114. h = dc.font.ascent + dc.font.descent;
  115. y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
  116. x = dc.x + (h / 2);
  117. /* shorten text if necessary */
  118. while(len && (w = textnw(buf, len)) > dc.w - h)
  119. buf[--len] = 0;
  120. if(len < olen) {
  121. if(len > 1)
  122. buf[len - 1] = '.';
  123. if(len > 2)
  124. buf[len - 2] = '.';
  125. if(len > 3)
  126. buf[len - 3] = '.';
  127. }
  128. if(w > dc.w)
  129. return; /* too long */
  130. XSetForeground(dpy, dc.gc, col[ColFG]);
  131. if(dc.font.set)
  132. XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
  133. else
  134. XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
  135. }
  136. static unsigned int
  137. textw(const char *text) {
  138. return textnw(text, strlen(text)) + dc.font.height;
  139. }
  140. static unsigned int
  141. textnw(const char *text, unsigned int len) {
  142. XRectangle r;
  143. if(dc.font.set) {
  144. XmbTextExtents(dc.font.set, text, len, NULL, &r);
  145. return r.width;
  146. }
  147. return XTextWidth(dc.font.xfont, text, len);
  148. }
  149. static void
  150. calcoffsets(void) {
  151. unsigned int tw, w;
  152. if(!curr)
  153. return;
  154. w = promptw + cmdw + 2 * SPACE;
  155. for(next = curr; next; next=next->right) {
  156. tw = textw(next->text);
  157. if(tw > mw / 3)
  158. tw = mw / 3;
  159. w += tw;
  160. if(w > mw)
  161. break;
  162. }
  163. w = promptw + cmdw + 2 * SPACE;
  164. for(prev = curr; prev && prev->left; prev=prev->left) {
  165. tw = textw(prev->left->text);
  166. if(tw > mw / 3)
  167. tw = mw / 3;
  168. w += tw;
  169. if(w > mw)
  170. break;
  171. }
  172. }
  173. static void
  174. drawmenu(void) {
  175. Item *i;
  176. dc.x = 0;
  177. dc.y = 0;
  178. dc.w = mw;
  179. dc.h = mh;
  180. drawtext(NULL, dc.norm);
  181. /* print prompt? */
  182. if(promptw) {
  183. dc.w = promptw;
  184. drawtext(prompt, dc.sel);
  185. }
  186. dc.x += promptw;
  187. dc.w = mw - promptw;
  188. /* print command */
  189. if(cmdw && item)
  190. dc.w = cmdw;
  191. drawtext(text[0] ? text : NULL, dc.norm);
  192. dc.x += cmdw;
  193. if(curr) {
  194. dc.w = SPACE;
  195. drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
  196. dc.x += dc.w;
  197. /* determine maximum items */
  198. for(i = curr; i != next; i=i->right) {
  199. dc.w = textw(i->text);
  200. if(dc.w > mw / 3)
  201. dc.w = mw / 3;
  202. drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
  203. dc.x += dc.w;
  204. }
  205. dc.x = mw - SPACE;
  206. dc.w = SPACE;
  207. drawtext(next ? ">" : NULL, dc.norm);
  208. }
  209. XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
  210. XFlush(dpy);
  211. }
  212. static Bool
  213. grabkeyboard(void) {
  214. unsigned int len;
  215. for(len = 1000; len; len--) {
  216. if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
  217. == GrabSuccess)
  218. break;
  219. usleep(1000);
  220. }
  221. return len > 0;
  222. }
  223. static unsigned long
  224. getcolor(const char *colstr) {
  225. Colormap cmap = DefaultColormap(dpy, screen);
  226. XColor color;
  227. if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
  228. eprint("error, cannot allocate color '%s'\n", colstr);
  229. return color.pixel;
  230. }
  231. static void
  232. initfont(const char *fontstr) {
  233. char *def, **missing;
  234. int i, n;
  235. if(!fontstr || fontstr[0] == '\0')
  236. eprint("error, cannot load font: '%s'\n", fontstr);
  237. missing = NULL;
  238. if(dc.font.set)
  239. XFreeFontSet(dpy, dc.font.set);
  240. dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
  241. if(missing)
  242. XFreeStringList(missing);
  243. if(dc.font.set) {
  244. XFontSetExtents *font_extents;
  245. XFontStruct **xfonts;
  246. char **font_names;
  247. dc.font.ascent = dc.font.descent = 0;
  248. font_extents = XExtentsOfFontSet(dc.font.set);
  249. n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
  250. for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
  251. if(dc.font.ascent < (*xfonts)->ascent)
  252. dc.font.ascent = (*xfonts)->ascent;
  253. if(dc.font.descent < (*xfonts)->descent)
  254. dc.font.descent = (*xfonts)->descent;
  255. xfonts++;
  256. }
  257. }
  258. else {
  259. if(dc.font.xfont)
  260. XFreeFont(dpy, dc.font.xfont);
  261. dc.font.xfont = NULL;
  262. if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))) {
  263. if(!(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
  264. eprint("error, cannot load font: '%s'\n", fontstr);
  265. }
  266. dc.font.ascent = dc.font.xfont->ascent;
  267. dc.font.descent = dc.font.xfont->descent;
  268. }
  269. dc.font.height = dc.font.ascent + dc.font.descent;
  270. }
  271. static int
  272. strido(const char *text, const char *pattern) {
  273. for(; *text && *pattern; text++)
  274. if (*text == *pattern)
  275. pattern++;
  276. return !*pattern;
  277. }
  278. static void
  279. match(char *pattern) {
  280. unsigned int plen;
  281. Item *i, *j;
  282. if(!pattern)
  283. return;
  284. plen = strlen(pattern);
  285. item = j = NULL;
  286. nitem = 0;
  287. for(i = allitems; i; i=i->next)
  288. if(!plen || !strncmp(pattern, i->text, plen)) {
  289. if(!j)
  290. item = i;
  291. else
  292. j->right = i;
  293. i->left = j;
  294. i->right = NULL;
  295. j = i;
  296. nitem++;
  297. }
  298. for(i = allitems; i; i=i->next)
  299. if(plen && strncmp(pattern, i->text, plen)
  300. && strstr(i->text, pattern)) {
  301. if(!j)
  302. item = i;
  303. else
  304. j->right = i;
  305. i->left = j;
  306. i->right = NULL;
  307. j = i;
  308. nitem++;
  309. }
  310. for(i = allitems; i; i=i->next)
  311. if(plen && strncmp(pattern, i->text, plen)
  312. && !strstr(i->text, pattern)
  313. && strido(i->text,pattern)) {
  314. if(!j)
  315. item = i;
  316. else
  317. j->right = i;
  318. i->left = j;
  319. i->right = NULL;
  320. j = i;
  321. nitem++;
  322. }
  323. curr = prev = next = sel = item;
  324. calcoffsets();
  325. }
  326. static void
  327. kpress(XKeyEvent * e) {
  328. char buf[32];
  329. int i, num;
  330. unsigned int len;
  331. KeySym ksym;
  332. len = strlen(text);
  333. buf[0] = 0;
  334. num = XLookupString(e, buf, sizeof buf, &ksym, 0);
  335. if(IsKeypadKey(ksym)) {
  336. if(ksym == XK_KP_Enter) {
  337. ksym = XK_Return;
  338. } else if(ksym >= XK_KP_0 && ksym <= XK_KP_9) {
  339. ksym = (ksym - XK_KP_0) + XK_0;
  340. }
  341. }
  342. if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
  343. || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
  344. || IsPrivateKeypadKey(ksym))
  345. return;
  346. /* first check if a control mask is omitted */
  347. if(e->state & ControlMask) {
  348. switch (ksym) {
  349. default: /* ignore other control sequences */
  350. return;
  351. case XK_bracketleft:
  352. ksym = XK_Escape;
  353. break;
  354. case XK_h:
  355. case XK_H:
  356. ksym = XK_BackSpace;
  357. break;
  358. case XK_i:
  359. case XK_I:
  360. ksym = XK_Tab;
  361. break;
  362. case XK_j:
  363. case XK_J:
  364. ksym = XK_Return;
  365. break;
  366. case XK_u:
  367. case XK_U:
  368. text[0] = 0;
  369. match(text);
  370. drawmenu();
  371. return;
  372. case XK_w:
  373. case XK_W:
  374. if(len) {
  375. i = len - 1;
  376. while(i >= 0 && text[i] == ' ')
  377. text[i--] = 0;
  378. while(i >= 0 && text[i] != ' ')
  379. text[i--] = 0;
  380. match(text);
  381. drawmenu();
  382. }
  383. return;
  384. }
  385. }
  386. if(CLEANMASK(e->state) & Mod1Mask) {
  387. switch(ksym) {
  388. default: return;
  389. case XK_h:
  390. ksym = XK_Left;
  391. break;
  392. case XK_l:
  393. ksym = XK_Right;
  394. break;
  395. case XK_j:
  396. ksym = XK_Next;
  397. break;
  398. case XK_k:
  399. ksym = XK_Prior;
  400. break;
  401. case XK_g:
  402. ksym = XK_Home;
  403. break;
  404. case XK_G:
  405. ksym = XK_End;
  406. break;
  407. }
  408. }
  409. switch(ksym) {
  410. default:
  411. if(num && !iscntrl((int) buf[0])) {
  412. buf[num] = 0;
  413. if(len > 0)
  414. strncat(text, buf, sizeof text);
  415. else
  416. strncpy(text, buf, sizeof text);
  417. match(text);
  418. }
  419. break;
  420. case XK_BackSpace:
  421. if(len) {
  422. text[--len] = 0;
  423. match(text);
  424. }
  425. break;
  426. case XK_End:
  427. if(!item)
  428. return;
  429. while(next) {
  430. sel = curr = next;
  431. calcoffsets();
  432. }
  433. while(sel && sel->right)
  434. sel = sel->right;
  435. break;
  436. case XK_Escape:
  437. ret = 1;
  438. running = False;
  439. break;
  440. case XK_Home:
  441. if(!item)
  442. return;
  443. sel = curr = item;
  444. calcoffsets();
  445. break;
  446. case XK_Left:
  447. if(!(sel && sel->left))
  448. return;
  449. sel=sel->left;
  450. if(sel->right == curr) {
  451. curr = prev;
  452. calcoffsets();
  453. }
  454. break;
  455. case XK_Next:
  456. if(!next)
  457. return;
  458. sel = curr = next;
  459. calcoffsets();
  460. break;
  461. case XK_Prior:
  462. if(!prev)
  463. return;
  464. sel = curr = prev;
  465. calcoffsets();
  466. break;
  467. case XK_Return:
  468. if((e->state & ShiftMask) && text)
  469. fprintf(stdout, "%s", text);
  470. else if(sel)
  471. fprintf(stdout, "%s", sel->text);
  472. else if(text)
  473. fprintf(stdout, "%s", text);
  474. fflush(stdout);
  475. running = False;
  476. break;
  477. case XK_Right:
  478. if(!(sel && sel->right))
  479. return;
  480. sel=sel->right;
  481. if(sel == next) {
  482. curr = next;
  483. calcoffsets();
  484. }
  485. break;
  486. case XK_Tab:
  487. if(!sel)
  488. return;
  489. strncpy(text, sel->text, sizeof text);
  490. match(text);
  491. break;
  492. }
  493. drawmenu();
  494. }
  495. static char *
  496. readstdin(void) {
  497. static char *maxname = NULL;
  498. char *p, buf[1024];
  499. unsigned int len = 0, max = 0;
  500. Item *i, *new;
  501. i = 0;
  502. while(fgets(buf, sizeof buf, stdin)) {
  503. len = strlen(buf);
  504. if (buf[len - 1] == '\n')
  505. buf[len - 1] = 0;
  506. p = estrdup(buf);
  507. if(max < len) {
  508. maxname = p;
  509. max = len;
  510. }
  511. new = emalloc(sizeof(Item));
  512. new->next = new->left = new->right = NULL;
  513. new->text = p;
  514. if(!i)
  515. allitems = new;
  516. else
  517. i->next = new;
  518. i = new;
  519. }
  520. return maxname;
  521. }
  522. static void
  523. usage(void) {
  524. eprint("usage: dmenu [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
  525. " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
  526. }
  527. int
  528. main(int argc, char *argv[]) {
  529. Bool bottom = False;
  530. char *font = FONT;
  531. char *maxname;
  532. char *normbg = NORMBGCOLOR;
  533. char *normfg = NORMFGCOLOR;
  534. char *selbg = SELBGCOLOR;
  535. char *selfg = SELFGCOLOR;
  536. int i, j;
  537. Item *itm;
  538. XEvent ev;
  539. XModifierKeymap *modmap;
  540. XSetWindowAttributes wa;
  541. /* command line args */
  542. for(i = 1; i < argc; i++)
  543. if(!strcmp(argv[i], "-b")) {
  544. bottom = True;
  545. }
  546. else if(!strcmp(argv[i], "-fn")) {
  547. if(++i < argc) font = argv[i];
  548. }
  549. else if(!strcmp(argv[i], "-nb")) {
  550. if(++i < argc) normbg = argv[i];
  551. }
  552. else if(!strcmp(argv[i], "-nf")) {
  553. if(++i < argc) normfg = argv[i];
  554. }
  555. else if(!strcmp(argv[i], "-p")) {
  556. if(++i < argc) prompt = argv[i];
  557. }
  558. else if(!strcmp(argv[i], "-sb")) {
  559. if(++i < argc) selbg = argv[i];
  560. }
  561. else if(!strcmp(argv[i], "-sf")) {
  562. if(++i < argc) selfg = argv[i];
  563. }
  564. else if(!strcmp(argv[i], "-v"))
  565. eprint("dmenu-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk\n");
  566. else
  567. usage();
  568. setlocale(LC_CTYPE, "");
  569. dpy = XOpenDisplay(0);
  570. if(!dpy)
  571. eprint("dmenu: cannot open display\n");
  572. screen = DefaultScreen(dpy);
  573. root = RootWindow(dpy, screen);
  574. if(isatty(STDIN_FILENO)) {
  575. maxname = readstdin();
  576. running = grabkeyboard();
  577. }
  578. else { /* prevent keypress loss */
  579. running = grabkeyboard();
  580. maxname = readstdin();
  581. }
  582. /* init modifier map */
  583. modmap = XGetModifierMapping(dpy);
  584. for (i = 0; i < 8; i++) {
  585. for (j = 0; j < modmap->max_keypermod; j++) {
  586. if(modmap->modifiermap[i * modmap->max_keypermod + j]
  587. == XKeysymToKeycode(dpy, XK_Num_Lock))
  588. numlockmask = (1 << i);
  589. }
  590. }
  591. XFreeModifiermap(modmap);
  592. /* style */
  593. dc.norm[ColBG] = getcolor(normbg);
  594. dc.norm[ColFG] = getcolor(normfg);
  595. dc.sel[ColBG] = getcolor(selbg);
  596. dc.sel[ColFG] = getcolor(selfg);
  597. initfont(font);
  598. /* menu window */
  599. wa.override_redirect = 1;
  600. wa.background_pixmap = ParentRelative;
  601. wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
  602. mw = DisplayWidth(dpy, screen);
  603. mh = dc.font.height + 2;
  604. win = XCreateWindow(dpy, root, 0,
  605. bottom ? DisplayHeight(dpy, screen) - mh : 0, mw, mh, 0,
  606. DefaultDepth(dpy, screen), CopyFromParent,
  607. DefaultVisual(dpy, screen),
  608. CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
  609. /* pixmap */
  610. dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
  611. dc.gc = XCreateGC(dpy, root, 0, 0);
  612. XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
  613. if(!dc.font.set)
  614. XSetFont(dpy, dc.gc, dc.font.xfont->fid);
  615. if(maxname)
  616. cmdw = textw(maxname);
  617. if(cmdw > mw / 3)
  618. cmdw = mw / 3;
  619. if(prompt)
  620. promptw = textw(prompt);
  621. if(promptw > mw / 5)
  622. promptw = mw / 5;
  623. text[0] = 0;
  624. match(text);
  625. XMapRaised(dpy, win);
  626. drawmenu();
  627. XSync(dpy, False);
  628. /* main event loop */
  629. while(running && !XNextEvent(dpy, &ev))
  630. switch (ev.type) {
  631. default: /* ignore all crap */
  632. break;
  633. case KeyPress:
  634. kpress(&ev.xkey);
  635. break;
  636. case Expose:
  637. if(ev.xexpose.count == 0)
  638. drawmenu();
  639. break;
  640. }
  641. /* cleanup */
  642. while(allitems) {
  643. itm = allitems->next;
  644. free(allitems->text);
  645. free(allitems);
  646. allitems = itm;
  647. }
  648. if(dc.font.set)
  649. XFreeFontSet(dpy, dc.font.set);
  650. else
  651. XFreeFont(dpy, dc.font.xfont);
  652. XFreePixmap(dpy, dc.drawable);
  653. XFreeGC(dpy, dc.gc);
  654. XDestroyWindow(dpy, win);
  655. XUngrabKeyboard(dpy, CurrentTime);
  656. XCloseDisplay(dpy);
  657. return ret;
  658. }