Xinqi Bao's Git

fd98d54340553f0f909af9fd2fb7c3e2a5a60353
[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 INRECT(x,y,rx,ry,rw,rh) ((x) >= (rx) && (x) < (rx)+(rw) && (y) >= (ry) && (y) < (ry)+(rh))
17 #define MIN(a,b) ((a) < (b) ? (a) : (b))
18 #define MAX(a,b) ((a) > (b) ? (a) : (b))
19
20 typedef struct Item Item;
21 struct Item {
22 char *text;
23 Item *left, *right;
24 };
25
26 static void appenditem(Item *item, Item **list, Item **last);
27 static void calcoffsets(void);
28 static char *cistrstr(const char *s, const char *sub);
29 static void drawmenu(void);
30 static void grabkeyboard(void);
31 static void insert(const char *str, ssize_t n);
32 static void keypress(XKeyEvent *ev);
33 static void match(Bool sub);
34 static size_t nextrune(int inc);
35 static void paste(void);
36 static void readstdin(void);
37 static void run(void);
38 static void setup(void);
39 static void usage(void);
40
41 static char text[BUFSIZ] = "";
42 static int bh, mw, mh;
43 static int inputw, promptw;
44 static int lines = 0;
45 static size_t cursor = 0;
46 static const char *font = NULL;
47 static const char *prompt = NULL;
48 static const char *normbgcolor = "#cccccc";
49 static const char *normfgcolor = "#000000";
50 static const char *selbgcolor = "#0066ff";
51 static const char *selfgcolor = "#ffffff";
52 static unsigned long normcol[ColLast];
53 static unsigned long selcol[ColLast];
54 static Atom utf8;
55 static Bool topbar = True;
56 static DC *dc;
57 static Item *items = NULL;
58 static Item *matches, *matchend;
59 static Item *prev, *curr, *next, *sel;
60 static Window win;
61
62 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
63 static char *(*fstrstr)(const char *, const char *) = strstr;
64
65 int
66 main(int argc, char *argv[]) {
67 Bool fast = False;
68 int i;
69
70 for(i = 1; i < argc; i++)
71 /* single flags */
72 if(!strcmp(argv[i], "-v")) {
73 puts("dmenu-"VERSION", © 2006-2011 dmenu engineers, see LICENSE for details");
74 exit(EXIT_SUCCESS);
75 }
76 else if(!strcmp(argv[i], "-b"))
77 topbar = False;
78 else if(!strcmp(argv[i], "-f"))
79 fast = True;
80 else if(!strcmp(argv[i], "-i")) {
81 fstrncmp = strncasecmp;
82 fstrstr = cistrstr;
83 }
84 else if(i+1 == argc)
85 usage();
86 /* double flags */
87 else if(!strcmp(argv[i], "-l"))
88 lines = atoi(argv[++i]);
89 else if(!strcmp(argv[i], "-p"))
90 prompt = argv[++i];
91 else if(!strcmp(argv[i], "-fn"))
92 font = argv[++i];
93 else if(!strcmp(argv[i], "-nb"))
94 normbgcolor = argv[++i];
95 else if(!strcmp(argv[i], "-nf"))
96 normfgcolor = argv[++i];
97 else if(!strcmp(argv[i], "-sb"))
98 selbgcolor = argv[++i];
99 else if(!strcmp(argv[i], "-sf"))
100 selfgcolor = argv[++i];
101 else
102 usage();
103
104 dc = initdc();
105 initfont(dc, font);
106
107 if(fast) {
108 grabkeyboard();
109 readstdin();
110 }
111 else {
112 readstdin();
113 grabkeyboard();
114 }
115 setup();
116 run();
117
118 return EXIT_FAILURE; /* unreachable */
119 }
120
121 void
122 appenditem(Item *item, Item **list, Item **last) {
123 if(!*last)
124 *list = item;
125 else
126 (*last)->right = item;
127
128 item->left = *last;
129 item->right = NULL;
130 *last = item;
131 }
132
133 void
134 calcoffsets(void) {
135 int i, n;
136
137 if(lines > 0)
138 n = lines * bh;
139 else
140 n = mw - (promptw + inputw + textw(dc, "<") + textw(dc, ">"));
141
142 for(i = 0, next = curr; next; next = next->right)
143 if((i += (lines > 0) ? bh : MIN(textw(dc, next->text), n)) > n)
144 break;
145 for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
146 if((i += (lines > 0) ? bh : MIN(textw(dc, prev->left->text), n)) > n)
147 break;
148 }
149
150 char *
151 cistrstr(const char *s, const char *sub) {
152 size_t len;
153
154 for(len = strlen(sub); *s; s++)
155 if(!strncasecmp(s, sub, len))
156 return (char *)s;
157 return NULL;
158 }
159
160 void
161 drawmenu(void) {
162 int curpos;
163 Item *item;
164
165 dc->x = 0;
166 dc->y = 0;
167 dc->h = bh;
168 drawrect(dc, 0, 0, mw, mh, True, BG(dc, normcol));
169
170 if(prompt) {
171 dc->w = promptw;
172 drawtext(dc, prompt, selcol);
173 dc->x = dc->w;
174 }
175 dc->w = (lines > 0 || !matches) ? mw - dc->x : inputw;
176 drawtext(dc, text, normcol);
177 if((curpos = textnw(dc, text, cursor) + dc->h/2 - 2) < dc->w)
178 drawrect(dc, curpos, 2, 1, dc->h - 4, True, FG(dc, normcol));
179
180 if(lines > 0) {
181 dc->w = mw - dc->x;
182 for(item = curr; item != next; item = item->right) {
183 dc->y += dc->h;
184 drawtext(dc, item->text, (item == sel) ? selcol : normcol);
185 }
186 }
187 else if(matches) {
188 dc->x += inputw;
189 dc->w = textw(dc, "<");
190 if(curr->left)
191 drawtext(dc, "<", normcol);
192 for(item = curr; item != next; item = item->right) {
193 dc->x += dc->w;
194 dc->w = MIN(textw(dc, item->text), mw - dc->x - textw(dc, ">"));
195 drawtext(dc, item->text, (item == sel) ? selcol : normcol);
196 }
197 dc->w = textw(dc, ">");
198 dc->x = mw - dc->w;
199 if(next)
200 drawtext(dc, ">", normcol);
201 }
202 mapdc(dc, win, mw, mh);
203 }
204
205 void
206 grabkeyboard(void) {
207 int i;
208
209 for(i = 0; i < 1000; i++) {
210 if(XGrabKeyboard(dc->dpy, DefaultRootWindow(dc->dpy), True,
211 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
212 return;
213 usleep(1000);
214 }
215 eprintf("cannot grab keyboard\n");
216 }
217
218 void
219 insert(const char *str, ssize_t n) {
220 if(strlen(text) + n > sizeof text - 1)
221 return;
222 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
223 if(n > 0)
224 memcpy(&text[cursor], str, n);
225 cursor += n;
226 match(n > 0 && text[cursor] == '\0');
227 }
228
229 void
230 keypress(XKeyEvent *ev) {
231 char buf[32];
232 KeySym ksym;
233
234 XLookupString(ev, buf, sizeof buf, &ksym, NULL);
235 if(ev->state & ControlMask) {
236 KeySym lower, upper;
237
238 XConvertCase(ksym, &lower, &upper);
239 switch(lower) {
240 case XK_a: ksym = XK_Home; break;
241 case XK_b: ksym = XK_Left; break;
242 case XK_c: ksym = XK_Escape; break;
243 case XK_d: ksym = XK_Delete; break;
244 case XK_e: ksym = XK_End; break;
245 case XK_f: ksym = XK_Right; break;
246 case XK_h: ksym = XK_BackSpace; break;
247 case XK_i: ksym = XK_Tab; break;
248 case XK_j: ksym = XK_Return; break;
249 case XK_m: ksym = XK_Return; break;
250 case XK_n: ksym = XK_Up; break;
251 case XK_p: ksym = XK_Down; break;
252
253 case XK_k: /* delete right */
254 text[cursor] = '\0';
255 match(False);
256 break;
257 case XK_u: /* delete left */
258 insert(NULL, 0 - cursor);
259 break;
260 case XK_w: /* delete word */
261 while(cursor > 0 && text[nextrune(-1)] == ' ')
262 insert(NULL, nextrune(-1) - cursor);
263 while(cursor > 0 && text[nextrune(-1)] != ' ')
264 insert(NULL, nextrune(-1) - cursor);
265 break;
266 case XK_y: /* paste selection */
267 XConvertSelection(dc->dpy, XA_PRIMARY, utf8, utf8, win, CurrentTime);
268 return;
269 default:
270 return;
271 }
272 }
273 switch(ksym) {
274 default:
275 if(!iscntrl(*buf))
276 insert(buf, strlen(buf));
277 break;
278 case XK_Delete:
279 if(text[cursor] == '\0')
280 return;
281 cursor = nextrune(+1);
282 /* fallthrough */
283 case XK_BackSpace:
284 if(cursor == 0)
285 return;
286 insert(NULL, nextrune(-1) - cursor);
287 break;
288 case XK_End:
289 if(text[cursor] != '\0') {
290 cursor = strlen(text);
291 break;
292 }
293 if(next) {
294 curr = matchend;
295 calcoffsets();
296 curr = prev;
297 calcoffsets();
298 while(next && (curr = curr->right))
299 calcoffsets();
300 }
301 sel = matchend;
302 break;
303 case XK_Escape:
304 exit(EXIT_FAILURE);
305 case XK_Home:
306 if(sel == matches) {
307 cursor = 0;
308 break;
309 }
310 sel = curr = matches;
311 calcoffsets();
312 break;
313 case XK_Left:
314 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
315 cursor = nextrune(-1);
316 break;
317 }
318 /* fallthrough */
319 case XK_Up:
320 if(sel && sel->left && (sel = sel->left)->right == curr) {
321 curr = prev;
322 calcoffsets();
323 }
324 break;
325 case XK_Next:
326 if(!next)
327 return;
328 sel = curr = next;
329 calcoffsets();
330 break;
331 case XK_Prior:
332 if(!prev)
333 return;
334 sel = curr = prev;
335 calcoffsets();
336 break;
337 case XK_Return:
338 case XK_KP_Enter:
339 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
340 exit(EXIT_SUCCESS);
341 case XK_Right:
342 if(text[cursor] != '\0') {
343 cursor = nextrune(+1);
344 break;
345 }
346 /* fallthrough */
347 case XK_Down:
348 if(sel && sel->right && (sel = sel->right) == next) {
349 curr = next;
350 calcoffsets();
351 }
352 break;
353 case XK_Tab:
354 if(!sel)
355 return;
356 strncpy(text, sel->text, sizeof text);
357 cursor = strlen(text);
358 match(True);
359 break;
360 }
361 drawmenu();
362 }
363
364 void
365 match(Bool sub) {
366 size_t len = strlen(text);
367 Item *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
368 Item *item, *lnext;
369
370 lexact = lprefix = lsubstr = exactend = prefixend = substrend = NULL;
371 for(item = sub ? matches : items; item && item->text; item = lnext) {
372 lnext = sub ? item->right : item + 1;
373 if(!fstrncmp(text, item->text, len + 1))
374 appenditem(item, &lexact, &exactend);
375 else if(!fstrncmp(text, item->text, len))
376 appenditem(item, &lprefix, &prefixend);
377 else if(fstrstr(item->text, text))
378 appenditem(item, &lsubstr, &substrend);
379 }
380 matches = lexact;
381 matchend = exactend;
382
383 if(lprefix) {
384 if(matchend) {
385 matchend->right = lprefix;
386 lprefix->left = matchend;
387 }
388 else
389 matches = lprefix;
390 matchend = prefixend;
391 }
392 if(lsubstr) {
393 if(matchend) {
394 matchend->right = lsubstr;
395 lsubstr->left = matchend;
396 }
397 else
398 matches = lsubstr;
399 matchend = substrend;
400 }
401 curr = sel = matches;
402 calcoffsets();
403 }
404
405 size_t
406 nextrune(int inc) {
407 ssize_t n;
408
409 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
410 return n;
411 }
412
413 void
414 paste(void) {
415 char *p, *q;
416 int di;
417 unsigned long dl;
418 Atom da;
419
420 XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
421 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
422 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
423 XFree(p);
424 drawmenu();
425 }
426
427 void
428 readstdin(void) {
429 char buf[sizeof text], *p, *maxstr = NULL;
430 size_t i, max = 0, size = 0;
431
432 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
433 if(i+1 >= size / sizeof *items)
434 if(!(items = realloc(items, (size += BUFSIZ))))
435 eprintf("cannot realloc %u bytes:", size);
436 if((p = strchr(buf, '\n')))
437 *p = '\0';
438 if(!(items[i].text = strdup(buf)))
439 eprintf("cannot strdup %u bytes:", strlen(buf)+1);
440 if(strlen(items[i].text) > max)
441 max = strlen(maxstr = items[i].text);
442 }
443 if(items)
444 items[i].text = NULL;
445 inputw = maxstr ? textw(dc, maxstr) : 0;
446 }
447
448 void
449 run(void) {
450 XEvent ev;
451
452 while(!XNextEvent(dc->dpy, &ev))
453 switch(ev.type) {
454 case Expose:
455 if(ev.xexpose.count == 0)
456 mapdc(dc, win, mw, mh);
457 break;
458 case KeyPress:
459 keypress(&ev.xkey);
460 break;
461 case SelectionNotify:
462 if(ev.xselection.property == utf8)
463 paste();
464 break;
465 case VisibilityNotify:
466 if(ev.xvisibility.state != VisibilityUnobscured)
467 XRaiseWindow(dc->dpy, win);
468 break;
469 }
470 }
471
472 void
473 setup(void) {
474 int x, y, screen = DefaultScreen(dc->dpy);
475 Window root = RootWindow(dc->dpy, screen);
476 XSetWindowAttributes wa;
477 #ifdef XINERAMA
478 int n;
479 XineramaScreenInfo *info;
480 #endif
481
482 normcol[ColBG] = getcolor(dc, normbgcolor);
483 normcol[ColFG] = getcolor(dc, normfgcolor);
484 selcol[ColBG] = getcolor(dc, selbgcolor);
485 selcol[ColFG] = getcolor(dc, selfgcolor);
486
487 utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
488
489 /* menu geometry */
490 bh = dc->font.height + 2;
491 lines = MAX(lines, 0);
492 mh = (lines + 1) * bh;
493 #ifdef XINERAMA
494 if((info = XineramaQueryScreens(dc->dpy, &n))) {
495 int i, di;
496 unsigned int du;
497 Window dw;
498
499 XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
500 for(i = 0; i < n-1; i++)
501 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
502 break;
503 x = info[i].x_org;
504 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
505 mw = info[i].width;
506 XFree(info);
507 }
508 else
509 #endif
510 {
511 x = 0;
512 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
513 mw = DisplayWidth(dc->dpy, screen);
514 }
515 promptw = prompt ? textw(dc, prompt) : 0;
516 inputw = MIN(inputw, mw/3);
517 match(False);
518
519 /* menu window */
520 wa.override_redirect = True;
521 wa.background_pixmap = ParentRelative;
522 wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
523 win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
524 DefaultDepth(dc->dpy, screen), CopyFromParent,
525 DefaultVisual(dc->dpy, screen),
526 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
527
528 XMapRaised(dc->dpy, win);
529 resizedc(dc, mw, mh);
530 drawmenu();
531 }
532
533 void
534 usage(void) {
535 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
536 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
537 exit(EXIT_FAILURE);
538 }