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