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 /* Return a newly allocated (and empty) completion list */
176 struct completions *
177 compls_new(size_t length)
179 struct completions *cs = malloc(sizeof(struct completions));
181 if (cs == NULL)
182 return cs;
184 cs->completions = calloc(length, sizeof(struct completion));
185 if (cs->completions == NULL) {
186 free(cs);
187 return NULL;
190 cs->selected = -1;
191 cs->length = length;
192 return cs;
195 /* Delete the wrapper and the whole list */
196 void
197 compls_delete(struct completions *cs)
199 if (cs == NULL)
200 return;
202 free(cs->completions);
203 free(cs);
206 /*
207 * Create a completion list from a text and the list of possible
208 * completions (null terminated). Expects a non-null `cs'. `lines' and
209 * `vlines' should have the same length OR `vlines' is NULL.
210 */
211 void
212 filter(struct completions *cs, char *text, char **lines, char **vlines)
214 size_t index = 0;
215 size_t matching = 0;
216 char *l;
218 if (vlines == NULL)
219 vlines = lines;
221 while (1) {
222 if (lines[index] == NULL)
223 break;
225 l = vlines[index] != NULL ? vlines[index] : lines[index];
227 if (strcasestr(l, text) != NULL) {
228 struct completion *c = &cs->completions[matching];
229 c->completion = l;
230 c->rcompletion = lines[index];
231 matching++;
234 index++;
236 cs->length = matching;
237 cs->selected = -1;
240 /* Update the given completion */
241 void
242 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
244 filter(cs, text, lines, vlines);
245 if (first_selected && cs->length > 0)
246 cs->selected = 0;
249 /*
250 * Select the next or previous selection and update some state. `text'
251 * will be updated with the text of the completion and `textlen' with
252 * the new length. If the memory cannot be allocated `status' will be
253 * set to `ERR'.
254 */
255 void
256 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
258 struct completion *n;
259 int index;
261 if (cs == NULL || cs->length == 0)
262 return;
264 /*
265 * If the first is always selected and the first entry is
266 * different from the text, expand the text and return
267 */
268 if (first_selected
269 && cs->selected == 0
270 && strcmp(cs->completions->completion, *text) != 0
271 && !p) {
272 free(*text);
273 *text = strdup(cs->completions->completion);
274 if (text == NULL) {
275 *status = ERR;
276 return;
278 *textlen = strlen(*text);
279 return;
282 index = cs->selected;
284 if (index == -1 && p)
285 index = 0;
286 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
288 n = &cs->completions[cs->selected];
290 free(*text);
291 *text = strdup(n->completion);
292 if (text == NULL) {
293 fprintf(stderr, "Memory allocation error!\n");
294 *status = ERR;
295 return;
297 *textlen = strlen(*text);
300 /* Push the character c at the end of the string pointed by p */
301 int
302 pushc(char **p, int maxlen, char c)
304 int len;
306 len = strnlen(*p, maxlen);
307 if (!(len < maxlen -2)) {
308 char *newptr;
310 maxlen += maxlen >> 1;
311 newptr = realloc(*p, maxlen);
312 if (newptr == NULL) /* bad */
313 return -1;
314 *p = newptr;
317 (*p)[len] = c;
318 (*p)[len+1] = '\0';
319 return maxlen;
322 /*
323 * Remove the last rune from the *UTF-8* string! This is different
324 * from just setting the last byte to 0 (in some cases ofc). Return a
325 * pointer (e) to the last nonzero char. If e < p then p is empty!
326 */
327 char *
328 popc(char *p)
330 int len = strlen(p);
331 char *e;
333 if (len == 0)
334 return p;
336 e = p + len - 1;
338 do {
339 char c = *e;
341 *e = '\0';
342 e -= 1;
344 /*
345 * If c is a starting byte (11......) or is under
346 * U+007F we're done.
347 */
348 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
349 break;
350 } while (e >= p);
352 return e;
355 /* Remove the last word plus trailing white spaces from the given string */
356 void
357 popw(char *w)
359 int len;
360 short in_word = 1;
362 if ((len = strlen(w)) == 0)
363 return;
365 while (1) {
366 char *e = popc(w);
368 if (e < w)
369 return;
371 if (in_word && isspace(*e))
372 in_word = 0;
374 if (!in_word && !isspace(*e))
375 return;
379 /*
380 * If the string is surrounded by quates (`"') remove them and replace
381 * every `\"' in the string with a single double-quote.
382 */
383 char *
384 normalize_str(const char *str)
386 int len, p;
387 char *s;
389 if ((len = strlen(str)) == 0)
390 return NULL;
392 s = calloc(len, sizeof(char));
393 check_allocation(s);
394 p = 0;
396 while (*str) {
397 char c = *str;
399 if (*str == '\\') {
400 if (*(str + 1)) {
401 s[p] = *(str + 1);
402 p++;
403 str += 2; /* skip this and the next char */
404 continue;
405 } else
406 break;
408 if (c == '"') {
409 str++; /* skip only this char */
410 continue;
412 s[p] = c;
413 p++;
414 str++;
417 return s;
420 size_t
421 read_stdin(char **buf)
423 size_t offset = 0;
424 size_t len = STDIN_CHUNKS;
426 *buf = malloc(len * sizeof(char));
427 if (*buf == NULL)
428 goto err;
430 while (1) {
431 ssize_t r;
432 size_t i;
434 r = read(0, *buf + offset, STDIN_CHUNKS);
436 if (r < 1)
437 return len;
439 offset += r;
441 len += STDIN_CHUNKS;
442 *buf = realloc(*buf, len);
443 if (*buf == NULL)
444 goto err;
446 for (i = offset; i < len; ++i)
447 (*buf)[i] = '\0';
450 err:
451 fprintf(stderr, "Error in allocating memory for stdin.\n");
452 exit(EX_UNAVAILABLE);
455 size_t
456 readlines(char ***lns, char **buf)
458 size_t i, len, ll, lines;
459 short in_line = 0;
461 lines = 0;
463 *buf = NULL;
464 len = read_stdin(buf);
466 ll = LINES_CHUNK;
467 *lns = malloc(ll * sizeof(char*));
469 if (*lns == NULL)
470 goto err;
472 for (i = 0; i < len; i++) {
473 char c = (*buf)[i];
475 if (c == '\0')
476 break;
478 if (c == '\n')
479 (*buf)[i] = '\0';
481 if (in_line && c == '\n')
482 in_line = 0;
484 if (!in_line && c != '\n') {
485 in_line = 1;
486 (*lns)[lines] = (*buf) + i;
487 lines++;
489 if (lines == ll) { /* resize */
490 ll += LINES_CHUNK;
491 *lns = realloc(*lns, ll * sizeof(char*));
492 if (*lns == NULL)
493 goto err;
498 (*lns)[lines] = NULL;
500 return lines;
502 err:
503 fprintf(stderr, "Error in memory allocation.\n");
504 exit(EX_UNAVAILABLE);
507 /*
508 * Compute the dimensions of the string str once rendered.
509 * It'll return the width and set ret_width and ret_height if not NULL
510 */
511 int
512 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
514 int height;
515 int width;
516 #ifdef USE_XFT
517 XGlyphInfo gi;
518 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
519 height = r->font->ascent - r->font->descent;
520 width = gi.width - gi.x;
521 #else
522 XRectangle rect;
523 XmbTextExtents(r->font, str, len, NULL, &rect);
524 height = rect.height;
525 width = rect.width;
526 #endif
527 if (ret_width != NULL) *ret_width = width;
528 if (ret_height != NULL) *ret_height = height;
529 return width;
532 void
533 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
535 #ifdef USE_XFT
536 XftColor xftcolor;
537 if (tt == PROMPT) xftcolor = r->xft_prompt;
538 if (tt == COMPL) xftcolor = r->xft_completion;
539 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
541 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
542 #else
543 GC gc;
544 if (tt == PROMPT) gc = r->prompt;
545 if (tt == COMPL) gc = r->completion;
546 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
547 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
548 #endif
551 /* Duplicate the string and substitute every space with a 'n` */
552 char *
553 strdupn(char *str)
555 int len, i;
556 char *dup;
558 len = strlen(str);
560 if (str == NULL || len == 0)
561 return NULL;
563 if ((dup = strdup(str)) == NULL)
564 return NULL;
566 for (i = 0; i < len; ++i)
567 if (dup[i] == ' ')
568 dup[i] = 'n';
570 return dup;
573 /* |------------------|----------------------------------------------| */
574 /* | 20 char text | completion | completion | completion | compl | */
575 /* |------------------|----------------------------------------------| */
576 void
577 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
579 size_t i;
580 int prompt_width, start_at;
581 int texty, textlen;
583 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
585 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
586 start_at *= prompt_width;
587 start_at += r->padding;
589 texty = (inner_height(r) + r->ps1h + r->y_zero) / 2;
591 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
593 textlen = strlen(text);
594 if (textlen > prompt_width)
595 text = text + textlen - prompt_width;
597 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
598 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + r->ps1w, texty, r, PROMPT);
600 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
602 for (i = r->offset; i < cs->length; ++i) {
603 struct completion *c;
604 enum text_type tt;
605 GC h;
606 int len, text_width;
608 c = &cs->completions[i];
609 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
610 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
611 len = strlen(c->completion);
612 text_width = text_extents(c->completion, len, r, NULL, NULL);
614 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
615 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
617 start_at += text_width + r->padding * 2;
619 if (start_at > inner_width(r))
620 break; /* don't draw completion out of the window */
624 /* |-----------------------------------------------------------------| */
625 /* | prompt | */
626 /* |-----------------------------------------------------------------| */
627 /* | completion | */
628 /* |-----------------------------------------------------------------| */
629 /* | completion | */
630 /* |-----------------------------------------------------------------| */
631 void
632 draw_vertically(struct rendering *r, char *text, struct completions *cs)
634 size_t i;
635 int height, start_at;
637 text_extents("fjpgl", 5, r, NULL, &height);
638 start_at = r->padding * 2 + height;
640 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
641 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
643 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
644 draw_string(text, strlen(text), r->x_zero + r->padding + r->ps1w, r->y_zero + height + r->padding, r, PROMPT);
646 start_at += r->y_zero;
648 for (i = r->offset; i < cs->length; ++i) {
649 struct completion *c;
650 enum text_type tt;
651 GC h;
652 int len;
654 c = &cs->completions[i];
655 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
656 h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
657 len = strlen(c->completion);
659 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
660 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
662 start_at += height + r->padding * 2;
664 if (start_at > inner_height(r))
665 break; /* don't draw completion out of the window */
669 void
670 draw(struct rendering *r, char *text, struct completions *cs)
672 if (r->horizontal_layout)
673 draw_horizontally(r, text, cs);
674 else
675 draw_vertically(r, text, cs);
677 /* Draw the borders */
678 if (r->border_w != 0)
679 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
681 if (r->border_e != 0)
682 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
684 if (r->border_n != 0)
685 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
687 if (r->border_s != 0)
688 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
690 /* render! */
691 XFlush(r->d);
694 /* Set some WM stuff */
695 void
696 set_win_atoms_hints(Display *d, Window w, int width, int height)
698 Atom type;
699 XClassHint *class_hint;
700 XSizeHints *size_hint;
702 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
703 XChangeProperty(d,
704 w,
705 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
706 XInternAtom(d, "ATOM", 0),
707 32,
708 PropModeReplace,
709 (unsigned char *)&type,
711 );
713 /* some window managers honor this properties */
714 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
715 XChangeProperty(d,
716 w,
717 XInternAtom(d, "_NET_WM_STATE", 0),
718 XInternAtom(d, "ATOM", 0),
719 32,
720 PropModeReplace,
721 (unsigned char *)&type,
723 );
725 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
726 XChangeProperty(d,
727 w,
728 XInternAtom(d, "_NET_WM_STATE", 0),
729 XInternAtom(d, "ATOM", 0),
730 32,
731 PropModeAppend,
732 (unsigned char *)&type,
734 );
736 /* Setting window hints */
737 class_hint = XAllocClassHint();
738 if (class_hint == NULL) {
739 fprintf(stderr, "Could not allocate memory for class hint\n");
740 exit(EX_UNAVAILABLE);
743 class_hint->res_name = resname;
744 class_hint->res_class = resclass;
745 XSetClassHint(d, w, class_hint);
746 XFree(class_hint);
748 size_hint = XAllocSizeHints();
749 if (size_hint == NULL) {
750 fprintf(stderr, "Could not allocate memory for size hint\n");
751 exit(EX_UNAVAILABLE);
754 size_hint->flags = PMinSize | PBaseSize;
755 size_hint->min_width = width;
756 size_hint->base_width = width;
757 size_hint->min_height = height;
758 size_hint->base_height = height;
760 XFlush(d);
763 /* Get the width and height of the window `w' */
764 void
765 get_wh(Display *d, Window *w, int *width, int *height)
767 XWindowAttributes win_attr;
769 XGetWindowAttributes(d, *w, &win_attr);
770 *height = win_attr.height;
771 *width = win_attr.width;
774 int
775 grabfocus(Display *d, Window w)
777 int i;
778 for (i = 0; i < 100; ++i) {
779 Window focuswin;
780 int revert_to_win;
782 XGetInputFocus(d, &focuswin, &revert_to_win);
784 if (focuswin == w)
785 return 1;
787 XSetInputFocus(d, w, RevertToParent, CurrentTime);
788 usleep(1000);
790 return 0;
793 /*
794 * I know this may seem a little hackish BUT is the only way I managed
795 * to actually grab that goddam keyboard. Only one call to
796 * XGrabKeyboard does not always end up with the keyboard grabbed!
797 */
798 int
799 take_keyboard(Display *d, Window w)
801 int i;
802 for (i = 0; i < 100; i++) {
803 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
804 return 1;
805 usleep(1000);
807 fprintf(stderr, "Cannot grab keyboard\n");
808 return 0;
811 unsigned long
812 parse_color(const char *str, const char *def)
814 size_t len;
815 rgba_t tmp;
816 char *ep;
818 if (str == NULL)
819 goto invc;
821 len = strlen(str);
823 /* +1 for the # ath the start */
824 if (*str != '#' || len > 9 || len < 4)
825 goto invc;
826 ++str; /* skip the # */
828 errno = 0;
829 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
831 if (errno)
832 goto invc;
834 switch (len-1) {
835 case 3:
836 /* expand #rgb -> #rrggbb */
837 tmp.v = (tmp.v & 0xf00) * 0x1100
838 | (tmp.v & 0x0f0) * 0x0110
839 | (tmp.v & 0x00f) * 0x0011;
840 case 6:
841 /* assume 0xff opacity */
842 tmp.rgba.a = 0xff;
843 break;
844 } /* colors in #aarrggbb need no adjustments */
846 /* premultiply the alpha */
847 if (tmp.rgba.a) {
848 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
849 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
850 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
851 return tmp.v;
854 return 0U;
856 invc:
857 fprintf(stderr, "Invalid color: \"%s\".\n", str);
858 if (def != NULL)
859 return parse_color(def, NULL);
860 else
861 return 0U;
864 /*
865 * Given a string try to parse it as a number or return `default_value'.
866 */
867 int
868 parse_integer(const char *str, int default_value)
870 long lval;
871 char *ep;
873 errno = 0;
874 lval = strtol(str, &ep, 10);
876 if (str[0] == '\0' || *ep != '\0') { /* NaN */
877 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
878 return default_value;
881 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
882 (lval > INT_MAX || lval < INT_MIN)) {
883 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
884 return default_value;
887 return lval;
890 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
891 int
892 parse_int_with_percentage(const char *str, int default_value, int max)
894 int len = strlen(str);
896 if (len > 0 && str[len-1] == '%') {
897 int val;
898 char *cpy;
900 cpy = strdup(str);
901 check_allocation(cpy);
902 cpy[len-1] = '\0';
903 val = parse_integer(cpy, default_value);
904 free(cpy);
905 return val * max / 100;
908 return parse_integer(str, default_value);
911 /*
912 * Like parse_int_with_percentage but understands some special values:
913 * - middle that is (max-self)/2
914 * - start that is 0
915 * - end that is (max-self)
916 */
917 int
918 parse_int_with_pos(const char *str, int default_value, int max, int self)
920 if (!strcmp(str, "start"))
921 return 0;
922 if (!strcmp(str, "middle"))
923 return (max - self)/2;
924 if (!strcmp(str, "end"))
925 return max-self;
926 return parse_int_with_percentage(str, default_value, max);
929 /* Parse a string like a CSS value. */
930 /* TODO: harden a bit this function */
931 char **
932 parse_csslike(const char *str)
934 int i, j;
935 char *s, *token, **ret;
936 short any_null;
938 s = strdup(str);
939 if (s == NULL)
940 return NULL;
942 ret = malloc(4 * sizeof(char*));
943 if (ret == NULL) {
944 free(s);
945 return NULL;
948 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
949 ret[i] = strdup(token);
951 if (i == 1)
952 for (j = 1; j < 4; j++)
953 ret[j] = strdup(ret[0]);
955 if (i == 2) {
956 ret[2] = strdup(ret[0]);
957 ret[3] = strdup(ret[1]);
960 if (i == 3)
961 ret[3] = strdup(ret[1]);
963 /* before we didn't check for the return type of strdup, here we will */
965 any_null = 0;
966 for (i = 0; i < 4; ++i)
967 any_null = ret[i] == NULL || any_null;
969 if (any_null)
970 for (i = 0; i < 4; ++i)
971 if (ret[i] != NULL)
972 free(ret[i]);
974 if (i == 0 || any_null) {
975 free(s);
976 free(ret);
977 return NULL;
980 return ret;
983 /*
984 * Given an event, try to understand what the users wants. If the
985 * return value is ADD_CHAR then `input' is a pointer to a string that
986 * will need to be free'ed later.
987 */
988 enum
989 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
991 char str[SYM_BUF_SIZE] = {0};
992 Status s;
994 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
995 return DEL_CHAR;
997 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
998 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1000 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1001 return CONFIRM;
1003 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1004 return EXIT;
1006 /* Try to read what key was pressed */
1007 s = 0;
1008 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1009 if (s == XBufferOverflow) {
1010 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1011 return EXIT;
1014 if (ev->state & ControlMask) {
1015 if (!strcmp(str, "")) /* C-u */
1016 return DEL_LINE;
1017 if (!strcmp(str, "")) /* C-w */
1018 return DEL_WORD;
1019 if (!strcmp(str, "")) /* C-h */
1020 return DEL_CHAR;
1021 if (!strcmp(str, "\r")) /* C-m */
1022 return CONFIRM_CONTINUE;
1023 if (!strcmp(str, "")) /* C-p */
1024 return PREV_COMPL;
1025 if (!strcmp(str, "")) /* C-n */
1026 return NEXT_COMPL;
1027 if (!strcmp(str, "")) /* C-c */
1028 return EXIT;
1029 if (!strcmp(str, "\t")) /* C-i */
1030 return TOGGLE_FIRST_SELECTED;
1033 *input = strdup(str);
1034 if (*input == NULL) {
1035 fprintf(stderr, "Error while allocating memory for key.\n");
1036 return EXIT;
1039 return ADD_CHAR;
1042 void
1043 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1045 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1046 /* if there is something selected expand it and return */
1047 int index = cs->selected == -1 ? 0 : cs->selected;
1048 struct completion *c = cs->completions;
1049 char *t;
1051 while (1) {
1052 if (index == 0)
1053 break;
1054 c++;
1055 index--;
1058 t = c->rcompletion;
1059 free(*text);
1060 *text = strdup(t);
1062 if (*text == NULL) {
1063 fprintf(stderr, "Memory allocation error\n");
1064 *status = ERR;
1067 *textlen = strlen(*text);
1068 return;
1071 if (!r->free_text) /* cannot accept arbitrary text */
1072 *status = LOOPING;
1075 /* event loop */
1076 enum state
1077 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1079 enum state status = LOOPING;
1081 while (status == LOOPING) {
1082 XEvent e;
1083 XNextEvent(r->d, &e);
1085 if (XFilterEvent(&e, r->w))
1086 continue;
1088 switch (e.type) {
1089 case KeymapNotify:
1090 XRefreshKeyboardMapping(&e.xmapping);
1091 break;
1093 case FocusIn:
1094 /* Re-grab focus */
1095 if (e.xfocus.window != r->w)
1096 grabfocus(r->d, r->w);
1097 break;
1099 case VisibilityNotify:
1100 if (e.xvisibility.state != VisibilityUnobscured)
1101 XRaiseWindow(r->d, r->w);
1102 break;
1104 case MapNotify:
1105 get_wh(r->d, &r->w, &r->width, &r->height);
1106 draw(r, *text, cs);
1107 break;
1109 case KeyPress: {
1110 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1111 char *input;
1113 switch (parse_event(r->d, ev, r->xic, &input)) {
1114 case EXIT:
1115 status = ERR;
1116 break;
1118 case CONFIRM: {
1119 status = OK;
1120 confirm(&status, r, cs, text, textlen);
1121 break;
1124 case CONFIRM_CONTINUE: {
1125 status = OK_LOOP;
1126 confirm(&status, r, cs, text, textlen);
1127 break;
1130 case PREV_COMPL: {
1131 complete(cs, r->first_selected, 1, text, textlen, &status);
1132 r->offset = cs->selected;
1133 break;
1136 case NEXT_COMPL: {
1137 complete(cs, r->first_selected, 0, text, textlen, &status);
1138 r->offset = cs->selected;
1139 break;
1142 case DEL_CHAR:
1143 popc(*text);
1144 update_completions(cs, *text, lines, vlines, r->first_selected);
1145 r->offset = 0;
1146 break;
1148 case DEL_WORD: {
1149 popw(*text);
1150 update_completions(cs, *text, lines, vlines, r->first_selected);
1151 break;
1154 case DEL_LINE: {
1155 int i;
1156 for (i = 0; i < *textlen; ++i)
1157 *(*text + i) = 0;
1158 update_completions(cs, *text, lines, vlines, r->first_selected);
1159 r->offset = 0;
1160 break;
1163 case ADD_CHAR: {
1164 int str_len, i;
1166 str_len = strlen(input);
1169 * sometimes a strange key is pressed
1170 * i.e. ctrl alone), so input will be
1171 * empty. Don't need to update
1172 * completion in that case
1174 if (str_len == 0)
1175 break;
1177 for (i = 0; i < str_len; ++i) {
1178 *textlen = pushc(text, *textlen, input[i]);
1179 if (*textlen == -1) {
1180 fprintf(stderr, "Memory allocation error\n");
1181 status = ERR;
1182 break;
1186 if (status != ERR) {
1187 update_completions(cs, *text, lines, vlines, r->first_selected);
1188 free(input);
1191 r->offset = 0;
1192 break;
1195 case TOGGLE_FIRST_SELECTED:
1196 r->first_selected = !r->first_selected;
1197 if (r->first_selected && cs->selected < 0)
1198 cs->selected = 0;
1199 if (!r->first_selected && cs->selected == 0)
1200 cs->selected = -1;
1201 break;
1205 case ButtonPress: {
1206 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1207 /* if (ev->button == Button1) { /\* click *\/ */
1208 /* int x = ev->x - r.border_w; */
1209 /* int y = ev->y - r.border_n; */
1210 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1211 /* } */
1213 if (ev->button == Button4) /* scroll up */
1214 r->offset = MAX((ssize_t)r->offset - 1, 0);
1216 if (ev->button == Button5) /* scroll down */
1217 r->offset = MIN(r->offset + 1, cs->length - 1);
1219 break;
1223 draw(r, *text, cs);
1226 return status;
1229 int
1230 load_font(struct rendering *r, const char *fontname)
1232 #ifdef USE_XFT
1233 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1234 return 0;
1235 #else
1236 char **missing_charset_list;
1237 int missing_charset_count;
1239 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1240 if (r->font != NULL)
1241 return 0;
1243 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1245 if (!strcmp(fontname, default_fontname))
1246 return -1;
1248 return load_font(r, default_fontname);
1249 #endif
1252 void
1253 xim_init(struct rendering *r, XrmDatabase *xdb)
1255 XIM xim;
1256 XIMStyle best_match_style;
1257 XIMStyles *xis;
1258 int i;
1260 /* Open the X input method */
1261 xim = XOpenIM(r->d, *xdb, resname, resclass);
1262 check_allocation(xim);
1264 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1265 fprintf(stderr, "Input Styles could not be retrieved\n");
1266 exit(EX_UNAVAILABLE);
1269 best_match_style = 0;
1270 for (i = 0; i < xis->count_styles; ++i) {
1271 XIMStyle ts = xis->supported_styles[i];
1272 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1273 best_match_style = ts;
1274 break;
1277 XFree(xis);
1279 if (!best_match_style)
1280 fprintf(stderr, "No matching input style could be determined\n");
1282 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1283 check_allocation(r->xic);
1286 void
1287 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1289 XSetWindowAttributes attr;
1291 /* Create the window */
1292 attr.colormap = cmap;
1293 attr.override_redirect = 1;
1294 attr.border_pixel = 0;
1295 attr.background_pixel = 0x80808080;
1296 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1298 r->w = XCreateWindow(r->d,
1299 parent_window,
1300 x + ox, y + oy,
1301 r->width, r->height,
1303 vinfo.depth,
1304 InputOutput,
1305 vinfo.visual,
1306 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1307 &attr);
1310 void
1311 ps1extents(struct rendering *r)
1313 char *dup;
1314 dup = strdupn(r->ps1);
1315 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1316 free(dup);
1319 void
1320 usage(char *prgname)
1322 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1323 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1324 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1325 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1328 int
1329 main(int argc, char **argv)
1331 struct completions *cs;
1332 struct rendering r;
1333 XVisualInfo vinfo;
1334 Colormap cmap;
1335 size_t nlines, i;
1336 Window parent_window;
1337 XrmDatabase xdb;
1338 unsigned long p_fg, compl_fg, compl_highlighted_fg;
1339 unsigned long p_bg, compl_bg, compl_highlighted_bg;
1340 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1341 enum state status;
1342 int ch;
1343 int offset_x, offset_y, x, y;
1344 int textlen, d_width, d_height;
1345 short embed;
1346 char *sep, *parent_window_id;
1347 char **lines, *buf, **vlines;
1348 char *fontname, *text, *xrm;
1350 #ifdef __OpenBSD__
1351 /* stdio & rpath: to read/write stdio/stdout/stderr */
1352 /* unix: to connect to XOrg */
1353 pledge("stdio rpath unix", "");
1354 #endif
1356 sep = NULL;
1357 parent_window_id = NULL;
1359 r.first_selected = 0;
1360 r.free_text = 1;
1361 r.multiple_select = 0;
1362 r.offset = 0;
1364 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1365 switch (ch) {
1366 case 'h': /* help */
1367 usage(*argv);
1368 return 0;
1369 case 'v': /* version */
1370 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1371 return 0;
1372 case 'e': /* embed */
1373 parent_window_id = strdup(optarg);
1374 check_allocation(parent_window_id);
1375 break;
1376 case 'd': {
1377 sep = strdup(optarg);
1378 check_allocation(sep);
1380 case 'A': {
1381 r.free_text = 0;
1382 break;
1384 case 'm': {
1385 r.multiple_select = 1;
1386 break;
1388 default:
1389 break;
1393 /* Read the completions */
1394 lines = NULL;
1395 buf = NULL;
1396 nlines = readlines(&lines, &buf);
1398 vlines = NULL;
1399 if (sep != NULL) {
1400 int l;
1401 l = strlen(sep);
1402 vlines = calloc(nlines, sizeof(char*));
1403 check_allocation(vlines);
1405 for (i = 0; i < nlines; i++) {
1406 char *t;
1407 t = strstr(lines[i], sep);
1408 if (t == NULL)
1409 vlines[i] = lines[i];
1410 else
1411 vlines[i] = t + l;
1415 setlocale(LC_ALL, getenv("LANG"));
1417 status = LOOPING;
1419 /* where the monitor start (used only with xinerama) */
1420 offset_x = offset_y = 0;
1422 /* default width and height */
1423 r.width = 400;
1424 r.height = 20;
1426 /* default position on the screen */
1427 x = y = 0;
1429 /* default padding */
1430 r.padding = 10;
1432 /* default borders */
1433 r.border_n = r.border_e = r.border_s = r.border_w = 0;
1435 /* the prompt. We duplicate the string so later is easy to
1436 * free (in the case it's been overwritten by the user) */
1437 r.ps1 = strdup("$ ");
1438 check_allocation(r.ps1);
1440 /* same for the font name */
1441 fontname = strdup(default_fontname);
1442 check_allocation(fontname);
1444 textlen = 10;
1445 text = malloc(textlen * sizeof(char));
1446 check_allocation(text);
1448 /* struct completions *cs = filter(text, lines); */
1449 cs = compls_new(nlines);
1450 check_allocation(cs);
1452 /* start talking to xorg */
1453 r.d = XOpenDisplay(NULL);
1454 if (r.d == NULL) {
1455 fprintf(stderr, "Could not open display!\n");
1456 return EX_UNAVAILABLE;
1459 embed = 1;
1460 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1461 parent_window = DefaultRootWindow(r.d);
1462 embed = 0;
1465 /* get display size */
1466 get_wh(r.d, &parent_window, &d_width, &d_height);
1468 #ifdef USE_XINERAMA
1469 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1470 XineramaScreenInfo *info;
1471 Window rr;
1472 Window root;
1473 int number_of_screens, monitors, i;
1474 int root_x, root_y, win_x, win_y;
1475 unsigned int mask;
1476 short res;
1478 number_of_screens = XScreenCount(r.d);
1479 for (i = 0; i < number_of_screens; ++i) {
1480 root = XRootWindow(r.d, i);
1481 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1482 if (res)
1483 break;
1486 if (!res) {
1487 fprintf(stderr, "No mouse found.\n");
1488 root_x = 0;
1489 root_y = 0;
1492 /* Now find in which monitor the mice is */
1493 info = XineramaQueryScreens(r.d, &monitors);
1494 if (info) {
1495 for (i = 0; i < monitors; ++i) {
1496 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1497 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1498 offset_x = info[i].x_org;
1499 offset_y = info[i].y_org;
1500 d_width = info[i].width;
1501 d_height = info[i].height;
1502 break;
1506 XFree(info);
1508 #endif
1510 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1511 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1513 p_fg = compl_fg = parse_color("#fff", NULL);
1514 compl_highlighted_fg = parse_color("#000", NULL);
1516 p_bg = compl_bg = parse_color("#000", NULL);
1517 compl_highlighted_bg = parse_color("#fff", NULL);
1519 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", NULL);
1521 r.horizontal_layout = 1;
1523 /* Read the resources */
1524 XrmInitialize();
1525 xrm = XResourceManagerString(r.d);
1526 xdb = NULL;
1527 if (xrm != NULL) {
1528 XrmValue value;
1529 char *datatype[20];
1531 xdb = XrmGetStringDatabase(xrm);
1533 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1534 free(fontname);
1535 fontname = strdup(value.addr);
1536 check_allocation(fontname);
1537 } else {
1538 fprintf(stderr, "no font defined, using %s\n", fontname);
1541 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1542 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1543 else
1544 fprintf(stderr, "no layout defined, using horizontal\n");
1546 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1547 free(r.ps1);
1548 r.ps1 = normalize_str(value.addr);
1549 } else {
1550 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1553 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1554 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1555 else
1556 fprintf(stderr, "no width defined, using %d\n", r.width);
1558 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1559 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1560 else
1561 fprintf(stderr, "no height defined, using %d\n", r.height);
1563 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1564 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1565 else
1566 fprintf(stderr, "no x defined, using %d\n", x);
1568 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1569 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1570 else
1571 fprintf(stderr, "no y defined, using %d\n", y);
1573 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1574 r.padding = parse_integer(value.addr, r.padding);
1575 else
1576 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1578 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1579 char **borders;
1581 borders = parse_csslike(value.addr);
1582 if (borders != NULL) {
1583 r.border_n = parse_integer(borders[0], 0);
1584 r.border_e = parse_integer(borders[1], 0);
1585 r.border_s = parse_integer(borders[2], 0);
1586 r.border_w = parse_integer(borders[3], 0);
1587 } else
1588 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1589 } else
1590 fprintf(stderr, "no border defined, using 0.\n");
1592 /* Prompt */
1593 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1594 p_fg = parse_color(value.addr, "#fff");
1596 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1597 p_bg = parse_color(value.addr, "#000");
1599 /* Completions */
1600 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1601 compl_fg = parse_color(value.addr, "#fff");
1603 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1604 compl_bg = parse_color(value.addr, "#000");
1605 else
1606 compl_bg = parse_color("#000", NULL);
1608 /* Completion Highlighted */
1609 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1610 compl_highlighted_fg = parse_color(value.addr, "#000");
1612 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1613 compl_highlighted_bg = parse_color(value.addr, "#fff");
1614 else
1615 compl_highlighted_bg = parse_color("#fff", NULL);
1617 /* Border */
1618 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1619 char **colors;
1620 colors = parse_csslike(value.addr);
1621 if (colors != NULL) {
1622 border_n_bg = parse_color(colors[0], "#000");
1623 border_e_bg = parse_color(colors[1], "#000");
1624 border_s_bg = parse_color(colors[2], "#000");
1625 border_w_bg = parse_color(colors[3], "#000");
1626 } else
1627 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1631 /* Second round of args parsing */
1632 optind = 0; /* reset the option index */
1633 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1634 switch (ch) {
1635 case 'a':
1636 r.first_selected = 1;
1637 break;
1638 case 'A':
1639 /* free_text -- already catched */
1640 case 'd':
1641 /* separator -- this case was already catched */
1642 case 'e':
1643 /* embedding mymenu this case was already catched. */
1644 case 'm':
1645 /* multiple selection this case was already catched. */
1646 break;
1647 case 'p': {
1648 char *newprompt;
1649 newprompt = strdup(optarg);
1650 if (newprompt != NULL) {
1651 free(r.ps1);
1652 r.ps1 = newprompt;
1654 break;
1656 case 'x':
1657 x = parse_int_with_pos(optarg, x, d_width, r.width);
1658 break;
1659 case 'y':
1660 y = parse_int_with_pos(optarg, y, d_height, r.height);
1661 break;
1662 case 'P':
1663 r.padding = parse_integer(optarg, r.padding);
1664 break;
1665 case 'l':
1666 r.horizontal_layout = !strcmp(optarg, "horizontal");
1667 break;
1668 case 'f': {
1669 char *newfont;
1670 if ((newfont = strdup(optarg)) != NULL) {
1671 free(fontname);
1672 fontname = newfont;
1674 break;
1676 case 'W':
1677 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1678 break;
1679 case 'H':
1680 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1681 break;
1682 case 'b': {
1683 char **borders;
1684 if ((borders = parse_csslike(optarg)) != NULL) {
1685 r.border_n = parse_integer(borders[0], 0);
1686 r.border_e = parse_integer(borders[1], 0);
1687 r.border_s = parse_integer(borders[2], 0);
1688 r.border_w = parse_integer(borders[3], 0);
1689 } else
1690 fprintf(stderr, "Error parsing b option\n");
1691 break;
1693 case 'B': {
1694 char **colors;
1695 if ((colors = parse_csslike(optarg)) != NULL) {
1696 border_n_bg = parse_color(colors[0], "#000");
1697 border_e_bg = parse_color(colors[1], "#000");
1698 border_s_bg = parse_color(colors[2], "#000");
1699 border_w_bg = parse_color(colors[3], "#000");
1700 } else
1701 fprintf(stderr, "error while parsing B option\n");
1702 break;
1704 case 't':
1705 p_fg = parse_color(optarg, NULL);
1706 break;
1707 case 'T':
1708 p_bg = parse_color(optarg, NULL);
1709 break;
1710 case 'c':
1711 compl_fg = parse_color(optarg, NULL);
1712 break;
1713 case 'C':
1714 compl_bg = parse_color(optarg, NULL);
1715 break;
1716 case 's':
1717 compl_highlighted_fg = parse_color(optarg, NULL);
1718 break;
1719 case 'S':
1720 compl_highlighted_bg = parse_color(optarg, NULL);
1721 break;
1722 default:
1723 fprintf(stderr, "Unrecognized option %c\n", ch);
1724 status = ERR;
1725 break;
1729 /* since only now we know if the first should be selected,
1730 * update the completion here */
1731 update_completions(cs, text, lines, vlines, r.first_selected);
1733 /* update the prompt lenght, only now we surely know the length of it */
1734 r.ps1len = strlen(r.ps1);
1736 /* Create the window */
1737 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1738 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1739 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1740 XMapRaised(r.d, r.w);
1742 /* If embed, listen for other events as well */
1743 if (embed) {
1744 Window *children, parent, root;
1745 unsigned int children_no;
1747 XSelectInput(r.d, parent_window, FocusChangeMask);
1748 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1749 for (i = 0; i < children_no && children[i] != r.w; ++i)
1750 XSelectInput(r.d, children[i], FocusChangeMask);
1751 XFree(children);
1753 grabfocus(r.d, r.w);
1756 take_keyboard(r.d, r.w);
1758 r.x_zero = r.border_w;
1759 r.y_zero = r.border_n;
1762 XGCValues values;
1764 r.prompt = XCreateGC(r.d, r.w, 0, &values),
1765 r.prompt_bg = XCreateGC(r.d, r.w, 0, &values);
1766 r.completion = XCreateGC(r.d, r.w, 0, &values);
1767 r.completion_bg = XCreateGC(r.d, r.w, 0, &values);
1768 r.completion_highlighted = XCreateGC(r.d, r.w, 0, &values);
1769 r.completion_highlighted_bg = XCreateGC(r.d, r.w, 0, &values);
1770 r.border_n_bg = XCreateGC(r.d, r.w, 0, &values);
1771 r.border_e_bg = XCreateGC(r.d, r.w, 0, &values);
1772 r.border_s_bg = XCreateGC(r.d, r.w, 0, &values);
1773 r.border_w_bg = XCreateGC(r.d, r.w, 0, &values);
1776 if (load_font(&r, fontname) == -1)
1777 status = ERR;
1779 #ifdef USE_XFT
1780 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1783 rgba_t c;
1784 XRenderColor xrcolor;
1786 /* Prompt */
1787 c = *(rgba_t*)&p_fg;
1788 xrcolor.red = EXPANDBITS(c.rgba.r);
1789 xrcolor.green = EXPANDBITS(c.rgba.g);
1790 xrcolor.blue = EXPANDBITS(c.rgba.b);
1791 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1792 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_prompt);
1794 /* Completion */
1795 c = *(rgba_t*)&compl_fg;
1796 xrcolor.red = EXPANDBITS(c.rgba.r);
1797 xrcolor.green = EXPANDBITS(c.rgba.g);
1798 xrcolor.blue = EXPANDBITS(c.rgba.b);
1799 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1800 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion);
1802 /* Completion highlighted */
1803 c = *(rgba_t*)&compl_highlighted_fg;
1804 xrcolor.red = EXPANDBITS(c.rgba.r);
1805 xrcolor.green = EXPANDBITS(c.rgba.g);
1806 xrcolor.blue = EXPANDBITS(c.rgba.b);
1807 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1808 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_completion_highlighted);
1810 #endif
1812 /* Load the colors in our GCs */
1813 XSetForeground(r.d, r.prompt, p_fg);
1814 XSetForeground(r.d, r.prompt_bg, p_bg);
1815 XSetForeground(r.d, r.completion, compl_fg);
1816 XSetForeground(r.d, r.completion_bg, compl_bg);
1817 XSetForeground(r.d, r.completion_highlighted, compl_highlighted_fg);
1818 XSetForeground(r.d, r.completion_highlighted_bg, compl_highlighted_bg);
1819 XSetForeground(r.d, r.border_n_bg, border_n_bg);
1820 XSetForeground(r.d, r.border_e_bg, border_e_bg);
1821 XSetForeground(r.d, r.border_s_bg, border_s_bg);
1822 XSetForeground(r.d, r.border_w_bg, border_w_bg);
1824 /* compute prompt dimensions */
1825 ps1extents(&r);
1827 xim_init(&r, &xdb);
1829 /* Draw the window for the first time */
1830 draw(&r, text, cs);
1832 #ifdef __OpenBSD__
1833 /* Now we need only the ability to write */
1834 pledge("stdio", "");
1835 #endif
1837 /* Main loop */
1838 while (status == LOOPING || status == OK_LOOP) {
1839 status = loop(&r, &text, &textlen, cs, lines, vlines);
1841 if (status != ERR)
1842 printf("%s\n", text);
1844 if (!r.multiple_select && status == OK_LOOP)
1845 status = OK;
1848 XUngrabKeyboard(r.d, CurrentTime);
1850 #ifdef USE_XFT
1851 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1852 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1853 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1854 #endif
1856 free(r.ps1);
1857 free(fontname);
1858 free(text);
1860 free(buf);
1861 free(lines);
1862 free(vlines);
1863 compls_delete(cs);
1865 XDestroyWindow(r.d, r.w);
1866 XCloseDisplay(r.d);
1868 return status != OK;