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