]> git.armaanb.net Git - dmenu.git/blob - dmenu.c
rebind ^N ^P
[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 && text[cursor] == '\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                 case XK_m:
264                         ksym = XK_Return;
265                         break;
266                 case XK_k:  /* delete right */
267                         text[cursor] = '\0';
268                         match(False);
269                         break;
270                 case XK_n:
271                         ksym = XK_Next;
272                         break;
273                 case XK_p:
274                         ksym = XK_Prior;
275                         break;
276                 case XK_u:  /* delete left */
277                         insert(NULL, 0 - cursor);
278                         break;
279                 case XK_w:  /* delete word */
280                         while(cursor > 0 && text[nextrune(-1)] == ' ')
281                                 insert(NULL, nextrune(-1) - cursor);
282                         while(cursor > 0 && text[nextrune(-1)] != ' ')
283                                 insert(NULL, nextrune(-1) - cursor);
284                         break;
285                 case XK_y:  /* paste selection */
286                         XConvertSelection(dc->dpy, XA_PRIMARY, utf8, utf8, win, CurrentTime);
287                         return;
288                 }
289         }
290         switch(ksym) {
291         default:
292                 if(!iscntrl(*buf))
293                         insert(buf, strlen(buf));
294                 break;
295         case XK_Delete:
296                 if(text[cursor] == '\0')
297                         return;
298                 cursor = nextrune(+1);
299         case XK_BackSpace:
300                 if(cursor > 0)
301                         insert(NULL, nextrune(-1) - cursor);
302                 break;
303         case XK_End:
304                 if(text[cursor] != '\0') {
305                         cursor = strlen(text);
306                         break;
307                 }
308                 if(next) {
309                         curr = matchend;
310                         calcoffsets();
311                         curr = prev;
312                         calcoffsets();
313                         while(next && (curr = curr->right))
314                                 calcoffsets();
315                 }
316                 sel = matchend;
317                 break;
318         case XK_Escape:
319                 exit(EXIT_FAILURE);
320         case XK_Home:
321                 if(sel == matches) {
322                         cursor = 0;
323                         break;
324                 }
325                 sel = curr = matches;
326                 calcoffsets();
327                 break;
328         case XK_Left:
329                 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
330                         cursor = nextrune(-1);
331                         break;
332                 }
333                 else if(lines > 0)
334                         return;
335         case XK_Up:
336                 if(sel && sel->left && (sel = sel->left)->right == curr) {
337                         curr = prev;
338                         calcoffsets();
339                 }
340                 break;
341         case XK_Next:
342                 if(!next)
343                         return;
344                 sel = curr = next;
345                 calcoffsets();
346                 break;
347         case XK_Prior:
348                 if(!prev)
349                         return;
350                 sel = curr = prev;
351                 calcoffsets();
352                 break;
353         case XK_Return:
354         case XK_KP_Enter:
355                 fputs((sel && !(ev->state & ShiftMask)) ? sel->text : text, stdout);
356                 exit(EXIT_SUCCESS);
357         case XK_Right:
358                 if(text[cursor] != '\0') {
359                         cursor = nextrune(+1);
360                         break;
361                 }
362                 else if(lines > 0)
363                         return;
364         case XK_Down:
365                 if(sel && sel->right && (sel = sel->right) == next) {
366                         curr = next;
367                         calcoffsets();
368                 }
369                 break;
370         case XK_Tab:
371                 if(!sel)
372                         return;
373                 strncpy(text, sel->text, sizeof text);
374                 cursor = strlen(text);
375                 match(True);
376                 break;
377         }
378         drawmenu();
379 }
380
381 void
382 match(Bool sub) {
383         size_t len = strlen(text);
384         Item *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
385         Item *item, *lnext;
386
387         lexact = lprefix = lsubstr = exactend = prefixend = substrend = NULL;
388         for(item = sub ? matches : items; item && item->text; item = lnext) {
389                 lnext = sub ? item->right : item + 1;
390                 if(!fstrncmp(text, item->text, len + 1))
391                         appenditem(item, &lexact, &exactend);
392                 else if(!fstrncmp(text, item->text, len))
393                         appenditem(item, &lprefix, &prefixend);
394                 else if(fstrstr(item->text, text))
395                         appenditem(item, &lsubstr, &substrend);
396         }
397         matches = lexact;
398         matchend = exactend;
399
400         if(lprefix) {
401                 if(matchend) {
402                         matchend->right = lprefix;
403                         lprefix->left = matchend;
404                 }
405                 else
406                         matches = lprefix;
407                 matchend = prefixend;
408         }
409         if(lsubstr) {
410                 if(matchend) {
411                         matchend->right = lsubstr;
412                         lsubstr->left = matchend;
413                 }
414                 else
415                         matches = lsubstr;
416                 matchend = substrend;
417         }
418         curr = sel = matches;
419         calcoffsets();
420 }
421
422 size_t
423 nextrune(int inc) {
424         ssize_t n;
425
426         for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
427         return n;
428 }
429
430 void
431 paste(void) {
432         char *p, *q;
433         int di;
434         unsigned long dl;
435         Atom da;
436
437         XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
438                            utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
439         insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
440         XFree(p);
441         drawmenu();
442 }
443
444 void
445 readstdin(void) {
446         char buf[sizeof text], *p, *maxstr = NULL;
447         size_t i, max = 0, size = 0;
448
449         for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
450                 if(i+1 >= size / sizeof *items)
451                         if(!(items = realloc(items, (size += BUFSIZ))))
452                                 eprintf("cannot realloc %u bytes:", size);
453                 if((p = strchr(buf, '\n')))
454                         *p = '\0';
455                 if(!(items[i].text = strdup(buf)))
456                         eprintf("cannot strdup %u bytes:", strlen(buf)+1);
457                 if(strlen(items[i].text) > max)
458                         max = strlen(maxstr = items[i].text);
459         }
460         if(items)
461                 items[i].text = NULL;
462         inputw = maxstr ? textw(dc, maxstr) : 0;
463 }
464
465 void
466 run(void) {
467         XEvent ev;
468
469         while(!XNextEvent(dc->dpy, &ev))
470                 switch(ev.type) {
471                 case Expose:
472                         if(ev.xexpose.count == 0)
473                                 drawmenu();
474                         break;
475                 case KeyPress:
476                         keypress(&ev.xkey);
477                         break;
478                 case SelectionNotify:
479                         if(ev.xselection.property == utf8)
480                                 paste();
481                         break;
482                 case VisibilityNotify:
483                         if(ev.xvisibility.state != VisibilityUnobscured)
484                                 XRaiseWindow(dc->dpy, win);
485                         break;
486                 }
487 }
488
489 void
490 setup(void) {
491         int x, y, screen = DefaultScreen(dc->dpy);
492         Window root = RootWindow(dc->dpy, screen);
493         XSetWindowAttributes wa;
494 #ifdef XINERAMA
495         int n;
496         XineramaScreenInfo *info;
497 #endif
498
499         normcol[ColBG] = getcolor(dc, normbgcolor);
500         normcol[ColFG] = getcolor(dc, normfgcolor);
501         selcol[ColBG]  = getcolor(dc, selbgcolor);
502         selcol[ColFG]  = getcolor(dc, selfgcolor);
503
504         utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
505
506         /* menu geometry */
507         bh = dc->font.height + 2;
508         lines = MAX(lines, 0);
509         mh = (lines + 1) * bh;
510 #ifdef XINERAMA
511         if((info = XineramaQueryScreens(dc->dpy, &n))) {
512                 int i, di;
513                 unsigned int du;
514                 Window dw;
515
516                 XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du);
517                 for(i = 0; i < n-1; i++)
518                         if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
519                                 break;
520                 x = info[i].x_org;
521                 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
522                 mw = info[i].width;
523                 XFree(info);
524         }
525         else
526 #endif
527         {
528                 x = 0;
529                 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
530                 mw = DisplayWidth(dc->dpy, screen);
531         }
532         promptw = prompt ? textw(dc, prompt) : 0;
533         inputw = MIN(inputw, mw/3);
534         match(False);
535
536         /* menu window */
537         wa.override_redirect = True;
538         wa.background_pixmap = ParentRelative;
539         wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
540         win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
541                             DefaultDepth(dc->dpy, screen), CopyFromParent,
542                             DefaultVisual(dc->dpy, screen),
543                             CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
544
545         XMapRaised(dc->dpy, win);
546         resizedc(dc, mw, mh);
547         drawmenu();
548 }
549
550 void
551 usage(void) {
552         fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
553               "             [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
554         exit(EXIT_FAILURE);
555 }