Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> /* strdup, strlen */
4 #include <ctype.h> /* isalnum */
5 #include <locale.h> /* setlocale */
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
11 #include <unistd.h>
12 #include <stdint.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xutil.h>
16 #include <X11/Xresource.h>
17 #include <X11/Xcms.h>
18 #include <X11/keysym.h>
20 #ifdef USE_XINERAMA
21 # include <X11/extensions/Xinerama.h>
22 #endif
24 #ifdef USE_XFT
25 # include <X11/Xft/Xft.h>
26 #endif
28 #ifndef VERSION
29 # define VERSION "unknown"
30 #endif
32 #define resname "MyMenu"
33 #define resclass "mymenu"
35 #define SYM_BUF_SIZE 4
37 #ifdef USE_XFT
38 # define default_fontname "monospace"
39 #else
40 # define default_fontname "fixed"
41 #endif
43 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
45 #define MIN(a, b) ((a) < (b) ? (a) : (b))
46 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
50 /*
51 * If we don't have or we don't want an "ignore case" completion
52 * style, fall back to `strstr(3)`
53 */
54 #ifndef USE_STRCASESTR
55 # define strcasestr strstr
56 #endif
58 /* The number of char to read */
59 #define STDIN_CHUNKS 64
61 /* The number of lines to allocate in advance */
62 #define LINES_CHUNK 32
64 /* Abort on NULL */
65 #define check_allocation(a) { \
66 if (a == NULL) { \
67 fprintf(stderr, "Could not allocate memory\n"); \
68 abort(); \
69 } \
70 }
72 #define inner_height(r) (r->height - r->border_n - r->border_s)
73 #define inner_width(r) (r->width - r->border_e - r->border_w)
75 /* The states of the event loop */
76 enum state {LOOPING, OK_LOOP, OK, ERR};
78 /*
79 * For the drawing-related function. The text to be rendere could be
80 * the prompt, a completion or a highlighted completion
81 */
82 enum text_type {PROMPT, COMPL, COMPL_HIGH};
84 /* These are the possible action to be performed after user input. */
85 enum action {
86 EXIT,
87 CONFIRM,
88 CONFIRM_CONTINUE,
89 NEXT_COMPL,
90 PREV_COMPL,
91 DEL_CHAR,
92 DEL_WORD,
93 DEL_LINE,
94 ADD_CHAR,
95 TOGGLE_FIRST_SELECTED
96 };
98 /* A big set of values that needs to be carried around for drawing. A
99 big struct to rule them all */
100 struct rendering {
101 Display *d; /* Connection to xorg */
102 Window w;
103 int width;
104 int height;
105 int padding;
106 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
107 int y_zero; /* like x_zero but for the y axis */
109 size_t offset; /* scroll offset */
111 bool free_text;
112 bool first_selected;
113 bool multiple_select;
115 /* four border width */
116 int border_n;
117 int border_e;
118 int border_s;
119 int border_w;
121 bool horizontal_layout;
123 /* prompt */
124 char *ps1;
125 int ps1len;
127 XIC xic;
129 /* colors */
130 GC prompt;
131 GC prompt_bg;
132 GC completion;
133 GC completion_bg;
134 GC completion_highlighted;
135 GC completion_highlighted_bg;
136 GC border_n_bg;
137 GC border_e_bg;
138 GC border_s_bg;
139 GC border_w_bg;
140 #ifdef USE_XFT
141 XftFont *font;
142 XftDraw *xftdraw;
143 XftColor xft_prompt;
144 XftColor xft_completion;
145 XftColor xft_completion_highlighted;
146 #else
147 XFontSet font;
148 #endif
149 };
151 struct completion {
152 char *completion;
153 char *rcompletion;
154 };
156 /* Wrap the linked list of completions */
157 struct completions {
158 struct completion *completions;
159 ssize_t selected;
160 size_t length;
161 };
163 /* idea stolen from lemonbar. ty lemonboy */
164 typedef union {
165 struct {
166 uint8_t b;
167 uint8_t g;
168 uint8_t r;
169 uint8_t a;
170 };
171 uint32_t v;
172 } rgba_t;
174 /* Return a newly allocated (and empty) completion list */
175 struct completions *
176 compls_new(size_t length)
178 struct completions *cs = malloc(sizeof(struct completions));
180 if (cs == NULL)
181 return cs;
183 cs->completions = calloc(length, sizeof(struct completion));
184 if (cs->completions == NULL) {
185 free(cs);
186 return NULL;
189 cs->selected = -1;
190 cs->length = length;
191 return cs;
194 /* Delete the wrapper and the whole list */
195 void
196 compls_delete(struct completions *cs)
198 if (cs == NULL)
199 return;
201 free(cs->completions);
202 free(cs);
205 /*
206 * Create a completion list from a text and the list of possible
207 * completions (null terminated). Expects a non-null `cs'. `lines' and
208 * `vlines' should have the same length OR `vlines' is NULL.
209 */
210 void
211 filter(struct completions *cs, char *text, char **lines, char **vlines)
213 size_t index = 0;
214 size_t matching = 0;
216 if (vlines == NULL)
217 vlines = lines;
219 while (true) {
220 if (lines[index] == NULL)
221 break;
223 char *l = vlines[index] != NULL ? vlines[index] : lines[index];
225 if (strcasestr(l, text) != NULL) {
226 struct completion *c = &cs->completions[matching];
227 c->completion = l;
228 c->rcompletion = lines[index];
229 matching++;
232 index++;
234 cs->length = matching;
235 cs->selected = -1;
238 /* Update the given completion */
239 void
240 update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected)
242 filter(cs, text, lines, vlines);
243 if (first_selected && cs->length > 0)
244 cs->selected = 0;
247 /*
248 * Select the next or previous selection and update some state. `text'
249 * will be updated with the text of the completion and `textlen' with
250 * the new length. If the memory cannot be allocated `status' will be
251 * set to `ERR'.
252 */
253 void
254 complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status)
256 struct completion *n;
257 int index;
259 if (cs == NULL || cs->length == 0)
260 return;
262 /*
263 * If the first is always selected and the first entry is
264 * different from the text, expand the text and return
265 */
266 if (first_selected
267 && cs->selected == 0
268 && strcmp(cs->completions->completion, *text) != 0
269 && !p) {
270 free(*text);
271 *text = strdup(cs->completions->completion);
272 if (text == NULL) {
273 *status = ERR;
274 return;
276 *textlen = strlen(*text);
277 return;
280 index = cs->selected;
282 if (index == -1 && p)
283 index = 0;
284 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
286 n = &cs->completions[cs->selected];
288 free(*text);
289 *text = strdup(n->completion);
290 if (text == NULL) {
291 fprintf(stderr, "Memory allocation error!\n");
292 *status = ERR;
293 return;
295 *textlen = strlen(*text);
298 /* Push the character c at the end of the string pointed by p */
299 int
300 pushc(char **p, int maxlen, char c)
302 int len = strnlen(*p, maxlen);
304 if (!(len < maxlen -2)) {
305 char *newptr;
307 maxlen += maxlen >> 1;
308 newptr = realloc(*p, maxlen);
309 if (newptr == NULL) /* bad */
310 return -1;
311 *p = newptr;
314 (*p)[len] = c;
315 (*p)[len+1] = '\0';
316 return maxlen;
319 /*
320 * Remove the last rune from the *UTF-8* string! This is different
321 * from just setting the last byte to 0 (in some cases ofc). Return a
322 * pointer (e) to the last nonzero char. If e < p then p is empty!
323 */
324 char *
325 popc(char *p)
327 int len = strlen(p);
328 char *e;
330 if (len == 0)
331 return p;
333 e = p + len - 1;
335 do {
336 char c = *e;
338 *e = 0;
339 e--;
341 /*
342 * If c is a starting byte (11......) or is under
343 * U+007F we're done.
344 */
345 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
346 break;
347 } while (e >= p);
349 return e;
352 /* Remove the last word plus trailing white spaces from the given string */
353 void
354 popw(char *w)
356 int len;
357 bool in_word;
359 len = strlen(w);
360 if (len == 0)
361 return;
363 in_word = true;
364 while (true) {
365 char *e = popc(w);
367 if (e < w)
368 return;
370 if (in_word && isspace(*e))
371 in_word = false;
373 if (!in_word && !isspace(*e))
374 return;
378 /*
379 * If the string is surrounded by quates (`"') remove them and replace
380 * every `\"' in the string with a single double-quote.
381 */
382 char *
383 normalize_str(const char *str)
385 int len, p;
386 char *s;
388 len = strlen(str);
389 if (len == 0)
390 return NULL;
392 s = calloc(len, sizeof(char));
393 check_allocation(s);
394 p = 0;
396 while (*str) {
397 char c = *str;
399 if (*str == '\\') {
400 if (*(str + 1)) {
401 s[p] = *(str + 1);
402 p++;
403 str += 2; /* skip this and the next char */
404 continue;
405 } else
406 break;
408 if (c == '"') {
409 str++; /* skip only this char */
410 continue;
412 s[p] = c;
413 p++;
414 str++;
417 return s;
420 size_t
421 read_stdin(char **buf)
423 size_t offset = 0;
424 size_t len = STDIN_CHUNKS;
426 *buf = malloc(len * sizeof(char));
427 if (*buf == NULL)
428 goto err;
430 while (true) {
431 ssize_t r;
432 size_t i;
434 r = read(0, *buf + offset, STDIN_CHUNKS);
436 if (r < 1)
437 return len;
439 offset += r;
441 len += STDIN_CHUNKS;
442 *buf = realloc(*buf, len);
443 if (*buf == NULL)
444 goto err;
446 for (i = offset; i < len; ++i)
447 (*buf)[i] = '\0';
450 err:
451 fprintf(stderr, "Error in allocating memory for stdin.\n");
452 exit(EX_UNAVAILABLE);
455 size_t
456 readlines(char ***lns, char **buf)
458 size_t len, ll, lines;
459 bool in_line = false;
461 lines = 0;
463 *buf = NULL;
464 len = read_stdin(buf);
466 ll = LINES_CHUNK;
467 *lns = malloc(ll * sizeof(char*));
469 if (*lns == NULL)
470 goto err;
472 for (size_t i = 0; i < len; i++) {
473 char c = (*buf)[i];
475 if (c == '\0')
476 break;
478 if (c == '\n')
479 (*buf)[i] = '\0';
481 if (in_line && c == '\n')
482 in_line = false;
484 if (!in_line && c != '\n') {
485 in_line = true;
486 (*lns)[lines] = (*buf) + i;
487 lines++;
489 if (lines == ll) { // resize
490 ll += LINES_CHUNK;
491 *lns = realloc(*lns, ll * sizeof(char*));
492 if (*lns == NULL)
493 goto err;
498 (*lns)[lines] = NULL;
500 return lines;
502 err:
503 fprintf(stderr, "Error in memory allocation.\n");
504 exit(EX_UNAVAILABLE);
507 /*
508 * Compute the dimensions of the string str once rendered.
509 * It'll return the width and set ret_width and ret_height if not NULL
510 */
511 int
512 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
514 int height;
515 int width;
516 #ifdef USE_XFT
517 XGlyphInfo gi;
518 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
519 height = r->font->ascent - r->font->descent;
520 width = gi.width - gi.x;
521 #else
522 XRectangle rect;
523 XmbTextExtents(r->font, str, len, NULL, &rect);
524 height = rect.height;
525 width = rect.width;
526 #endif
527 if (ret_width != NULL) *ret_width = width;
528 if (ret_height != NULL) *ret_height = height;
529 return width;
532 void
533 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
535 #ifdef USE_XFT
536 XftColor xftcolor;
537 if (tt == PROMPT) xftcolor = r->xft_prompt;
538 if (tt == COMPL) xftcolor = r->xft_completion;
539 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
541 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
542 #else
543 GC gc;
544 if (tt == PROMPT) gc = r->prompt;
545 if (tt == COMPL) gc = r->completion;
546 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
547 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
548 #endif
551 /* Duplicate the string and substitute every space with a 'n` */
552 char *
553 strdupn(char *str)
555 int len, i;
556 char *dup;
558 len = strlen(str);
560 if (str == NULL || len == 0)
561 return NULL;
563 dup = strdup(str);
564 if (dup == NULL)
565 return NULL;
567 for (i = 0; i < len; ++i)
568 if (dup[i] == ' ')
569 dup[i] = 'n';
571 return dup;
574 /* |------------------|----------------------------------------------| */
575 /* | 20 char text | completion | completion | completion | compl | */
576 /* |------------------|----------------------------------------------| */
577 void
578 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
580 size_t i;
581 int prompt_width, ps1xlen, start_at;
582 int width, height;
583 int texty, textlen;
584 char *ps1dup;
586 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
588 ps1dup = strdupn(r->ps1);
589 ps1xlen = text_extents(ps1dup != NULL ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
590 free(ps1dup);
592 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
593 start_at *= prompt_width;
594 start_at += r->padding;
596 texty = (inner_height(r) + height + r->y_zero) / 2;
598 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
600 textlen = strlen(text);
601 if (textlen > prompt_width)
602 text = text + textlen - prompt_width;
604 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
605 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
607 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
609 for (i = r->offset; i < cs->length; ++i) {
610 struct completion *c;
611 enum text_type tt;
612 GC h;
613 int len, text_width;
615 c = &cs->completions[i];
616 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
617 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
618 len = strlen(c->completion);
619 text_width = text_extents(c->completion, len, r, NULL, NULL);
621 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
622 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
624 start_at += text_width + r->padding * 2;
626 if (start_at > inner_width(r))
627 break; /* don't draw completion out of the window */
631 /* |-----------------------------------------------------------------| */
632 /* | prompt | */
633 /* |-----------------------------------------------------------------| */
634 /* | completion | */
635 /* |-----------------------------------------------------------------| */
636 /* | completion | */
637 /* |-----------------------------------------------------------------| */
638 void
639 draw_vertically(struct rendering *r, char *text, struct completions *cs)
641 size_t i;
642 int height, start_at;
643 int ps1xlen;
644 char *ps1dup;
646 text_extents("fjpgl", 5, r, NULL, &height);
647 start_at = r->padding * 2 + height;
649 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
650 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
652 ps1dup = strdupn(r->ps1);
653 ps1xlen = text_extents(ps1dup == NULL ? ps1dup : r->ps1, r->ps1len, r, NULL, NULL);
654 free(ps1dup);
656 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
657 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
659 start_at += r->y_zero;
661 for (i = r->offset; i < cs->length; ++i) {
662 struct completion *c;
663 enum text_type tt;
664 GC h;
665 int len;
667 c = &cs->completions[i];
668 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
669 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
670 len = strlen(c->completion);
672 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
673 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
675 start_at += height + r->padding * 2;
677 if (start_at > inner_height(r))
678 break; /* don't draw completion out of the window */
682 void
683 draw(struct rendering *r, char *text, struct completions *cs)
685 if (r->horizontal_layout)
686 draw_horizontally(r, text, cs);
687 else
688 draw_vertically(r, text, cs);
690 /* Draw the borders */
691 if (r->border_w != 0)
692 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
694 if (r->border_e != 0)
695 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
697 if (r->border_n != 0)
698 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
700 if (r->border_s != 0)
701 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
703 /* render! */
704 XFlush(r->d);
707 /* Set some WM stuff */
708 void
709 set_win_atoms_hints(Display *d, Window w, int width, int height)
711 Atom type;
712 XClassHint *class_hint;
713 XSizeHints *size_hint;
715 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
716 XChangeProperty(
717 d,
718 w,
719 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
720 XInternAtom(d, "ATOM", false),
721 32,
722 PropModeReplace,
723 (unsigned char *)&type,
725 );
727 /* some window managers honor this properties */
728 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
729 XChangeProperty(d,
730 w,
731 XInternAtom(d, "_NET_WM_STATE", false),
732 XInternAtom(d, "ATOM", false),
733 32,
734 PropModeReplace,
735 (unsigned char *)&type,
737 );
739 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
740 XChangeProperty(d,
741 w,
742 XInternAtom(d, "_NET_WM_STATE", false),
743 XInternAtom(d, "ATOM", false),
744 32,
745 PropModeAppend,
746 (unsigned char *)&type,
748 );
750 /* Setting window hints */
751 class_hint = XAllocClassHint();
752 if (class_hint == NULL) {
753 fprintf(stderr, "Could not allocate memory for class hint\n");
754 exit(EX_UNAVAILABLE);
756 class_hint->res_name = resname;
757 class_hint->res_class = resclass;
758 XSetClassHint(d, w, class_hint);
759 XFree(class_hint);
761 size_hint = XAllocSizeHints();
762 if (size_hint == NULL) {
763 fprintf(stderr, "Could not allocate memory for size hint\n");
764 exit(EX_UNAVAILABLE);
766 size_hint->flags = PMinSize | PBaseSize;
767 size_hint->min_width = width;
768 size_hint->base_width = width;
769 size_hint->min_height = height;
770 size_hint->base_height = height;
772 XFlush(d);
775 /* Get the width and height of the window `w' */
776 void
777 get_wh(Display *d, Window *w, int *width, int *height)
779 XWindowAttributes win_attr;
781 XGetWindowAttributes(d, *w, &win_attr);
782 *height = win_attr.height;
783 *width = win_attr.width;
786 int
787 grabfocus(Display *d, Window w)
789 int i;
790 for (i = 0; i < 100; ++i) {
791 Window focuswin;
792 int revert_to_win;
794 XGetInputFocus(d, &focuswin, &revert_to_win);
796 if (focuswin == w)
797 return true;
799 XSetInputFocus(d, w, RevertToParent, CurrentTime);
800 usleep(1000);
802 return 0;
805 /*
806 * I know this may seem a little hackish BUT is the only way I managed
807 * to actually grab that goddam keyboard. Only one call to
808 * XGrabKeyboard does not always end up with the keyboard grabbed!
809 */
810 int
811 take_keyboard(Display *d, Window w)
813 int i;
815 for (i = 0; i < 100; i++) {
816 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
817 return 1;
818 usleep(1000);
820 fprintf(stderr, "Cannot grab keyboard\n");
821 return 0;
824 unsigned long
825 parse_color(const char *str, const char *def)
827 size_t len;
828 rgba_t tmp;
829 char *ep;
831 if (str == NULL)
832 goto invc;
834 len = strlen(str);
836 /* +1 for the # ath the start */
837 if (*str != '#' || len > 9 || len < 4)
838 goto invc;
839 ++str; /* skip the # */
841 errno = 0;
842 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
844 if (errno)
845 goto invc;
847 switch (len-1) {
848 case 3:
849 /* expand #rgb -> #rrggbb */
850 tmp.v = (tmp.v & 0xf00) * 0x1100
851 | (tmp.v & 0x0f0) * 0x0110
852 | (tmp.v & 0x00f) * 0x0011;
853 case 6:
854 /* assume 0xff opacity */
855 tmp.a = 0xff;
856 break;
857 } /* colors in #aarrggbb need no adjustments */
859 /* premultiply the alpha */
860 if (tmp.a) {
861 tmp.r = (tmp.r * tmp.a) / 255;
862 tmp.g = (tmp.g * tmp.a) / 255;
863 tmp.b = (tmp.b * tmp.a) / 255;
864 return tmp.v;
867 return 0U;
869 invc:
870 fprintf(stderr, "Invalid color: \"%s\".\n", str);
871 if (def != NULL)
872 return parse_color(def, NULL);
873 else
874 return 0U;
877 // Given a string, try to parse it as a number or return
878 // `default_value'.
879 int
880 parse_integer(const char *str, int default_value)
882 long lval;
883 char *ep;
885 errno = 0;
886 lval = strtol(str, &ep, 10);
888 if (str[0] == '\0' || *ep != '\0') { // NaN
889 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
890 return default_value;
893 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
894 (lval > INT_MAX || lval < INT_MIN)) {
895 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
896 return default_value;
899 return lval;
902 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
903 int
904 parse_int_with_percentage(const char *str, int default_value, int max)
906 int len = strlen(str);
908 if (len > 0 && str[len-1] == '%') {
909 int val;
910 char *cpy;
912 cpy = strdup(str);
913 check_allocation(cpy);
914 cpy[len-1] = '\0';
915 val = parse_integer(cpy, default_value);
916 free(cpy);
917 return val * max / 100;
919 return parse_integer(str, default_value);
922 /*
923 * Like parse_int_with_percentage but understands some special values:
924 * - middle that is (max-self)/2
925 * - start that is 0
926 * - end that is (max-self)
927 */
928 int
929 parse_int_with_pos(const char *str, int default_value, int max, int self)
931 if (!strcmp(str, "start"))
932 return 0;
933 if (!strcmp(str, "middle"))
934 return (max - self)/2;
935 if (!strcmp(str, "end"))
936 return max-self;
937 return parse_int_with_percentage(str, default_value, max);
940 /* Parse a string like a CSS value. */
941 /* TODO: harden a bit this function */
942 char **
943 parse_csslike(const char *str)
945 int i;
946 char *s, *token, **ret;
947 bool any_null;
949 s = strdup(str);
950 if (s == NULL)
951 return NULL;
953 ret = malloc(4 * sizeof(char*));
954 if (ret == NULL) {
955 free(s);
956 return NULL;
959 i = 0;
960 while ((token = strsep(&s, " ")) != NULL && i < 4) {
961 ret[i] = strdup(token);
962 i++;
965 if (i == 1)
966 for (int j = 1; j < 4; j++)
967 ret[j] = strdup(ret[0]);
969 if (i == 2) {
970 ret[2] = strdup(ret[0]);
971 ret[3] = strdup(ret[1]);
974 if (i == 3)
975 ret[3] = strdup(ret[1]);
977 /* before we didn't check for the return type of strdup, here we will */
979 any_null = false;
980 for (i = 0; i < 4; ++i)
981 any_null = ret[i] == NULL || any_null;
983 if (any_null)
984 for (i = 0; i < 4; ++i)
985 if (ret[i] != NULL)
986 free(ret[i]);
988 if (i == 0 || any_null) {
989 free(s);
990 free(ret);
991 return NULL;
994 return ret;
997 /*
998 * Given an event, try to understand what the users wants. If the
999 * return value is ADD_CHAR then `input' is a pointer to a string that
1000 * will need to be free'ed later.
1002 enum
1003 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1005 char str[SYM_BUF_SIZE] = {0};
1006 Status s;
1008 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1009 return DEL_CHAR;
1011 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1012 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1014 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1015 return CONFIRM;
1017 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1018 return EXIT;
1020 /* Try to read what key was pressed */
1021 s = 0;
1022 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1023 if (s == XBufferOverflow) {
1024 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1025 return EXIT;
1028 if (ev->state & ControlMask) {
1029 if (!strcmp(str, "")) /* C-u */
1030 return DEL_LINE;
1031 if (!strcmp(str, "")) /* C-w */
1032 return DEL_WORD;
1033 if (!strcmp(str, "")) /* C-h */
1034 return DEL_CHAR;
1035 if (!strcmp(str, "\r")) /* C-m */
1036 return CONFIRM_CONTINUE;
1037 if (!strcmp(str, "")) /* C-p */
1038 return PREV_COMPL;
1039 if (!strcmp(str, "")) /* C-n */
1040 return NEXT_COMPL;
1041 if (!strcmp(str, "")) /* C-c */
1042 return EXIT;
1043 if (!strcmp(str, "\t")) /* C-i */
1044 return TOGGLE_FIRST_SELECTED;
1047 *input = strdup(str);
1048 if (*input == NULL) {
1049 fprintf(stderr, "Error while allocating memory for key.\n");
1050 return EXIT;
1053 return ADD_CHAR;
1056 void
1057 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1059 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1060 /* if there is something selected expand it and return */
1061 int index = cs->selected == -1 ? 0 : cs->selected;
1062 struct completion *c = cs->completions;
1063 char *t;
1065 while (true) {
1066 if (index == 0)
1067 break;
1068 c++;
1069 index--;
1072 t = c->rcompletion;
1073 free(*text);
1074 *text = strdup(t);
1076 if (*text == NULL) {
1077 fprintf(stderr, "Memory allocation error\n");
1078 *status = ERR;
1081 *textlen = strlen(*text);
1082 return;
1085 if (!r->free_text) /* cannot accept arbitrary text */
1086 *status = LOOPING;
1089 /* event loop */
1090 enum state
1091 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1093 enum state status = LOOPING;
1095 while (status == LOOPING) {
1096 XEvent e;
1097 XNextEvent(r->d, &e);
1099 if (XFilterEvent(&e, r->w))
1100 continue;
1102 switch (e.type) {
1103 case KeymapNotify:
1104 XRefreshKeyboardMapping(&e.xmapping);
1105 break;
1107 case FocusIn:
1108 /* Re-grab focus */
1109 if (e.xfocus.window != r->w)
1110 grabfocus(r->d, r->w);
1111 break;
1113 case VisibilityNotify:
1114 if (e.xvisibility.state != VisibilityUnobscured)
1115 XRaiseWindow(r->d, r->w);
1116 break;
1118 case MapNotify:
1119 get_wh(r->d, &r->w, &r->width, &r->height);
1120 draw(r, *text, cs);
1121 break;
1123 case KeyPress: {
1124 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1125 char *input;
1127 switch (parse_event(r->d, ev, r->xic, &input)) {
1128 case EXIT:
1129 status = ERR;
1130 break;
1132 case CONFIRM: {
1133 status = OK;
1134 confirm(&status, r, cs, text, textlen);
1135 break;
1138 case CONFIRM_CONTINUE: {
1139 status = OK_LOOP;
1140 confirm(&status, r, cs, text, textlen);
1141 break;
1144 case PREV_COMPL: {
1145 complete(cs, r->first_selected, true, text, textlen, &status);
1146 r->offset = cs->selected;
1147 break;
1150 case NEXT_COMPL: {
1151 complete(cs, r->first_selected, false, text, textlen, &status);
1152 r->offset = cs->selected;
1153 break;
1156 case DEL_CHAR:
1157 popc(*text);
1158 update_completions(cs, *text, lines, vlines, r->first_selected);
1159 r->offset = 0;
1160 break;
1162 case DEL_WORD: {
1163 popw(*text);
1164 update_completions(cs, *text, lines, vlines, r->first_selected);
1165 break;
1168 case DEL_LINE: {
1169 int i;
1170 for (i = 0; i < *textlen; ++i)
1171 *(*text + i) = 0;
1172 update_completions(cs, *text, lines, vlines, r->first_selected);
1173 r->offset = 0;
1174 break;
1177 case ADD_CHAR: {
1178 int str_len, i;
1180 str_len = strlen(input);
1183 * sometimes a strange key is pressed
1184 * i.e. ctrl alone), so input will be
1185 * empty. Don't need to update
1186 * completion in that case
1188 if (str_len == 0)
1189 break;
1191 for (i = 0; i < str_len; ++i) {
1192 *textlen = pushc(text, *textlen, input[i]);
1193 if (*textlen == -1) {
1194 fprintf(stderr, "Memory allocation error\n");
1195 status = ERR;
1196 break;
1200 if (status != ERR) {
1201 update_completions(cs, *text, lines, vlines, r->first_selected);
1202 free(input);
1205 r->offset = 0;
1206 break;
1209 case TOGGLE_FIRST_SELECTED:
1210 r->first_selected = !r->first_selected;
1211 if (r->first_selected && cs->selected < 0)
1212 cs->selected = 0;
1213 if (!r->first_selected && cs->selected == 0)
1214 cs->selected = -1;
1215 break;
1219 case ButtonPress: {
1220 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1221 /* if (ev->button == Button1) { /\* click *\/ */
1222 /* int x = ev->x - r.border_w; */
1223 /* int y = ev->y - r.border_n; */
1224 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1225 /* } */
1227 if (ev->button == Button4) /* scroll up */
1228 r->offset = MAX((ssize_t)r->offset - 1, 0);
1230 if (ev->button == Button5) /* scroll down */
1231 r->offset = MIN(r->offset + 1, cs->length - 1);
1233 break;
1237 draw(r, *text, cs);
1240 return status;
1243 int
1244 load_font(struct rendering *r, const char *fontname)
1246 #ifdef USE_XFT
1247 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1248 return 0;
1249 #else
1250 char **missing_charset_list;
1251 int missing_charset_count;
1253 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1254 if (r->font != NULL)
1255 return 0;
1257 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1259 if (!strcmp(fontname, default_fontname))
1260 return -1;
1262 return load_font(r, default_fontname);
1263 #endif
1266 void
1267 usage(char *prgname)
1269 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1270 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1271 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1272 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1275 int
1276 main(int argc, char **argv)
1278 struct completions *cs;
1279 XSetWindowAttributes attr;
1281 size_t nlines, i;
1282 Display *d;
1283 Window parent_window, w;
1284 XVisualInfo vinfo;
1285 Colormap cmap;
1286 XGCValues values;
1287 XrmDatabase xdb;
1288 XIM xim;
1289 XIMStyle best_match_style;
1290 XIMStyles *xis;
1291 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1292 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1293 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1294 int ch;
1295 int offset_x, offset_y, width, height, x, y;
1296 int padding, textlen;
1297 int border_n, border_e, border_s, border_w;
1298 int d_width, d_height;
1299 enum state status;
1300 bool first_selected, free_text, multiple_select;
1301 bool embed, horizontal_layout;
1302 char *sep, *parent_window_id;
1303 char **lines, *buf, **vlines;
1304 char *ps1, *fontname, *text, *xrm;
1306 #ifdef __OpenBSD__
1307 /* stdio & rpath: to read/write stdio/stdout/stderr */
1308 /* unix: to connect to XOrg */
1309 pledge("stdio rpath unix", "");
1310 #endif
1312 sep = NULL;
1313 first_selected = false;
1314 parent_window_id = NULL;
1315 free_text = true;
1316 multiple_select = false;
1318 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1319 switch (ch) {
1320 case 'h': /* help */
1321 usage(*argv);
1322 return 0;
1323 case 'v': /* version */
1324 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1325 return 0;
1326 case 'e': /* embed */
1327 parent_window_id = strdup(optarg);
1328 check_allocation(parent_window_id);
1329 break;
1330 case 'd': {
1331 sep = strdup(optarg);
1332 check_allocation(sep);
1334 case 'A': {
1335 free_text = false;
1336 break;
1338 case 'm': {
1339 multiple_select = true;
1340 break;
1342 default:
1343 break;
1347 /* Read the completions */
1348 lines = NULL;
1349 buf = NULL;
1350 nlines = readlines(&lines, &buf);
1352 vlines = NULL;
1353 if (sep != NULL) {
1354 int l;
1355 l = strlen(sep);
1356 vlines = calloc(nlines, sizeof(char*));
1357 check_allocation(vlines);
1359 for (i = 0; i < nlines; i++) {
1360 char *t;
1361 t = strstr(lines[i], sep);
1362 if (t == NULL)
1363 vlines[i] = lines[i];
1364 else
1365 vlines[i] = t + l;
1369 setlocale(LC_ALL, getenv("LANG"));
1371 status = LOOPING;
1373 /* where the monitor start (used only with xinerama) */
1374 offset_x = offset_y = 0;
1376 /* default width and height */
1377 width = 400;
1378 height = 20;
1380 /* default position on the screen */
1381 x = y = 0;
1383 /* default padding */
1384 padding = 10;
1386 /* default borders */
1387 border_n = border_e = border_s = border_w = 0;
1389 /* the prompt. We duplicate the string so later is easy to
1390 * free (in the case it's been overwritten by the user) */
1391 ps1 = strdup("$ ");
1392 check_allocation(ps1);
1394 /* same for the font name */
1395 fontname = strdup(default_fontname);
1396 check_allocation(fontname);
1398 textlen = 10;
1399 text = malloc(textlen * sizeof(char));
1400 check_allocation(text);
1402 /* struct completions *cs = filter(text, lines); */
1403 cs = compls_new(nlines);
1404 check_allocation(cs);
1406 /* start talking to xorg */
1407 d = XOpenDisplay(NULL);
1408 if (d == NULL) {
1409 fprintf(stderr, "Could not open display!\n");
1410 return EX_UNAVAILABLE;
1413 embed = true;
1414 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1415 parent_window = DefaultRootWindow(d);
1416 embed = false;
1419 /* get display size */
1420 get_wh(d, &parent_window, &d_width, &d_height);
1422 #ifdef USE_XINERAMA
1423 if (!embed && XineramaIsActive(d)) { /* find the mice */
1424 XineramaScreenInfo *info;
1425 Window r;
1426 Window root;
1427 int number_of_screens, monitors, i;
1428 int root_x, root_y, win_x, win_y;
1429 unsigned int mask;
1430 bool res;
1432 number_of_screens = XScreenCount(d);
1433 for (i = 0; i < number_of_screens; ++i) {
1434 root = XRootWindow(d, i);
1435 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1436 if (res) break;
1438 if (!res) {
1439 fprintf(stderr, "No mouse found.\n");
1440 root_x = 0;
1441 root_y = 0;
1444 // now find in which monitor the mice is on
1445 info = XineramaQueryScreens(d, &monitors);
1446 if (info) {
1447 for (i = 0; i < monitors; ++i) {
1448 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1449 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1450 offset_x = info[i].x_org;
1451 offset_y = info[i].y_org;
1452 d_width = info[i].width;
1453 d_height = info[i].height;
1454 break;
1458 XFree(info);
1460 #endif
1461 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1463 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1465 p_fg = compl_fg = parse_color("#fff", NULL);
1466 compl_highlighted_fg = parse_color("#000", NULL);
1468 p_bg = compl_bg = parse_color("#000", NULL);
1469 compl_highlighted_bg = parse_color("#fff", NULL);
1471 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1473 horizontal_layout = true;
1475 /* Read the resources */
1476 XrmInitialize();
1477 xrm = XResourceManagerString(d);
1478 xdb = NULL;
1479 if (xrm != NULL) {
1480 XrmValue value;
1481 char *datatype[20];
1483 xdb = XrmGetStringDatabase(xrm);
1485 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1486 free(fontname);
1487 fontname = strdup(value.addr);
1488 check_allocation(fontname);
1489 } else {
1490 fprintf(stderr, "no font defined, using %s\n", fontname);
1493 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1494 horizontal_layout = !strcmp(value.addr, "horizontal");
1495 else
1496 fprintf(stderr, "no layout defined, using horizontal\n");
1498 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1499 free(ps1);
1500 ps1 = normalize_str(value.addr);
1501 } else {
1502 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1505 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1506 width = parse_int_with_percentage(value.addr, width, d_width);
1507 else
1508 fprintf(stderr, "no width defined, using %d\n", width);
1510 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1511 height = parse_int_with_percentage(value.addr, height, d_height);
1512 else
1513 fprintf(stderr, "no height defined, using %d\n", height);
1515 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1516 x = parse_int_with_pos(value.addr, x, d_width, width);
1517 else
1518 fprintf(stderr, "no x defined, using %d\n", x);
1520 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1521 y = parse_int_with_pos(value.addr, y, d_height, height);
1522 else
1523 fprintf(stderr, "no y defined, using %d\n", y);
1525 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1526 padding = parse_integer(value.addr, padding);
1527 else
1528 fprintf(stderr, "no padding defined, using %d\n", padding);
1530 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1531 char **borders;
1533 borders = parse_csslike(value.addr);
1534 if (borders != NULL) {
1535 border_n = parse_integer(borders[0], 0);
1536 border_e = parse_integer(borders[1], 0);
1537 border_s = parse_integer(borders[2], 0);
1538 border_w = parse_integer(borders[3], 0);
1539 } else
1540 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1541 } else
1542 fprintf(stderr, "no border defined, using 0.\n");
1544 /* Prompt */
1545 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1546 p_fg = parse_color(value.addr, "#fff");
1548 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1549 p_bg = parse_color(value.addr, "#000");
1551 /* Completions */
1552 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1553 compl_fg = parse_color(value.addr, "#fff");
1555 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1556 compl_bg = parse_color(value.addr, "#000");
1557 else
1558 compl_bg = parse_color("#000", NULL);
1560 /* Completion Highlighted */
1561 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1562 compl_highlighted_fg = parse_color(value.addr, "#000");
1564 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1565 compl_highlighted_bg = parse_color(value.addr, "#fff");
1566 else
1567 compl_highlighted_bg = parse_color("#fff", NULL);
1569 // border
1570 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1571 char **colors;
1572 colors = parse_csslike(value.addr);
1573 if (colors != NULL) {
1574 border_n_bg = parse_color(colors[0], "#000");
1575 border_e_bg = parse_color(colors[1], "#000");
1576 border_s_bg = parse_color(colors[2], "#000");
1577 border_w_bg = parse_color(colors[3], "#000");
1578 } else
1579 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1583 // second round of args parsing
1584 optind = 0; // reset the option index
1585 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1586 switch (ch) {
1587 case 'a':
1588 first_selected = true;
1589 break;
1591 case 'A':
1592 /* free_text -- already catched */
1593 case 'd':
1594 /* separator -- this case was already catched */
1595 case 'e':
1596 /* embedding mymenu this case was already catched. */
1597 case 'm':
1598 /* multiple selection this case was already catched. */
1600 break;
1601 case 'p': {
1602 char *newprompt;
1603 newprompt = strdup(optarg);
1604 if (newprompt != NULL) {
1605 free(ps1);
1606 ps1 = newprompt;
1608 break;
1610 case 'x':
1611 x = parse_int_with_pos(optarg, x, d_width, width);
1612 break;
1613 case 'y':
1614 y = parse_int_with_pos(optarg, y, d_height, height);
1615 break;
1616 case 'P':
1617 padding = parse_integer(optarg, padding);
1618 break;
1619 case 'l':
1620 horizontal_layout = !strcmp(optarg, "horizontal");
1621 break;
1622 case 'f': {
1623 char *newfont;
1624 if ((newfont = strdup(optarg)) != NULL) {
1625 free(fontname);
1626 fontname = newfont;
1628 break;
1630 case 'W':
1631 width = parse_int_with_percentage(optarg, width, d_width);
1632 break;
1633 case 'H':
1634 height = parse_int_with_percentage(optarg, height, d_height);
1635 break;
1636 case 'b': {
1637 char **borders;
1638 if ((borders = parse_csslike(optarg)) != NULL) {
1639 border_n = parse_integer(borders[0], 0);
1640 border_e = parse_integer(borders[1], 0);
1641 border_s = parse_integer(borders[2], 0);
1642 border_w = parse_integer(borders[3], 0);
1643 } else
1644 fprintf(stderr, "Error parsing b option\n");
1645 break;
1647 case 'B': {
1648 char **colors;
1649 if ((colors = parse_csslike(optarg)) != NULL) {
1650 border_n_bg = parse_color(colors[0], "#000");
1651 border_e_bg = parse_color(colors[1], "#000");
1652 border_s_bg = parse_color(colors[2], "#000");
1653 border_w_bg = parse_color(colors[3], "#000");
1654 } else
1655 fprintf(stderr, "error while parsing B option\n");
1656 break;
1658 case 't': {
1659 p_fg = parse_color(optarg, NULL);
1660 break;
1662 case 'T': {
1663 p_bg = parse_color(optarg, NULL);
1664 break;
1666 case 'c': {
1667 compl_fg = parse_color(optarg, NULL);
1668 break;
1670 case 'C': {
1671 compl_bg = parse_color(optarg, NULL);
1672 break;
1674 case 's': {
1675 compl_highlighted_fg = parse_color(optarg, NULL);
1676 break;
1678 case 'S': {
1679 compl_highlighted_bg = parse_color(optarg, NULL);
1680 break;
1682 default:
1683 fprintf(stderr, "Unrecognized option %c\n", ch);
1684 status = ERR;
1685 break;
1689 /* since only now we know if the first should be selected,
1690 * update the completion here */
1691 update_completions(cs, text, lines, vlines, first_selected);
1693 // create the window
1694 attr.colormap = cmap;
1695 attr.override_redirect = true;
1696 attr.border_pixel = 0;
1697 attr.background_pixel = 0x80808080;
1698 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1700 w = XCreateWindow(d,
1701 parent_window,
1702 x + offset_x, y + offset_y,
1703 width, height,
1705 vinfo.depth,
1706 InputOutput,
1707 vinfo.visual,
1708 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1709 &attr);
1711 set_win_atoms_hints(d, w, width, height);
1713 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1714 XMapRaised(d, w);
1716 /* If embed, listen for other events as well */
1717 if (embed) {
1718 Window *children, parent, root;
1719 unsigned int children_no;
1721 XSelectInput(d, parent_window, FocusChangeMask);
1722 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1723 for (i = 0; i < children_no && children[i] != w; ++i)
1724 XSelectInput(d, children[i], FocusChangeMask);
1725 XFree(children);
1727 grabfocus(d, w);
1730 take_keyboard(d, w);
1732 struct rendering r = {
1733 .d = d,
1734 .w = w,
1735 .width = width,
1736 .height = height,
1737 .padding = padding,
1738 .x_zero = border_w,
1739 .y_zero = border_n,
1740 .offset = 0,
1741 .free_text = free_text,
1742 .first_selected = first_selected,
1743 .multiple_select = multiple_select,
1744 .border_n = border_n,
1745 .border_e = border_e,
1746 .border_s = border_s,
1747 .border_w = border_w,
1748 .horizontal_layout = horizontal_layout,
1749 .ps1 = ps1,
1750 .ps1len = strlen(ps1),
1751 .prompt = XCreateGC(d, w, 0, &values),
1752 .prompt_bg = XCreateGC(d, w, 0, &values),
1753 .completion = XCreateGC(d, w, 0, &values),
1754 .completion_bg = XCreateGC(d, w, 0, &values),
1755 .completion_highlighted = XCreateGC(d, w, 0, &values),
1756 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1757 .border_n_bg = XCreateGC(d, w, 0, &values),
1758 .border_e_bg = XCreateGC(d, w, 0, &values),
1759 .border_s_bg = XCreateGC(d, w, 0, &values),
1760 .border_w_bg = XCreateGC(d, w, 0, &values),
1763 if (load_font(&r, fontname) == -1)
1764 status = ERR;
1766 #ifdef USE_XFT
1767 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1770 rgba_t c;
1771 XRenderColor xrcolor;
1773 /* Prompt */
1774 c = *(rgba_t*)&p_fg;
1775 xrcolor.red = EXPANDBITS(c.r);
1776 xrcolor.green = EXPANDBITS(c.g);
1777 xrcolor.blue = EXPANDBITS(c.b);
1778 xrcolor.alpha = EXPANDBITS(c.a);
1779 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1781 /* Completion */
1782 c = *(rgba_t*)&compl_fg;
1783 xrcolor.red = EXPANDBITS(c.r);
1784 xrcolor.green = EXPANDBITS(c.g);
1785 xrcolor.blue = EXPANDBITS(c.b);
1786 xrcolor.alpha = EXPANDBITS(c.a);
1787 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1789 /* Completion highlighted */
1790 c = *(rgba_t*)&compl_highlighted_fg;
1791 xrcolor.red = EXPANDBITS(c.r);
1792 xrcolor.green = EXPANDBITS(c.g);
1793 xrcolor.blue = EXPANDBITS(c.b);
1794 xrcolor.alpha = EXPANDBITS(c.a);
1795 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1797 #endif
1799 /* Load the colors in our GCs */
1800 XSetForeground(d, r.prompt, p_fg);
1801 XSetForeground(d, r.prompt_bg, p_bg);
1802 XSetForeground(d, r.completion, compl_fg);
1803 XSetForeground(d, r.completion_bg, compl_bg);
1804 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1805 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1806 XSetForeground(d, r.border_n_bg, border_n_bg);
1807 XSetForeground(d, r.border_e_bg, border_e_bg);
1808 XSetForeground(d, r.border_s_bg, border_s_bg);
1809 XSetForeground(d, r.border_w_bg, border_w_bg);
1811 /* Open the X input method */
1812 xim = XOpenIM(d, xdb, resname, resclass);
1813 check_allocation(xim);
1815 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1816 fprintf(stderr, "Input Styles could not be retrieved\n");
1817 return EX_UNAVAILABLE;
1820 best_match_style = 0;
1821 for (int i = 0; i < xis->count_styles; ++i) {
1822 XIMStyle ts = xis->supported_styles[i];
1823 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1824 best_match_style = ts;
1825 break;
1828 XFree(xis);
1830 if (!best_match_style)
1831 fprintf(stderr, "No matching input style could be determined\n");
1833 r.xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, w, XNFocusWindow, w, NULL);
1834 check_allocation(r.xic);
1836 /* Draw the window for the first time */
1837 draw(&r, text, cs);
1839 /* Main loop */
1840 while (status == LOOPING || status == OK_LOOP) {
1841 status = loop(&r, &text, &textlen, cs, lines, vlines);
1843 if (status != ERR)
1844 printf("%s\n", text);
1846 if (!multiple_select && status == OK_LOOP)
1847 status = OK;
1850 XUngrabKeyboard(d, CurrentTime);
1852 #ifdef USE_XFT
1853 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1854 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1855 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1856 #endif
1858 free(ps1);
1859 free(fontname);
1860 free(text);
1862 free(buf);
1863 free(lines);
1864 free(vlines);
1865 compls_delete(cs);
1867 XDestroyWindow(r.d, r.w);
1868 XCloseDisplay(r.d);
1870 return status != OK;