Xinqi Bao's Git

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