Xinqi Bao's Git

efc1e54b16e6e47d9f6643fb829df688f7ffe0fb
[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);
396 cursor = strlen(text);
397 match();
398 break;
399 }
400 drawmenu();
401 }
402
403 void
404 match(void) {
405 static char **tokv = NULL;
406 static int tokn = 0;
407
408 char buf[sizeof text], *s;
409 int i, tokc = 0;
410 size_t len;
411 Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
412
413 strcpy(buf, text);
414 /* separate input text into tokens to be matched individually */
415 for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
416 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
417 eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
418 len = tokc ? strlen(tokv[0]) : 0;
419
420 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
421 for(item = items; item && item->text; item++) {
422 for(i = 0; i < tokc; i++)
423 if(!fstrstr(item->text, tokv[i]))
424 break;
425 if(i != tokc) /* not all tokens match */
426 continue;
427 /* exact matches go first, then prefixes, then substrings */
428 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
429 appenditem(item, &matches, &matchend);
430 else if(!fstrncmp(tokv[0], item->text, len))
431 appenditem(item, &lprefix, &prefixend);
432 else
433 appenditem(item, &lsubstr, &substrend);
434 }
435 if(lprefix) {
436 if(matches) {
437 matchend->right = lprefix;
438 lprefix->left = matchend;
439 }
440 else
441 matches = lprefix;
442 matchend = prefixend;
443 }
444 if(lsubstr) {
445 if(matches) {
446 matchend->right = lsubstr;
447 lsubstr->left = matchend;
448 }
449 else
450 matches = lsubstr;
451 matchend = substrend;
452 }
453 curr = sel = matches;
454 calcoffsets();
455 }
456
457 size_t
458 nextrune(int inc) {
459 ssize_t n;
460
461 /* return location of next utf8 rune in the given direction (+1 or -1) */
462 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
463 return n;
464 }
465
466 void
467 paste(void) {
468 char *p, *q;
469 int di;
470 unsigned long dl;
471 Atom da;
472
473 /* we have been given the current selection, now insert it into input */
474 XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
475 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
476 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
477 XFree(p);
478 drawmenu();
479 }
480
481 void
482 readstdin(void) {
483 char buf[sizeof text], *p, *maxstr = NULL;
484 size_t i, max = 0, size = 0;
485
486 /* read each line from stdin and add it to the item list */
487 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
488 if(i+1 >= size / sizeof *items)
489 if(!(items = realloc(items, (size += BUFSIZ))))
490 eprintf("cannot realloc %u bytes:", size);
491 if((p = strchr(buf, '\n')))
492 *p = '\0';
493 if(!(items[i].text = strdup(buf)))
494 eprintf("cannot strdup %u bytes:", strlen(buf)+1);
495 items[i].out = False;
496 if(strlen(items[i].text) > max)
497 max = strlen(maxstr = items[i].text);
498 }
499 if(items)
500 items[i].text = NULL;
501 inputw = maxstr ? textw(dc, maxstr) : 0;
502 lines = MIN(lines, i);
503 }
504
505 void
506 run(void) {
507 XEvent ev;
508
509 while(!XNextEvent(dc->dpy, &ev)) {
510 if(XFilterEvent(&ev, win))
511 continue;
512 switch(ev.type) {
513 case Expose:
514 if(ev.xexpose.count == 0)
515 mapdc(dc, win, mw, mh);
516 break;
517 case KeyPress:
518 keypress(&ev.xkey);
519 break;
520 case SelectionNotify:
521 if(ev.xselection.property == utf8)
522 paste();
523 break;
524 case VisibilityNotify:
525 if(ev.xvisibility.state != VisibilityUnobscured)
526 XRaiseWindow(dc->dpy, win);
527 break;
528 }
529 }
530 }
531
532 void
533 setup(void) {
534 int x, y, screen = DefaultScreen(dc->dpy);
535 Window root = RootWindow(dc->dpy, screen);
536 XSetWindowAttributes swa;
537 XIM xim;
538 #ifdef XINERAMA
539 int n;
540 XineramaScreenInfo *info;
541 #endif
542
543 normcol[ColBG] = getcolor(dc, normbgcolor);
544 normcol[ColFG] = getcolor(dc, normfgcolor);
545 selcol[ColBG] = getcolor(dc, selbgcolor);
546 selcol[ColFG] = getcolor(dc, selfgcolor);
547 outcol[ColBG] = getcolor(dc, outbgcolor);
548 outcol[ColFG] = getcolor(dc, outfgcolor);
549
550 clip = XInternAtom(dc->dpy, "CLIPBOARD", False);
551 utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
552
553 /* calculate menu geometry */
554 bh = dc->font.height + 2;
555 lines = MAX(lines, 0);
556 mh = (lines + 1) * bh;
557 #ifdef XINERAMA
558 if((info = XineramaQueryScreens(dc->dpy, &n))) {
559 int a, j, di, i = 0, area = 0;
560 unsigned int du;
561 Window w, pw, dw, *dws;
562 XWindowAttributes wa;
563
564 XGetInputFocus(dc->dpy, &w, &di);
565 if(w != root && w != PointerRoot && w != None) {
566 /* find top-level window containing current input focus */
567 do {
568 if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
569 XFree(dws);
570 } while(w != root && w != pw);
571 /* find xinerama screen with which the window intersects most */
572 if(XGetWindowAttributes(dc->dpy, pw, &wa))
573 for(j = 0; j < n; j++)
574 if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
575 area = a;
576 i = j;
577 }
578 }
579 /* no focused window is on screen, so use pointer location instead */
580 if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
581 for(i = 0; i < n; i++)
582 if(INTERSECT(x, y, 1, 1, info[i]))
583 break;
584
585 x = info[i].x_org;
586 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
587 mw = info[i].width;
588 XFree(info);
589 }
590 else
591 #endif
592 {
593 x = 0;
594 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
595 mw = DisplayWidth(dc->dpy, screen);
596 }
597 promptw = (prompt && *prompt) ? textw(dc, prompt) : 0;
598 inputw = MIN(inputw, mw/3);
599 match();
600
601 /* create menu window */
602 swa.override_redirect = True;
603 swa.background_pixel = normcol[ColBG];
604 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
605 win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
606 DefaultDepth(dc->dpy, screen), CopyFromParent,
607 DefaultVisual(dc->dpy, screen),
608 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
609
610 /* open input methods */
611 xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
612 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
613 XNClientWindow, win, XNFocusWindow, win, NULL);
614
615 XMapRaised(dc->dpy, win);
616 resizedc(dc, mw, mh);
617 drawmenu();
618 }
619
620 void
621 usage(void) {
622 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
623 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
624 exit(EXIT_FAILURE);
625 }