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 #define USE_XFT
20 #define USE_XINERAMA
22 #ifdef USE_XINERAMA
23 # include <X11/extensions/Xinerama.h>
24 #endif
26 #ifdef USE_XFT
27 # include <X11/Xft/Xft.h>
28 #endif
30 #ifndef VERSION
31 # define VERSION "unknown"
32 #endif
34 #define resname "MyMenu"
35 #define resclass "mymenu"
37 #define SYM_BUF_SIZE 4
39 #ifdef USE_XFT
40 # define default_fontname "monospace"
41 #else
42 # define default_fontname "fixed"
43 #endif
45 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
52 /*
53 * If we don't have or we don't want an "ignore case" completion
54 * style, fall back to `strstr(3)`
55 */
56 #ifndef USE_STRCASESTR
57 # define strcasestr strstr
58 #endif
60 /* The number of char to read */
61 #define STDIN_CHUNKS 128
63 /* The number of lines to allocate in advance */
64 #define LINES_CHUNK 64
66 /* Abort on NULL */
67 #define check_allocation(a) { \
68 if (a == NULL) { \
69 fprintf(stderr, "Could not allocate memory\n"); \
70 abort(); \
71 } \
72 }
74 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
75 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
77 /* The states of the event loop */
78 enum state {LOOPING, OK_LOOP, OK, ERR};
80 /*
81 * For the drawing-related function. The text to be rendere could be
82 * the prompt, a completion or a highlighted completion
83 */
84 enum text_type {PROMPT, COMPL, COMPL_HIGH};
86 /* These are the possible action to be performed after user input. */
87 enum action {
88 EXIT,
89 CONFIRM,
90 CONFIRM_CONTINUE,
91 NEXT_COMPL,
92 PREV_COMPL,
93 DEL_CHAR,
94 DEL_WORD,
95 DEL_LINE,
96 ADD_CHAR,
97 TOGGLE_FIRST_SELECTED
98 };
100 /* A big set of values that needs to be carried around for drawing. A
101 big struct to rule them all */
102 struct rendering {
103 Display *d; /* Connection to xorg */
104 Window w;
105 int width;
106 int height;
107 int padding;
108 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
109 int y_zero; /* like x_zero but for the y axis */
111 size_t offset; /* scroll offset */
113 short free_text;
114 short first_selected;
115 short multiple_select;
117 /* four border width */
118 int borders[4];
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 fgs[4];
132 GC bgs[4];
133 GC borders_bg[4];
134 #ifdef USE_XFT
135 XftFont *font;
136 XftDraw *xftdraw;
137 XftColor xft_colors[3];
138 #else
139 XFontSet font;
140 #endif
141 };
143 struct completion {
144 char *completion;
145 char *rcompletion;
146 };
148 /* Wrap the linked list of completions */
149 struct completions {
150 struct completion *completions;
151 ssize_t selected;
152 size_t length;
153 };
155 /* idea stolen from lemonbar. ty lemonboy */
156 typedef union {
157 struct {
158 uint8_t b;
159 uint8_t g;
160 uint8_t r;
161 uint8_t a;
162 } rgba;
163 uint32_t v;
164 } rgba_t;
166 extern char *optarg;
167 extern int optind;
169 /* Return a newly allocated (and empty) completion list */
170 struct completions *
171 compls_new(size_t length)
173 struct completions *cs = malloc(sizeof(struct completions));
175 if (cs == NULL)
176 return cs;
178 cs->completions = calloc(length, sizeof(struct completion));
179 if (cs->completions == NULL) {
180 free(cs);
181 return NULL;
184 cs->selected = -1;
185 cs->length = length;
186 return cs;
189 /* Delete the wrapper and the whole list */
190 void
191 compls_delete(struct completions *cs)
193 if (cs == NULL)
194 return;
196 free(cs->completions);
197 free(cs);
200 /*
201 * Create a completion list from a text and the list of possible
202 * completions (null terminated). Expects a non-null `cs'. `lines' and
203 * `vlines' should have the same length OR `vlines' is NULL.
204 */
205 void
206 filter(struct completions *cs, char *text, char **lines, char **vlines)
208 size_t index = 0;
209 size_t matching = 0;
210 char *l;
212 if (vlines == NULL)
213 vlines = lines;
215 while (1) {
216 if (lines[index] == NULL)
217 break;
219 l = vlines[index] != NULL ? vlines[index] : lines[index];
221 if (strcasestr(l, text) != NULL) {
222 struct completion *c = &cs->completions[matching];
223 c->completion = l;
224 c->rcompletion = lines[index];
225 matching++;
228 index++;
230 cs->length = matching;
231 cs->selected = -1;
234 /* Update the given completion */
235 void
236 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
238 filter(cs, text, lines, vlines);
239 if (first_selected && cs->length > 0)
240 cs->selected = 0;
243 /*
244 * Select the next or previous selection and update some state. `text'
245 * will be updated with the text of the completion and `textlen' with
246 * the new length. If the memory cannot be allocated `status' will be
247 * set to `ERR'.
248 */
249 void
250 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
252 struct completion *n;
253 int index;
255 if (cs == NULL || cs->length == 0)
256 return;
258 /*
259 * If the first is always selected and the first entry is
260 * different from the text, expand the text and return
261 */
262 if (first_selected
263 && cs->selected == 0
264 && strcmp(cs->completions->completion, *text) != 0
265 && !p) {
266 free(*text);
267 *text = strdup(cs->completions->completion);
268 if (text == NULL) {
269 *status = ERR;
270 return;
272 *textlen = strlen(*text);
273 return;
276 index = cs->selected;
278 if (index == -1 && p)
279 index = 0;
280 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
282 n = &cs->completions[cs->selected];
284 free(*text);
285 *text = strdup(n->completion);
286 if (text == NULL) {
287 fprintf(stderr, "Memory allocation error!\n");
288 *status = ERR;
289 return;
291 *textlen = strlen(*text);
294 /* Push the character c at the end of the string pointed by p */
295 int
296 pushc(char **p, int maxlen, char c)
298 int len;
300 len = strnlen(*p, maxlen);
301 if (!(len < maxlen -2)) {
302 char *newptr;
304 maxlen += maxlen >> 1;
305 newptr = realloc(*p, maxlen);
306 if (newptr == NULL) /* bad */
307 return -1;
308 *p = newptr;
311 (*p)[len] = c;
312 (*p)[len+1] = '\0';
313 return maxlen;
316 /*
317 * Remove the last rune from the *UTF-8* string! This is different
318 * from just setting the last byte to 0 (in some cases ofc). Return a
319 * pointer (e) to the last nonzero char. If e < p then p is empty!
320 */
321 char *
322 popc(char *p)
324 int len = strlen(p);
325 char *e;
327 if (len == 0)
328 return p;
330 e = p + len - 1;
332 do {
333 char c = *e;
335 *e = '\0';
336 e -= 1;
338 /*
339 * If c is a starting byte (11......) or is under
340 * U+007F we're done.
341 */
342 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
343 break;
344 } while (e >= p);
346 return e;
349 /* Remove the last word plus trailing white spaces from the given string */
350 void
351 popw(char *w)
353 int len;
354 short in_word = 1;
356 if ((len = strlen(w)) == 0)
357 return;
359 while (1) {
360 char *e = popc(w);
362 if (e < w)
363 return;
365 if (in_word && isspace(*e))
366 in_word = 0;
368 if (!in_word && !isspace(*e))
369 return;
373 /*
374 * If the string is surrounded by quates (`"') remove them and replace
375 * every `\"' in the string with a single double-quote.
376 */
377 char *
378 normalize_str(const char *str)
380 int len, p;
381 char *s;
383 if ((len = strlen(str)) == 0)
384 return NULL;
386 s = calloc(len, sizeof(char));
387 check_allocation(s);
388 p = 0;
390 while (*str) {
391 char c = *str;
393 if (*str == '\\') {
394 if (*(str + 1)) {
395 s[p] = *(str + 1);
396 p++;
397 str += 2; /* skip this and the next char */
398 continue;
399 } else
400 break;
402 if (c == '"') {
403 str++; /* skip only this char */
404 continue;
406 s[p] = c;
407 p++;
408 str++;
411 return s;
414 size_t
415 read_stdin(char **buf)
417 size_t offset = 0;
418 size_t len = STDIN_CHUNKS;
420 *buf = malloc(len * sizeof(char));
421 if (*buf == NULL)
422 goto err;
424 while (1) {
425 ssize_t r;
426 size_t i;
428 r = read(0, *buf + offset, STDIN_CHUNKS);
430 if (r < 1)
431 return len;
433 offset += r;
435 len += STDIN_CHUNKS;
436 *buf = realloc(*buf, len);
437 if (*buf == NULL)
438 goto err;
440 for (i = offset; i < len; ++i)
441 (*buf)[i] = '\0';
444 err:
445 fprintf(stderr, "Error in allocating memory for stdin.\n");
446 exit(EX_UNAVAILABLE);
449 size_t
450 readlines(char ***lns, char **buf)
452 size_t i, len, ll, lines;
453 short in_line = 0;
455 lines = 0;
457 *buf = NULL;
458 len = read_stdin(buf);
460 ll = LINES_CHUNK;
461 *lns = malloc(ll * sizeof(char*));
463 if (*lns == NULL)
464 goto err;
466 for (i = 0; i < len; i++) {
467 char c = (*buf)[i];
469 if (c == '\0')
470 break;
472 if (c == '\n')
473 (*buf)[i] = '\0';
475 if (in_line && c == '\n')
476 in_line = 0;
478 if (!in_line && c != '\n') {
479 in_line = 1;
480 (*lns)[lines] = (*buf) + i;
481 lines++;
483 if (lines == ll) { /* resize */
484 ll += LINES_CHUNK;
485 *lns = realloc(*lns, ll * sizeof(char*));
486 if (*lns == NULL)
487 goto err;
492 (*lns)[lines] = NULL;
494 return lines;
496 err:
497 fprintf(stderr, "Error in memory allocation.\n");
498 exit(EX_UNAVAILABLE);
501 /*
502 * Compute the dimensions of the string str once rendered.
503 * It'll return the width and set ret_width and ret_height if not NULL
504 */
505 int
506 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
508 int height;
509 int width;
510 #ifdef USE_XFT
511 XGlyphInfo gi;
512 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
513 height = r->font->ascent - r->font->descent;
514 width = gi.width - gi.x;
515 #else
516 XRectangle rect;
517 XmbTextExtents(r->font, str, len, NULL, &rect);
518 height = rect.height;
519 width = rect.width;
520 #endif
521 if (ret_width != NULL) *ret_width = width;
522 if (ret_height != NULL) *ret_height = height;
523 return width;
526 void
527 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
529 #ifdef USE_XFT
530 XftColor xftcolor;
531 if (tt == PROMPT) xftcolor = r->xft_colors[0];
532 if (tt == COMPL) xftcolor = r->xft_colors[1];
533 if (tt == COMPL_HIGH) xftcolor = r->xft_colors[2];
535 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
536 #else
537 GC gc;
538 if (tt == PROMPT) gc = r->prompt;
539 if (tt == COMPL) gc = r->completion;
540 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
541 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
542 #endif
545 /* Duplicate the string and substitute every space with a 'n` */
546 char *
547 strdupn(char *str)
549 int len, i;
550 char *dup;
552 len = strlen(str);
554 if (str == NULL || len == 0)
555 return NULL;
557 if ((dup = strdup(str)) == NULL)
558 return NULL;
560 for (i = 0; i < len; ++i)
561 if (dup[i] == ' ')
562 dup[i] = 'n';
564 return dup;
567 /* ,-----------------------------------------------------------------, */
568 /* | 20 char text | completion | completion | completion | compl | */
569 /* `-----------------------------------------------------------------' */
570 void
571 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
573 size_t i;
574 int prompt_width, start_at;
575 int texty, textlen;
577 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
579 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
580 start_at *= prompt_width;
581 start_at += r->padding;
583 texty = (inner_height(r) + r->ps1h + r->y_zero) / 2;
585 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, start_at, inner_height(r));
587 textlen = strlen(text);
588 if (textlen > prompt_width)
589 text = text + textlen - prompt_width;
591 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
592 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + r->ps1w, texty, r, PROMPT);
594 XFillRectangle(r->d, r->w, r->bgs[1], start_at, r->y_zero, r->width, inner_height(r));
596 for (i = r->offset; i < cs->length; ++i) {
597 struct completion *c;
598 enum text_type tt;
599 GC h;
600 int len, text_width;
602 c = &cs->completions[i];
603 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
604 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
605 len = strlen(c->completion);
606 text_width = text_extents(c->completion, len, r, NULL, NULL);
608 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
609 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
611 start_at += text_width + r->padding * 2;
613 if (start_at > inner_width(r))
614 break; /* don't draw completion out of the window */
618 /* ,-----------------------------------------------------------------, */
619 /* | prompt | */
620 /* |-----------------------------------------------------------------| */
621 /* | completion | */
622 /* |-----------------------------------------------------------------| */
623 /* | completion | */
624 /* `-----------------------------------------------------------------' */
625 void
626 draw_vertically(struct rendering *r, char *text, struct completions *cs)
628 size_t i;
629 int height, start_at;
631 text_extents("fjpgl", 5, r, NULL, &height);
632 start_at = r->padding * 2 + height;
634 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, r->width, r->height);
635 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, r->width, start_at);
637 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
638 draw_string(text, strlen(text), r->x_zero + r->padding + r->ps1w, r->y_zero + height + r->padding, r, PROMPT);
640 start_at += r->y_zero;
642 for (i = r->offset; i < cs->length; ++i) {
643 struct completion *c;
644 enum text_type tt;
645 GC h;
646 int len;
648 c = &cs->completions[i];
649 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
650 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
651 len = strlen(c->completion);
653 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
654 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
656 start_at += height + r->padding * 2;
658 if (start_at > inner_height(r))
659 break; /* don't draw completion out of the window */
663 void
664 draw(struct rendering *r, char *text, struct completions *cs)
666 if (r->horizontal_layout)
667 draw_horizontally(r, text, cs);
668 else
669 draw_vertically(r, text, cs);
671 /* Draw the borders */
672 if (r->borders[0] != 0)
673 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
675 if (r->borders[1] != 0)
676 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0, r->borders[1], r->height);
678 if (r->borders[2] != 0)
679 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width, r->borders[2]);
681 if (r->borders[3] != 0)
682 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
684 /* render! */
685 XFlush(r->d);
688 /* Set some WM stuff */
689 void
690 set_win_atoms_hints(Display *d, Window w, int width, int height)
692 Atom type;
693 XClassHint *class_hint;
694 XSizeHints *size_hint;
696 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
697 XChangeProperty(d,
698 w,
699 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
700 XInternAtom(d, "ATOM", 0),
701 32,
702 PropModeReplace,
703 (unsigned char *)&type,
705 );
707 /* some window managers honor this properties */
708 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
709 XChangeProperty(d,
710 w,
711 XInternAtom(d, "_NET_WM_STATE", 0),
712 XInternAtom(d, "ATOM", 0),
713 32,
714 PropModeReplace,
715 (unsigned char *)&type,
717 );
719 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
720 XChangeProperty(d,
721 w,
722 XInternAtom(d, "_NET_WM_STATE", 0),
723 XInternAtom(d, "ATOM", 0),
724 32,
725 PropModeAppend,
726 (unsigned char *)&type,
728 );
730 /* Setting window hints */
731 class_hint = XAllocClassHint();
732 if (class_hint == NULL) {
733 fprintf(stderr, "Could not allocate memory for class hint\n");
734 exit(EX_UNAVAILABLE);
737 class_hint->res_name = resname;
738 class_hint->res_class = resclass;
739 XSetClassHint(d, w, class_hint);
740 XFree(class_hint);
742 size_hint = XAllocSizeHints();
743 if (size_hint == NULL) {
744 fprintf(stderr, "Could not allocate memory for size hint\n");
745 exit(EX_UNAVAILABLE);
748 size_hint->flags = PMinSize | PBaseSize;
749 size_hint->min_width = width;
750 size_hint->base_width = width;
751 size_hint->min_height = height;
752 size_hint->base_height = height;
754 XFlush(d);
757 /* Get the width and height of the window `w' */
758 void
759 get_wh(Display *d, Window *w, int *width, int *height)
761 XWindowAttributes win_attr;
763 XGetWindowAttributes(d, *w, &win_attr);
764 *height = win_attr.height;
765 *width = win_attr.width;
768 int
769 grabfocus(Display *d, Window w)
771 int i;
772 for (i = 0; i < 100; ++i) {
773 Window focuswin;
774 int revert_to_win;
776 XGetInputFocus(d, &focuswin, &revert_to_win);
778 if (focuswin == w)
779 return 1;
781 XSetInputFocus(d, w, RevertToParent, CurrentTime);
782 usleep(1000);
784 return 0;
787 /*
788 * I know this may seem a little hackish BUT is the only way I managed
789 * to actually grab that goddam keyboard. Only one call to
790 * XGrabKeyboard does not always end up with the keyboard grabbed!
791 */
792 int
793 take_keyboard(Display *d, Window w)
795 int i;
796 for (i = 0; i < 100; i++) {
797 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
798 return 1;
799 usleep(1000);
801 fprintf(stderr, "Cannot grab keyboard\n");
802 return 0;
805 unsigned long
806 parse_color(const char *str, const char *def)
808 size_t len;
809 rgba_t tmp;
810 char *ep;
812 if (str == NULL)
813 goto invc;
815 len = strlen(str);
817 /* +1 for the # ath the start */
818 if (*str != '#' || len > 9 || len < 4)
819 goto invc;
820 ++str; /* skip the # */
822 errno = 0;
823 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
825 if (errno)
826 goto invc;
828 switch (len-1) {
829 case 3:
830 /* expand #rgb -> #rrggbb */
831 tmp.v = (tmp.v & 0xf00) * 0x1100
832 | (tmp.v & 0x0f0) * 0x0110
833 | (tmp.v & 0x00f) * 0x0011;
834 case 6:
835 /* assume 0xff opacity */
836 tmp.rgba.a = 0xff;
837 break;
838 } /* colors in #aarrggbb need no adjustments */
840 /* premultiply the alpha */
841 if (tmp.rgba.a) {
842 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
843 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
844 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
845 return tmp.v;
848 return 0U;
850 invc:
851 fprintf(stderr, "Invalid color: \"%s\".\n", str);
852 if (def != NULL)
853 return parse_color(def, NULL);
854 else
855 return 0U;
858 /*
859 * Given a string try to parse it as a number or return `default_value'.
860 */
861 int
862 parse_integer(const char *str, int default_value)
864 long lval;
865 char *ep;
867 errno = 0;
868 lval = strtol(str, &ep, 10);
870 if (str[0] == '\0' || *ep != '\0') { /* NaN */
871 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
872 return default_value;
875 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
876 (lval > INT_MAX || lval < INT_MIN)) {
877 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
878 return default_value;
881 return lval;
884 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
885 int
886 parse_int_with_percentage(const char *str, int default_value, int max)
888 int len = strlen(str);
890 if (len > 0 && str[len-1] == '%') {
891 int val;
892 char *cpy;
894 cpy = strdup(str);
895 check_allocation(cpy);
896 cpy[len-1] = '\0';
897 val = parse_integer(cpy, default_value);
898 free(cpy);
899 return val * max / 100;
902 return parse_integer(str, default_value);
905 /*
906 * Like parse_int_with_percentage but understands some special values:
907 * - middle that is (max-self)/2
908 * - start that is 0
909 * - end that is (max-self)
910 */
911 int
912 parse_int_with_pos(const char *str, int default_value, int max, int self)
914 if (!strcmp(str, "start"))
915 return 0;
916 if (!strcmp(str, "middle"))
917 return (max - self)/2;
918 if (!strcmp(str, "end"))
919 return max-self;
920 return parse_int_with_percentage(str, default_value, max);
923 /* Parse a string like a CSS value. */
924 /* TODO: harden a bit this function */
925 char **
926 parse_csslike(const char *str)
928 int i, j;
929 char *s, *token, **ret;
930 short any_null;
932 s = strdup(str);
933 if (s == NULL)
934 return NULL;
936 ret = malloc(4 * sizeof(char*));
937 if (ret == NULL) {
938 free(s);
939 return NULL;
942 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
943 ret[i] = strdup(token);
945 if (i == 1)
946 for (j = 1; j < 4; j++)
947 ret[j] = strdup(ret[0]);
949 if (i == 2) {
950 ret[2] = strdup(ret[0]);
951 ret[3] = strdup(ret[1]);
954 if (i == 3)
955 ret[3] = strdup(ret[1]);
957 /* before we didn't check for the return type of strdup, here we will */
959 any_null = 0;
960 for (i = 0; i < 4; ++i)
961 any_null = ret[i] == NULL || any_null;
963 if (any_null)
964 for (i = 0; i < 4; ++i)
965 if (ret[i] != NULL)
966 free(ret[i]);
968 if (i == 0 || any_null) {
969 free(s);
970 free(ret);
971 return NULL;
974 return ret;
977 /*
978 * Given an event, try to understand what the users wants. If the
979 * return value is ADD_CHAR then `input' is a pointer to a string that
980 * will need to be free'ed later.
981 */
982 enum
983 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
985 char str[SYM_BUF_SIZE] = {0};
986 Status s;
988 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
989 return DEL_CHAR;
991 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
992 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
994 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
995 return CONFIRM;
997 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
998 return EXIT;
1000 /* Try to read what key was pressed */
1001 s = 0;
1002 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1003 if (s == XBufferOverflow) {
1004 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1005 return EXIT;
1008 if (ev->state & ControlMask) {
1009 if (!strcmp(str, "")) /* C-u */
1010 return DEL_LINE;
1011 if (!strcmp(str, "")) /* C-w */
1012 return DEL_WORD;
1013 if (!strcmp(str, "")) /* C-h */
1014 return DEL_CHAR;
1015 if (!strcmp(str, "\r")) /* C-m */
1016 return CONFIRM_CONTINUE;
1017 if (!strcmp(str, "")) /* C-p */
1018 return PREV_COMPL;
1019 if (!strcmp(str, "")) /* C-n */
1020 return NEXT_COMPL;
1021 if (!strcmp(str, "")) /* C-c */
1022 return EXIT;
1023 if (!strcmp(str, "\t")) /* C-i */
1024 return TOGGLE_FIRST_SELECTED;
1027 *input = strdup(str);
1028 if (*input == NULL) {
1029 fprintf(stderr, "Error while allocating memory for key.\n");
1030 return EXIT;
1033 return ADD_CHAR;
1036 void
1037 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1039 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1040 /* if there is something selected expand it and return */
1041 int index = cs->selected == -1 ? 0 : cs->selected;
1042 struct completion *c = cs->completions;
1043 char *t;
1045 while (1) {
1046 if (index == 0)
1047 break;
1048 c++;
1049 index--;
1052 t = c->rcompletion;
1053 free(*text);
1054 *text = strdup(t);
1056 if (*text == NULL) {
1057 fprintf(stderr, "Memory allocation error\n");
1058 *status = ERR;
1061 *textlen = strlen(*text);
1062 return;
1065 if (!r->free_text) /* cannot accept arbitrary text */
1066 *status = LOOPING;
1069 /* event loop */
1070 enum state
1071 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1073 enum state status = LOOPING;
1075 while (status == LOOPING) {
1076 XEvent e;
1077 XNextEvent(r->d, &e);
1079 if (XFilterEvent(&e, r->w))
1080 continue;
1082 switch (e.type) {
1083 case KeymapNotify:
1084 XRefreshKeyboardMapping(&e.xmapping);
1085 break;
1087 case FocusIn:
1088 /* Re-grab focus */
1089 if (e.xfocus.window != r->w)
1090 grabfocus(r->d, r->w);
1091 break;
1093 case VisibilityNotify:
1094 if (e.xvisibility.state != VisibilityUnobscured)
1095 XRaiseWindow(r->d, r->w);
1096 break;
1098 case MapNotify:
1099 get_wh(r->d, &r->w, &r->width, &r->height);
1100 draw(r, *text, cs);
1101 break;
1103 case KeyPress: {
1104 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1105 char *input;
1107 switch (parse_event(r->d, ev, r->xic, &input)) {
1108 case EXIT:
1109 status = ERR;
1110 break;
1112 case CONFIRM: {
1113 status = OK;
1114 confirm(&status, r, cs, text, textlen);
1115 break;
1118 case CONFIRM_CONTINUE: {
1119 status = OK_LOOP;
1120 confirm(&status, r, cs, text, textlen);
1121 break;
1124 case PREV_COMPL: {
1125 complete(cs, r->first_selected, 1, text, textlen, &status);
1126 r->offset = cs->selected;
1127 break;
1130 case NEXT_COMPL: {
1131 complete(cs, r->first_selected, 0, text, textlen, &status);
1132 r->offset = cs->selected;
1133 break;
1136 case DEL_CHAR:
1137 popc(*text);
1138 update_completions(cs, *text, lines, vlines, r->first_selected);
1139 r->offset = 0;
1140 break;
1142 case DEL_WORD: {
1143 popw(*text);
1144 update_completions(cs, *text, lines, vlines, r->first_selected);
1145 break;
1148 case DEL_LINE: {
1149 int i;
1150 for (i = 0; i < *textlen; ++i)
1151 *(*text + i) = 0;
1152 update_completions(cs, *text, lines, vlines, r->first_selected);
1153 r->offset = 0;
1154 break;
1157 case ADD_CHAR: {
1158 int str_len, i;
1160 str_len = strlen(input);
1163 * sometimes a strange key is pressed
1164 * i.e. ctrl alone), so input will be
1165 * empty. Don't need to update
1166 * completion in that case
1168 if (str_len == 0)
1169 break;
1171 for (i = 0; i < str_len; ++i) {
1172 *textlen = pushc(text, *textlen, input[i]);
1173 if (*textlen == -1) {
1174 fprintf(stderr, "Memory allocation error\n");
1175 status = ERR;
1176 break;
1180 if (status != ERR) {
1181 update_completions(cs, *text, lines, vlines, r->first_selected);
1182 free(input);
1185 r->offset = 0;
1186 break;
1189 case TOGGLE_FIRST_SELECTED:
1190 r->first_selected = !r->first_selected;
1191 if (r->first_selected && cs->selected < 0)
1192 cs->selected = 0;
1193 if (!r->first_selected && cs->selected == 0)
1194 cs->selected = -1;
1195 break;
1199 case ButtonPress: {
1200 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1201 /* if (ev->button == Button1) { /\* click *\/ */
1202 /* int x = ev->x - r.border_w; */
1203 /* int y = ev->y - r.border_n; */
1204 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1205 /* } */
1207 if (ev->button == Button4) /* scroll up */
1208 r->offset = MAX((ssize_t)r->offset - 1, 0);
1210 if (ev->button == Button5) /* scroll down */
1211 r->offset = MIN(r->offset + 1, cs->length - 1);
1213 break;
1217 draw(r, *text, cs);
1220 return status;
1223 int
1224 load_font(struct rendering *r, const char *fontname)
1226 #ifdef USE_XFT
1227 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1228 return 0;
1229 #else
1230 char **missing_charset_list;
1231 int missing_charset_count;
1233 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1234 if (r->font != NULL)
1235 return 0;
1237 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1239 if (!strcmp(fontname, default_fontname))
1240 return -1;
1242 return load_font(r, default_fontname);
1243 #endif
1246 void
1247 xim_init(struct rendering *r, XrmDatabase *xdb)
1249 XIM xim;
1250 XIMStyle best_match_style;
1251 XIMStyles *xis;
1252 int i;
1254 /* Open the X input method */
1255 xim = XOpenIM(r->d, *xdb, resname, resclass);
1256 check_allocation(xim);
1258 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1259 fprintf(stderr, "Input Styles could not be retrieved\n");
1260 exit(EX_UNAVAILABLE);
1263 best_match_style = 0;
1264 for (i = 0; i < xis->count_styles; ++i) {
1265 XIMStyle ts = xis->supported_styles[i];
1266 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1267 best_match_style = ts;
1268 break;
1271 XFree(xis);
1273 if (!best_match_style)
1274 fprintf(stderr, "No matching input style could be determined\n");
1276 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1277 check_allocation(r->xic);
1280 void
1281 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1283 XSetWindowAttributes attr;
1285 /* Create the window */
1286 attr.colormap = cmap;
1287 attr.override_redirect = 1;
1288 attr.border_pixel = 0;
1289 attr.background_pixel = 0x80808080;
1290 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1292 r->w = XCreateWindow(r->d,
1293 parent_window,
1294 x + ox, y + oy,
1295 r->width, r->height,
1297 vinfo.depth,
1298 InputOutput,
1299 vinfo.visual,
1300 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1301 &attr);
1304 void
1305 ps1extents(struct rendering *r)
1307 char *dup;
1308 dup = strdupn(r->ps1);
1309 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1310 free(dup);
1313 void
1314 usage(char *prgname)
1316 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1317 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1318 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1319 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1322 int
1323 main(int argc, char **argv)
1325 struct completions *cs;
1326 struct rendering r;
1327 XVisualInfo vinfo;
1328 Colormap cmap;
1329 size_t nlines, i;
1330 Window parent_window;
1331 XrmDatabase xdb;
1332 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1333 unsigned long borders_bg[4]; /* N E S W */
1334 enum state status;
1335 int ch;
1336 int offset_x, offset_y, x, y;
1337 int textlen, d_width, d_height;
1338 short embed;
1339 char *sep, *parent_window_id;
1340 char **lines, *buf, **vlines;
1341 char *fontname, *text, *xrm;
1343 #ifdef __OpenBSD__
1344 /* stdio & rpath: to read/write stdio/stdout/stderr */
1345 /* unix: to connect to XOrg */
1346 pledge("stdio rpath unix", "");
1347 #endif
1349 sep = NULL;
1350 parent_window_id = NULL;
1352 r.first_selected = 0;
1353 r.free_text = 1;
1354 r.multiple_select = 0;
1355 r.offset = 0;
1357 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1358 switch (ch) {
1359 case 'h': /* help */
1360 usage(*argv);
1361 return 0;
1362 case 'v': /* version */
1363 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1364 return 0;
1365 case 'e': /* embed */
1366 parent_window_id = strdup(optarg);
1367 check_allocation(parent_window_id);
1368 break;
1369 case 'd':
1370 sep = strdup(optarg);
1371 check_allocation(sep);
1372 case 'A':
1373 r.free_text = 0;
1374 break;
1375 case 'm':
1376 r.multiple_select = 1;
1377 break;
1378 default:
1379 break;
1383 /* Read the completions */
1384 lines = NULL;
1385 buf = NULL;
1386 nlines = readlines(&lines, &buf);
1388 vlines = NULL;
1389 if (sep != NULL) {
1390 int l;
1391 l = strlen(sep);
1392 vlines = calloc(nlines, sizeof(char*));
1393 check_allocation(vlines);
1395 for (i = 0; i < nlines; i++) {
1396 char *t;
1397 t = strstr(lines[i], sep);
1398 if (t == NULL)
1399 vlines[i] = lines[i];
1400 else
1401 vlines[i] = t + l;
1405 setlocale(LC_ALL, getenv("LANG"));
1407 status = LOOPING;
1409 /* where the monitor start (used only with xinerama) */
1410 offset_x = offset_y = 0;
1412 /* default width and height */
1413 r.width = 400;
1414 r.height = 20;
1416 /* default position on the screen */
1417 x = y = 0;
1419 /* default padding */
1420 r.padding = 10;
1422 /* default borders */
1423 r.borders[0] = r.borders[1] = r.borders[2] = r.borders[3] = 0;
1425 /* the prompt. We duplicate the string so later is easy to
1426 * free (in the case it's been overwritten by the user) */
1427 r.ps1 = strdup("$ ");
1428 check_allocation(r.ps1);
1430 /* same for the font name */
1431 fontname = strdup(default_fontname);
1432 check_allocation(fontname);
1434 textlen = 10;
1435 text = malloc(textlen * sizeof(char));
1436 check_allocation(text);
1438 /* struct completions *cs = filter(text, lines); */
1439 cs = compls_new(nlines);
1440 check_allocation(cs);
1442 /* start talking to xorg */
1443 r.d = XOpenDisplay(NULL);
1444 if (r.d == NULL) {
1445 fprintf(stderr, "Could not open display!\n");
1446 return EX_UNAVAILABLE;
1449 embed = 1;
1450 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1451 parent_window = DefaultRootWindow(r.d);
1452 embed = 0;
1455 /* get display size */
1456 get_wh(r.d, &parent_window, &d_width, &d_height);
1458 #ifdef USE_XINERAMA
1459 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1460 XineramaScreenInfo *info;
1461 Window rr;
1462 Window root;
1463 int number_of_screens, monitors, i;
1464 int root_x, root_y, win_x, win_y;
1465 unsigned int mask;
1466 short res;
1468 number_of_screens = XScreenCount(r.d);
1469 for (i = 0; i < number_of_screens; ++i) {
1470 root = XRootWindow(r.d, i);
1471 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1472 if (res)
1473 break;
1476 if (!res) {
1477 fprintf(stderr, "No mouse found.\n");
1478 root_x = 0;
1479 root_y = 0;
1482 /* Now find in which monitor the mice is */
1483 info = XineramaQueryScreens(r.d, &monitors);
1484 if (info) {
1485 for (i = 0; i < monitors; ++i) {
1486 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1487 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1488 offset_x = info[i].x_org;
1489 offset_y = info[i].y_org;
1490 d_width = info[i].width;
1491 d_height = info[i].height;
1492 break;
1496 XFree(info);
1498 #endif
1500 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1501 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1503 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1504 fgs[2] = parse_color("#000", NULL);
1506 bgs[0] = bgs[1] = parse_color("#000", NULL);
1507 bgs[2] = parse_color("#fff", NULL);
1509 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1511 r.horizontal_layout = 1;
1513 /* Read the resources */
1514 XrmInitialize();
1515 xrm = XResourceManagerString(r.d);
1516 xdb = NULL;
1517 if (xrm != NULL) {
1518 XrmValue value;
1519 char *datatype[20];
1521 xdb = XrmGetStringDatabase(xrm);
1523 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1524 free(fontname);
1525 fontname = strdup(value.addr);
1526 check_allocation(fontname);
1527 } else {
1528 fprintf(stderr, "no font defined, using %s\n", fontname);
1531 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1532 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1533 else
1534 fprintf(stderr, "no layout defined, using horizontal\n");
1536 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1537 free(r.ps1);
1538 r.ps1 = normalize_str(value.addr);
1539 } else {
1540 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1543 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1544 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1545 else
1546 fprintf(stderr, "no width defined, using %d\n", r.width);
1548 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1549 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1550 else
1551 fprintf(stderr, "no height defined, using %d\n", r.height);
1553 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1554 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1555 else
1556 fprintf(stderr, "no x defined, using %d\n", x);
1558 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1559 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1560 else
1561 fprintf(stderr, "no y defined, using %d\n", y);
1563 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1564 r.padding = parse_integer(value.addr, r.padding);
1565 else
1566 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1568 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1569 char **borders;
1571 borders = parse_csslike(value.addr);
1572 if (borders != NULL) {
1573 r.borders[0] = parse_integer(borders[0], 0);
1574 r.borders[1] = parse_integer(borders[1], 0);
1575 r.borders[2] = parse_integer(borders[2], 0);
1576 r.borders[3] = parse_integer(borders[3], 0);
1577 } else
1578 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1579 } else
1580 fprintf(stderr, "no border defined, using 0.\n");
1582 /* Prompt */
1583 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1584 fgs[0] = parse_color(value.addr, "#fff");
1586 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1587 bgs[0] = parse_color(value.addr, "#000");
1589 /* Completions */
1590 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1591 fgs[1] = parse_color(value.addr, "#fff");
1593 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1594 bgs[1] = parse_color(value.addr, "#000");
1596 /* Completion Highlighted */
1597 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1598 fgs[2] = parse_color(value.addr, "#000");
1600 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1601 bgs[2] = parse_color(value.addr, "#fff");
1603 /* Border */
1604 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1605 char **colors;
1606 colors = parse_csslike(value.addr);
1607 if (colors != NULL) {
1608 borders_bg[0] = parse_color(colors[0], "#000");
1609 borders_bg[1] = parse_color(colors[1], "#000");
1610 borders_bg[2] = parse_color(colors[2], "#000");
1611 borders_bg[3] = parse_color(colors[3], "#000");
1612 } else
1613 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1617 /* Second round of args parsing */
1618 optind = 0; /* reset the option index */
1619 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1620 switch (ch) {
1621 case 'a':
1622 r.first_selected = 1;
1623 break;
1624 case 'A':
1625 /* free_text -- already catched */
1626 case 'd':
1627 /* separator -- this case was already catched */
1628 case 'e':
1629 /* embedding mymenu this case was already catched. */
1630 case 'm':
1631 /* multiple selection this case was already catched. */
1632 break;
1633 case 'p': {
1634 char *newprompt;
1635 newprompt = strdup(optarg);
1636 if (newprompt != NULL) {
1637 free(r.ps1);
1638 r.ps1 = newprompt;
1640 break;
1642 case 'x':
1643 x = parse_int_with_pos(optarg, x, d_width, r.width);
1644 break;
1645 case 'y':
1646 y = parse_int_with_pos(optarg, y, d_height, r.height);
1647 break;
1648 case 'P':
1649 r.padding = parse_integer(optarg, r.padding);
1650 break;
1651 case 'l':
1652 r.horizontal_layout = !strcmp(optarg, "horizontal");
1653 break;
1654 case 'f': {
1655 char *newfont;
1656 if ((newfont = strdup(optarg)) != NULL) {
1657 free(fontname);
1658 fontname = newfont;
1660 break;
1662 case 'W':
1663 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1664 break;
1665 case 'H':
1666 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1667 break;
1668 case 'b': {
1669 char **borders;
1670 if ((borders = parse_csslike(optarg)) != NULL) {
1671 r.borders[0] = parse_integer(borders[0], 0);
1672 r.borders[1] = parse_integer(borders[1], 0);
1673 r.borders[2] = parse_integer(borders[2], 0);
1674 r.borders[3] = parse_integer(borders[3], 0);
1675 } else
1676 fprintf(stderr, "Error parsing b option\n");
1677 break;
1679 case 'B': {
1680 char **colors;
1681 if ((colors = parse_csslike(optarg)) != NULL) {
1682 borders_bg[0] = parse_color(colors[0], "#000");
1683 borders_bg[1] = parse_color(colors[1], "#000");
1684 borders_bg[2] = parse_color(colors[2], "#000");
1685 borders_bg[3] = parse_color(colors[3], "#000");
1686 } else
1687 fprintf(stderr, "error while parsing B option\n");
1688 break;
1690 case 't':
1691 fgs[0] = parse_color(optarg, NULL);
1692 break;
1693 case 'T':
1694 bgs[0] = parse_color(optarg, NULL);
1695 break;
1696 case 'c':
1697 fgs[1] = parse_color(optarg, NULL);
1698 break;
1699 case 'C':
1700 bgs[1] = parse_color(optarg, NULL);
1701 break;
1702 case 's':
1703 fgs[2] = parse_color(optarg, NULL);
1704 break;
1705 case 'S':
1706 fgs[2] = parse_color(optarg, NULL);
1707 break;
1708 default:
1709 fprintf(stderr, "Unrecognized option %c\n", ch);
1710 status = ERR;
1711 break;
1715 /* since only now we know if the first should be selected,
1716 * update the completion here */
1717 update_completions(cs, text, lines, vlines, r.first_selected);
1719 /* update the prompt lenght, only now we surely know the length of it */
1720 r.ps1len = strlen(r.ps1);
1722 /* Create the window */
1723 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1724 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1725 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1726 XMapRaised(r.d, r.w);
1728 /* If embed, listen for other events as well */
1729 if (embed) {
1730 Window *children, parent, root;
1731 unsigned int children_no;
1733 XSelectInput(r.d, parent_window, FocusChangeMask);
1734 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1735 for (i = 0; i < children_no && children[i] != r.w; ++i)
1736 XSelectInput(r.d, children[i], FocusChangeMask);
1737 XFree(children);
1739 grabfocus(r.d, r.w);
1742 take_keyboard(r.d, r.w);
1744 r.x_zero = r.borders[3];
1745 r.y_zero = r.borders[0];
1748 XGCValues values;
1750 r.fgs[0] = XCreateGC(r.d, r.w, 0, &values),
1751 r.fgs[1] = XCreateGC(r.d, r.w, 0, &values),
1752 r.fgs[2] = XCreateGC(r.d, r.w, 0, &values),
1753 r.bgs[0] = XCreateGC(r.d, r.w, 0, &values),
1754 r.bgs[1] = XCreateGC(r.d, r.w, 0, &values),
1755 r.bgs[2] = XCreateGC(r.d, r.w, 0, &values),
1756 r.borders_bg[0] = XCreateGC(r.d, r.w, 0, &values);
1757 r.borders_bg[1] = XCreateGC(r.d, r.w, 0, &values);
1758 r.borders_bg[2] = XCreateGC(r.d, r.w, 0, &values);
1759 r.borders_bg[3] = XCreateGC(r.d, r.w, 0, &values);
1762 if (load_font(&r, fontname) == -1)
1763 status = ERR;
1765 #ifdef USE_XFT
1766 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1769 rgba_t c;
1770 XRenderColor xrcolor;
1772 /* Prompt */
1773 c = *(rgba_t*)&fgs[0];
1774 xrcolor.red = EXPANDBITS(c.rgba.r);
1775 xrcolor.green = EXPANDBITS(c.rgba.g);
1776 xrcolor.blue = EXPANDBITS(c.rgba.b);
1777 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1778 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[0]);
1780 /* Completion */
1781 c = *(rgba_t*)&fgs[1];
1782 xrcolor.red = EXPANDBITS(c.rgba.r);
1783 xrcolor.green = EXPANDBITS(c.rgba.g);
1784 xrcolor.blue = EXPANDBITS(c.rgba.b);
1785 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1786 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[1]);
1788 /* Completion highlighted */
1789 c = *(rgba_t*)&fgs[2];
1790 xrcolor.red = EXPANDBITS(c.rgba.r);
1791 xrcolor.green = EXPANDBITS(c.rgba.g);
1792 xrcolor.blue = EXPANDBITS(c.rgba.b);
1793 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1794 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[2]);
1796 #endif
1798 /* Load the colors in our GCs */
1799 XSetForeground(r.d, r.fgs[0], fgs[0]);
1800 XSetForeground(r.d, r.bgs[0], bgs[0]);
1801 XSetForeground(r.d, r.fgs[1], fgs[1]);
1802 XSetForeground(r.d, r.bgs[1], bgs[1]);
1803 XSetForeground(r.d, r.fgs[2], fgs[2]);
1804 XSetForeground(r.d, r.bgs[2], bgs[2]);
1805 XSetForeground(r.d, r.borders_bg[0], borders_bg[0]);
1806 XSetForeground(r.d, r.borders_bg[1], borders_bg[1]);
1807 XSetForeground(r.d, r.borders_bg[2], borders_bg[2]);
1808 XSetForeground(r.d, r.borders_bg[3], borders_bg[3]);
1810 /* compute prompt dimensions */
1811 ps1extents(&r);
1813 xim_init(&r, &xdb);
1815 #ifdef __OpenBSD__
1816 /* Now we need only the ability to write */
1817 pledge("stdio", "");
1818 #endif
1820 /* Draw the window for the first time */
1821 draw(&r, text, cs);
1823 /* Main loop */
1824 while (status == LOOPING || status == OK_LOOP) {
1825 status = loop(&r, &text, &textlen, cs, lines, vlines);
1827 if (status != ERR)
1828 printf("%s\n", text);
1830 if (!r.multiple_select && status == OK_LOOP)
1831 status = OK;
1834 XUngrabKeyboard(r.d, CurrentTime);
1836 #ifdef USE_XFT
1837 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[0]);
1838 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[1]);
1839 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[2]);
1840 #endif
1842 free(r.ps1);
1843 free(fontname);
1844 free(text);
1846 free(buf);
1847 free(lines);
1848 free(vlines);
1849 compls_delete(cs);
1851 XDestroyWindow(r.d, r.w);
1852 XCloseDisplay(r.d);
1854 return status != OK;