03c8b1f68d78cfb733053bc8ee3f2413709d113f
[dmenu.git] / main.c
1 /*
2  * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
3  * (C)opyright MMVI Sander van Dijk <a dot h dot vandijk at gmail dot com>
4  * See LICENSE file for license details.
5  */
6
7 #include "dmenu.h"
8
9 #include <ctype.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <sys/select.h>
15 #include <sys/time.h>
16 #include <X11/cursorfont.h>
17 #include <X11/Xutil.h>
18 #include <X11/keysym.h>
19
20 typedef struct Item Item;
21 struct Item {
22         Item *next;             /* traverses all items */
23         Item *left, *right;     /* traverses items matching current search pattern */
24         char *text;
25 };
26
27 /* static */
28
29 static char text[4096];
30 static int mx, my, mw, mh;
31 static int ret = 0;
32 static int nitem = 0;
33 static unsigned int cmdw = 0;
34 static Bool running = True;
35 static Item *allitems = NULL;   /* first of all items */
36 static Item *item = NULL;       /* first of pattern matching items */
37 static Item *sel = NULL;
38 static Item *next = NULL;
39 static Item *prev = NULL;
40 static Item *curr = NULL;
41 static Window root;
42 static Window win;
43
44 static void
45 calcoffsets()
46 {
47         unsigned int tw, w;
48
49         if(!curr)
50                 return;
51
52         w = cmdw + 2 * SPACE;
53         for(next = curr; next; next=next->right) {
54                 tw = textw(next->text);
55                 if(tw > mw / 3)
56                         tw = mw / 3;
57                 w += tw;
58                 if(w > mw)
59                         break;
60         }
61
62         w = cmdw + 2 * SPACE;
63         for(prev = curr; prev && prev->left; prev=prev->left) {
64                 tw = textw(prev->left->text);
65                 if(tw > mw / 3)
66                         tw = mw / 3;
67                 w += tw;
68                 if(w > mw)
69                         break;
70         }
71 }
72
73 static void
74 drawmenu()
75 {
76         Item *i;
77
78         dc.x = 0;
79         dc.y = 0;
80         dc.w = mw;
81         dc.h = mh;
82         drawtext(NULL, dc.norm);
83
84         /* print command */
85         if(cmdw && item)
86                 dc.w = cmdw;
87         drawtext(text[0] ? text : NULL, dc.norm);
88         dc.x += cmdw;
89
90         if(curr) {
91                 dc.w = SPACE;
92                 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
93                 dc.x += dc.w;
94
95                 /* determine maximum items */
96                 for(i = curr; i != next; i=i->right) {
97                         dc.w = textw(i->text);
98                         if(dc.w > mw / 3)
99                                 dc.w = mw / 3;
100                         drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
101                         dc.x += dc.w;
102                 }
103
104                 dc.x = mw - SPACE;
105                 dc.w = SPACE;
106                 drawtext(next ? ">" : NULL, dc.norm);
107         }
108         XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
109         XFlush(dpy);
110 }
111
112 static void
113 match(char *pattern)
114 {
115         unsigned int plen;
116         Item *i, *j;
117
118         if(!pattern)
119                 return;
120
121         plen = strlen(pattern);
122         item = j = NULL;
123         nitem = 0;
124
125         for(i = allitems; i; i=i->next)
126                 if(!plen || !strncmp(pattern, i->text, plen)) {
127                         if(!j)
128                                 item = i;
129                         else
130                                 j->right = i;
131                         i->left = j;
132                         i->right = NULL;
133                         j = i;
134                         nitem++;
135                 }
136         for(i = allitems; i; i=i->next)
137                 if(plen && strncmp(pattern, i->text, plen)
138                                 && strstr(i->text, pattern)) {
139                         if(!j)
140                                 item = i;
141                         else
142                                 j->right = i;
143                         i->left = j;
144                         i->right = NULL;
145                         j = i;
146                         nitem++;
147                 }
148
149         curr = prev = next = sel = item;
150         calcoffsets();
151 }
152
153 static void
154 kpress(XKeyEvent * e)
155 {
156         char buf[32];
157         int num, prev_nitem;
158         unsigned int i, len;
159         KeySym ksym;
160
161         len = strlen(text);
162         buf[0] = 0;
163         num = XLookupString(e, buf, sizeof(buf), &ksym, 0);
164
165         if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
166                         || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
167                         || IsPrivateKeypadKey(ksym))
168                 return;
169
170         /* first check if a control mask is omitted */
171         if(e->state & ControlMask) {
172                 switch (ksym) {
173                 default:        /* ignore other control sequences */
174                         return;
175                         break;
176                 case XK_h:
177                 case XK_H:
178                         ksym = XK_BackSpace;
179                         break;
180                 case XK_u:
181                 case XK_U:
182                         text[0] = 0;
183                         match(text);
184                         drawmenu();
185                         return;
186                         break;
187                 }
188         }
189         switch(ksym) {
190         case XK_Left:
191                 if(!(sel && sel->left))
192                         return;
193                 sel=sel->left;
194                 if(sel->right == curr) {
195                         curr = prev;
196                         calcoffsets();
197                 }
198                 break;
199         case XK_Tab:
200                 if(!sel)
201                         return;
202                 strncpy(text, sel->text, sizeof(text));
203                 match(text);
204                 break;
205         case XK_Right:
206                 if(!(sel && sel->right))
207                         return;
208                 sel=sel->right;
209                 if(sel == next) {
210                         curr = next;
211                         calcoffsets();
212                 }
213                 break;
214         case XK_Return:
215                 if(e->state & ShiftMask) {
216                         if(text)
217                                 fprintf(stdout, "%s", text);
218                 }
219                 else if(sel)
220                         fprintf(stdout, "%s", sel->text);
221                 else if(text)
222                         fprintf(stdout, "%s", text);
223                 fflush(stdout);
224                 running = False;
225                 break;
226         case XK_Escape:
227                 ret = 1;
228                 running = False;
229                 break;
230         case XK_BackSpace:
231                 if((i = len)) {
232                         prev_nitem = nitem;
233                         do {
234                                 text[--i] = 0;
235                                 match(text);
236                         } while(i && nitem && prev_nitem == nitem);
237                         match(text);
238                 }
239                 break;
240         default:
241                 if(num && !iscntrl((int) buf[0])) {
242                         buf[num] = 0;
243                         if(len > 0)
244                                 strncat(text, buf, sizeof(text));
245                         else
246                                 strncpy(text, buf, sizeof(text));
247                         match(text);
248                 }
249         }
250         drawmenu();
251 }
252
253 static char *
254 readstdin()
255 {
256         static char *maxname = NULL;
257         char *p, buf[1024];
258         unsigned int len = 0, max = 0;
259         Item *i, *new;
260
261         i = 0;
262         while(fgets(buf, sizeof(buf), stdin)) {
263                 len = strlen(buf);
264                 if (buf[len - 1] == '\n')
265                         buf[len - 1] = 0;
266                 p = estrdup(buf);
267                 if(max < len) {
268                         maxname = p;
269                         max = len;
270                 }
271
272                 new = emalloc(sizeof(Item));
273                 new->next = new->left = new->right = NULL;
274                 new->text = p;
275                 if(!i)
276                         allitems = new;
277                 else 
278                         i->next = new;
279                 i = new;
280         }
281
282         return maxname;
283 }
284
285 /* extern */
286
287 int screen;
288 Display *dpy;
289 DC dc = {0};
290
291 int
292 main(int argc, char *argv[])
293 {
294         char *maxname;
295         fd_set rd;
296         struct timeval timeout;
297         Item *i;
298         XEvent ev;
299         XSetWindowAttributes wa;
300
301         if(argc == 2 && !strncmp("-v", argv[1], 3)) {
302                 fputs("dmenu-"VERSION", (C)opyright MMVI Anselm R. Garbe\n", stdout);
303                 exit(EXIT_SUCCESS);
304         }
305         else if(argc != 1)
306                 eprint("usage: dmenu [-v]\n");
307
308         dpy = XOpenDisplay(0);
309         if(!dpy)
310                 eprint("dmenu: cannot open display\n");
311         screen = DefaultScreen(dpy);
312         root = RootWindow(dpy, screen);
313
314         /* Note, the select() construction allows to grab all keypresses as
315          * early as possible, to not loose them. But if there is no standard
316          * input supplied, we will make sure to exit after MAX_WAIT_STDIN
317          * seconds. This is convenience behavior for rapid typers.
318          */ 
319         while(XGrabKeyboard(dpy, root, True, GrabModeAsync,
320                          GrabModeAsync, CurrentTime) != GrabSuccess)
321                 usleep(1000);
322
323         timeout.tv_usec = 0;
324         timeout.tv_sec = STDIN_TIMEOUT;
325         FD_ZERO(&rd);
326         FD_SET(STDIN_FILENO, &rd);
327         if(select(ConnectionNumber(dpy) + 1, &rd, NULL, NULL, &timeout) < 1)
328                 goto UninitializedEnd;
329         maxname = readstdin();
330
331         /* style */
332         dc.sel[ColBG] = getcolor(SELBGCOLOR);
333         dc.sel[ColFG] = getcolor(SELFGCOLOR);
334         dc.norm[ColBG] = getcolor(NORMBGCOLOR);
335         dc.norm[ColFG] = getcolor(NORMFGCOLOR);
336         setfont(FONT);
337
338         wa.override_redirect = 1;
339         wa.background_pixmap = ParentRelative;
340         wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
341
342         mx = my = 0;
343         mw = DisplayWidth(dpy, screen);
344         mh = dc.font.height + 2;
345
346         win = XCreateWindow(dpy, root, mx, my, mw, mh, 0,
347                         DefaultDepth(dpy, screen), CopyFromParent,
348                         DefaultVisual(dpy, screen),
349                         CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
350         XDefineCursor(dpy, win, XCreateFontCursor(dpy, XC_xterm));
351
352         /* pixmap */
353         dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
354         dc.gc = XCreateGC(dpy, root, 0, 0);
355         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
356
357         if(maxname)
358                 cmdw = textw(maxname);
359         if(cmdw > mw / 3)
360                 cmdw = mw / 3;
361
362         text[0] = 0;
363         match(text);
364         XMapRaised(dpy, win);
365         drawmenu();
366         XSync(dpy, False);
367
368         /* main event loop */
369         while(running && !XNextEvent(dpy, &ev)) {
370                 switch (ev.type) {
371                 default:        /* ignore all crap */
372                         break;
373                 case KeyPress:
374                         kpress(&ev.xkey);
375                         break;
376                 case Expose:
377                         if(ev.xexpose.count == 0)
378                                 drawmenu();
379                         break;
380                 }
381         }
382
383         while(allitems) {
384                 i = allitems->next;
385                 free(allitems->text);
386                 free(allitems);
387                 allitems = i;
388         }
389         if(dc.font.set)
390                 XFreeFontSet(dpy, dc.font.set);
391         else
392                 XFreeFont(dpy, dc.font.xfont);
393         XFreePixmap(dpy, dc.drawable);
394         XFreeGC(dpy, dc.gc);
395         XDestroyWindow(dpy, win);
396 UninitializedEnd:
397         XUngrabKeyboard(dpy, CurrentTime);
398         XCloseDisplay(dpy);
399
400         return ret;
401 }