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