dmenu-noxz

[fork] suckless dmenu - personal fork
git clone https://noxz.tech/git/dmenu-noxz.git
Log | Files | README | LICENSE

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