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;
125 int ps1w; /* ps1 width */
126 int ps1h; /* ps1 height */
128 XIC xic;
130 /* colors */
131 GC prompt;
132 GC prompt_bg;
133 GC completion;
134 GC completion_bg;
135 GC completion_highlighted;
136 GC completion_highlighted_bg;
137 GC border_n_bg;
138 GC border_e_bg;
139 GC border_s_bg;
140 GC border_w_bg;
141 #ifdef USE_XFT
142 XftFont *font;
143 XftDraw *xftdraw;
144 XftColor xft_prompt;
145 XftColor xft_completion;
146 XftColor xft_completion_highlighted;
147 #else
148 XFontSet font;
149 #endif
150 };
152 struct completion {
153 char *completion;
154 char *rcompletion;
155 };
157 /* Wrap the linked list of completions */
158 struct completions {
159 struct completion *completions;
160 ssize_t selected;
161 size_t length;
162 };
164 /* idea stolen from lemonbar. ty lemonboy */
165 typedef union {
166 struct {
167 uint8_t b;
168 uint8_t g;
169 uint8_t r;
170 uint8_t a;
171 } rgba;
172 uint32_t v;
173 } rgba_t;
175 extern char *optarg;
176 extern int optind;
178 /* Return a newly allocated (and empty) completion list */
179 struct completions *
180 compls_new(size_t length)
182 struct completions *cs = malloc(sizeof(struct completions));
184 if (cs == NULL)
185 return cs;
187 cs->completions = calloc(length, sizeof(struct completion));
188 if (cs->completions == NULL) {
189 free(cs);
190 return NULL;
193 cs->selected = -1;
194 cs->length = length;
195 return cs;
198 /* Delete the wrapper and the whole list */
199 void
200 compls_delete(struct completions *cs)
202 if (cs == NULL)
203 return;
205 free(cs->completions);
206 free(cs);
209 /*
210 * Create a completion list from a text and the list of possible
211 * completions (null terminated). Expects a non-null `cs'. `lines' and
212 * `vlines' should have the same length OR `vlines' is NULL.
213 */
214 void
215 filter(struct completions *cs, char *text, char **lines, char **vlines)
217 size_t index = 0;
218 size_t matching = 0;
219 char *l;
221 if (vlines == NULL)
222 vlines = lines;
224 while (1) {
225 if (lines[index] == NULL)
226 break;
228 l = vlines[index] != NULL ? vlines[index] : lines[index];
230 if (strcasestr(l, text) != NULL) {
231 struct completion *c = &cs->completions[matching];
232 c->completion = l;
233 c->rcompletion = lines[index];
234 matching++;
237 index++;
239 cs->length = matching;
240 cs->selected = -1;
243 /* Update the given completion */
244 void
245 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
247 filter(cs, text, lines, vlines);
248 if (first_selected && cs->length > 0)
249 cs->selected = 0;
252 /*
253 * Select the next or previous selection and update some state. `text'
254 * will be updated with the text of the completion and `textlen' with
255 * the new length. If the memory cannot be allocated `status' will be
256 * set to `ERR'.
257 */
258 void
259 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
261 struct completion *n;
262 int index;
264 if (cs == NULL || cs->length == 0)
265 return;
267 /*
268 * If the first is always selected and the first entry is
269 * different from the text, expand the text and return
270 */
271 if (first_selected
272 && cs->selected == 0
273 && strcmp(cs->completions->completion, *text) != 0
274 && !p) {
275 free(*text);
276 *text = strdup(cs->completions->completion);
277 if (text == NULL) {
278 *status = ERR;
279 return;
281 *textlen = strlen(*text);
282 return;
285 index = cs->selected;
287 if (index == -1 && p)
288 index = 0;
289 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
291 n = &cs->completions[cs->selected];
293 free(*text);
294 *text = strdup(n->completion);
295 if (text == NULL) {
296 fprintf(stderr, "Memory allocation error!\n");
297 *status = ERR;
298 return;
300 *textlen = strlen(*text);
303 /* Push the character c at the end of the string pointed by p */
304 int
305 pushc(char **p, int maxlen, char c)
307 int len;
309 len = strnlen(*p, maxlen);
310 if (!(len < maxlen -2)) {
311 char *newptr;
313 maxlen += maxlen >> 1;
314 newptr = realloc(*p, maxlen);
315 if (newptr == NULL) /* bad */
316 return -1;
317 *p = newptr;
320 (*p)[len] = c;
321 (*p)[len+1] = '\0';
322 return maxlen;
325 /*
326 * Remove the last rune from the *UTF-8* string! This is different
327 * from just setting the last byte to 0 (in some cases ofc). Return a
328 * pointer (e) to the last nonzero char. If e < p then p is empty!
329 */
330 char *
331 popc(char *p)
333 int len = strlen(p);
334 char *e;
336 if (len == 0)
337 return p;
339 e = p + len - 1;
341 do {
342 char c = *e;
344 *e = '\0';
345 e -= 1;
347 /*
348 * If c is a starting byte (11......) or is under
349 * U+007F we're done.
350 */
351 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
352 break;
353 } while (e >= p);
355 return e;
358 /* Remove the last word plus trailing white spaces from the given string */
359 void
360 popw(char *w)
362 int len;
363 short in_word = 1;
365 if ((len = strlen(w)) == 0)
366 return;
368 while (1) {
369 char *e = popc(w);
371 if (e < w)
372 return;
374 if (in_word && isspace(*e))
375 in_word = 0;
377 if (!in_word && !isspace(*e))
378 return;
382 /*
383 * If the string is surrounded by quates (`"') remove them and replace
384 * every `\"' in the string with a single double-quote.
385 */
386 char *
387 normalize_str(const char *str)
389 int len, p;
390 char *s;
392 if ((len = strlen(str)) == 0)
393 return NULL;
395 s = calloc(len, sizeof(char));
396 check_allocation(s);
397 p = 0;
399 while (*str) {
400 char c = *str;
402 if (*str == '\\') {
403 if (*(str + 1)) {
404 s[p] = *(str + 1);
405 p++;
406 str += 2; /* skip this and the next char */
407 continue;
408 } else
409 break;
411 if (c == '"') {
412 str++; /* skip only this char */
413 continue;
415 s[p] = c;
416 p++;
417 str++;
420 return s;
423 size_t
424 read_stdin(char **buf)
426 size_t offset = 0;
427 size_t len = STDIN_CHUNKS;
429 *buf = malloc(len * sizeof(char));
430 if (*buf == NULL)
431 goto err;
433 while (1) {
434 ssize_t r;
435 size_t i;
437 r = read(0, *buf + offset, STDIN_CHUNKS);
439 if (r < 1)
440 return len;
442 offset += r;
444 len += STDIN_CHUNKS;
445 *buf = realloc(*buf, len);
446 if (*buf == NULL)
447 goto err;
449 for (i = offset; i < len; ++i)
450 (*buf)[i] = '\0';
453 err:
454 fprintf(stderr, "Error in allocating memory for stdin.\n");
455 exit(EX_UNAVAILABLE);
458 size_t
459 readlines(char ***lns, char **buf)
461 size_t i, len, ll, lines;
462 short in_line = 0;
464 lines = 0;
466 *buf = NULL;
467 len = read_stdin(buf);
469 ll = LINES_CHUNK;
470 *lns = malloc(ll * sizeof(char*));
472 if (*lns == NULL)
473 goto err;
475 for (i = 0; i < len; i++) {
476 char c = (*buf)[i];
478 if (c == '\0')
479 break;
481 if (c == '\n')
482 (*buf)[i] = '\0';
484 if (in_line && c == '\n')
485 in_line = 0;
487 if (!in_line && c != '\n') {
488 in_line = 1;
489 (*lns)[lines] = (*buf) + i;
490 lines++;
492 if (lines == ll) { /* resize */
493 ll += LINES_CHUNK;
494 *lns = realloc(*lns, ll * sizeof(char*));
495 if (*lns == NULL)
496 goto err;
501 (*lns)[lines] = NULL;
503 return lines;
505 err:
506 fprintf(stderr, "Error in memory allocation.\n");
507 exit(EX_UNAVAILABLE);
510 /*
511 * Compute the dimensions of the string str once rendered.
512 * It'll return the width and set ret_width and ret_height if not NULL
513 */
514 int
515 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
517 int height;
518 int width;
519 #ifdef USE_XFT
520 XGlyphInfo gi;
521 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
522 height = r->font->ascent - r->font->descent;
523 width = gi.width - gi.x;
524 #else
525 XRectangle rect;
526 XmbTextExtents(r->font, str, len, NULL, &rect);
527 height = rect.height;
528 width = rect.width;
529 #endif
530 if (ret_width != NULL) *ret_width = width;
531 if (ret_height != NULL) *ret_height = height;
532 return width;
535 void
536 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
538 #ifdef USE_XFT
539 XftColor xftcolor;
540 if (tt == PROMPT) xftcolor = r->xft_prompt;
541 if (tt == COMPL) xftcolor = r->xft_completion;
542 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
544 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
545 #else
546 GC gc;
547 if (tt == PROMPT) gc = r->prompt;
548 if (tt == COMPL) gc = r->completion;
549 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
550 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
551 #endif
554 /* Duplicate the string and substitute every space with a 'n` */
555 char *
556 strdupn(char *str)
558 int len, i;
559 char *dup;
561 len = strlen(str);
563 if (str == NULL || len == 0)
564 return NULL;
566 if ((dup = strdup(str)) == NULL)
567 return NULL;
569 for (i = 0; i < len; ++i)
570 if (dup[i] == ' ')
571 dup[i] = 'n';
573 return dup;
576 /* ,-----------------------------------------------------------------, */
577 /* | 20 char text | completion | completion | completion | compl | */
578 /* `-----------------------------------------------------------------' */
579 void
580 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
582 size_t i;
583 int prompt_width, start_at;
584 int texty, textlen;
586 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
588 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
589 start_at *= prompt_width;
590 start_at += r->padding;
592 texty = (inner_height(r) + r->ps1h + r->y_zero) / 2;
594 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
596 textlen = strlen(text);
597 if (textlen > prompt_width)
598 text = text + textlen - prompt_width;
600 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
601 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + r->ps1w, texty, r, PROMPT);
603 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
605 for (i = r->offset; i < cs->length; ++i) {
606 struct completion *c;
607 enum text_type tt;
608 GC h;
609 int len, text_width;
611 c = &cs->completions[i];
612 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
613 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
614 len = strlen(c->completion);
615 text_width = text_extents(c->completion, len, r, NULL, NULL);
617 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
618 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
620 start_at += text_width + r->padding * 2;
622 if (start_at > inner_width(r))
623 break; /* don't draw completion out of the window */
627 /* ,-----------------------------------------------------------------, */
628 /* | prompt | */
629 /* |-----------------------------------------------------------------| */
630 /* | completion | */
631 /* |-----------------------------------------------------------------| */
632 /* | completion | */
633 /* `-----------------------------------------------------------------' */
634 void
635 draw_vertically(struct rendering *r, char *text, struct completions *cs)
637 size_t i;
638 int height, start_at;
640 text_extents("fjpgl", 5, r, NULL, &height);
641 start_at = r->padding * 2 + height;
643 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
644 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
646 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
647 draw_string(text, strlen(text), r->x_zero + r->padding + r->ps1w, r->y_zero + height + r->padding, r, PROMPT);
649 start_at += r->y_zero;
651 for (i = r->offset; i < cs->length; ++i) {
652 struct completion *c;
653 enum text_type tt;
654 GC h;
655 int len;
657 c = &cs->completions[i];
658 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
659 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
660 len = strlen(c->completion);
662 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
663 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
665 start_at += height + r->padding * 2;
667 if (start_at > inner_height(r))
668 break; /* don't draw completion out of the window */
672 void
673 draw(struct rendering *r, char *text, struct completions *cs)
675 if (r->horizontal_layout)
676 draw_horizontally(r, text, cs);
677 else
678 draw_vertically(r, text, cs);
680 /* Draw the borders */
681 if (r->border_w != 0)
682 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
684 if (r->border_e != 0)
685 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
687 if (r->border_n != 0)
688 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
690 if (r->border_s != 0)
691 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
693 /* render! */
694 XFlush(r->d);
697 /* Set some WM stuff */
698 void
699 set_win_atoms_hints(Display *d, Window w, int width, int height)
701 Atom type;
702 XClassHint *class_hint;
703 XSizeHints *size_hint;
705 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
706 XChangeProperty(d,
707 w,
708 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
709 XInternAtom(d, "ATOM", 0),
710 32,
711 PropModeReplace,
712 (unsigned char *)&type,
714 );
716 /* some window managers honor this properties */
717 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
718 XChangeProperty(d,
719 w,
720 XInternAtom(d, "_NET_WM_STATE", 0),
721 XInternAtom(d, "ATOM", 0),
722 32,
723 PropModeReplace,
724 (unsigned char *)&type,
726 );
728 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
729 XChangeProperty(d,
730 w,
731 XInternAtom(d, "_NET_WM_STATE", 0),
732 XInternAtom(d, "ATOM", 0),
733 32,
734 PropModeAppend,
735 (unsigned char *)&type,
737 );
739 /* Setting window hints */
740 class_hint = XAllocClassHint();
741 if (class_hint == NULL) {
742 fprintf(stderr, "Could not allocate memory for class hint\n");
743 exit(EX_UNAVAILABLE);
746 class_hint->res_name = resname;
747 class_hint->res_class = resclass;
748 XSetClassHint(d, w, class_hint);
749 XFree(class_hint);
751 size_hint = XAllocSizeHints();
752 if (size_hint == NULL) {
753 fprintf(stderr, "Could not allocate memory for size hint\n");
754 exit(EX_UNAVAILABLE);
757 size_hint->flags = PMinSize | PBaseSize;
758 size_hint->min_width = width;
759 size_hint->base_width = width;
760 size_hint->min_height = height;
761 size_hint->base_height = height;
763 XFlush(d);
766 /* Get the width and height of the window `w' */
767 void
768 get_wh(Display *d, Window *w, int *width, int *height)
770 XWindowAttributes win_attr;
772 XGetWindowAttributes(d, *w, &win_attr);
773 *height = win_attr.height;
774 *width = win_attr.width;
777 int
778 grabfocus(Display *d, Window w)
780 int i;
781 for (i = 0; i < 100; ++i) {
782 Window focuswin;
783 int revert_to_win;
785 XGetInputFocus(d, &focuswin, &revert_to_win);
787 if (focuswin == w)
788 return 1;
790 XSetInputFocus(d, w, RevertToParent, CurrentTime);
791 usleep(1000);
793 return 0;
796 /*
797 * I know this may seem a little hackish BUT is the only way I managed
798 * to actually grab that goddam keyboard. Only one call to
799 * XGrabKeyboard does not always end up with the keyboard grabbed!
800 */
801 int
802 take_keyboard(Display *d, Window w)
804 int i;
805 for (i = 0; i < 100; i++) {
806 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
807 return 1;
808 usleep(1000);
810 fprintf(stderr, "Cannot grab keyboard\n");
811 return 0;
814 unsigned long
815 parse_color(const char *str, const char *def)
817 size_t len;
818 rgba_t tmp;
819 char *ep;
821 if (str == NULL)
822 goto invc;
824 len = strlen(str);
826 /* +1 for the # ath the start */
827 if (*str != '#' || len > 9 || len < 4)
828 goto invc;
829 ++str; /* skip the # */
831 errno = 0;
832 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
834 if (errno)
835 goto invc;
837 switch (len-1) {
838 case 3:
839 /* expand #rgb -> #rrggbb */
840 tmp.v = (tmp.v & 0xf00) * 0x1100
841 | (tmp.v & 0x0f0) * 0x0110
842 | (tmp.v & 0x00f) * 0x0011;
843 case 6:
844 /* assume 0xff opacity */
845 tmp.rgba.a = 0xff;
846 break;
847 } /* colors in #aarrggbb need no adjustments */
849 /* premultiply the alpha */
850 if (tmp.rgba.a) {
851 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
852 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
853 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
854 return tmp.v;
857 return 0U;
859 invc:
860 fprintf(stderr, "Invalid color: \"%s\".\n", str);
861 if (def != NULL)
862 return parse_color(def, NULL);
863 else
864 return 0U;
867 /*
868 * Given a string try to parse it as a number or return `default_value'.
869 */
870 int
871 parse_integer(const char *str, int default_value)
873 long lval;
874 char *ep;
876 errno = 0;
877 lval = strtol(str, &ep, 10);
879 if (str[0] == '\0' || *ep != '\0') { /* NaN */
880 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
881 return default_value;
884 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
885 (lval > INT_MAX || lval < INT_MIN)) {
886 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
887 return default_value;
890 return lval;
893 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
894 int
895 parse_int_with_percentage(const char *str, int default_value, int max)
897 int len = strlen(str);
899 if (len > 0 && str[len-1] == '%') {
900 int val;
901 char *cpy;
903 cpy = strdup(str);
904 check_allocation(cpy);
905 cpy[len-1] = '\0';
906 val = parse_integer(cpy, default_value);
907 free(cpy);
908 return val * max / 100;
911 return parse_integer(str, default_value);
914 /*
915 * Like parse_int_with_percentage but understands some special values:
916 * - middle that is (max-self)/2
917 * - start that is 0
918 * - end that is (max-self)
919 */
920 int
921 parse_int_with_pos(const char *str, int default_value, int max, int self)
923 if (!strcmp(str, "start"))
924 return 0;
925 if (!strcmp(str, "middle"))
926 return (max - self)/2;
927 if (!strcmp(str, "end"))
928 return max-self;
929 return parse_int_with_percentage(str, default_value, max);
932 /* Parse a string like a CSS value. */
933 /* TODO: harden a bit this function */
934 char **
935 parse_csslike(const char *str)
937 int i, j;
938 char *s, *token, **ret;
939 short any_null;
941 s = strdup(str);
942 if (s == NULL)
943 return NULL;
945 ret = malloc(4 * sizeof(char*));
946 if (ret == NULL) {
947 free(s);
948 return NULL;
951 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
952 ret[i] = strdup(token);
954 if (i == 1)
955 for (j = 1; j < 4; j++)
956 ret[j] = strdup(ret[0]);
958 if (i == 2) {
959 ret[2] = strdup(ret[0]);
960 ret[3] = strdup(ret[1]);
963 if (i == 3)
964 ret[3] = strdup(ret[1]);
966 /* before we didn't check for the return type of strdup, here we will */
968 any_null = 0;
969 for (i = 0; i < 4; ++i)
970 any_null = ret[i] == NULL || any_null;
972 if (any_null)
973 for (i = 0; i < 4; ++i)
974 if (ret[i] != NULL)
975 free(ret[i]);
977 if (i == 0 || any_null) {
978 free(s);
979 free(ret);
980 return NULL;
983 return ret;
986 /*
987 * Given an event, try to understand what the users wants. If the
988 * return value is ADD_CHAR then `input' is a pointer to a string that
989 * will need to be free'ed later.
990 */
991 enum
992 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
994 char str[SYM_BUF_SIZE] = {0};
995 Status s;
997 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
998 return DEL_CHAR;
1000 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1001 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1003 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1004 return CONFIRM;
1006 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1007 return EXIT;
1009 /* Try to read what key was pressed */
1010 s = 0;
1011 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1012 if (s == XBufferOverflow) {
1013 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1014 return EXIT;
1017 if (ev->state & ControlMask) {
1018 if (!strcmp(str, "")) /* C-u */
1019 return DEL_LINE;
1020 if (!strcmp(str, "")) /* C-w */
1021 return DEL_WORD;
1022 if (!strcmp(str, "")) /* C-h */
1023 return DEL_CHAR;
1024 if (!strcmp(str, "\r")) /* C-m */
1025 return CONFIRM_CONTINUE;
1026 if (!strcmp(str, "")) /* C-p */
1027 return PREV_COMPL;
1028 if (!strcmp(str, "")) /* C-n */
1029 return NEXT_COMPL;
1030 if (!strcmp(str, "")) /* C-c */
1031 return EXIT;
1032 if (!strcmp(str, "\t")) /* C-i */
1033 return TOGGLE_FIRST_SELECTED;
1036 *input = strdup(str);
1037 if (*input == NULL) {
1038 fprintf(stderr, "Error while allocating memory for key.\n");
1039 return EXIT;
1042 return ADD_CHAR;
1045 void
1046 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1048 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1049 /* if there is something selected expand it and return */
1050 int index = cs->selected == -1 ? 0 : cs->selected;
1051 struct completion *c = cs->completions;
1052 char *t;
1054 while (1) {
1055 if (index == 0)
1056 break;
1057 c++;
1058 index--;
1061 t = c->rcompletion;
1062 free(*text);
1063 *text = strdup(t);
1065 if (*text == NULL) {
1066 fprintf(stderr, "Memory allocation error\n");
1067 *status = ERR;
1070 *textlen = strlen(*text);
1071 return;
1074 if (!r->free_text) /* cannot accept arbitrary text */
1075 *status = LOOPING;
1078 /* event loop */
1079 enum state
1080 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1082 enum state status = LOOPING;
1084 while (status == LOOPING) {
1085 XEvent e;
1086 XNextEvent(r->d, &e);
1088 if (XFilterEvent(&e, r->w))
1089 continue;
1091 switch (e.type) {
1092 case KeymapNotify:
1093 XRefreshKeyboardMapping(&e.xmapping);
1094 break;
1096 case FocusIn:
1097 /* Re-grab focus */
1098 if (e.xfocus.window != r->w)
1099 grabfocus(r->d, r->w);
1100 break;
1102 case VisibilityNotify:
1103 if (e.xvisibility.state != VisibilityUnobscured)
1104 XRaiseWindow(r->d, r->w);
1105 break;
1107 case MapNotify:
1108 get_wh(r->d, &r->w, &r->width, &r->height);
1109 draw(r, *text, cs);
1110 break;
1112 case KeyPress: {
1113 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1114 char *input;
1116 switch (parse_event(r->d, ev, r->xic, &input)) {
1117 case EXIT:
1118 status = ERR;
1119 break;
1121 case CONFIRM: {
1122 status = OK;
1123 confirm(&status, r, cs, text, textlen);
1124 break;
1127 case CONFIRM_CONTINUE: {
1128 status = OK_LOOP;
1129 confirm(&status, r, cs, text, textlen);
1130 break;
1133 case PREV_COMPL: {
1134 complete(cs, r->first_selected, 1, text, textlen, &status);
1135 r->offset = cs->selected;
1136 break;
1139 case NEXT_COMPL: {
1140 complete(cs, r->first_selected, 0, text, textlen, &status);
1141 r->offset = cs->selected;
1142 break;
1145 case DEL_CHAR:
1146 popc(*text);
1147 update_completions(cs, *text, lines, vlines, r->first_selected);
1148 r->offset = 0;
1149 break;
1151 case DEL_WORD: {
1152 popw(*text);
1153 update_completions(cs, *text, lines, vlines, r->first_selected);
1154 break;
1157 case DEL_LINE: {
1158 int i;
1159 for (i = 0; i < *textlen; ++i)
1160 *(*text + i) = 0;
1161 update_completions(cs, *text, lines, vlines, r->first_selected);
1162 r->offset = 0;
1163 break;
1166 case ADD_CHAR: {
1167 int str_len, i;
1169 str_len = strlen(input);
1172 * sometimes a strange key is pressed
1173 * i.e. ctrl alone), so input will be
1174 * empty. Don't need to update
1175 * completion in that case
1177 if (str_len == 0)
1178 break;
1180 for (i = 0; i < str_len; ++i) {
1181 *textlen = pushc(text, *textlen, input[i]);
1182 if (*textlen == -1) {
1183 fprintf(stderr, "Memory allocation error\n");
1184 status = ERR;
1185 break;
1189 if (status != ERR) {
1190 update_completions(cs, *text, lines, vlines, r->first_selected);
1191 free(input);
1194 r->offset = 0;
1195 break;
1198 case TOGGLE_FIRST_SELECTED:
1199 r->first_selected = !r->first_selected;
1200 if (r->first_selected && cs->selected < 0)
1201 cs->selected = 0;
1202 if (!r->first_selected && cs->selected == 0)
1203 cs->selected = -1;
1204 break;
1208 case ButtonPress: {
1209 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1210 /* if (ev->button == Button1) { /\* click *\/ */
1211 /* int x = ev->x - r.border_w; */
1212 /* int y = ev->y - r.border_n; */
1213 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1214 /* } */
1216 if (ev->button == Button4) /* scroll up */
1217 r->offset = MAX((ssize_t)r->offset - 1, 0);
1219 if (ev->button == Button5) /* scroll down */
1220 r->offset = MIN(r->offset + 1, cs->length - 1);
1222 break;
1226 draw(r, *text, cs);
1229 return status;
1232 int
1233 load_font(struct rendering *r, const char *fontname)
1235 #ifdef USE_XFT
1236 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1237 return 0;
1238 #else
1239 char **missing_charset_list;
1240 int missing_charset_count;
1242 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1243 if (r->font != NULL)
1244 return 0;
1246 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1248 if (!strcmp(fontname, default_fontname))
1249 return -1;
1251 return load_font(r, default_fontname);
1252 #endif
1255 void
1256 xim_init(struct rendering *r, XrmDatabase *xdb)
1258 XIM xim;
1259 XIMStyle best_match_style;
1260 XIMStyles *xis;
1261 int i;
1263 /* Open the X input method */
1264 xim = XOpenIM(r->d, *xdb, resname, resclass);
1265 check_allocation(xim);
1267 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1268 fprintf(stderr, "Input Styles could not be retrieved\n");
1269 exit(EX_UNAVAILABLE);
1272 best_match_style = 0;
1273 for (i = 0; i < xis->count_styles; ++i) {
1274 XIMStyle ts = xis->supported_styles[i];
1275 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1276 best_match_style = ts;
1277 break;
1280 XFree(xis);
1282 if (!best_match_style)
1283 fprintf(stderr, "No matching input style could be determined\n");
1285 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1286 check_allocation(r->xic);
1289 void
1290 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1292 XSetWindowAttributes attr;
1294 /* Create the window */
1295 attr.colormap = cmap;
1296 attr.override_redirect = 1;
1297 attr.border_pixel = 0;
1298 attr.background_pixel = 0x80808080;
1299 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1301 r->w = XCreateWindow(r->d,
1302 parent_window,
1303 x + ox, y + oy,
1304 r->width, r->height,
1306 vinfo.depth,
1307 InputOutput,
1308 vinfo.visual,
1309 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1310 &attr);
1313 void
1314 ps1extents(struct rendering *r)
1316 char *dup;
1317 dup = strdupn(r->ps1);
1318 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1319 free(dup);
1322 void
1323 usage(char *prgname)
1325 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1326 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1327 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1328 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1331 int
1332 main(int argc, char **argv)
1334 struct completions *cs;
1335 struct rendering r;
1336 XVisualInfo vinfo;
1337 Colormap cmap;
1338 size_t nlines, i;
1339 Window parent_window;
1340 XrmDatabase xdb;
1341 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1342 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1343 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1344 enum state status;
1345 int ch;
1346 int offset_x, offset_y, x, y;
1347 int textlen, d_width, d_height;
1348 short embed;
1349 char *sep, *parent_window_id;
1350 char **lines, *buf, **vlines;
1351 char *fontname, *text, *xrm;
1353 #ifdef __OpenBSD__
1354 /* stdio & rpath: to read/write stdio/stdout/stderr */
1355 /* unix: to connect to XOrg */
1356 pledge("stdio rpath unix", "");
1357 #endif
1359 sep = NULL;
1360 parent_window_id = NULL;
1362 r.first_selected = 0;
1363 r.free_text = 1;
1364 r.multiple_select = 0;
1365 r.offset = 0;
1367 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1368 switch (ch) {
1369 case 'h': /* help */
1370 usage(*argv);
1371 return 0;
1372 case 'v': /* version */
1373 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1374 return 0;
1375 case 'e': /* embed */
1376 parent_window_id = strdup(optarg);
1377 check_allocation(parent_window_id);
1378 break;
1379 case 'd': {
1380 sep = strdup(optarg);
1381 check_allocation(sep);
1383 case 'A': {
1384 r.free_text = 0;
1385 break;
1387 case 'm': {
1388 r.multiple_select = 1;
1389 break;
1391 default:
1392 break;
1396 /* Read the completions */
1397 lines = NULL;
1398 buf = NULL;
1399 nlines = readlines(&lines, &buf);
1401 vlines = NULL;
1402 if (sep != NULL) {
1403 int l;
1404 l = strlen(sep);
1405 vlines = calloc(nlines, sizeof(char*));
1406 check_allocation(vlines);
1408 for (i = 0; i < nlines; i++) {
1409 char *t;
1410 t = strstr(lines[i], sep);
1411 if (t == NULL)
1412 vlines[i] = lines[i];
1413 else
1414 vlines[i] = t + l;
1418 setlocale(LC_ALL, getenv("LANG"));
1420 status = LOOPING;
1422 /* where the monitor start (used only with xinerama) */
1423 offset_x = offset_y = 0;
1425 /* default width and height */
1426 r.width = 400;
1427 r.height = 20;
1429 /* default position on the screen */
1430 x = y = 0;
1432 /* default padding */
1433 r.padding = 10;
1435 /* default borders */
1436 r.border_n = r.border_e = r.border_s = r.border_w = 0;
1438 /* the prompt. We duplicate the string so later is easy to
1439 * free (in the case it's been overwritten by the user) */
1440 r.ps1 = strdup("$ ");
1441 check_allocation(r.ps1);
1443 /* same for the font name */
1444 fontname = strdup(default_fontname);
1445 check_allocation(fontname);
1447 textlen = 10;
1448 text = malloc(textlen * sizeof(char));
1449 check_allocation(text);
1451 /* struct completions *cs = filter(text, lines); */
1452 cs = compls_new(nlines);
1453 check_allocation(cs);
1455 /* start talking to xorg */
1456 r.d = XOpenDisplay(NULL);
1457 if (r.d == NULL) {
1458 fprintf(stderr, "Could not open display!\n");
1459 return EX_UNAVAILABLE;
1462 embed = 1;
1463 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1464 parent_window = DefaultRootWindow(r.d);
1465 embed = 0;
1468 /* get display size */
1469 get_wh(r.d, &parent_window, &d_width, &d_height);
1471 #ifdef USE_XINERAMA
1472 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1473 XineramaScreenInfo *info;
1474 Window rr;
1475 Window root;
1476 int number_of_screens, monitors, i;
1477 int root_x, root_y, win_x, win_y;
1478 unsigned int mask;
1479 short res;
1481 number_of_screens = XScreenCount(r.d);
1482 for (i = 0; i < number_of_screens; ++i) {
1483 root = XRootWindow(r.d, i);
1484 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1485 if (res)
1486 break;
1489 if (!res) {
1490 fprintf(stderr, "No mouse found.\n");
1491 root_x = 0;
1492 root_y = 0;
1495 /* Now find in which monitor the mice is */
1496 info = XineramaQueryScreens(r.d, &monitors);
1497 if (info) {
1498 for (i = 0; i < monitors; ++i) {
1499 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1500 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1501 offset_x = info[i].x_org;
1502 offset_y = info[i].y_org;
1503 d_width = info[i].width;
1504 d_height = info[i].height;
1505 break;
1509 XFree(info);
1511 #endif
1513 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1514 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1516 p_fg = compl_fg = parse_color("#fff", NULL);
1517 compl_highlighted_fg = parse_color("#000", NULL);
1519 p_bg = compl_bg = parse_color("#000", NULL);
1520 compl_highlighted_bg = parse_color("#fff", NULL);
1522 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1524 r.horizontal_layout = 1;
1526 /* Read the resources */
1527 XrmInitialize();
1528 xrm = XResourceManagerString(r.d);
1529 xdb = NULL;
1530 if (xrm != NULL) {
1531 XrmValue value;
1532 char *datatype[20];
1534 xdb = XrmGetStringDatabase(xrm);
1536 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1537 free(fontname);
1538 fontname = strdup(value.addr);
1539 check_allocation(fontname);
1540 } else {
1541 fprintf(stderr, "no font defined, using %s\n", fontname);
1544 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1545 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1546 else
1547 fprintf(stderr, "no layout defined, using horizontal\n");
1549 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1550 free(r.ps1);
1551 r.ps1 = normalize_str(value.addr);
1552 } else {
1553 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1556 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1557 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1558 else
1559 fprintf(stderr, "no width defined, using %d\n", r.width);
1561 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1562 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1563 else
1564 fprintf(stderr, "no height defined, using %d\n", r.height);
1566 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1567 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1568 else
1569 fprintf(stderr, "no x defined, using %d\n", x);
1571 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1572 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1573 else
1574 fprintf(stderr, "no y defined, using %d\n", y);
1576 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1577 r.padding = parse_integer(value.addr, r.padding);
1578 else
1579 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1581 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1582 char **borders;
1584 borders = parse_csslike(value.addr);
1585 if (borders != NULL) {
1586 r.border_n = parse_integer(borders[0], 0);
1587 r.border_e = parse_integer(borders[1], 0);
1588 r.border_s = parse_integer(borders[2], 0);
1589 r.border_w = parse_integer(borders[3], 0);
1590 } else
1591 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1592 } else
1593 fprintf(stderr, "no border defined, using 0.\n");
1595 /* Prompt */
1596 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1597 p_fg = parse_color(value.addr, "#fff");
1599 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1600 p_bg = parse_color(value.addr, "#000");
1602 /* Completions */
1603 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1604 compl_fg = parse_color(value.addr, "#fff");
1606 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1607 compl_bg = parse_color(value.addr, "#000");
1608 else
1609 compl_bg = parse_color("#000", NULL);
1611 /* Completion Highlighted */
1612 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1613 compl_highlighted_fg = parse_color(value.addr, "#000");
1615 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1616 compl_highlighted_bg = parse_color(value.addr, "#fff");
1617 else
1618 compl_highlighted_bg = parse_color("#fff", NULL);
1620 /* Border */
1621 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1622 char **colors;
1623 colors = parse_csslike(value.addr);
1624 if (colors != NULL) {
1625 border_n_bg = parse_color(colors[0], "#000");
1626 border_e_bg = parse_color(colors[1], "#000");
1627 border_s_bg = parse_color(colors[2], "#000");
1628 border_w_bg = parse_color(colors[3], "#000");
1629 } else
1630 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1634 /* Second round of args parsing */
1635 optind = 0; /* reset the option index */
1636 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1637 switch (ch) {
1638 case 'a':
1639 r.first_selected = 1;
1640 break;
1641 case 'A':
1642 /* free_text -- already catched */
1643 case 'd':
1644 /* separator -- this case was already catched */
1645 case 'e':
1646 /* embedding mymenu this case was already catched. */
1647 case 'm':
1648 /* multiple selection this case was already catched. */
1649 break;
1650 case 'p': {
1651 char *newprompt;
1652 newprompt = strdup(optarg);
1653 if (newprompt != NULL) {
1654 free(r.ps1);
1655 r.ps1 = newprompt;
1657 break;
1659 case 'x':
1660 x = parse_int_with_pos(optarg, x, d_width, r.width);
1661 break;
1662 case 'y':
1663 y = parse_int_with_pos(optarg, y, d_height, r.height);
1664 break;
1665 case 'P':
1666 r.padding = parse_integer(optarg, r.padding);
1667 break;
1668 case 'l':
1669 r.horizontal_layout = !strcmp(optarg, "horizontal");
1670 break;
1671 case 'f': {
1672 char *newfont;
1673 if ((newfont = strdup(optarg)) != NULL) {
1674 free(fontname);
1675 fontname = newfont;
1677 break;
1679 case 'W':
1680 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1681 break;
1682 case 'H':
1683 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1684 break;
1685 case 'b': {
1686 char **borders;
1687 if ((borders = parse_csslike(optarg)) != NULL) {
1688 r.border_n = parse_integer(borders[0], 0);
1689 r.border_e = parse_integer(borders[1], 0);
1690 r.border_s = parse_integer(borders[2], 0);
1691 r.border_w = parse_integer(borders[3], 0);
1692 } else
1693 fprintf(stderr, "Error parsing b option\n");
1694 break;
1696 case 'B': {
1697 char **colors;
1698 if ((colors = parse_csslike(optarg)) != NULL) {
1699 border_n_bg = parse_color(colors[0], "#000");
1700 border_e_bg = parse_color(colors[1], "#000");
1701 border_s_bg = parse_color(colors[2], "#000");
1702 border_w_bg = parse_color(colors[3], "#000");
1703 } else
1704 fprintf(stderr, "error while parsing B option\n");
1705 break;
1707 case 't':
1708 p_fg = parse_color(optarg, NULL);
1709 break;
1710 case 'T':
1711 p_bg = parse_color(optarg, NULL);
1712 break;
1713 case 'c':
1714 compl_fg = parse_color(optarg, NULL);
1715 break;
1716 case 'C':
1717 compl_bg = parse_color(optarg, NULL);
1718 break;
1719 case 's':
1720 compl_highlighted_fg = parse_color(optarg, NULL);
1721 break;
1722 case 'S':
1723 compl_highlighted_bg = parse_color(optarg, NULL);
1724 break;
1725 default:
1726 fprintf(stderr, "Unrecognized option %c\n", ch);
1727 status = ERR;
1728 break;
1732 /* since only now we know if the first should be selected,
1733 * update the completion here */
1734 update_completions(cs, text, lines, vlines, r.first_selected);
1736 /* update the prompt lenght, only now we surely know the length of it */
1737 r.ps1len = strlen(r.ps1);
1739 /* Create the window */
1740 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1741 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1742 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1743 XMapRaised(r.d, r.w);
1745 /* If embed, listen for other events as well */
1746 if (embed) {
1747 Window *children, parent, root;
1748 unsigned int children_no;
1750 XSelectInput(r.d, parent_window, FocusChangeMask);
1751 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1752 for (i = 0; i < children_no && children[i] != r.w; ++i)
1753 XSelectInput(r.d, children[i], FocusChangeMask);
1754 XFree(children);
1756 grabfocus(r.d, r.w);
1759 take_keyboard(r.d, r.w);
1761 r.x_zero = r.border_w;
1762 r.y_zero = r.border_n;
1765 XGCValues values;
1767 r.prompt = XCreateGC(r.d, r.w, 0, &values),
1768 r.prompt_bg = XCreateGC(r.d, r.w, 0, &values);
1769 r.completion = XCreateGC(r.d, r.w, 0, &values);
1770 r.completion_bg = XCreateGC(r.d, r.w, 0, &values);
1771 r.completion_highlighted = XCreateGC(r.d, r.w, 0, &values);
1772 r.completion_highlighted_bg = XCreateGC(r.d, r.w, 0, &values);
1773 r.border_n_bg = XCreateGC(r.d, r.w, 0, &values);
1774 r.border_e_bg = XCreateGC(r.d, r.w, 0, &values);
1775 r.border_s_bg = XCreateGC(r.d, r.w, 0, &values);
1776 r.border_w_bg = XCreateGC(r.d, r.w, 0, &values);
1779 if (load_font(&r, fontname) == -1)
1780 status = ERR;
1782 #ifdef USE_XFT
1783 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1786 rgba_t c;
1787 XRenderColor xrcolor;
1789 /* Prompt */
1790 c = *(rgba_t*)&p_fg;
1791 xrcolor.red = EXPANDBITS(c.rgba.r);
1792 xrcolor.green = EXPANDBITS(c.rgba.g);
1793 xrcolor.blue = EXPANDBITS(c.rgba.b);
1794 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1795 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_prompt);
1797 /* Completion */
1798 c = *(rgba_t*)&compl_fg;
1799 xrcolor.red = EXPANDBITS(c.rgba.r);
1800 xrcolor.green = EXPANDBITS(c.rgba.g);
1801 xrcolor.blue = EXPANDBITS(c.rgba.b);
1802 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1803 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion);
1805 /* Completion highlighted */
1806 c = *(rgba_t*)&compl_highlighted_fg;
1807 xrcolor.red = EXPANDBITS(c.rgba.r);
1808 xrcolor.green = EXPANDBITS(c.rgba.g);
1809 xrcolor.blue = EXPANDBITS(c.rgba.b);
1810 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1811 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion_highlighted);
1813 #endif
1815 /* Load the colors in our GCs */
1816 XSetForeground(r.d, r.prompt, p_fg);
1817 XSetForeground(r.d, r.prompt_bg, p_bg);
1818 XSetForeground(r.d, r.completion, compl_fg);
1819 XSetForeground(r.d, r.completion_bg, compl_bg);
1820 XSetForeground(r.d, r.completion_highlighted, compl_highlighted_fg);
1821 XSetForeground(r.d, r.completion_highlighted_bg, compl_highlighted_bg);
1822 XSetForeground(r.d, r.border_n_bg, border_n_bg);
1823 XSetForeground(r.d, r.border_e_bg, border_e_bg);
1824 XSetForeground(r.d, r.border_s_bg, border_s_bg);
1825 XSetForeground(r.d, r.border_w_bg, border_w_bg);
1827 /* compute prompt dimensions */
1828 ps1extents(&r);
1830 xim_init(&r, &xdb);
1832 /* Draw the window for the first time */
1833 draw(&r, text, cs);
1835 #ifdef __OpenBSD__
1836 /* Now we need only the ability to write */
1837 pledge("stdio", "");
1838 #endif
1840 /* Main loop */
1841 while (status == LOOPING || status == OK_LOOP) {
1842 status = loop(&r, &text, &textlen, cs, lines, vlines);
1844 if (status != ERR)
1845 printf("%s\n", text);
1847 if (!r.multiple_select && status == OK_LOOP)
1848 status = OK;
1851 XUngrabKeyboard(r.d, CurrentTime);
1853 #ifdef USE_XFT
1854 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1855 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1856 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1857 #endif
1859 free(r.ps1);
1860 free(fontname);
1861 free(text);
1863 free(buf);
1864 free(lines);
1865 free(vlines);
1866 compls_delete(cs);
1868 XDestroyWindow(r.d, r.w);
1869 XCloseDisplay(r.d);
1871 return status != OK;