4c90cd76ec9ac590a7e3982913a00e28f3d28b7f
[dmenu.git] / dinput.c
1 /* See LICENSE file for copyright and license details. */
2 #include <ctype.h>
3 #include <locale.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <X11/keysym.h>
9 #include <X11/Xlib.h>
10 #include <X11/Xutil.h>
11 #ifdef XINERAMA
12 #include <X11/extensions/Xinerama.h>
13 #endif
14 #include <draw.h>
15
16 /* macros */
17 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
18 #define MIN(a, b)               ((a) < (b) ? (a) : (b))
19 #define MAX(a, b)               ((a) > (b) ? (a) : (b))
20 #define IS_UTF8_1ST_CHAR(c)     ((((c) & 0xc0) == 0xc0) || !((c) & 0x80))
21
22 /* forward declarations */
23 static void cleanup(void);
24 static void drawcursor(void);
25 static void drawinput(void);
26 static Bool grabkeyboard(void);
27 static void kpress(XKeyEvent *e);
28 static void run(void);
29 static void setup(void);
30
31 #include "config.h"
32
33 /* variables */
34 static char *prompt = NULL;
35 static char text[4096];
36 static int promptw = 0;
37 static int screen;
38 static unsigned int cursor = 0;
39 static unsigned int numlockmask = 0;
40 static unsigned int mw, mh;
41 static unsigned long normcol[ColLast];
42 static unsigned long selcol[ColLast];
43 static Bool topbar = True;
44 static DC dc;
45 static Display *dpy;
46 static Window win, root;
47
48 void
49 cleanup(void) {
50         cleanupdraw(&dc);
51         XDestroyWindow(dpy, win);
52         XUngrabKeyboard(dpy, CurrentTime);
53         XCloseDisplay(dpy);
54 }
55
56 void
57 drawcursor(void) {
58         XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
59
60         r.x += textnw(&dc, text, cursor) + dc.font.height / 2;
61
62         XSetForeground(dpy, dc.gc, normcol[ColFG]);
63         XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
64 }
65
66 void
67 drawinput(void)
68 {
69         dc.x = 0;
70         dc.y = 0;
71         dc.w = mw;
72         dc.h = mh;
73         drawtext(&dc, NULL, normcol, False);
74         /* print prompt? */
75         if(prompt) {
76                 dc.w = promptw;
77                 drawtext(&dc, prompt, selcol, False);
78                 dc.x += dc.w;
79         }
80         dc.w = mw - dc.x;
81         drawtext(&dc, *text ? text : NULL, normcol, False);
82         drawcursor();
83         XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
84 }
85
86 Bool
87 grabkeyboard(void) {
88         unsigned int len;
89
90         for(len = 1000; len; len--) {
91                 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
92                 == GrabSuccess)
93                         break;
94                 usleep(1000);
95         }
96         return len > 0;
97 }
98
99 void
100 kpress(XKeyEvent *e) {
101         char buf[sizeof text];
102         int num;
103         unsigned int i, len;
104         KeySym ksym;
105
106         len = strlen(text);
107         num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
108         if(ksym == XK_KP_Enter)
109                 ksym = XK_Return;
110         else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
111                 ksym = (ksym - XK_KP_0) + XK_0;
112         else if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
113         || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
114         || IsPrivateKeypadKey(ksym))
115                 return;
116         /* first check if a control mask is omitted */
117         if(e->state & ControlMask) {
118                 switch(tolower(ksym)) {
119                 default:
120                         return;
121                 case XK_a:
122                         ksym = XK_Home;
123                         break;
124                 case XK_b:
125                         ksym = XK_Left;
126                         break;
127                 case XK_c:
128                         ksym = XK_Escape;
129                         break;
130                 case XK_e:
131                         ksym = XK_End;
132                         break;
133                 case XK_f:
134                         ksym = XK_Right;
135                         break;
136                 case XK_h:
137                         ksym = XK_BackSpace;
138                         break;
139                 case XK_j:
140                 case XK_m:
141                         ksym = XK_Return;
142                         break;
143                 case XK_k:
144                         text[cursor] = '\0';
145                         break;
146                 case XK_u:
147                         memmove(text, text + cursor, sizeof text - cursor + 1);
148                         cursor = 0;
149                         break;
150                 case XK_w:
151                         if(cursor > 0) {
152                                 i = cursor;
153                                 while(i-- > 0 && text[i] == ' ');
154                                 while(i-- > 0 && text[i] != ' ');
155                                 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
156                                 cursor = i + 1;
157                         }
158                         break;
159                 case XK_y:
160                         {
161                                 FILE *fp;
162                                 char *s;
163                                 if(!(fp = popen("sselp", "r")))
164                                         eprint("cannot popen sselp\n");
165                                 s = fgets(buf, sizeof buf, fp);
166                                 pclose(fp);
167                                 if(s == NULL)
168                                         return;
169                         }
170                         num = strlen(buf);
171                         if(num && buf[num-1] == '\n')
172                                 buf[--num] = '\0';
173                         break;
174                 }
175         }
176         switch(ksym) {
177         default:
178                 num = MIN(num, sizeof text - cursor);
179                 if(num && !iscntrl((int) buf[0])) {
180                         memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
181                         memcpy(text + cursor, buf, num);
182                         cursor += num;
183                 }
184                 break;
185         case XK_BackSpace:
186                 if(cursor == 0)
187                         return;
188                 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
189                 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
190                 cursor -= i;
191                 break;
192         case XK_Delete:
193                 if(cursor == len)
194                         return;
195                 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
196                 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
197                 break;
198         case XK_End:
199                 cursor = len;
200                 break;
201         case XK_Escape:
202                 exit(EXIT_FAILURE);
203         case XK_Home:
204                 cursor = 0;
205                 break;
206         case XK_Left:
207                 if(cursor == 0)
208                         return;
209                 while(cursor-- > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
210                 break;
211         case XK_Return:
212                 fprintf(stdout, "%s", text);
213                 fflush(stdout);
214                 exit(EXIT_SUCCESS);
215         case XK_Right:
216                 if(cursor == len)
217                         return;
218                 while(cursor++ < len && !IS_UTF8_1ST_CHAR(text[cursor]));
219                 break;
220         }
221         drawinput();
222 }
223
224 void
225 run(void) {
226         XEvent ev;
227
228         /* main event loop */
229         XSync(dpy, False);
230         while(!XNextEvent(dpy, &ev))
231                 switch(ev.type) {
232                 case KeyPress:
233                         kpress(&ev.xkey);
234                         break;
235                 case Expose:
236                         if(ev.xexpose.count == 0)
237                                 drawinput();
238                         break;
239                 case VisibilityNotify:
240                         if(ev.xvisibility.state != VisibilityUnobscured)
241                                 XRaiseWindow(dpy, win);
242                         break;
243                 }
244         exit(EXIT_FAILURE);
245 }
246
247 void
248 setup(void) {
249         int i, j, x, y;
250 #if XINERAMA
251         int n;
252         XineramaScreenInfo *info = NULL;
253 #endif
254         XModifierKeymap *modmap;
255         XSetWindowAttributes wa;
256
257         /* init modifier map */
258         modmap = XGetModifierMapping(dpy);
259         for(i = 0; i < 8; i++)
260                 for(j = 0; j < modmap->max_keypermod; j++) {
261                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
262                         == XKeysymToKeycode(dpy, XK_Num_Lock))
263                                 numlockmask = (1 << i);
264                 }
265         XFreeModifiermap(modmap);
266
267         dc.dpy = dpy;
268         normcol[ColBG] = getcolor(&dc, normbgcolor);
269         normcol[ColFG] = getcolor(&dc, normfgcolor);
270         selcol[ColBG] = getcolor(&dc, selbgcolor);
271         selcol[ColFG] = getcolor(&dc, selfgcolor);
272         initfont(&dc, font);
273
274         /* input window */
275         wa.override_redirect = True;
276         wa.background_pixmap = ParentRelative;
277         wa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
278
279         /* input window geometry */
280         mh = dc.font.height + 2;
281 #if XINERAMA
282         if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
283                 i = 0;
284                 if(n > 1) {
285                         int di;
286                         unsigned int dui;
287                         Window dummy;
288                         if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
289                                 for(i = 0; i < n; i++)
290                                         if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
291                                                 break;
292                 }
293                 x = info[i].x_org;
294                 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
295                 mw = info[i].width;
296                 XFree(info);
297         }
298         else
299 #endif
300         {
301                 x = 0;
302                 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
303                 mw = DisplayWidth(dpy, screen);
304         }
305
306         win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
307                         DefaultDepth(dpy, screen), CopyFromParent,
308                         DefaultVisual(dpy, screen),
309                         CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
310
311         setupdraw(&dc, win);
312         if(prompt)
313                 promptw = MIN(textw(&dc, prompt), mw / 5);
314         cursor = strlen(text);
315         XMapRaised(dpy, win);
316 }
317
318 int
319 main(int argc, char *argv[]) {
320         unsigned int i;
321
322         /* command line args */
323         progname = "dinput";
324         for(i = 1; i < argc; i++)
325                 if(!strcmp(argv[i], "-i"))
326                         ;  /* ignore flag */
327                 else if(!strcmp(argv[i], "-b"))
328                         topbar = False;
329                 else if(!strcmp(argv[i], "-l"))
330                         i++;  /* ignore flag */
331                 else if(!strcmp(argv[i], "-fn")) {
332                         if(++i < argc) font = argv[i];
333                 }
334                 else if(!strcmp(argv[i], "-nb")) {
335                         if(++i < argc) normbgcolor = argv[i];
336                 }
337                 else if(!strcmp(argv[i], "-nf")) {
338                         if(++i < argc) normfgcolor = argv[i];
339                 }
340                 else if(!strcmp(argv[i], "-p")) {
341                         if(++i < argc) prompt = argv[i];
342                 }
343                 else if(!strcmp(argv[i], "-sb")) {
344                         if(++i < argc) selbgcolor = argv[i];
345                 }
346                 else if(!strcmp(argv[i], "-sf")) {
347                         if(++i < argc) selfgcolor = argv[i];
348                 }
349                 else if(!strcmp(argv[i], "-v")) {
350                         printf("dinput-"VERSION", © 2006-2010 dinput engineers, see LICENSE for details\n");
351                         exit(EXIT_SUCCESS);
352                 }
353                 else if(!*text)
354                         strncpy(text, argv[i], sizeof text);
355                 else {
356                         fputs("usage: dinput [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
357                               "              [-p <prompt>] [-sb <color>] [-sf <color>] [-v] [<text>]\n", stderr);
358                         exit(EXIT_FAILURE);
359                 }
360         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
361                 fprintf(stderr, "dinput: warning: no locale support\n");
362         if(!(dpy = XOpenDisplay(NULL)))
363                 eprint("cannot open display\n");
364         if(atexit(&cleanup) != 0)
365                 eprint("cannot register cleanup\n");
366         screen = DefaultScreen(dpy);
367         root = RootWindow(dpy, screen);
368
369         grabkeyboard();
370         setup();
371         run();
372         return 0;
373 }