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 128
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 64
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 } rgba;
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;
214 char *l;
216 if (vlines == NULL)
217 vlines = lines;
219 while (1) {
220 if (lines[index] == NULL)
221 break;
223 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, short 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, short first_selected, short 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;
304 len = strnlen(*p, maxlen);
305 if (!(len < maxlen -2)) {
306 char *newptr;
308 maxlen += maxlen >> 1;
309 newptr = realloc(*p, maxlen);
310 if (newptr == NULL) /* bad */
311 return -1;
312 *p = newptr;
315 (*p)[len] = c;
316 (*p)[len+1] = '\0';
317 return maxlen;
320 /*
321 * Remove the last rune from the *UTF-8* string! This is different
322 * from just setting the last byte to 0 (in some cases ofc). Return a
323 * pointer (e) to the last nonzero char. If e < p then p is empty!
324 */
325 char *
326 popc(char *p)
328 int len = strlen(p);
329 char *e;
331 if (len == 0)
332 return p;
334 e = p + len - 1;
336 do {
337 char c = *e;
339 *e = '\0';
340 e -= 1;
342 /*
343 * If c is a starting byte (11......) or is under
344 * U+007F we're done.
345 */
346 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
347 break;
348 } while (e >= p);
350 return e;
353 /* Remove the last word plus trailing white spaces from the given string */
354 void
355 popw(char *w)
357 int len;
358 short in_word = 1;
360 if ((len = strlen(w)) == 0)
361 return;
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 if ((len = strlen(str)) == 0)
388 return NULL;
390 s = calloc(len, sizeof(char));
391 check_allocation(s);
392 p = 0;
394 while (*str) {
395 char c = *str;
397 if (*str == '\\') {
398 if (*(str + 1)) {
399 s[p] = *(str + 1);
400 p++;
401 str += 2; /* skip this and the next char */
402 continue;
403 } else
404 break;
406 if (c == '"') {
407 str++; /* skip only this char */
408 continue;
410 s[p] = c;
411 p++;
412 str++;
415 return s;
418 size_t
419 read_stdin(char **buf)
421 size_t offset = 0;
422 size_t len = STDIN_CHUNKS;
424 *buf = malloc(len * sizeof(char));
425 if (*buf == NULL)
426 goto err;
428 while (1) {
429 ssize_t r;
430 size_t i;
432 r = read(0, *buf + offset, STDIN_CHUNKS);
434 if (r < 1)
435 return len;
437 offset += r;
439 len += STDIN_CHUNKS;
440 *buf = realloc(*buf, len);
441 if (*buf == NULL)
442 goto err;
444 for (i = offset; i < len; ++i)
445 (*buf)[i] = '\0';
448 err:
449 fprintf(stderr, "Error in allocating memory for stdin.\n");
450 exit(EX_UNAVAILABLE);
453 size_t
454 readlines(char ***lns, char **buf)
456 size_t i, len, ll, lines;
457 short in_line = 0;
459 lines = 0;
461 *buf = NULL;
462 len = read_stdin(buf);
464 ll = LINES_CHUNK;
465 *lns = malloc(ll * sizeof(char*));
467 if (*lns == NULL)
468 goto err;
470 for (i = 0; i < len; i++) {
471 char c = (*buf)[i];
473 if (c == '\0')
474 break;
476 if (c == '\n')
477 (*buf)[i] = '\0';
479 if (in_line && c == '\n')
480 in_line = 0;
482 if (!in_line && c != '\n') {
483 in_line = 1;
484 (*lns)[lines] = (*buf) + i;
485 lines++;
487 if (lines == ll) { /* resize */
488 ll += LINES_CHUNK;
489 *lns = realloc(*lns, ll * sizeof(char*));
490 if (*lns == NULL)
491 goto err;
496 (*lns)[lines] = NULL;
498 return lines;
500 err:
501 fprintf(stderr, "Error in memory allocation.\n");
502 exit(EX_UNAVAILABLE);
505 /*
506 * Compute the dimensions of the string str once rendered.
507 * It'll return the width and set ret_width and ret_height if not NULL
508 */
509 int
510 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
512 int height;
513 int width;
514 #ifdef USE_XFT
515 XGlyphInfo gi;
516 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
517 height = r->font->ascent - r->font->descent;
518 width = gi.width - gi.x;
519 #else
520 XRectangle rect;
521 XmbTextExtents(r->font, str, len, NULL, &rect);
522 height = rect.height;
523 width = rect.width;
524 #endif
525 if (ret_width != NULL) *ret_width = width;
526 if (ret_height != NULL) *ret_height = height;
527 return width;
530 void
531 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
533 #ifdef USE_XFT
534 XftColor xftcolor;
535 if (tt == PROMPT) xftcolor = r->xft_prompt;
536 if (tt == COMPL) xftcolor = r->xft_completion;
537 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
539 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
540 #else
541 GC gc;
542 if (tt == PROMPT) gc = r->prompt;
543 if (tt == COMPL) gc = r->completion;
544 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
545 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
546 #endif
549 /* Duplicate the string and substitute every space with a 'n` */
550 char *
551 strdupn(char *str)
553 int len, i;
554 char *dup;
556 len = strlen(str);
558 if (str == NULL || len == 0)
559 return NULL;
561 if ((dup = strdup(str)) == NULL)
562 return NULL;
564 for (i = 0; i < len; ++i)
565 if (dup[i] == ' ')
566 dup[i] = 'n';
568 return dup;
571 /* |------------------|----------------------------------------------| */
572 /* | 20 char text | completion | completion | completion | compl | */
573 /* |------------------|----------------------------------------------| */
574 void
575 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
577 size_t i;
578 int prompt_width, ps1xlen, start_at;
579 int width, height;
580 int texty, textlen;
581 char *ps1dup;
583 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
585 ps1dup = strdupn(r->ps1);
586 ps1xlen = text_extents(ps1dup != NULL ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
587 free(ps1dup);
589 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
590 start_at *= prompt_width;
591 start_at += r->padding;
593 texty = (inner_height(r) + height + r->y_zero) / 2;
595 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
597 textlen = strlen(text);
598 if (textlen > prompt_width)
599 text = text + textlen - prompt_width;
601 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
602 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
604 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
606 for (i = r->offset; i < cs->length; ++i) {
607 struct completion *c;
608 enum text_type tt;
609 GC h;
610 int len, text_width;
612 c = &cs->completions[i];
613 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
614 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
615 len = strlen(c->completion);
616 text_width = text_extents(c->completion, len, r, NULL, NULL);
618 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
619 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
621 start_at += text_width + r->padding * 2;
623 if (start_at > inner_width(r))
624 break; /* don't draw completion out of the window */
628 /* |-----------------------------------------------------------------| */
629 /* | prompt | */
630 /* |-----------------------------------------------------------------| */
631 /* | completion | */
632 /* |-----------------------------------------------------------------| */
633 /* | completion | */
634 /* |-----------------------------------------------------------------| */
635 void
636 draw_vertically(struct rendering *r, char *text, struct completions *cs)
638 size_t i;
639 int height, start_at;
640 int ps1xlen;
641 char *ps1dup;
643 text_extents("fjpgl", 5, r, NULL, &height);
644 start_at = r->padding * 2 + height;
646 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
647 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
649 ps1dup = strdupn(r->ps1);
650 ps1xlen = text_extents(ps1dup == NULL ? ps1dup : r->ps1, r->ps1len, r, NULL, NULL);
651 free(ps1dup);
653 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
654 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
656 start_at += r->y_zero;
658 for (i = r->offset; i < cs->length; ++i) {
659 struct completion *c;
660 enum text_type tt;
661 GC h;
662 int len;
664 c = &cs->completions[i];
665 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
666 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
667 len = strlen(c->completion);
669 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
670 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
672 start_at += height + r->padding * 2;
674 if (start_at > inner_height(r))
675 break; /* don't draw completion out of the window */
679 void
680 draw(struct rendering *r, char *text, struct completions *cs)
682 if (r->horizontal_layout)
683 draw_horizontally(r, text, cs);
684 else
685 draw_vertically(r, text, cs);
687 /* Draw the borders */
688 if (r->border_w != 0)
689 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
691 if (r->border_e != 0)
692 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
694 if (r->border_n != 0)
695 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
697 if (r->border_s != 0)
698 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
700 /* render! */
701 XFlush(r->d);
704 /* Set some WM stuff */
705 void
706 set_win_atoms_hints(Display *d, Window w, int width, int height)
708 Atom type;
709 XClassHint *class_hint;
710 XSizeHints *size_hint;
712 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
713 XChangeProperty(d,
714 w,
715 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
716 XInternAtom(d, "ATOM", 0),
717 32,
718 PropModeReplace,
719 (unsigned char *)&type,
721 );
723 /* some window managers honor this properties */
724 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
725 XChangeProperty(d,
726 w,
727 XInternAtom(d, "_NET_WM_STATE", 0),
728 XInternAtom(d, "ATOM", 0),
729 32,
730 PropModeReplace,
731 (unsigned char *)&type,
733 );
735 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
736 XChangeProperty(d,
737 w,
738 XInternAtom(d, "_NET_WM_STATE", 0),
739 XInternAtom(d, "ATOM", 0),
740 32,
741 PropModeAppend,
742 (unsigned char *)&type,
744 );
746 /* Setting window hints */
747 class_hint = XAllocClassHint();
748 if (class_hint == NULL) {
749 fprintf(stderr, "Could not allocate memory for class hint\n");
750 exit(EX_UNAVAILABLE);
753 class_hint->res_name = resname;
754 class_hint->res_class = resclass;
755 XSetClassHint(d, w, class_hint);
756 XFree(class_hint);
758 size_hint = XAllocSizeHints();
759 if (size_hint == NULL) {
760 fprintf(stderr, "Could not allocate memory for size hint\n");
761 exit(EX_UNAVAILABLE);
764 size_hint->flags = PMinSize | PBaseSize;
765 size_hint->min_width = width;
766 size_hint->base_width = width;
767 size_hint->min_height = height;
768 size_hint->base_height = height;
770 XFlush(d);
773 /* Get the width and height of the window `w' */
774 void
775 get_wh(Display *d, Window *w, int *width, int *height)
777 XWindowAttributes win_attr;
779 XGetWindowAttributes(d, *w, &win_attr);
780 *height = win_attr.height;
781 *width = win_attr.width;
784 int
785 grabfocus(Display *d, Window w)
787 int i;
788 for (i = 0; i < 100; ++i) {
789 Window focuswin;
790 int revert_to_win;
792 XGetInputFocus(d, &focuswin, &revert_to_win);
794 if (focuswin == w)
795 return 1;
797 XSetInputFocus(d, w, RevertToParent, CurrentTime);
798 usleep(1000);
800 return 0;
803 /*
804 * I know this may seem a little hackish BUT is the only way I managed
805 * to actually grab that goddam keyboard. Only one call to
806 * XGrabKeyboard does not always end up with the keyboard grabbed!
807 */
808 int
809 take_keyboard(Display *d, Window w)
811 int i;
812 for (i = 0; i < 100; i++) {
813 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
814 return 1;
815 usleep(1000);
817 fprintf(stderr, "Cannot grab keyboard\n");
818 return 0;
821 unsigned long
822 parse_color(const char *str, const char *def)
824 size_t len;
825 rgba_t tmp;
826 char *ep;
828 if (str == NULL)
829 goto invc;
831 len = strlen(str);
833 /* +1 for the # ath the start */
834 if (*str != '#' || len > 9 || len < 4)
835 goto invc;
836 ++str; /* skip the # */
838 errno = 0;
839 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
841 if (errno)
842 goto invc;
844 switch (len-1) {
845 case 3:
846 /* expand #rgb -> #rrggbb */
847 tmp.v = (tmp.v & 0xf00) * 0x1100
848 | (tmp.v & 0x0f0) * 0x0110
849 | (tmp.v & 0x00f) * 0x0011;
850 case 6:
851 /* assume 0xff opacity */
852 tmp.rgba.a = 0xff;
853 break;
854 } /* colors in #aarrggbb need no adjustments */
856 /* premultiply the alpha */
857 if (tmp.rgba.a) {
858 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
859 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
860 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
861 return tmp.v;
864 return 0U;
866 invc:
867 fprintf(stderr, "Invalid color: \"%s\".\n", str);
868 if (def != NULL)
869 return parse_color(def, NULL);
870 else
871 return 0U;
874 /*
875 * Given a string try to parse it as a number or return `default_value'.
876 */
877 int
878 parse_integer(const char *str, int default_value)
880 long lval;
881 char *ep;
883 errno = 0;
884 lval = strtol(str, &ep, 10);
886 if (str[0] == '\0' || *ep != '\0') { /* NaN */
887 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
888 return default_value;
891 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
892 (lval > INT_MAX || lval < INT_MIN)) {
893 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
894 return default_value;
897 return lval;
900 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
901 int
902 parse_int_with_percentage(const char *str, int default_value, int max)
904 int len = strlen(str);
906 if (len > 0 && str[len-1] == '%') {
907 int val;
908 char *cpy;
910 cpy = strdup(str);
911 check_allocation(cpy);
912 cpy[len-1] = '\0';
913 val = parse_integer(cpy, default_value);
914 free(cpy);
915 return val * max / 100;
918 return parse_integer(str, default_value);
921 /*
922 * Like parse_int_with_percentage but understands some special values:
923 * - middle that is (max-self)/2
924 * - start that is 0
925 * - end that is (max-self)
926 */
927 int
928 parse_int_with_pos(const char *str, int default_value, int max, int self)
930 if (!strcmp(str, "start"))
931 return 0;
932 if (!strcmp(str, "middle"))
933 return (max - self)/2;
934 if (!strcmp(str, "end"))
935 return max-self;
936 return parse_int_with_percentage(str, default_value, max);
939 /* Parse a string like a CSS value. */
940 /* TODO: harden a bit this function */
941 char **
942 parse_csslike(const char *str)
944 int i, j;
945 char *s, *token, **ret;
946 short any_null;
948 s = strdup(str);
949 if (s == NULL)
950 return NULL;
952 ret = malloc(4 * sizeof(char*));
953 if (ret == NULL) {
954 free(s);
955 return NULL;
958 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
959 ret[i] = strdup(token);
961 if (i == 1)
962 for (j = 1; j < 4; j++)
963 ret[j] = strdup(ret[0]);
965 if (i == 2) {
966 ret[2] = strdup(ret[0]);
967 ret[3] = strdup(ret[1]);
970 if (i == 3)
971 ret[3] = strdup(ret[1]);
973 /* before we didn't check for the return type of strdup, here we will */
975 any_null = 0;
976 for (i = 0; i < 4; ++i)
977 any_null = ret[i] == NULL || any_null;
979 if (any_null)
980 for (i = 0; i < 4; ++i)
981 if (ret[i] != NULL)
982 free(ret[i]);
984 if (i == 0 || any_null) {
985 free(s);
986 free(ret);
987 return NULL;
990 return ret;
993 /*
994 * Given an event, try to understand what the users wants. If the
995 * return value is ADD_CHAR then `input' is a pointer to a string that
996 * will need to be free'ed later.
997 */
998 enum
999 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1001 char str[SYM_BUF_SIZE] = {0};
1002 Status s;
1004 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1005 return DEL_CHAR;
1007 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1008 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1010 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1011 return CONFIRM;
1013 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1014 return EXIT;
1016 /* Try to read what key was pressed */
1017 s = 0;
1018 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1019 if (s == XBufferOverflow) {
1020 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1021 return EXIT;
1024 if (ev->state & ControlMask) {
1025 if (!strcmp(str, "")) /* C-u */
1026 return DEL_LINE;
1027 if (!strcmp(str, "")) /* C-w */
1028 return DEL_WORD;
1029 if (!strcmp(str, "")) /* C-h */
1030 return DEL_CHAR;
1031 if (!strcmp(str, "\r")) /* C-m */
1032 return CONFIRM_CONTINUE;
1033 if (!strcmp(str, "")) /* C-p */
1034 return PREV_COMPL;
1035 if (!strcmp(str, "")) /* C-n */
1036 return NEXT_COMPL;
1037 if (!strcmp(str, "")) /* C-c */
1038 return EXIT;
1039 if (!strcmp(str, "\t")) /* C-i */
1040 return TOGGLE_FIRST_SELECTED;
1043 *input = strdup(str);
1044 if (*input == NULL) {
1045 fprintf(stderr, "Error while allocating memory for key.\n");
1046 return EXIT;
1049 return ADD_CHAR;
1052 void
1053 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1055 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1056 /* if there is something selected expand it and return */
1057 int index = cs->selected == -1 ? 0 : cs->selected;
1058 struct completion *c = cs->completions;
1059 char *t;
1061 while (1) {
1062 if (index == 0)
1063 break;
1064 c++;
1065 index--;
1068 t = c->rcompletion;
1069 free(*text);
1070 *text = strdup(t);
1072 if (*text == NULL) {
1073 fprintf(stderr, "Memory allocation error\n");
1074 *status = ERR;
1077 *textlen = strlen(*text);
1078 return;
1081 if (!r->free_text) /* cannot accept arbitrary text */
1082 *status = LOOPING;
1085 /* event loop */
1086 enum state
1087 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1089 enum state status = LOOPING;
1091 while (status == LOOPING) {
1092 XEvent e;
1093 XNextEvent(r->d, &e);
1095 if (XFilterEvent(&e, r->w))
1096 continue;
1098 switch (e.type) {
1099 case KeymapNotify:
1100 XRefreshKeyboardMapping(&e.xmapping);
1101 break;
1103 case FocusIn:
1104 /* Re-grab focus */
1105 if (e.xfocus.window != r->w)
1106 grabfocus(r->d, r->w);
1107 break;
1109 case VisibilityNotify:
1110 if (e.xvisibility.state != VisibilityUnobscured)
1111 XRaiseWindow(r->d, r->w);
1112 break;
1114 case MapNotify:
1115 get_wh(r->d, &r->w, &r->width, &r->height);
1116 draw(r, *text, cs);
1117 break;
1119 case KeyPress: {
1120 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1121 char *input;
1123 switch (parse_event(r->d, ev, r->xic, &input)) {
1124 case EXIT:
1125 status = ERR;
1126 break;
1128 case CONFIRM: {
1129 status = OK;
1130 confirm(&status, r, cs, text, textlen);
1131 break;
1134 case CONFIRM_CONTINUE: {
1135 status = OK_LOOP;
1136 confirm(&status, r, cs, text, textlen);
1137 break;
1140 case PREV_COMPL: {
1141 complete(cs, r->first_selected, 1, text, textlen, &status);
1142 r->offset = cs->selected;
1143 break;
1146 case NEXT_COMPL: {
1147 complete(cs, r->first_selected, 0, text, textlen, &status);
1148 r->offset = cs->selected;
1149 break;
1152 case DEL_CHAR:
1153 popc(*text);
1154 update_completions(cs, *text, lines, vlines, r->first_selected);
1155 r->offset = 0;
1156 break;
1158 case DEL_WORD: {
1159 popw(*text);
1160 update_completions(cs, *text, lines, vlines, r->first_selected);
1161 break;
1164 case DEL_LINE: {
1165 int i;
1166 for (i = 0; i < *textlen; ++i)
1167 *(*text + i) = 0;
1168 update_completions(cs, *text, lines, vlines, r->first_selected);
1169 r->offset = 0;
1170 break;
1173 case ADD_CHAR: {
1174 int str_len, i;
1176 str_len = strlen(input);
1179 * sometimes a strange key is pressed
1180 * i.e. ctrl alone), so input will be
1181 * empty. Don't need to update
1182 * completion in that case
1184 if (str_len == 0)
1185 break;
1187 for (i = 0; i < str_len; ++i) {
1188 *textlen = pushc(text, *textlen, input[i]);
1189 if (*textlen == -1) {
1190 fprintf(stderr, "Memory allocation error\n");
1191 status = ERR;
1192 break;
1196 if (status != ERR) {
1197 update_completions(cs, *text, lines, vlines, r->first_selected);
1198 free(input);
1201 r->offset = 0;
1202 break;
1205 case TOGGLE_FIRST_SELECTED:
1206 r->first_selected = !r->first_selected;
1207 if (r->first_selected && cs->selected < 0)
1208 cs->selected = 0;
1209 if (!r->first_selected && cs->selected == 0)
1210 cs->selected = -1;
1211 break;
1215 case ButtonPress: {
1216 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1217 /* if (ev->button == Button1) { /\* click *\/ */
1218 /* int x = ev->x - r.border_w; */
1219 /* int y = ev->y - r.border_n; */
1220 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1221 /* } */
1223 if (ev->button == Button4) /* scroll up */
1224 r->offset = MAX((ssize_t)r->offset - 1, 0);
1226 if (ev->button == Button5) /* scroll down */
1227 r->offset = MIN(r->offset + 1, cs->length - 1);
1229 break;
1233 draw(r, *text, cs);
1236 return status;
1239 int
1240 load_font(struct rendering *r, const char *fontname)
1242 #ifdef USE_XFT
1243 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1244 return 0;
1245 #else
1246 char **missing_charset_list;
1247 int missing_charset_count;
1249 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1250 if (r->font != NULL)
1251 return 0;
1253 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1255 if (!strcmp(fontname, default_fontname))
1256 return -1;
1258 return load_font(r, default_fontname);
1259 #endif
1262 void
1263 xim_init(struct rendering *r, XrmDatabase *xdb)
1265 XIM xim;
1266 XIMStyle best_match_style;
1267 XIMStyles *xis;
1268 int i;
1270 /* Open the X input method */
1271 xim = XOpenIM(r->d, *xdb, resname, resclass);
1272 check_allocation(xim);
1274 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1275 fprintf(stderr, "Input Styles could not be retrieved\n");
1276 exit(EX_UNAVAILABLE);
1279 best_match_style = 0;
1280 for (i = 0; i < xis->count_styles; ++i) {
1281 XIMStyle ts = xis->supported_styles[i];
1282 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1283 best_match_style = ts;
1284 break;
1287 XFree(xis);
1289 if (!best_match_style)
1290 fprintf(stderr, "No matching input style could be determined\n");
1292 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1293 check_allocation(r->xic);
1296 void
1297 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1299 XSetWindowAttributes attr;
1301 /* Create the window */
1302 attr.colormap = cmap;
1303 attr.override_redirect = 1;
1304 attr.border_pixel = 0;
1305 attr.background_pixel = 0x80808080;
1306 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1308 r->w = XCreateWindow(r->d,
1309 parent_window,
1310 x + ox, y + oy,
1311 r->width, r->height,
1313 vinfo.depth,
1314 InputOutput,
1315 vinfo.visual,
1316 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1317 &attr);
1320 void
1321 usage(char *prgname)
1323 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1324 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1325 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1326 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1329 int
1330 main(int argc, char **argv)
1332 struct completions *cs;
1333 struct rendering r;
1334 XVisualInfo vinfo;
1335 Colormap cmap;
1336 size_t nlines, i;
1337 Window parent_window;
1338 XrmDatabase xdb;
1339 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1340 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1341 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1342 enum state status;
1343 int ch;
1344 int offset_x, offset_y, x, y;
1345 int textlen, d_width, d_height;
1346 short embed;
1347 char *sep, *parent_window_id;
1348 char **lines, *buf, **vlines;
1349 char *fontname, *text, *xrm;
1351 #ifdef __OpenBSD__
1352 /* stdio & rpath: to read/write stdio/stdout/stderr */
1353 /* unix: to connect to XOrg */
1354 pledge("stdio rpath unix", "");
1355 #endif
1357 sep = NULL;
1358 parent_window_id = NULL;
1360 r.first_selected = 0;
1361 r.free_text = 1;
1362 r.multiple_select = 0;
1363 r.offset = 0;
1365 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1366 switch (ch) {
1367 case 'h': /* help */
1368 usage(*argv);
1369 return 0;
1370 case 'v': /* version */
1371 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1372 return 0;
1373 case 'e': /* embed */
1374 parent_window_id = strdup(optarg);
1375 check_allocation(parent_window_id);
1376 break;
1377 case 'd': {
1378 sep = strdup(optarg);
1379 check_allocation(sep);
1381 case 'A': {
1382 r.free_text = 0;
1383 break;
1385 case 'm': {
1386 r.multiple_select = 1;
1387 break;
1389 default:
1390 break;
1394 /* Read the completions */
1395 lines = NULL;
1396 buf = NULL;
1397 nlines = readlines(&lines, &buf);
1399 vlines = NULL;
1400 if (sep != NULL) {
1401 int l;
1402 l = strlen(sep);
1403 vlines = calloc(nlines, sizeof(char*));
1404 check_allocation(vlines);
1406 for (i = 0; i < nlines; i++) {
1407 char *t;
1408 t = strstr(lines[i], sep);
1409 if (t == NULL)
1410 vlines[i] = lines[i];
1411 else
1412 vlines[i] = t + l;
1416 setlocale(LC_ALL, getenv("LANG"));
1418 status = LOOPING;
1420 /* where the monitor start (used only with xinerama) */
1421 offset_x = offset_y = 0;
1423 /* default width and height */
1424 r.width = 400;
1425 r.height = 20;
1427 /* default position on the screen */
1428 x = y = 0;
1430 /* default padding */
1431 r.padding = 10;
1433 /* default borders */
1434 r.border_n = r.border_e = r.border_s = r.border_w = 0;
1436 /* the prompt. We duplicate the string so later is easy to
1437 * free (in the case it's been overwritten by the user) */
1438 r.ps1 = strdup("$ ");
1439 check_allocation(r.ps1);
1441 /* same for the font name */
1442 fontname = strdup(default_fontname);
1443 check_allocation(fontname);
1445 textlen = 10;
1446 text = malloc(textlen * sizeof(char));
1447 check_allocation(text);
1449 /* struct completions *cs = filter(text, lines); */
1450 cs = compls_new(nlines);
1451 check_allocation(cs);
1453 /* start talking to xorg */
1454 r.d = XOpenDisplay(NULL);
1455 if (r.d == NULL) {
1456 fprintf(stderr, "Could not open display!\n");
1457 return EX_UNAVAILABLE;
1460 embed = 1;
1461 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1462 parent_window = DefaultRootWindow(r.d);
1463 embed = 0;
1466 /* get display size */
1467 get_wh(r.d, &parent_window, &d_width, &d_height);
1469 #ifdef USE_XINERAMA
1470 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1471 XineramaScreenInfo *info;
1472 Window rr;
1473 Window root;
1474 int number_of_screens, monitors, i;
1475 int root_x, root_y, win_x, win_y;
1476 unsigned int mask;
1477 short res;
1479 number_of_screens = XScreenCount(r.d);
1480 for (i = 0; i < number_of_screens; ++i) {
1481 root = XRootWindow(r.d, i);
1482 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1483 if (res)
1484 break;
1487 if (!res) {
1488 fprintf(stderr, "No mouse found.\n");
1489 root_x = 0;
1490 root_y = 0;
1493 /* Now find in which monitor the mice is */
1494 info = XineramaQueryScreens(r.d, &monitors);
1495 if (info) {
1496 for (i = 0; i < monitors; ++i) {
1497 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1498 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1499 offset_x = info[i].x_org;
1500 offset_y = info[i].y_org;
1501 d_width = info[i].width;
1502 d_height = info[i].height;
1503 break;
1507 XFree(info);
1509 #endif
1511 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1512 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1514 p_fg = compl_fg = parse_color("#fff", NULL);
1515 compl_highlighted_fg = parse_color("#000", NULL);
1517 p_bg = compl_bg = parse_color("#000", NULL);
1518 compl_highlighted_bg = parse_color("#fff", NULL);
1520 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1522 r.horizontal_layout = 1;
1524 /* Read the resources */
1525 XrmInitialize();
1526 xrm = XResourceManagerString(r.d);
1527 xdb = NULL;
1528 if (xrm != NULL) {
1529 XrmValue value;
1530 char *datatype[20];
1532 xdb = XrmGetStringDatabase(xrm);
1534 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1535 free(fontname);
1536 fontname = strdup(value.addr);
1537 check_allocation(fontname);
1538 } else {
1539 fprintf(stderr, "no font defined, using %s\n", fontname);
1542 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1543 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1544 else
1545 fprintf(stderr, "no layout defined, using horizontal\n");
1547 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1548 free(r.ps1);
1549 r.ps1 = normalize_str(value.addr);
1550 } else {
1551 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1554 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1555 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1556 else
1557 fprintf(stderr, "no width defined, using %d\n", r.width);
1559 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1560 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1561 else
1562 fprintf(stderr, "no height defined, using %d\n", r.height);
1564 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1565 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1566 else
1567 fprintf(stderr, "no x defined, using %d\n", x);
1569 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1570 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1571 else
1572 fprintf(stderr, "no y defined, using %d\n", y);
1574 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1575 r.padding = parse_integer(value.addr, r.padding);
1576 else
1577 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1579 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1580 char **borders;
1582 borders = parse_csslike(value.addr);
1583 if (borders != NULL) {
1584 r.border_n = parse_integer(borders[0], 0);
1585 r.border_e = parse_integer(borders[1], 0);
1586 r.border_s = parse_integer(borders[2], 0);
1587 r.border_w = parse_integer(borders[3], 0);
1588 } else
1589 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1590 } else
1591 fprintf(stderr, "no border defined, using 0.\n");
1593 /* Prompt */
1594 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1595 p_fg = parse_color(value.addr, "#fff");
1597 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1598 p_bg = parse_color(value.addr, "#000");
1600 /* Completions */
1601 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1602 compl_fg = parse_color(value.addr, "#fff");
1604 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1605 compl_bg = parse_color(value.addr, "#000");
1606 else
1607 compl_bg = parse_color("#000", NULL);
1609 /* Completion Highlighted */
1610 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1611 compl_highlighted_fg = parse_color(value.addr, "#000");
1613 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1614 compl_highlighted_bg = parse_color(value.addr, "#fff");
1615 else
1616 compl_highlighted_bg = parse_color("#fff", NULL);
1618 /* Border */
1619 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1620 char **colors;
1621 colors = parse_csslike(value.addr);
1622 if (colors != NULL) {
1623 border_n_bg = parse_color(colors[0], "#000");
1624 border_e_bg = parse_color(colors[1], "#000");
1625 border_s_bg = parse_color(colors[2], "#000");
1626 border_w_bg = parse_color(colors[3], "#000");
1627 } else
1628 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1632 /* Second round of args parsing */
1633 optind = 0; /* reset the option index */
1634 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1635 switch (ch) {
1636 case 'a':
1637 r.first_selected = 1;
1638 break;
1639 case 'A':
1640 /* free_text -- already catched */
1641 case 'd':
1642 /* separator -- this case was already catched */
1643 case 'e':
1644 /* embedding mymenu this case was already catched. */
1645 case 'm':
1646 /* multiple selection this case was already catched. */
1647 break;
1648 case 'p': {
1649 char *newprompt;
1650 newprompt = strdup(optarg);
1651 if (newprompt != NULL) {
1652 free(r.ps1);
1653 r.ps1 = newprompt;
1655 break;
1657 case 'x':
1658 x = parse_int_with_pos(optarg, x, d_width, r.width);
1659 break;
1660 case 'y':
1661 y = parse_int_with_pos(optarg, y, d_height, r.height);
1662 break;
1663 case 'P':
1664 r.padding = parse_integer(optarg, r.padding);
1665 break;
1666 case 'l':
1667 r.horizontal_layout = !strcmp(optarg, "horizontal");
1668 break;
1669 case 'f': {
1670 char *newfont;
1671 if ((newfont = strdup(optarg)) != NULL) {
1672 free(fontname);
1673 fontname = newfont;
1675 break;
1677 case 'W':
1678 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1679 break;
1680 case 'H':
1681 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1682 break;
1683 case 'b': {
1684 char **borders;
1685 if ((borders = parse_csslike(optarg)) != NULL) {
1686 r.border_n = parse_integer(borders[0], 0);
1687 r.border_e = parse_integer(borders[1], 0);
1688 r.border_s = parse_integer(borders[2], 0);
1689 r.border_w = parse_integer(borders[3], 0);
1690 } else
1691 fprintf(stderr, "Error parsing b option\n");
1692 break;
1694 case 'B': {
1695 char **colors;
1696 if ((colors = parse_csslike(optarg)) != NULL) {
1697 border_n_bg = parse_color(colors[0], "#000");
1698 border_e_bg = parse_color(colors[1], "#000");
1699 border_s_bg = parse_color(colors[2], "#000");
1700 border_w_bg = parse_color(colors[3], "#000");
1701 } else
1702 fprintf(stderr, "error while parsing B option\n");
1703 break;
1705 case 't':
1706 p_fg = parse_color(optarg, NULL);
1707 break;
1708 case 'T':
1709 p_bg = parse_color(optarg, NULL);
1710 break;
1711 case 'c':
1712 compl_fg = parse_color(optarg, NULL);
1713 break;
1714 case 'C':
1715 compl_bg = parse_color(optarg, NULL);
1716 break;
1717 case 's':
1718 compl_highlighted_fg = parse_color(optarg, NULL);
1719 break;
1720 case 'S':
1721 compl_highlighted_bg = parse_color(optarg, NULL);
1722 break;
1723 default:
1724 fprintf(stderr, "Unrecognized option %c\n", ch);
1725 status = ERR;
1726 break;
1730 /* since only now we know if the first should be selected,
1731 * update the completion here */
1732 update_completions(cs, text, lines, vlines, r.first_selected);
1734 /* update the prompt lenght, only now we surely know the length of it */
1735 r.ps1len = strlen(r.ps1);
1737 /* Create the window */
1738 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1739 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1740 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1741 XMapRaised(r.d, r.w);
1743 /* If embed, listen for other events as well */
1744 if (embed) {
1745 Window *children, parent, root;
1746 unsigned int children_no;
1748 XSelectInput(r.d, parent_window, FocusChangeMask);
1749 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1750 for (i = 0; i < children_no && children[i] != r.w; ++i)
1751 XSelectInput(r.d, children[i], FocusChangeMask);
1752 XFree(children);
1754 grabfocus(r.d, r.w);
1757 take_keyboard(r.d, r.w);
1759 r.x_zero = r.border_w;
1760 r.y_zero = r.border_n;
1763 XGCValues values;
1765 r.prompt = XCreateGC(r.d, r.w, 0, &values),
1766 r.prompt_bg = XCreateGC(r.d, r.w, 0, &values);
1767 r.completion = XCreateGC(r.d, r.w, 0, &values);
1768 r.completion_bg = XCreateGC(r.d, r.w, 0, &values);
1769 r.completion_highlighted = XCreateGC(r.d, r.w, 0, &values);
1770 r.completion_highlighted_bg = XCreateGC(r.d, r.w, 0, &values);
1771 r.border_n_bg = XCreateGC(r.d, r.w, 0, &values);
1772 r.border_e_bg = XCreateGC(r.d, r.w, 0, &values);
1773 r.border_s_bg = XCreateGC(r.d, r.w, 0, &values);
1774 r.border_w_bg = XCreateGC(r.d, r.w, 0, &values);
1777 if (load_font(&r, fontname) == -1)
1778 status = ERR;
1780 #ifdef USE_XFT
1781 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1784 rgba_t c;
1785 XRenderColor xrcolor;
1787 /* Prompt */
1788 c = *(rgba_t*)&p_fg;
1789 xrcolor.red = EXPANDBITS(c.rgba.r);
1790 xrcolor.green = EXPANDBITS(c.rgba.g);
1791 xrcolor.blue = EXPANDBITS(c.rgba.b);
1792 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1793 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_prompt);
1795 /* Completion */
1796 c = *(rgba_t*)&compl_fg;
1797 xrcolor.red = EXPANDBITS(c.rgba.r);
1798 xrcolor.green = EXPANDBITS(c.rgba.g);
1799 xrcolor.blue = EXPANDBITS(c.rgba.b);
1800 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1801 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion);
1803 /* Completion highlighted */
1804 c = *(rgba_t*)&compl_highlighted_fg;
1805 xrcolor.red = EXPANDBITS(c.rgba.r);
1806 xrcolor.green = EXPANDBITS(c.rgba.g);
1807 xrcolor.blue = EXPANDBITS(c.rgba.b);
1808 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1809 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion_highlighted);
1811 #endif
1813 /* Load the colors in our GCs */
1814 XSetForeground(r.d, r.prompt, p_fg);
1815 XSetForeground(r.d, r.prompt_bg, p_bg);
1816 XSetForeground(r.d, r.completion, compl_fg);
1817 XSetForeground(r.d, r.completion_bg, compl_bg);
1818 XSetForeground(r.d, r.completion_highlighted, compl_highlighted_fg);
1819 XSetForeground(r.d, r.completion_highlighted_bg, compl_highlighted_bg);
1820 XSetForeground(r.d, r.border_n_bg, border_n_bg);
1821 XSetForeground(r.d, r.border_e_bg, border_e_bg);
1822 XSetForeground(r.d, r.border_s_bg, border_s_bg);
1823 XSetForeground(r.d, r.border_w_bg, border_w_bg);
1825 xim_init(&r, &xdb);
1827 /* Draw the window for the first time */
1828 draw(&r, text, cs);
1830 /* Main loop */
1831 while (status == LOOPING || status == OK_LOOP) {
1832 status = loop(&r, &text, &textlen, cs, lines, vlines);
1834 if (status != ERR)
1835 printf("%s\n", text);
1837 if (!r.multiple_select && status == OK_LOOP)
1838 status = OK;
1841 XUngrabKeyboard(r.d, CurrentTime);
1843 #ifdef USE_XFT
1844 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1845 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1846 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1847 #endif
1849 free(r.ps1);
1850 free(fontname);
1851 free(text);
1853 free(buf);
1854 free(lines);
1855 free(vlines);
1856 compls_delete(cs);
1858 XDestroyWindow(r.d, r.w);
1859 XCloseDisplay(r.d);
1861 return status != OK;