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