dmenu.c 24 KB

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