dmenu.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /* See LICENSE file for copyright and license details. */
  2. #include <ctype.h>
  3. #include <locale.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <strings.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. #ifdef XINERAMA
  14. #include <X11/extensions/Xinerama.h>
  15. #endif
  16. #include <X11/Xft/Xft.h>
  17. #include "drw.h"
  18. #include "util.h"
  19. /* macros */
  20. #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
  21. * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
  22. #define LENGTH(X) (sizeof X / sizeof X[0])
  23. #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
  24. #define NUMBERSMAXDIGITS 100
  25. #define NUMBERSBUFSIZE (NUMBERSMAXDIGITS * 2) + 1
  26. /* enums */
  27. enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
  28. struct item {
  29. char *text;
  30. struct item *left, *right;
  31. int out;
  32. };
  33. static char numbers[NUMBERSBUFSIZE] = "";
  34. static char text[BUFSIZ] = "";
  35. static char *embed;
  36. static int bh, mw, mh;
  37. static int inputw = 0, promptw;
  38. static int lrpad; /* sum of left and right padding */
  39. static size_t cursor;
  40. static struct item *items = NULL;
  41. static struct item *matches, *matchend;
  42. static struct item *prev, *curr, *next, *sel;
  43. static int mon = -1, screen;
  44. static Atom clip, utf8;
  45. static Display *dpy;
  46. static Window root, parentwin, win;
  47. static XIC xic;
  48. static Drw *drw;
  49. static Clr *scheme[SchemeLast];
  50. #include "config.h"
  51. static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
  52. static char *(*fstrstr)(const char *, const char *) = strstr;
  53. static void
  54. appenditem(struct item *item, struct item **list, struct item **last)
  55. {
  56. if (*last)
  57. (*last)->right = item;
  58. else
  59. *list = item;
  60. item->left = *last;
  61. item->right = NULL;
  62. *last = item;
  63. }
  64. static void
  65. calcoffsets(void)
  66. {
  67. int i, n;
  68. if (lines > 0)
  69. n = lines * bh;
  70. else
  71. n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
  72. /* calculate which items will begin the next page and previous page */
  73. for (i = 0, next = curr; next; next = next->right)
  74. if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
  75. break;
  76. for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
  77. if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
  78. break;
  79. }
  80. static void
  81. cleanup(void)
  82. {
  83. size_t i;
  84. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  85. for (i = 0; i < SchemeLast; i++)
  86. free(scheme[i]);
  87. drw_free(drw);
  88. XSync(dpy, False);
  89. XCloseDisplay(dpy);
  90. }
  91. static char *
  92. cistrstr(const char *s, const char *sub)
  93. {
  94. size_t len;
  95. for (len = strlen(sub); *s; s++)
  96. if (!strncasecmp(s, sub, len))
  97. return (char *)s;
  98. return NULL;
  99. }
  100. static int
  101. drawitem(struct item *item, int x, int y, int w)
  102. {
  103. if (item == sel)
  104. drw_setscheme(drw, scheme[SchemeSel]);
  105. else if (item->out)
  106. drw_setscheme(drw, scheme[SchemeOut]);
  107. else
  108. drw_setscheme(drw, scheme[SchemeNorm]);
  109. return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
  110. }
  111. static void
  112. recalculatenumbers()
  113. {
  114. unsigned int numer = 0, denom = 0;
  115. struct item *item;
  116. if (matchend) {
  117. numer++;
  118. for (item = matchend; item && item->left; item = item->left)
  119. numer++;
  120. }
  121. for (item = items; item && item->text; item++)
  122. denom++;
  123. snprintf(numbers, NUMBERSBUFSIZE, "%d/%d", numer, denom);
  124. }
  125. static void
  126. drawmenu(void)
  127. {
  128. unsigned int curpos;
  129. struct item *item;
  130. int x = 0, y = 0, w;
  131. drw_setscheme(drw, scheme[SchemeNorm]);
  132. drw_rect(drw, 0, 0, mw, mh, 1, 1);
  133. if (prompt && *prompt) {
  134. drw_setscheme(drw, scheme[SchemeSel]);
  135. x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
  136. }
  137. /* draw input field */
  138. w = (lines > 0 || !matches) ? mw - x : inputw;
  139. drw_setscheme(drw, scheme[SchemeNorm]);
  140. drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
  141. curpos = TEXTW(text) - TEXTW(&text[cursor]);
  142. if ((curpos += lrpad / 2 - 1) < w) {
  143. drw_setscheme(drw, scheme[SchemeNorm]);
  144. drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
  145. }
  146. recalculatenumbers();
  147. if (lines > 0) {
  148. /* draw vertical list */
  149. for (item = curr; item != next; item = item->right)
  150. drawitem(item, x, y += bh, mw - x);
  151. } else if (matches) {
  152. /* draw horizontal list */
  153. x += inputw;
  154. w = TEXTW("<");
  155. if (curr->left) {
  156. drw_setscheme(drw, scheme[SchemeNorm]);
  157. drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
  158. }
  159. x += w;
  160. for (item = curr; item != next; item = item->right)
  161. x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">") - TEXTW(numbers)));
  162. if (next) {
  163. w = TEXTW(">");
  164. drw_setscheme(drw, scheme[SchemeNorm]);
  165. drw_text(drw, mw - w - TEXTW(numbers), 0, w, bh, lrpad / 2, ">", 0);
  166. }
  167. }
  168. drw_setscheme(drw, scheme[SchemeNorm]);
  169. drw_text(drw, mw - TEXTW(numbers), 0, TEXTW(numbers), bh, lrpad / 2, numbers, 0);
  170. drw_map(drw, win, 0, 0, mw, mh);
  171. }
  172. static void
  173. grabfocus(void)
  174. {
  175. struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
  176. Window focuswin;
  177. int i, revertwin;
  178. for (i = 0; i < 100; ++i) {
  179. XGetInputFocus(dpy, &focuswin, &revertwin);
  180. if (focuswin == win)
  181. return;
  182. XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
  183. nanosleep(&ts, NULL);
  184. }
  185. die("cannot grab focus");
  186. }
  187. static void
  188. grabkeyboard(void)
  189. {
  190. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  191. int i;
  192. if (embed)
  193. return;
  194. /* try to grab keyboard, we may have to wait for another process to ungrab */
  195. for (i = 0; i < 1000; i++) {
  196. if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
  197. GrabModeAsync, CurrentTime) == GrabSuccess)
  198. return;
  199. nanosleep(&ts, NULL);
  200. }
  201. die("cannot grab keyboard");
  202. }
  203. static void
  204. match(void)
  205. {
  206. static char **tokv = NULL;
  207. static int tokn = 0;
  208. char buf[sizeof text], *s;
  209. int i, tokc = 0;
  210. size_t len, textsize;
  211. struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  212. strcpy(buf, text);
  213. /* separate input text into tokens to be matched individually */
  214. for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
  215. if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  216. die("cannot realloc %u bytes:", tokn * sizeof *tokv);
  217. len = tokc ? strlen(tokv[0]) : 0;
  218. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  219. textsize = strlen(text) + 1;
  220. for (item = items; item && item->text; item++) {
  221. for (i = 0; i < tokc; i++)
  222. if (!fstrstr(item->text, tokv[i]))
  223. break;
  224. if (i != tokc) /* not all tokens match */
  225. continue;
  226. /* exact matches go first, then prefixes, then substrings */
  227. if (!tokc || !fstrncmp(text, item->text, textsize))
  228. appenditem(item, &matches, &matchend);
  229. else if (!fstrncmp(tokv[0], item->text, len))
  230. appenditem(item, &lprefix, &prefixend);
  231. else
  232. appenditem(item, &lsubstr, &substrend);
  233. }
  234. if (lprefix) {
  235. if (matches) {
  236. matchend->right = lprefix;
  237. lprefix->left = matchend;
  238. } else
  239. matches = lprefix;
  240. matchend = prefixend;
  241. }
  242. if (lsubstr) {
  243. if (matches) {
  244. matchend->right = lsubstr;
  245. lsubstr->left = matchend;
  246. } else
  247. matches = lsubstr;
  248. matchend = substrend;
  249. }
  250. curr = sel = matches;
  251. calcoffsets();
  252. }
  253. static void
  254. insert(const char *str, ssize_t n)
  255. {
  256. if (strlen(text) + n > sizeof text - 1)
  257. return;
  258. /* move existing text out of the way, insert new text, and update cursor */
  259. memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
  260. if (n > 0)
  261. memcpy(&text[cursor], str, n);
  262. cursor += n;
  263. match();
  264. }
  265. static size_t
  266. nextrune(int inc)
  267. {
  268. ssize_t n;
  269. /* return location of next utf8 rune in the given direction (+1 or -1) */
  270. for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
  271. ;
  272. return n;
  273. }
  274. static void
  275. movewordedge(int dir)
  276. {
  277. if (dir < 0) { /* move cursor to the start of the word*/
  278. while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
  279. cursor = nextrune(-1);
  280. while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
  281. cursor = nextrune(-1);
  282. } else { /* move cursor to the end of the word */
  283. while (text[cursor] && strchr(worddelimiters, text[cursor]))
  284. cursor = nextrune(+1);
  285. while (text[cursor] && !strchr(worddelimiters, text[cursor]))
  286. cursor = nextrune(+1);
  287. }
  288. }
  289. static void
  290. keypress(XKeyEvent *ev)
  291. {
  292. char buf[32];
  293. int len;
  294. KeySym ksym;
  295. Status status;
  296. len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
  297. switch (status) {
  298. default: /* XLookupNone, XBufferOverflow */
  299. return;
  300. case XLookupChars:
  301. goto insert;
  302. case XLookupKeySym:
  303. case XLookupBoth:
  304. break;
  305. }
  306. if (ev->state & ControlMask) {
  307. switch(ksym) {
  308. case XK_a: ksym = XK_Home; break;
  309. case XK_b: ksym = XK_Left; break;
  310. case XK_c: ksym = XK_Escape; break;
  311. case XK_d: ksym = XK_Delete; break;
  312. case XK_e: ksym = XK_End; break;
  313. case XK_f: ksym = XK_Right; break;
  314. case XK_g: ksym = XK_Escape; break;
  315. case XK_h: ksym = XK_BackSpace; break;
  316. case XK_i: ksym = XK_Tab; break;
  317. case XK_j: /* fallthrough */
  318. case XK_J: /* fallthrough */
  319. case XK_m: /* fallthrough */
  320. case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
  321. case XK_n: ksym = XK_Down; break;
  322. case XK_p: ksym = XK_Up; break;
  323. case XK_k: /* delete right */
  324. text[cursor] = '\0';
  325. match();
  326. break;
  327. case XK_u: /* delete left */
  328. insert(NULL, 0 - cursor);
  329. break;
  330. case XK_w: /* delete word */
  331. while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
  332. insert(NULL, nextrune(-1) - cursor);
  333. while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
  334. insert(NULL, nextrune(-1) - cursor);
  335. break;
  336. case XK_y: /* paste selection */
  337. case XK_Y:
  338. XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
  339. utf8, utf8, win, CurrentTime);
  340. return;
  341. case XK_Left:
  342. case XK_KP_Left:
  343. movewordedge(-1);
  344. goto draw;
  345. case XK_Right:
  346. case XK_KP_Right:
  347. movewordedge(+1);
  348. goto draw;
  349. case XK_Return:
  350. case XK_KP_Enter:
  351. break;
  352. case XK_bracketleft:
  353. cleanup();
  354. exit(1);
  355. default:
  356. return;
  357. }
  358. } else if (ev->state & Mod1Mask) {
  359. switch(ksym) {
  360. case XK_b:
  361. movewordedge(-1);
  362. goto draw;
  363. case XK_f:
  364. movewordedge(+1);
  365. goto draw;
  366. case XK_g: ksym = XK_Home; break;
  367. case XK_G: ksym = XK_End; break;
  368. case XK_h: ksym = XK_Up; break;
  369. case XK_j: ksym = XK_Next; break;
  370. case XK_k: ksym = XK_Prior; break;
  371. case XK_l: ksym = XK_Down; break;
  372. default:
  373. return;
  374. }
  375. }
  376. switch(ksym) {
  377. default:
  378. insert:
  379. if (!iscntrl(*buf))
  380. insert(buf, len);
  381. break;
  382. case XK_Delete:
  383. case XK_KP_Delete:
  384. if (text[cursor] == '\0')
  385. return;
  386. cursor = nextrune(+1);
  387. /* fallthrough */
  388. case XK_BackSpace:
  389. if (cursor == 0)
  390. return;
  391. insert(NULL, nextrune(-1) - cursor);
  392. break;
  393. case XK_End:
  394. case XK_KP_End:
  395. if (text[cursor] != '\0') {
  396. cursor = strlen(text);
  397. break;
  398. }
  399. if (next) {
  400. /* jump to end of list and position items in reverse */
  401. curr = matchend;
  402. calcoffsets();
  403. curr = prev;
  404. calcoffsets();
  405. while (next && (curr = curr->right))
  406. calcoffsets();
  407. }
  408. sel = matchend;
  409. break;
  410. case XK_Escape:
  411. cleanup();
  412. exit(1);
  413. case XK_Home:
  414. case XK_KP_Home:
  415. if (sel == matches) {
  416. cursor = 0;
  417. break;
  418. }
  419. sel = curr = matches;
  420. calcoffsets();
  421. break;
  422. case XK_Left:
  423. case XK_KP_Left:
  424. if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
  425. cursor = nextrune(-1);
  426. break;
  427. }
  428. if (lines > 0)
  429. return;
  430. /* fallthrough */
  431. case XK_Up:
  432. case XK_KP_Up:
  433. if (sel && sel->left && (sel = sel->left)->right == curr) {
  434. curr = prev;
  435. calcoffsets();
  436. }
  437. break;
  438. case XK_Next:
  439. case XK_KP_Next:
  440. if (!next)
  441. return;
  442. sel = curr = next;
  443. calcoffsets();
  444. break;
  445. case XK_Prior:
  446. case XK_KP_Prior:
  447. if (!prev)
  448. return;
  449. sel = curr = prev;
  450. calcoffsets();
  451. break;
  452. case XK_Return:
  453. case XK_KP_Enter:
  454. puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
  455. if (!(ev->state & ControlMask)) {
  456. cleanup();
  457. exit(0);
  458. }
  459. if (sel)
  460. sel->out = 1;
  461. break;
  462. case XK_Right:
  463. case XK_KP_Right:
  464. if (text[cursor] != '\0') {
  465. cursor = nextrune(+1);
  466. break;
  467. }
  468. if (lines > 0)
  469. return;
  470. /* fallthrough */
  471. case XK_Down:
  472. case XK_KP_Down:
  473. if (sel && sel->right && (sel = sel->right) == next) {
  474. curr = next;
  475. calcoffsets();
  476. }
  477. break;
  478. case XK_Tab:
  479. if (!sel)
  480. return;
  481. strncpy(text, sel->text, sizeof text - 1);
  482. text[sizeof text - 1] = '\0';
  483. cursor = strlen(text);
  484. match();
  485. break;
  486. }
  487. draw:
  488. drawmenu();
  489. }
  490. static void
  491. buttonpress(XEvent *e)
  492. {
  493. struct item *item;
  494. XButtonPressedEvent *ev = &e->xbutton;
  495. int x = 0, y = 0, h = bh, w;
  496. if (ev->window != win)
  497. return;
  498. /* right-click: exit */
  499. if (ev->button == Button3)
  500. exit(1);
  501. if (prompt && *prompt)
  502. x += promptw;
  503. /* input field */
  504. w = (lines > 0 || !matches) ? mw - x : inputw;
  505. /* left-click on input: clear input,
  506. * NOTE: if there is no left-arrow the space for < is reserved so
  507. * add that to the input width */
  508. if (ev->button == Button1 &&
  509. ((lines <= 0 && ev->x >= 0 && ev->x <= x + w +
  510. ((!prev || !curr->left) ? TEXTW("<") : 0)) ||
  511. (lines > 0 && ev->y >= y && ev->y <= y + h))) {
  512. insert(NULL, -cursor);
  513. drawmenu();
  514. return;
  515. }
  516. /* middle-mouse click: paste selection */
  517. if (ev->button == Button2) {
  518. XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
  519. utf8, utf8, win, CurrentTime);
  520. drawmenu();
  521. return;
  522. }
  523. /* scroll up */
  524. if (ev->button == Button4 && prev) {
  525. sel = curr = prev;
  526. calcoffsets();
  527. drawmenu();
  528. return;
  529. }
  530. /* scroll down */
  531. if (ev->button == Button5 && next) {
  532. sel = curr = next;
  533. calcoffsets();
  534. drawmenu();
  535. return;
  536. }
  537. if (ev->button != Button1)
  538. return;
  539. if (ev->state & ~ControlMask)
  540. return;
  541. if (lines > 0) {
  542. /* vertical list: (ctrl)left-click on item */
  543. w = mw - x;
  544. for (item = curr; item != next; item = item->right) {
  545. y += h;
  546. if (ev->y >= y && ev->y <= (y + h)) {
  547. puts(item->text);
  548. if (!(ev->state & ControlMask))
  549. exit(0);
  550. sel = item;
  551. if (sel) {
  552. sel->out = 1;
  553. drawmenu();
  554. }
  555. return;
  556. }
  557. }
  558. } else if (matches) {
  559. /* left-click on left arrow */
  560. x += inputw;
  561. w = TEXTW("<");
  562. if (prev && curr->left) {
  563. if (ev->x >= x && ev->x <= x + w) {
  564. sel = curr = prev;
  565. calcoffsets();
  566. drawmenu();
  567. return;
  568. }
  569. }
  570. /* horizontal list: (ctrl)left-click on item */
  571. for (item = curr; item != next; item = item->right) {
  572. x += w;
  573. w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
  574. if (ev->x >= x && ev->x <= x + w) {
  575. puts(item->text);
  576. if (!(ev->state & ControlMask))
  577. exit(0);
  578. sel = item;
  579. if (sel) {
  580. sel->out = 1;
  581. drawmenu();
  582. }
  583. return;
  584. }
  585. }
  586. /* left-click on right arrow */
  587. w = TEXTW(">");
  588. x = mw - w;
  589. if (next && ev->x >= x && ev->x <= x + w) {
  590. sel = curr = next;
  591. calcoffsets();
  592. drawmenu();
  593. return;
  594. }
  595. }
  596. }
  597. static void
  598. paste(void)
  599. {
  600. char *p, *q;
  601. int di;
  602. unsigned long dl;
  603. Atom da;
  604. /* we have been given the current selection, now insert it into input */
  605. if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
  606. utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
  607. == Success && p) {
  608. insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
  609. XFree(p);
  610. }
  611. drawmenu();
  612. }
  613. static void
  614. readstdin(void)
  615. {
  616. char buf[sizeof text], *p;
  617. size_t i, imax = 0, size = 0;
  618. unsigned int tmpmax = 0;
  619. /* read each line from stdin and add it to the item list */
  620. for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
  621. if (i + 1 >= size / sizeof *items)
  622. if (!(items = realloc(items, (size += BUFSIZ))))
  623. die("cannot realloc %u bytes:", size);
  624. if ((p = strchr(buf, '\n')))
  625. *p = '\0';
  626. if (!(items[i].text = strdup(buf)))
  627. die("cannot strdup %u bytes:", strlen(buf) + 1);
  628. items[i].out = 0;
  629. drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
  630. if (tmpmax > inputw) {
  631. inputw = tmpmax;
  632. imax = i;
  633. }
  634. }
  635. if (items)
  636. items[i].text = NULL;
  637. inputw = items ? TEXTW(items[imax].text) : 0;
  638. lines = MIN(lines, i);
  639. }
  640. static void
  641. run(void)
  642. {
  643. XEvent ev;
  644. while (!XNextEvent(dpy, &ev)) {
  645. if (XFilterEvent(&ev, win))
  646. continue;
  647. switch(ev.type) {
  648. case DestroyNotify:
  649. if (ev.xdestroywindow.window != win)
  650. break;
  651. cleanup();
  652. exit(1);
  653. case ButtonPress:
  654. buttonpress(&ev);
  655. break;
  656. case Expose:
  657. if (ev.xexpose.count == 0)
  658. drw_map(drw, win, 0, 0, mw, mh);
  659. break;
  660. case FocusIn:
  661. /* regrab focus from parent window */
  662. if (ev.xfocus.window != win)
  663. grabfocus();
  664. break;
  665. case KeyPress:
  666. keypress(&ev.xkey);
  667. break;
  668. case SelectionNotify:
  669. if (ev.xselection.property == utf8)
  670. paste();
  671. break;
  672. case VisibilityNotify:
  673. if (ev.xvisibility.state != VisibilityUnobscured)
  674. XRaiseWindow(dpy, win);
  675. break;
  676. }
  677. }
  678. }
  679. static void
  680. setup(void)
  681. {
  682. int x, y, i, j;
  683. unsigned int du;
  684. XSetWindowAttributes swa;
  685. XIM xim;
  686. Window w, dw, *dws;
  687. XWindowAttributes wa;
  688. XClassHint ch = {"dmenu", "dmenu"};
  689. #ifdef XINERAMA
  690. XineramaScreenInfo *info;
  691. Window pw;
  692. int a, di, n, area = 0;
  693. #endif
  694. /* init appearance */
  695. for (j = 0; j < SchemeLast; j++)
  696. scheme[j] = drw_scm_create(drw, colors[j], 2);
  697. clip = XInternAtom(dpy, "CLIPBOARD", False);
  698. utf8 = XInternAtom(dpy, "UTF8_STRING", False);
  699. /* calculate menu geometry */
  700. bh = drw->fonts->h + 2;
  701. lines = MAX(lines, 0);
  702. mh = (lines + 1) * bh;
  703. #ifdef XINERAMA
  704. i = 0;
  705. if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
  706. XGetInputFocus(dpy, &w, &di);
  707. if (mon >= 0 && mon < n)
  708. i = mon;
  709. else if (w != root && w != PointerRoot && w != None) {
  710. /* find top-level window containing current input focus */
  711. do {
  712. if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  713. XFree(dws);
  714. } while (w != root && w != pw);
  715. /* find xinerama screen with which the window intersects most */
  716. if (XGetWindowAttributes(dpy, pw, &wa))
  717. for (j = 0; j < n; j++)
  718. if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  719. area = a;
  720. i = j;
  721. }
  722. }
  723. /* no focused window is on screen, so use pointer location instead */
  724. if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  725. for (i = 0; i < n; i++)
  726. if (INTERSECT(x, y, 1, 1, info[i]))
  727. break;
  728. x = info[i].x_org;
  729. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  730. mw = info[i].width;
  731. XFree(info);
  732. } else
  733. #endif
  734. {
  735. if (!XGetWindowAttributes(dpy, parentwin, &wa))
  736. die("could not get embedding window attributes: 0x%lx",
  737. parentwin);
  738. x = 0;
  739. y = topbar ? 0 : wa.height - mh;
  740. mw = wa.width;
  741. }
  742. promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
  743. inputw = MIN(inputw, mw/3);
  744. match();
  745. /* create menu window */
  746. swa.override_redirect = True;
  747. swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
  748. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask |
  749. ButtonPressMask;
  750. win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
  751. CopyFromParent, CopyFromParent, CopyFromParent,
  752. CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
  753. XSetClassHint(dpy, win, &ch);
  754. /* input methods */
  755. if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
  756. die("XOpenIM failed: could not open input device");
  757. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  758. XNClientWindow, win, XNFocusWindow, win, NULL);
  759. XMapRaised(dpy, win);
  760. if (embed) {
  761. XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
  762. if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
  763. for (i = 0; i < du && dws[i] != win; ++i)
  764. XSelectInput(dpy, dws[i], FocusChangeMask);
  765. XFree(dws);
  766. }
  767. grabfocus();
  768. }
  769. drw_resize(drw, mw, mh);
  770. drawmenu();
  771. }
  772. static void
  773. usage(void)
  774. {
  775. fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
  776. " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
  777. exit(1);
  778. }
  779. int
  780. main(int argc, char *argv[])
  781. {
  782. XWindowAttributes wa;
  783. int i, fast = 0;
  784. for (i = 1; i < argc; i++)
  785. /* these options take no arguments */
  786. if (!strcmp(argv[i], "-v")) { /* prints version information */
  787. puts("dmenu-"VERSION);
  788. exit(0);
  789. } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
  790. topbar = 0;
  791. else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
  792. fast = 1;
  793. else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
  794. fstrncmp = strncasecmp;
  795. fstrstr = cistrstr;
  796. } else if (i + 1 == argc)
  797. usage();
  798. /* these options take one argument */
  799. else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
  800. lines = atoi(argv[++i]);
  801. else if (!strcmp(argv[i], "-m"))
  802. mon = atoi(argv[++i]);
  803. else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
  804. prompt = argv[++i];
  805. else if (!strcmp(argv[i], "-fn")) /* font or font set */
  806. fonts[0] = argv[++i];
  807. else if (!strcmp(argv[i], "-nb")) /* normal background color */
  808. colors[SchemeNorm][ColBg] = argv[++i];
  809. else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
  810. colors[SchemeNorm][ColFg] = argv[++i];
  811. else if (!strcmp(argv[i], "-sb")) /* selected background color */
  812. colors[SchemeSel][ColBg] = argv[++i];
  813. else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
  814. colors[SchemeSel][ColFg] = argv[++i];
  815. else if (!strcmp(argv[i], "-w")) /* embedding window id */
  816. embed = argv[++i];
  817. else
  818. usage();
  819. if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
  820. fputs("warning: no locale support\n", stderr);
  821. if (!(dpy = XOpenDisplay(NULL)))
  822. die("cannot open display");
  823. screen = DefaultScreen(dpy);
  824. root = RootWindow(dpy, screen);
  825. if (!embed || !(parentwin = strtol(embed, NULL, 0)))
  826. parentwin = root;
  827. if (!XGetWindowAttributes(dpy, parentwin, &wa))
  828. die("could not get embedding window attributes: 0x%lx",
  829. parentwin);
  830. drw = drw_create(dpy, screen, root, wa.width, wa.height);
  831. if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
  832. die("no fonts could be loaded.");
  833. lrpad = drw->fonts->h;
  834. #ifdef __OpenBSD__
  835. if (pledge("stdio rpath", NULL) == -1)
  836. die("pledge");
  837. #endif
  838. if (fast && !isatty(0)) {
  839. grabkeyboard();
  840. readstdin();
  841. } else {
  842. readstdin();
  843. grabkeyboard();
  844. }
  845. setup();
  846. run();
  847. return 1; /* unreachable */
  848. }