Xinqi Bao's Git

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