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.
 
 
 
 
 
 

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