Xinqi Bao's Git

c25dc82373f623757393c593eff6bf6292a76151
[dmenu.git] / dmenu.c
1 /* See LICENSE file for copyright and license details. */
2 #include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <strings.h>
7 #include <unistd.h>
8 #include <X11/Xlib.h>
9 #include <X11/Xatom.h>
10 #include <X11/Xutil.h>
11 #ifdef XINERAMA
12 #include <X11/extensions/Xinerama.h>
13 #endif
14 #include "draw.h"
15
16 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
17 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
18 #define MIN(a,b) ((a) < (b) ? (a) : (b))
19 #define MAX(a,b) ((a) > (b) ? (a) : (b))
20
21 typedef struct Item Item;
22 struct Item {
23 char *text;
24 Item *left, *right;
25 Bool out;
26 };
27
28 static void appenditem(Item *item, Item **list, Item **last);
29 static void calcoffsets(void);
30 static char *cistrstr(const char *s, const char *sub);
31 static void drawmenu(void);
32 static void grabkeyboard(void);
33 static void insert(const char *str, ssize_t n);
34 static void keypress(XKeyEvent *ev);
35 static void match(void);
36 static size_t nextrune(int inc);
37 static void paste(void);
38 static void readstdin(void);
39 static void run(void);
40 static void setup(void);
41 static void usage(void);
42
43 static char text[BUFSIZ] = "";
44 static int bh, mw, mh;
45 static int inputw, promptw;
46 static size_t cursor = 0;
47 static const char *font = NULL;
48 static const char *prompt = NULL;
49 static const char *normbgcolor = "#222222";
50 static const char *normfgcolor = "#bbbbbb";
51 static const char *selbgcolor = "#005577";
52 static const char *selfgcolor = "#eeeeee";
53 static const char *outbgcolor = "#00ffff";
54 static const char *outfgcolor = "#000000";
55 static unsigned int lines = 0;
56 static unsigned long normcol[ColLast];
57 static unsigned long selcol[ColLast];
58 static unsigned long outcol[ColLast];
59 static Atom clip, utf8;
60 static Bool topbar = True;
61 static DC *dc;
62 static Item *items = NULL;
63 static Item *matches, *matchend;
64 static Item *prev, *curr, *next, *sel;
65 static Window win;
66 static XIC xic;
67
68 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
69 static char *(*fstrstr)(const char *, const char *) = strstr;
70
71 int
72 main(int argc, char *argv[]) {
73 Bool fast = False;
74 int i;
75
76 for(i = 1; i < argc; i++)
77 /* these options take no arguments */
78 if(!strcmp(argv[i], "-v")) { /* prints version information */
79 puts("dmenu-"VERSION", © 2006-2012 dmenu engineers, see LICENSE for details");
80 exit(EXIT_SUCCESS);
81 }
82 else if(!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
83 topbar = False;
84 else if(!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
85 fast = True;
86 else if(!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
87 fstrncmp = strncasecmp;
88 fstrstr = cistrstr;
89 }
90 else if(i+1 == argc)
91 usage();
92 /* these options take one argument */
93 else if(!strcmp(argv[i], "-l")) /* number of lines in vertical list */
94 lines = atoi(argv[++i]);
95 else if(!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
96 prompt = argv[++i];
97 else if(!strcmp(argv[i], "-fn")) /* font or font set */
98 font = argv[++i];
99 else if(!strcmp(argv[i], "-nb")) /* normal background color */
100 normbgcolor = argv[++i];
101 else if(!strcmp(argv[i], "-nf")) /* normal foreground color */
102 normfgcolor = argv[++i];
103 else if(!strcmp(argv[i], "-sb")) /* selected background color */
104 selbgcolor = argv[++i];
105 else if(!strcmp(argv[i], "-sf")) /* selected foreground color */
106 selfgcolor = argv[++i];
107 else
108 usage();
109
110 dc = initdc();
111 initfont(dc, font);
112
113 if(fast) {
114 grabkeyboard();
115 readstdin();
116 }
117 else {
118 readstdin();
119 grabkeyboard();
120 }
121 setup();
122 run();
123
124 return 1; /* unreachable */
125 }
126
127 void
128 appenditem(Item *item, Item **list, Item **last) {
129 if(*last)
130 (*last)->right = item;
131 else
132 *list = item;
133
134 item->left = *last;
135 item->right = NULL;
136 *last = item;
137 }
138
139 void
140 calcoffsets(void) {
141 int i, n;
142
143 if(lines > 0)
144 n = lines * bh;
145 else
146 n = mw - (promptw + inputw + textw(dc, "<") + textw(dc, ">"));
147 /* calculate which items will begin the next page and previous page */
148 for(i = 0, next = curr; next; next = next->right)
149 if((i += (lines > 0) ? bh : MIN(textw(dc, next->text), n)) > n)
150 break;
151 for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
152 if((i += (lines > 0) ? bh : MIN(textw(dc, prev->left->text), n)) > n)
153 break;
154 }
155
156 char *
157 cistrstr(const char *s, const char *sub) {
158 size_t len;
159
160 for(len = strlen(sub); *s; s++)
161 if(!strncasecmp(s, sub, len))
162 return (char *)s;
163 return NULL;
164 }
165
166 void
167 drawmenu(void) {
168 int curpos;
169 Item *item;
170
171 dc->x = 0;
172 dc->y = 0;
173 dc->h = bh;
174 drawrect(dc, 0, 0, mw, mh, True, BG(dc, normcol));
175
176 if(prompt && *prompt) {
177 dc->w = promptw;
178 drawtext(dc, prompt, selcol);
179 dc->x = dc->w;
180 }
181 /* draw input field */
182 dc->w = (lines > 0 || !matches) ? mw - dc->x : inputw;
183 drawtext(dc, text, normcol);
184 if((curpos = textnw(dc, text, cursor) + dc->h/2 - 2) < dc->w)
185 drawrect(dc, curpos, 2, 1, dc->h - 4, True, FG(dc, normcol));
186
187 if(lines > 0) {
188 /* draw vertical list */
189 dc->w = mw - dc->x;
190 for(item = curr; item != next; item = item->right) {
191 dc->y += dc->h;
192 drawtext(dc, item->text, (item == sel) ? selcol :
193 (item->out) ? outcol : normcol);
194 }
195 }
196 else if(matches) {
197 /* draw horizontal list */
198 dc->x += inputw;
199 dc->w = textw(dc, "<");
200 if(curr->left)
201 drawtext(dc, "<", normcol);
202 for(item = curr; item != next; item = item->right) {
203 dc->x += dc->w;
204 dc->w = MIN(textw(dc, item->text), mw - dc->x - textw(dc, ">"));
205 drawtext(dc, item->text, (item == sel) ? selcol :
206 (item->out) ? outcol : normcol);
207 }
208 dc->w = textw(dc, ">");
209 dc->x = mw - dc->w;
210 if(next)
211 drawtext(dc, ">", normcol);
212 }
213 mapdc(dc, win, mw, mh);
214 }
215
216 void
217 grabkeyboard(void) {
218 int i;
219
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(dc->dpy, DefaultRootWindow(dc->dpy), True,
223 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
224 return;
225 usleep(1000);
226 }
227 eprintf("cannot grab keyboard\n");
228 }
229
230 void
231 insert(const char *str, ssize_t n) {
232 if(strlen(text) + n > sizeof text - 1)
233 return;
234 /* move existing text out of the way, insert new text, and update cursor */
235 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
236 if(n > 0)
237 memcpy(&text[cursor], str, n);
238 cursor += n;
239 match();
240 }
241
242 void
243 keypress(XKeyEvent *ev) {
244 char buf[32];
245 int len;
246 KeySym ksym = NoSymbol;
247 Status status;
248
249 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
250 if(status == XBufferOverflow)
251 return;
252 if(ev->state & ControlMask)
253 switch(ksym) {
254 case XK_a: ksym = XK_Home; break;
255 case XK_b: ksym = XK_Left; break;
256 case XK_c: ksym = XK_Escape; break;
257 case XK_d: ksym = XK_Delete; break;
258 case XK_e: ksym = XK_End; break;
259 case XK_f: ksym = XK_Right; break;
260 case XK_g: ksym = XK_Escape; break;
261 case XK_h: ksym = XK_BackSpace; break;
262 case XK_i: ksym = XK_Tab; break;
263 case XK_j: /* fallthrough */
264 case XK_J: ksym = XK_Return; break;
265 case XK_m: /* fallthrough */
266 case XK_M: ksym = XK_Return; break;
267 case XK_n: ksym = XK_Down; break;
268 case XK_p: ksym = XK_Up; break;
269
270 case XK_k: /* delete right */
271 text[cursor] = '\0';
272 match();
273 break;
274 case XK_u: /* delete left */
275 insert(NULL, 0 - cursor);
276 break;
277 case XK_w: /* delete word */
278 while(cursor > 0 && text[nextrune(-1)] == ' ')
279 insert(NULL, nextrune(-1) - cursor);
280 while(cursor > 0 && text[nextrune(-1)] != ' ')
281 insert(NULL, nextrune(-1) - cursor);
282 break;
283 case XK_y: /* paste selection */
284 XConvertSelection(dc->dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
285 utf8, utf8, win, CurrentTime);
286 return;
287 case XK_Return:
288 case XK_KP_Enter:
289 break;
290 default:
291 return;
292 }
293 else if(ev->state & Mod1Mask)
294 switch(ksym) {
295 case XK_g: ksym = XK_Home; break;
296 case XK_G: ksym = XK_End; break;
297 case XK_h: ksym = XK_Up; break;
298 case XK_j: ksym = XK_Next; break;
299 case XK_k: ksym = XK_Prior; break;
300 case XK_l: ksym = XK_Down; break;
301 default:
302 return;
303 }
304 switch(ksym) {
305 default:
306 if(!iscntrl(*buf))
307 insert(buf, len);
308 break;
309 case XK_Delete:
310 if(text[cursor] == '\0')
311 return;
312 cursor = nextrune(+1);
313 /* fallthrough */
314 case XK_BackSpace:
315 if(cursor == 0)
316 return;
317 insert(NULL, nextrune(-1) - cursor);
318 break;
319 case XK_End:
320 if(text[cursor] != '\0') {
321 cursor = strlen(text);
322 break;
323 }
324 if(next) {
325 /* jump to end of list and position items in reverse */
326 curr = matchend;
327 calcoffsets();
328 curr = prev;
329 calcoffsets();
330 while(next && (curr = curr->right))
331 calcoffsets();
332 }
333 sel = matchend;
334 break;
335 case XK_Escape:
336 exit(EXIT_FAILURE);
337 case XK_Home:
338 if(sel == matches) {
339 cursor = 0;
340 break;
341 }
342 sel = curr = matches;
343 calcoffsets();
344 break;
345 case XK_Left:
346 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
347 cursor = nextrune(-1);
348 break;
349 }
350 if(lines > 0)
351 return;
352 /* fallthrough */
353 case XK_Up:
354 if(sel && sel->left && (sel = sel->left)->right == curr) {
355 curr = prev;
356 calcoffsets();
357 }
358 break;
359 case XK_Next:
360 if(!next)
361 return;
362 sel = curr = next;
363 calcoffsets();
364 break;
365 case XK_Prior:
366 if(!prev)
367 return;
368 sel = curr = prev;
369 calcoffsets();
370 break;
371 case XK_Return:
372 case XK_KP_Enter:
373 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
374 if(!(ev->state & ControlMask))
375 exit(EXIT_SUCCESS);
376 sel->out = True;
377 break;
378 case XK_Right:
379 if(text[cursor] != '\0') {
380 cursor = nextrune(+1);
381 break;
382 }
383 if(lines > 0)
384 return;
385 /* fallthrough */
386 case XK_Down:
387 if(sel && sel->right && (sel = sel->right) == next) {
388 curr = next;
389 calcoffsets();
390 }
391 break;
392 case XK_Tab:
393 if(!sel)
394 return;
395 strncpy(text, sel->text, sizeof text - 1);
396 text[sizeof text - 1] = '\0';
397 cursor = strlen(text);
398 match();
399 break;
400 }
401 drawmenu();
402 }
403
404 void
405 match(void) {
406 static char **tokv = NULL;
407 static int tokn = 0;
408
409 char buf[sizeof text], *s;
410 int i, tokc = 0;
411 size_t len;
412 Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
413
414 strcpy(buf, text);
415 /* separate input text into tokens to be matched individually */
416 for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
417 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
418 eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
419 len = tokc ? strlen(tokv[0]) : 0;
420
421 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
422 for(item = items; item && item->text; item++) {
423 for(i = 0; i < tokc; i++)
424 if(!fstrstr(item->text, tokv[i]))
425 break;
426 if(i != tokc) /* not all tokens match */
427 continue;
428 /* exact matches go first, then prefixes, then substrings */
429 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
430 appenditem(item, &matches, &matchend);
431 else if(!fstrncmp(tokv[0], item->text, len))
432 appenditem(item, &lprefix, &prefixend);
433 else
434 appenditem(item, &lsubstr, &substrend);
435 }
436 if(lprefix) {
437 if(matches) {
438 matchend->right = lprefix;
439 lprefix->left = matchend;
440 }
441 else
442 matches = lprefix;
443 matchend = prefixend;
444 }
445 if(lsubstr) {
446 if(matches) {
447 matchend->right = lsubstr;
448 lsubstr->left = matchend;
449 }
450 else
451 matches = lsubstr;
452 matchend = substrend;
453 }
454 curr = sel = matches;
455 calcoffsets();
456 }
457
458 size_t
459 nextrune(int inc) {
460 ssize_t n;
461
462 /* return location of next utf8 rune in the given direction (+1 or -1) */
463 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
464 return n;
465 }
466
467 void
468 paste(void) {
469 char *p, *q;
470 int di;
471 unsigned long dl;
472 Atom da;
473
474 /* we have been given the current selection, now insert it into input */
475 XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
476 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
477 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
478 XFree(p);
479 drawmenu();
480 }
481
482 void
483 readstdin(void) {
484 char buf[sizeof text], *p, *maxstr = NULL;
485 size_t i, max = 0, size = 0;
486
487 /* read each line from stdin and add it to the item list */
488 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
489 if(i+1 >= size / sizeof *items)
490 if(!(items = realloc(items, (size += BUFSIZ))))
491 eprintf("cannot realloc %u bytes:", size);
492 if((p = strchr(buf, '\n')))
493 *p = '\0';
494 if(!(items[i].text = strdup(buf)))
495 eprintf("cannot strdup %u bytes:", strlen(buf)+1);
496 items[i].out = False;
497 if(strlen(items[i].text) > max)
498 max = strlen(maxstr = items[i].text);
499 }
500 if(items)
501 items[i].text = NULL;
502 inputw = maxstr ? textw(dc, maxstr) : 0;
503 lines = MIN(lines, i);
504 }
505
506 void
507 run(void) {
508 XEvent ev;
509
510 while(!XNextEvent(dc->dpy, &ev)) {
511 if(XFilterEvent(&ev, win))
512 continue;
513 switch(ev.type) {
514 case Expose:
515 if(ev.xexpose.count == 0)
516 mapdc(dc, win, mw, mh);
517 break;
518 case KeyPress:
519 keypress(&ev.xkey);
520 break;
521 case SelectionNotify:
522 if(ev.xselection.property == utf8)
523 paste();
524 break;
525 case VisibilityNotify:
526 if(ev.xvisibility.state != VisibilityUnobscured)
527 XRaiseWindow(dc->dpy, win);
528 break;
529 }
530 }
531 }
532
533 void
534 setup(void) {
535 int x, y, screen = DefaultScreen(dc->dpy);
536 Window root = RootWindow(dc->dpy, screen);
537 XSetWindowAttributes swa;
538 XIM xim;
539 #ifdef XINERAMA
540 int n;
541 XineramaScreenInfo *info;
542 #endif
543
544 normcol[ColBG] = getcolor(dc, normbgcolor);
545 normcol[ColFG] = getcolor(dc, normfgcolor);
546 selcol[ColBG] = getcolor(dc, selbgcolor);
547 selcol[ColFG] = getcolor(dc, selfgcolor);
548 outcol[ColBG] = getcolor(dc, outbgcolor);
549 outcol[ColFG] = getcolor(dc, outfgcolor);
550
551 clip = XInternAtom(dc->dpy, "CLIPBOARD", False);
552 utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
553
554 /* calculate menu geometry */
555 bh = dc->font.height + 2;
556 lines = MAX(lines, 0);
557 mh = (lines + 1) * bh;
558 #ifdef XINERAMA
559 if((info = XineramaQueryScreens(dc->dpy, &n))) {
560 int a, j, di, i = 0, area = 0;
561 unsigned int du;
562 Window w, pw, dw, *dws;
563 XWindowAttributes wa;
564
565 XGetInputFocus(dc->dpy, &w, &di);
566 if(w != root && w != PointerRoot && w != None) {
567 /* find top-level window containing current input focus */
568 do {
569 if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
570 XFree(dws);
571 } while(w != root && w != pw);
572 /* find xinerama screen with which the window intersects most */
573 if(XGetWindowAttributes(dc->dpy, pw, &wa))
574 for(j = 0; j < n; j++)
575 if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
576 area = a;
577 i = j;
578 }
579 }
580 /* no focused window is on screen, so use pointer location instead */
581 if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
582 for(i = 0; i < n; i++)
583 if(INTERSECT(x, y, 1, 1, info[i]))
584 break;
585
586 x = info[i].x_org;
587 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
588 mw = info[i].width;
589 XFree(info);
590 }
591 else
592 #endif
593 {
594 x = 0;
595 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
596 mw = DisplayWidth(dc->dpy, screen);
597 }
598 promptw = (prompt && *prompt) ? textw(dc, prompt) : 0;
599 inputw = MIN(inputw, mw/3);
600 match();
601
602 /* create menu window */
603 swa.override_redirect = True;
604 swa.background_pixel = normcol[ColBG];
605 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
606 win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
607 DefaultDepth(dc->dpy, screen), CopyFromParent,
608 DefaultVisual(dc->dpy, screen),
609 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
610
611 /* open input methods */
612 xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
613 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
614 XNClientWindow, win, XNFocusWindow, win, NULL);
615
616 XMapRaised(dc->dpy, win);
617 resizedc(dc, mw, mh);
618 drawmenu();
619 }
620
621 void
622 usage(void) {
623 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
624 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
625 exit(EXIT_FAILURE);
626 }