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 <limits.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <stdint.h>
13 #include <X11/Xlib.h>
14 #include <X11/Xutil.h>
15 #include <X11/Xresource.h>
16 #include <X11/Xcms.h>
17 #include <X11/keysym.h>
19 #ifdef USE_XINERAMA
20 # include <X11/extensions/Xinerama.h>
21 #endif
23 #ifdef USE_XFT
24 # include <X11/Xft/Xft.h>
25 #endif
27 #ifndef VERSION
28 # define VERSION "unknown"
29 #endif
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #define SYM_BUF_SIZE 4
36 #ifdef USE_XFT
37 # define default_fontname "monospace"
38 #else
39 # define default_fontname "fixed"
40 #endif
42 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
49 /*
50 * If we don't have or we don't want an "ignore case" completion
51 * style, fall back to `strstr(3)`
52 */
53 #ifndef USE_STRCASESTR
54 # define strcasestr strstr
55 #endif
57 /* The number of char to read */
58 #define STDIN_CHUNKS 64
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 32
63 /* Abort on NULL */
64 #define check_allocation(a) { \
65 if (a == NULL) { \
66 fprintf(stderr, "Could not allocate memory\n"); \
67 abort(); \
68 } \
69 }
71 #define inner_height(r) (r->height - r->border_n - r->border_s)
72 #define inner_width(r) (r->width - r->border_e - r->border_w)
74 /* The states of the event loop */
75 enum state {LOOPING, OK_LOOP, OK, ERR};
77 /*
78 * For the drawing-related function. The text to be rendere could be
79 * the prompt, a completion or a highlighted completion
80 */
81 enum text_type {PROMPT, COMPL, COMPL_HIGH};
83 /* These are the possible action to be performed after user input. */
84 enum action {
85 EXIT,
86 CONFIRM,
87 CONFIRM_CONTINUE,
88 NEXT_COMPL,
89 PREV_COMPL,
90 DEL_CHAR,
91 DEL_WORD,
92 DEL_LINE,
93 ADD_CHAR,
94 TOGGLE_FIRST_SELECTED
95 };
97 /* A big set of values that needs to be carried around for drawing. A
98 big struct to rule them all */
99 struct rendering {
100 Display *d; /* Connection to xorg */
101 Window w;
102 int width;
103 int height;
104 int padding;
105 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
106 int y_zero; /* like x_zero but for the y axis */
108 size_t offset; /* scroll offset */
110 short free_text;
111 short first_selected;
112 short multiple_select;
114 /* four border width */
115 int border_n;
116 int border_e;
117 int border_s;
118 int border_w;
120 short horizontal_layout;
122 /* prompt */
123 char *ps1;
124 int ps1len;
126 XIC xic;
128 /* colors */
129 GC prompt;
130 GC prompt_bg;
131 GC completion;
132 GC completion_bg;
133 GC completion_highlighted;
134 GC completion_highlighted_bg;
135 GC border_n_bg;
136 GC border_e_bg;
137 GC border_s_bg;
138 GC border_w_bg;
139 #ifdef USE_XFT
140 XftFont *font;
141 XftDraw *xftdraw;
142 XftColor xft_prompt;
143 XftColor xft_completion;
144 XftColor xft_completion_highlighted;
145 #else
146 XFontSet font;
147 #endif
148 };
150 struct completion {
151 char *completion;
152 char *rcompletion;
153 };
155 /* Wrap the linked list of completions */
156 struct completions {
157 struct completion *completions;
158 ssize_t selected;
159 size_t length;
160 };
162 /* idea stolen from lemonbar. ty lemonboy */
163 typedef union {
164 struct {
165 uint8_t b;
166 uint8_t g;
167 uint8_t r;
168 uint8_t a;
169 };
170 uint32_t v;
171 } rgba_t;
173 /* Return a newly allocated (and empty) completion list */
174 struct completions *
175 compls_new(size_t length)
177 struct completions *cs = malloc(sizeof(struct completions));
179 if (cs == NULL)
180 return cs;
182 cs->completions = calloc(length, sizeof(struct completion));
183 if (cs->completions == NULL) {
184 free(cs);
185 return NULL;
188 cs->selected = -1;
189 cs->length = length;
190 return cs;
193 /* Delete the wrapper and the whole list */
194 void
195 compls_delete(struct completions *cs)
197 if (cs == NULL)
198 return;
200 free(cs->completions);
201 free(cs);
204 /*
205 * Create a completion list from a text and the list of possible
206 * completions (null terminated). Expects a non-null `cs'. `lines' and
207 * `vlines' should have the same length OR `vlines' is NULL.
208 */
209 void
210 filter(struct completions *cs, char *text, char **lines, char **vlines)
212 size_t index = 0;
213 size_t matching = 0;
215 if (vlines == NULL)
216 vlines = lines;
218 while (1) {
219 if (lines[index] == NULL)
220 break;
222 char *l = vlines[index] != NULL ? vlines[index] : lines[index];
224 if (strcasestr(l, text) != NULL) {
225 struct completion *c = &cs->completions[matching];
226 c->completion = l;
227 c->rcompletion = lines[index];
228 matching++;
231 index++;
233 cs->length = matching;
234 cs->selected = -1;
237 /* Update the given completion */
238 void
239 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
241 filter(cs, text, lines, vlines);
242 if (first_selected && cs->length > 0)
243 cs->selected = 0;
246 /*
247 * Select the next or previous selection and update some state. `text'
248 * will be updated with the text of the completion and `textlen' with
249 * the new length. If the memory cannot be allocated `status' will be
250 * set to `ERR'.
251 */
252 void
253 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
255 struct completion *n;
256 int index;
258 if (cs == NULL || cs->length == 0)
259 return;
261 /*
262 * If the first is always selected and the first entry is
263 * different from the text, expand the text and return
264 */
265 if (first_selected
266 && cs->selected == 0
267 && strcmp(cs->completions->completion, *text) != 0
268 && !p) {
269 free(*text);
270 *text = strdup(cs->completions->completion);
271 if (text == NULL) {
272 *status = ERR;
273 return;
275 *textlen = strlen(*text);
276 return;
279 index = cs->selected;
281 if (index == -1 && p)
282 index = 0;
283 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
285 n = &cs->completions[cs->selected];
287 free(*text);
288 *text = strdup(n->completion);
289 if (text == NULL) {
290 fprintf(stderr, "Memory allocation error!\n");
291 *status = ERR;
292 return;
294 *textlen = strlen(*text);
297 /* Push the character c at the end of the string pointed by p */
298 int
299 pushc(char **p, int maxlen, char c)
301 int len = strnlen(*p, maxlen);
303 if (!(len < maxlen -2)) {
304 char *newptr;
306 maxlen += maxlen >> 1;
307 newptr = realloc(*p, maxlen);
308 if (newptr == NULL) /* bad */
309 return -1;
310 *p = newptr;
313 (*p)[len] = c;
314 (*p)[len+1] = '\0';
315 return maxlen;
318 /*
319 * Remove the last rune from the *UTF-8* string! This is different
320 * from just setting the last byte to 0 (in some cases ofc). Return a
321 * pointer (e) to the last nonzero char. If e < p then p is empty!
322 */
323 char *
324 popc(char *p)
326 int len = strlen(p);
327 char *e;
329 if (len == 0)
330 return p;
332 e = p + len - 1;
334 do {
335 char c = *e;
337 *e = 0;
338 e--;
340 /*
341 * If c is a starting byte (11......) or is under
342 * U+007F we're done.
343 */
344 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
345 break;
346 } while (e >= p);
348 return e;
351 /* Remove the last word plus trailing white spaces from the given string */
352 void
353 popw(char *w)
355 int len;
356 short in_word;
358 len = strlen(w);
359 if (len == 0)
360 return;
362 in_word = 1;
363 while (1) {
364 char *e = popc(w);
366 if (e < w)
367 return;
369 if (in_word && isspace(*e))
370 in_word = 0;
372 if (!in_word && !isspace(*e))
373 return;
377 /*
378 * If the string is surrounded by quates (`"') remove them and replace
379 * every `\"' in the string with a single double-quote.
380 */
381 char *
382 normalize_str(const char *str)
384 int len, p;
385 char *s;
387 len = strlen(str);
388 if (len == 0)
389 return NULL;
391 s = calloc(len, sizeof(char));
392 check_allocation(s);
393 p = 0;
395 while (*str) {
396 char c = *str;
398 if (*str == '\\') {
399 if (*(str + 1)) {
400 s[p] = *(str + 1);
401 p++;
402 str += 2; /* skip this and the next char */
403 continue;
404 } else
405 break;
407 if (c == '"') {
408 str++; /* skip only this char */
409 continue;
411 s[p] = c;
412 p++;
413 str++;
416 return s;
419 size_t
420 read_stdin(char **buf)
422 size_t offset = 0;
423 size_t len = STDIN_CHUNKS;
425 *buf = malloc(len * sizeof(char));
426 if (*buf == NULL)
427 goto err;
429 while (1) {
430 ssize_t r;
431 size_t i;
433 r = read(0, *buf + offset, STDIN_CHUNKS);
435 if (r < 1)
436 return len;
438 offset += r;
440 len += STDIN_CHUNKS;
441 *buf = realloc(*buf, len);
442 if (*buf == NULL)
443 goto err;
445 for (i = offset; i < len; ++i)
446 (*buf)[i] = '\0';
449 err:
450 fprintf(stderr, "Error in allocating memory for stdin.\n");
451 exit(EX_UNAVAILABLE);
454 size_t
455 readlines(char ***lns, char **buf)
457 size_t len, ll, lines;
458 short in_line = 0;
460 lines = 0;
462 *buf = NULL;
463 len = read_stdin(buf);
465 ll = LINES_CHUNK;
466 *lns = malloc(ll * sizeof(char*));
468 if (*lns == NULL)
469 goto err;
471 for (size_t i = 0; i < len; i++) {
472 char c = (*buf)[i];
474 if (c == '\0')
475 break;
477 if (c == '\n')
478 (*buf)[i] = '\0';
480 if (in_line && c == '\n')
481 in_line = 0;
483 if (!in_line && c != '\n') {
484 in_line = 1;
485 (*lns)[lines] = (*buf) + i;
486 lines++;
488 if (lines == ll) { /* resize */
489 ll += LINES_CHUNK;
490 *lns = realloc(*lns, ll * sizeof(char*));
491 if (*lns == NULL)
492 goto err;
497 (*lns)[lines] = NULL;
499 return lines;
501 err:
502 fprintf(stderr, "Error in memory allocation.\n");
503 exit(EX_UNAVAILABLE);
506 /*
507 * Compute the dimensions of the string str once rendered.
508 * It'll return the width and set ret_width and ret_height if not NULL
509 */
510 int
511 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
513 int height;
514 int width;
515 #ifdef USE_XFT
516 XGlyphInfo gi;
517 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
518 height = r->font->ascent - r->font->descent;
519 width = gi.width - gi.x;
520 #else
521 XRectangle rect;
522 XmbTextExtents(r->font, str, len, NULL, &rect);
523 height = rect.height;
524 width = rect.width;
525 #endif
526 if (ret_width != NULL) *ret_width = width;
527 if (ret_height != NULL) *ret_height = height;
528 return width;
531 void
532 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
534 #ifdef USE_XFT
535 XftColor xftcolor;
536 if (tt == PROMPT) xftcolor = r->xft_prompt;
537 if (tt == COMPL) xftcolor = r->xft_completion;
538 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
540 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
541 #else
542 GC gc;
543 if (tt == PROMPT) gc = r->prompt;
544 if (tt == COMPL) gc = r->completion;
545 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
546 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
547 #endif
550 /* Duplicate the string and substitute every space with a 'n` */
551 char *
552 strdupn(char *str)
554 int len, i;
555 char *dup;
557 len = strlen(str);
559 if (str == NULL || len == 0)
560 return NULL;
562 dup = strdup(str);
563 if (dup == NULL)
564 return NULL;
566 for (i = 0; i < len; ++i)
567 if (dup[i] == ' ')
568 dup[i] = 'n';
570 return dup;
573 /* |------------------|----------------------------------------------| */
574 /* | 20 char text | completion | completion | completion | compl | */
575 /* |------------------|----------------------------------------------| */
576 void
577 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
579 size_t i;
580 int prompt_width, ps1xlen, start_at;
581 int width, height;
582 int texty, textlen;
583 char *ps1dup;
585 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
587 ps1dup = strdupn(r->ps1);
588 ps1xlen = text_extents(ps1dup != NULL ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
589 free(ps1dup);
591 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
592 start_at *= prompt_width;
593 start_at += r->padding;
595 texty = (inner_height(r) + height + r->y_zero) / 2;
597 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
599 textlen = strlen(text);
600 if (textlen > prompt_width)
601 text = text + textlen - prompt_width;
603 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
604 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
606 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
608 for (i = r->offset; i < cs->length; ++i) {
609 struct completion *c;
610 enum text_type tt;
611 GC h;
612 int len, text_width;
614 c = &cs->completions[i];
615 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
616 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
617 len = strlen(c->completion);
618 text_width = text_extents(c->completion, len, r, NULL, NULL);
620 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
621 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
623 start_at += text_width + r->padding * 2;
625 if (start_at > inner_width(r))
626 break; /* don't draw completion out of the window */
630 /* |-----------------------------------------------------------------| */
631 /* | prompt | */
632 /* |-----------------------------------------------------------------| */
633 /* | completion | */
634 /* |-----------------------------------------------------------------| */
635 /* | completion | */
636 /* |-----------------------------------------------------------------| */
637 void
638 draw_vertically(struct rendering *r, char *text, struct completions *cs)
640 size_t i;
641 int height, start_at;
642 int ps1xlen;
643 char *ps1dup;
645 text_extents("fjpgl", 5, r, NULL, &height);
646 start_at = r->padding * 2 + height;
648 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
649 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
651 ps1dup = strdupn(r->ps1);
652 ps1xlen = text_extents(ps1dup == NULL ? ps1dup : r->ps1, r->ps1len, r, NULL, NULL);
653 free(ps1dup);
655 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
656 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
658 start_at += r->y_zero;
660 for (i = r->offset; i < cs->length; ++i) {
661 struct completion *c;
662 enum text_type tt;
663 GC h;
664 int len;
666 c = &cs->completions[i];
667 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
668 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
669 len = strlen(c->completion);
671 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
672 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
674 start_at += height + r->padding * 2;
676 if (start_at > inner_height(r))
677 break; /* don't draw completion out of the window */
681 void
682 draw(struct rendering *r, char *text, struct completions *cs)
684 if (r->horizontal_layout)
685 draw_horizontally(r, text, cs);
686 else
687 draw_vertically(r, text, cs);
689 /* Draw the borders */
690 if (r->border_w != 0)
691 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
693 if (r->border_e != 0)
694 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
696 if (r->border_n != 0)
697 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
699 if (r->border_s != 0)
700 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
702 /* render! */
703 XFlush(r->d);
706 /* Set some WM stuff */
707 void
708 set_win_atoms_hints(Display *d, Window w, int width, int height)
710 Atom type;
711 XClassHint *class_hint;
712 XSizeHints *size_hint;
714 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
715 XChangeProperty(
716 d,
717 w,
718 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
719 XInternAtom(d, "ATOM", 0),
720 32,
721 PropModeReplace,
722 (unsigned char *)&type,
724 );
726 /* some window managers honor this properties */
727 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
728 XChangeProperty(d,
729 w,
730 XInternAtom(d, "_NET_WM_STATE", 0),
731 XInternAtom(d, "ATOM", 0),
732 32,
733 PropModeReplace,
734 (unsigned char *)&type,
736 );
738 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
739 XChangeProperty(d,
740 w,
741 XInternAtom(d, "_NET_WM_STATE", 0),
742 XInternAtom(d, "ATOM", 0),
743 32,
744 PropModeAppend,
745 (unsigned char *)&type,
747 );
749 /* Setting window hints */
750 class_hint = XAllocClassHint();
751 if (class_hint == NULL) {
752 fprintf(stderr, "Could not allocate memory for class hint\n");
753 exit(EX_UNAVAILABLE);
755 class_hint->res_name = resname;
756 class_hint->res_class = resclass;
757 XSetClassHint(d, w, class_hint);
758 XFree(class_hint);
760 size_hint = XAllocSizeHints();
761 if (size_hint == NULL) {
762 fprintf(stderr, "Could not allocate memory for size hint\n");
763 exit(EX_UNAVAILABLE);
765 size_hint->flags = PMinSize | PBaseSize;
766 size_hint->min_width = width;
767 size_hint->base_width = width;
768 size_hint->min_height = height;
769 size_hint->base_height = height;
771 XFlush(d);
774 /* Get the width and height of the window `w' */
775 void
776 get_wh(Display *d, Window *w, int *width, int *height)
778 XWindowAttributes win_attr;
780 XGetWindowAttributes(d, *w, &win_attr);
781 *height = win_attr.height;
782 *width = win_attr.width;
785 int
786 grabfocus(Display *d, Window w)
788 int i;
789 for (i = 0; i < 100; ++i) {
790 Window focuswin;
791 int revert_to_win;
793 XGetInputFocus(d, &focuswin, &revert_to_win);
795 if (focuswin == w)
796 return 1;
798 XSetInputFocus(d, w, RevertToParent, CurrentTime);
799 usleep(1000);
801 return 0;
804 /*
805 * I know this may seem a little hackish BUT is the only way I managed
806 * to actually grab that goddam keyboard. Only one call to
807 * XGrabKeyboard does not always end up with the keyboard grabbed!
808 */
809 int
810 take_keyboard(Display *d, Window w)
812 int i;
814 for (i = 0; i < 100; i++) {
815 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
816 return 1;
817 usleep(1000);
819 fprintf(stderr, "Cannot grab keyboard\n");
820 return 0;
823 unsigned long
824 parse_color(const char *str, const char *def)
826 size_t len;
827 rgba_t tmp;
828 char *ep;
830 if (str == NULL)
831 goto invc;
833 len = strlen(str);
835 /* +1 for the # ath the start */
836 if (*str != '#' || len > 9 || len < 4)
837 goto invc;
838 ++str; /* skip the # */
840 errno = 0;
841 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
843 if (errno)
844 goto invc;
846 switch (len-1) {
847 case 3:
848 /* expand #rgb -> #rrggbb */
849 tmp.v = (tmp.v & 0xf00) * 0x1100
850 | (tmp.v & 0x0f0) * 0x0110
851 | (tmp.v & 0x00f) * 0x0011;
852 case 6:
853 /* assume 0xff opacity */
854 tmp.a = 0xff;
855 break;
856 } /* colors in #aarrggbb need no adjustments */
858 /* premultiply the alpha */
859 if (tmp.a) {
860 tmp.r = (tmp.r * tmp.a) / 255;
861 tmp.g = (tmp.g * tmp.a) / 255;
862 tmp.b = (tmp.b * tmp.a) / 255;
863 return tmp.v;
866 return 0U;
868 invc:
869 fprintf(stderr, "Invalid color: \"%s\".\n", str);
870 if (def != NULL)
871 return parse_color(def, NULL);
872 else
873 return 0U;
876 /*
877 * Given a string try to parse it as a number or return `default_value'.
878 */
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 short 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 = 0;
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 (1) {
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, 1, text, textlen, &status);
1146 r->offset = cs->selected;
1147 break;
1150 case NEXT_COMPL: {
1151 complete(cs, r->first_selected, 0, 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 short first_selected, free_text, multiple_select;
1301 short 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 = 0;
1314 parent_window_id = NULL;
1315 free_text = 1;
1316 multiple_select = 0;
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 = 0;
1336 break;
1338 case 'm': {
1339 multiple_select = 1;
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 = 1;
1414 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1415 parent_window = DefaultRootWindow(d);
1416 embed = 0;
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 short 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 */
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 = 1;
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) == 1) {
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) == 1)
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) == 1) {
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) == 1)
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) == 1)
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) == 1)
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) == 1)
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) == 1)
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) == 1) {
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) == 1)
1546 p_fg = parse_color(value.addr, "#fff");
1548 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1549 p_bg = parse_color(value.addr, "#000");
1551 /* Completions */
1552 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1553 compl_fg = parse_color(value.addr, "#fff");
1555 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
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) == 1)
1562 compl_highlighted_fg = parse_color(value.addr, "#000");
1564 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
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) == 1) {
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 = 1;
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 = 1;
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 (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;