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) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
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->borders[0] - r->borders[2])
72 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
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 borders[4];
117 short horizontal_layout;
119 /* prompt */
120 char *ps1;
121 int ps1len;
122 int ps1w; /* ps1 width */
123 int ps1h; /* ps1 height */
125 XIC xic;
127 /* colors */
128 GC fgs[4];
129 GC bgs[4];
130 GC borders_bg[4];
131 #ifdef USE_XFT
132 XftFont *font;
133 XftDraw *xftdraw;
134 XftColor xft_colors[3];
135 #else
136 XFontSet font;
137 #endif
138 };
140 struct completion {
141 char *completion;
142 char *rcompletion;
143 };
145 /* Wrap the linked list of completions */
146 struct completions {
147 struct completion *completions;
148 ssize_t selected;
149 size_t length;
150 };
152 /* idea stolen from lemonbar. ty lemonboy */
153 typedef union {
154 struct {
155 uint8_t b;
156 uint8_t g;
157 uint8_t r;
158 uint8_t a;
159 } rgba;
160 uint32_t v;
161 } rgba_t;
163 extern char *optarg;
164 extern int optind;
166 /* Return a newly allocated (and empty) completion list */
167 struct completions *
168 compls_new(size_t length)
170 struct completions *cs = malloc(sizeof(struct completions));
172 if (cs == NULL)
173 return cs;
175 cs->completions = calloc(length, sizeof(struct completion));
176 if (cs->completions == NULL) {
177 free(cs);
178 return NULL;
181 cs->selected = -1;
182 cs->length = length;
183 return cs;
186 /* Delete the wrapper and the whole list */
187 void
188 compls_delete(struct completions *cs)
190 if (cs == NULL)
191 return;
193 free(cs->completions);
194 free(cs);
197 /*
198 * Create a completion list from a text and the list of possible
199 * completions (null terminated). Expects a non-null `cs'. `lines' and
200 * `vlines' should have the same length OR `vlines' is NULL.
201 */
202 void
203 filter(struct completions *cs, char *text, char **lines, char **vlines)
205 size_t index = 0;
206 size_t matching = 0;
207 char *l;
209 if (vlines == NULL)
210 vlines = lines;
212 while (1) {
213 if (lines[index] == NULL)
214 break;
216 l = vlines[index] != NULL ? vlines[index] : lines[index];
218 if (strcasestr(l, text) != NULL) {
219 struct completion *c = &cs->completions[matching];
220 c->completion = l;
221 c->rcompletion = lines[index];
222 matching++;
225 index++;
227 cs->length = matching;
228 cs->selected = -1;
231 /* Update the given completion */
232 void
233 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
235 filter(cs, text, lines, vlines);
236 if (first_selected && cs->length > 0)
237 cs->selected = 0;
240 /*
241 * Select the next or previous selection and update some state. `text'
242 * will be updated with the text of the completion and `textlen' with
243 * the new length. If the memory cannot be allocated `status' will be
244 * set to `ERR'.
245 */
246 void
247 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
249 struct completion *n;
250 int index;
252 if (cs == NULL || cs->length == 0)
253 return;
255 /*
256 * If the first is always selected and the first entry is
257 * different from the text, expand the text and return
258 */
259 if (first_selected
260 && cs->selected == 0
261 && strcmp(cs->completions->completion, *text) != 0
262 && !p) {
263 free(*text);
264 *text = strdup(cs->completions->completion);
265 if (text == NULL) {
266 *status = ERR;
267 return;
269 *textlen = strlen(*text);
270 return;
273 index = cs->selected;
275 if (index == -1 && p)
276 index = 0;
277 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
279 n = &cs->completions[cs->selected];
281 free(*text);
282 *text = strdup(n->completion);
283 if (text == NULL) {
284 fprintf(stderr, "Memory allocation error!\n");
285 *status = ERR;
286 return;
288 *textlen = strlen(*text);
291 /* Push the character c at the end of the string pointed by p */
292 int
293 pushc(char **p, int maxlen, char c)
295 int len;
297 len = strnlen(*p, maxlen);
298 if (!(len < maxlen -2)) {
299 char *newptr;
301 maxlen += maxlen >> 1;
302 newptr = realloc(*p, maxlen);
303 if (newptr == NULL) /* bad */
304 return -1;
305 *p = newptr;
308 (*p)[len] = c;
309 (*p)[len+1] = '\0';
310 return maxlen;
313 /*
314 * Remove the last rune from the *UTF-8* string! This is different
315 * from just setting the last byte to 0 (in some cases ofc). Return a
316 * pointer (e) to the last nonzero char. If e < p then p is empty!
317 */
318 char *
319 popc(char *p)
321 int len = strlen(p);
322 char *e;
324 if (len == 0)
325 return p;
327 e = p + len - 1;
329 do {
330 char c = *e;
332 *e = '\0';
333 e -= 1;
335 /*
336 * If c is a starting byte (11......) or is under
337 * U+007F we're done.
338 */
339 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
340 break;
341 } while (e >= p);
343 return e;
346 /* Remove the last word plus trailing white spaces from the given string */
347 void
348 popw(char *w)
350 int len;
351 short in_word = 1;
353 if ((len = strlen(w)) == 0)
354 return;
356 while (1) {
357 char *e = popc(w);
359 if (e < w)
360 return;
362 if (in_word && isspace(*e))
363 in_word = 0;
365 if (!in_word && !isspace(*e))
366 return;
370 /*
371 * If the string is surrounded by quates (`"') remove them and replace
372 * every `\"' in the string with a single double-quote.
373 */
374 char *
375 normalize_str(const char *str)
377 int len, p;
378 char *s;
380 if ((len = strlen(str)) == 0)
381 return NULL;
383 s = calloc(len, sizeof(char));
384 check_allocation(s);
385 p = 0;
387 while (*str) {
388 char c = *str;
390 if (*str == '\\') {
391 if (*(str + 1)) {
392 s[p] = *(str + 1);
393 p++;
394 str += 2; /* skip this and the next char */
395 continue;
396 } else
397 break;
399 if (c == '"') {
400 str++; /* skip only this char */
401 continue;
403 s[p] = c;
404 p++;
405 str++;
408 return s;
411 size_t
412 read_stdin(char **buf)
414 size_t offset = 0;
415 size_t len = STDIN_CHUNKS;
417 *buf = malloc(len * sizeof(char));
418 if (*buf == NULL)
419 goto err;
421 while (1) {
422 ssize_t r;
423 size_t i;
425 r = read(0, *buf + offset, STDIN_CHUNKS);
427 if (r < 1)
428 return len;
430 offset += r;
432 len += STDIN_CHUNKS;
433 *buf = realloc(*buf, len);
434 if (*buf == NULL)
435 goto err;
437 for (i = offset; i < len; ++i)
438 (*buf)[i] = '\0';
441 err:
442 fprintf(stderr, "Error in allocating memory for stdin.\n");
443 exit(EX_UNAVAILABLE);
446 size_t
447 readlines(char ***lns, char **buf)
449 size_t i, len, ll, lines;
450 short in_line = 0;
452 lines = 0;
454 *buf = NULL;
455 len = read_stdin(buf);
457 ll = LINES_CHUNK;
458 *lns = malloc(ll * sizeof(char*));
460 if (*lns == NULL)
461 goto err;
463 for (i = 0; i < len; i++) {
464 char c = (*buf)[i];
466 if (c == '\0')
467 break;
469 if (c == '\n')
470 (*buf)[i] = '\0';
472 if (in_line && c == '\n')
473 in_line = 0;
475 if (!in_line && c != '\n') {
476 in_line = 1;
477 (*lns)[lines] = (*buf) + i;
478 lines++;
480 if (lines == ll) { /* resize */
481 ll += LINES_CHUNK;
482 *lns = realloc(*lns, ll * sizeof(char*));
483 if (*lns == NULL)
484 goto err;
489 (*lns)[lines] = NULL;
491 return lines;
493 err:
494 fprintf(stderr, "Error in memory allocation.\n");
495 exit(EX_UNAVAILABLE);
498 /*
499 * Compute the dimensions of the string str once rendered.
500 * It'll return the width and set ret_width and ret_height if not NULL
501 */
502 int
503 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
505 int height;
506 int width;
507 #ifdef USE_XFT
508 XGlyphInfo gi;
509 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
510 height = r->font->ascent - r->font->descent;
511 width = gi.width - gi.x;
512 #else
513 XRectangle rect;
514 XmbTextExtents(r->font, str, len, NULL, &rect);
515 height = rect.height;
516 width = rect.width;
517 #endif
518 if (ret_width != NULL) *ret_width = width;
519 if (ret_height != NULL) *ret_height = height;
520 return width;
523 void
524 draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt)
526 #ifdef USE_XFT
527 XftColor xftcolor;
528 if (tt == PROMPT) xftcolor = r->xft_colors[0];
529 if (tt == COMPL) xftcolor = r->xft_colors[1];
530 if (tt == COMPL_HIGH) xftcolor = r->xft_colors[2];
532 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
533 #else
534 GC gc;
535 if (tt == PROMPT) gc = r->fgs[0];
536 if (tt == COMPL) gc = r->fgs[1];
537 if (tt == COMPL_HIGH) gc = r->fgs[2];
538 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
539 #endif
542 /* Duplicate the string and substitute every space with a 'n` */
543 char *
544 strdupn(char *str)
546 int len, i;
547 char *dup;
549 len = strlen(str);
551 if (str == NULL || len == 0)
552 return NULL;
554 if ((dup = strdup(str)) == NULL)
555 return NULL;
557 for (i = 0; i < len; ++i)
558 if (dup[i] == ' ')
559 dup[i] = 'n';
561 return dup;
564 /* ,-----------------------------------------------------------------, */
565 /* | 20 char text | completion | completion | completion | compl | */
566 /* `-----------------------------------------------------------------' */
567 void
568 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
570 size_t i;
571 int prompt_width, start_at;
572 int texty, textlen;
574 prompt_width = 20; /* TODO: calculate the correct amount of char to show */
576 start_at = r->x_zero + text_extents("n", 1, r, NULL, NULL);
577 start_at *= prompt_width;
578 start_at += r->padding;
580 texty = (inner_height(r) + r->ps1h + r->y_zero) / 2;
582 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, start_at, inner_height(r));
584 textlen = strlen(text);
585 if (textlen > prompt_width)
586 text = text + textlen - prompt_width;
588 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
589 draw_string(text, MIN(textlen, prompt_width), r->x_zero + r->padding + r->ps1w, texty, r, PROMPT);
591 XFillRectangle(r->d, r->w, r->bgs[1], start_at, r->y_zero, r->width, inner_height(r));
593 for (i = r->offset; i < cs->length; ++i) {
594 struct completion *c;
595 enum text_type tt;
596 GC h;
597 int len, text_width;
599 c = &cs->completions[i];
600 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
601 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
602 len = strlen(c->completion);
603 text_width = text_extents(c->completion, len, r, NULL, NULL);
605 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
606 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
608 start_at += text_width + r->padding * 2;
610 if (start_at > inner_width(r))
611 break; /* don't draw completion out of the window */
615 /* ,-----------------------------------------------------------------, */
616 /* | prompt | */
617 /* |-----------------------------------------------------------------| */
618 /* | completion | */
619 /* |-----------------------------------------------------------------| */
620 /* | completion | */
621 /* `-----------------------------------------------------------------' */
622 void
623 draw_vertically(struct rendering *r, char *text, struct completions *cs)
625 size_t i;
626 int height, start_at;
628 text_extents("fjpgl", 5, r, NULL, &height);
629 start_at = r->padding * 2 + height;
631 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, r->width, r->height);
632 XFillRectangle(r->d, r->w, r->bgs[0], r->x_zero, r->y_zero, r->width, start_at);
634 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
635 draw_string(text, strlen(text), r->x_zero + r->padding + r->ps1w, r->y_zero + height + r->padding, r, PROMPT);
637 start_at += r->y_zero;
639 for (i = r->offset; i < cs->length; ++i) {
640 struct completion *c;
641 enum text_type tt;
642 GC h;
643 int len;
645 c = &cs->completions[i];
646 tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
647 h = cs->selected == (ssize_t)i ? r->bgs[2] : r->bgs[1];
648 len = strlen(c->completion);
650 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
651 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
653 start_at += height + r->padding * 2;
655 if (start_at > inner_height(r))
656 break; /* don't draw completion out of the window */
660 void
661 draw(struct rendering *r, char *text, struct completions *cs)
663 if (r->horizontal_layout)
664 draw_horizontally(r, text, cs);
665 else
666 draw_vertically(r, text, cs);
668 /* Draw the borders */
669 if (r->borders[0] != 0)
670 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
672 if (r->borders[1] != 0)
673 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0, r->borders[1], r->height);
675 if (r->borders[2] != 0)
676 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width, r->borders[2]);
678 if (r->borders[3] != 0)
679 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
681 /* render! */
682 XFlush(r->d);
685 /* Set some WM stuff */
686 void
687 set_win_atoms_hints(Display *d, Window w, int width, int height)
689 Atom type;
690 XClassHint *class_hint;
691 XSizeHints *size_hint;
693 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
694 XChangeProperty(d,
695 w,
696 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
697 XInternAtom(d, "ATOM", 0),
698 32,
699 PropModeReplace,
700 (unsigned char *)&type,
702 );
704 /* some window managers honor this properties */
705 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
706 XChangeProperty(d,
707 w,
708 XInternAtom(d, "_NET_WM_STATE", 0),
709 XInternAtom(d, "ATOM", 0),
710 32,
711 PropModeReplace,
712 (unsigned char *)&type,
714 );
716 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
717 XChangeProperty(d,
718 w,
719 XInternAtom(d, "_NET_WM_STATE", 0),
720 XInternAtom(d, "ATOM", 0),
721 32,
722 PropModeAppend,
723 (unsigned char *)&type,
725 );
727 /* Setting window hints */
728 class_hint = XAllocClassHint();
729 if (class_hint == NULL) {
730 fprintf(stderr, "Could not allocate memory for class hint\n");
731 exit(EX_UNAVAILABLE);
734 class_hint->res_name = resname;
735 class_hint->res_class = resclass;
736 XSetClassHint(d, w, class_hint);
737 XFree(class_hint);
739 size_hint = XAllocSizeHints();
740 if (size_hint == NULL) {
741 fprintf(stderr, "Could not allocate memory for size hint\n");
742 exit(EX_UNAVAILABLE);
745 size_hint->flags = PMinSize | PBaseSize;
746 size_hint->min_width = width;
747 size_hint->base_width = width;
748 size_hint->min_height = height;
749 size_hint->base_height = height;
751 XFlush(d);
754 /* Get the width and height of the window `w' */
755 void
756 get_wh(Display *d, Window *w, int *width, int *height)
758 XWindowAttributes win_attr;
760 XGetWindowAttributes(d, *w, &win_attr);
761 *height = win_attr.height;
762 *width = win_attr.width;
765 int
766 grabfocus(Display *d, Window w)
768 int i;
769 for (i = 0; i < 100; ++i) {
770 Window focuswin;
771 int revert_to_win;
773 XGetInputFocus(d, &focuswin, &revert_to_win);
775 if (focuswin == w)
776 return 1;
778 XSetInputFocus(d, w, RevertToParent, CurrentTime);
779 usleep(1000);
781 return 0;
784 /*
785 * I know this may seem a little hackish BUT is the only way I managed
786 * to actually grab that goddam keyboard. Only one call to
787 * XGrabKeyboard does not always end up with the keyboard grabbed!
788 */
789 int
790 take_keyboard(Display *d, Window w)
792 int i;
793 for (i = 0; i < 100; i++) {
794 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
795 return 1;
796 usleep(1000);
798 fprintf(stderr, "Cannot grab keyboard\n");
799 return 0;
802 unsigned long
803 parse_color(const char *str, const char *def)
805 size_t len;
806 rgba_t tmp;
807 char *ep;
809 if (str == NULL)
810 goto invc;
812 len = strlen(str);
814 /* +1 for the # ath the start */
815 if (*str != '#' || len > 9 || len < 4)
816 goto invc;
817 ++str; /* skip the # */
819 errno = 0;
820 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
822 if (errno)
823 goto invc;
825 switch (len-1) {
826 case 3:
827 /* expand #rgb -> #rrggbb */
828 tmp.v = (tmp.v & 0xf00) * 0x1100
829 | (tmp.v & 0x0f0) * 0x0110
830 | (tmp.v & 0x00f) * 0x0011;
831 case 6:
832 /* assume 0xff opacity */
833 tmp.rgba.a = 0xff;
834 break;
835 } /* colors in #aarrggbb need no adjustments */
837 /* premultiply the alpha */
838 if (tmp.rgba.a) {
839 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
840 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
841 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
842 return tmp.v;
845 return 0U;
847 invc:
848 fprintf(stderr, "Invalid color: \"%s\".\n", str);
849 if (def != NULL)
850 return parse_color(def, NULL);
851 else
852 return 0U;
855 /*
856 * Given a string try to parse it as a number or return `default_value'.
857 */
858 int
859 parse_integer(const char *str, int default_value)
861 long lval;
862 char *ep;
864 errno = 0;
865 lval = strtol(str, &ep, 10);
867 if (str[0] == '\0' || *ep != '\0') { /* NaN */
868 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
869 return default_value;
872 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
873 (lval > INT_MAX || lval < INT_MIN)) {
874 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
875 return default_value;
878 return lval;
881 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
882 int
883 parse_int_with_percentage(const char *str, int default_value, int max)
885 int len = strlen(str);
887 if (len > 0 && str[len-1] == '%') {
888 int val;
889 char *cpy;
891 cpy = strdup(str);
892 check_allocation(cpy);
893 cpy[len-1] = '\0';
894 val = parse_integer(cpy, default_value);
895 free(cpy);
896 return val * max / 100;
899 return parse_integer(str, default_value);
902 /*
903 * Like parse_int_with_percentage but understands some special values:
904 * - middle that is (max-self)/2
905 * - start that is 0
906 * - end that is (max-self)
907 */
908 int
909 parse_int_with_pos(const char *str, int default_value, int max, int self)
911 if (!strcmp(str, "start"))
912 return 0;
913 if (!strcmp(str, "middle"))
914 return (max - self)/2;
915 if (!strcmp(str, "end"))
916 return max-self;
917 return parse_int_with_percentage(str, default_value, max);
920 /* Parse a string like a CSS value. */
921 /* TODO: harden a bit this function */
922 char **
923 parse_csslike(const char *str)
925 int i, j;
926 char *s, *token, **ret;
927 short any_null;
929 s = strdup(str);
930 if (s == NULL)
931 return NULL;
933 ret = malloc(4 * sizeof(char*));
934 if (ret == NULL) {
935 free(s);
936 return NULL;
939 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
940 ret[i] = strdup(token);
942 if (i == 1)
943 for (j = 1; j < 4; j++)
944 ret[j] = strdup(ret[0]);
946 if (i == 2) {
947 ret[2] = strdup(ret[0]);
948 ret[3] = strdup(ret[1]);
951 if (i == 3)
952 ret[3] = strdup(ret[1]);
954 /* before we didn't check for the return type of strdup, here we will */
956 any_null = 0;
957 for (i = 0; i < 4; ++i)
958 any_null = ret[i] == NULL || any_null;
960 if (any_null)
961 for (i = 0; i < 4; ++i)
962 if (ret[i] != NULL)
963 free(ret[i]);
965 if (i == 0 || any_null) {
966 free(s);
967 free(ret);
968 return NULL;
971 return ret;
974 /*
975 * Given an event, try to understand what the users wants. If the
976 * return value is ADD_CHAR then `input' is a pointer to a string that
977 * will need to be free'ed later.
978 */
979 enum
980 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
982 char str[SYM_BUF_SIZE] = {0};
983 Status s;
985 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
986 return DEL_CHAR;
988 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
989 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
991 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
992 return CONFIRM;
994 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
995 return EXIT;
997 /* Try to read what key was pressed */
998 s = 0;
999 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1000 if (s == XBufferOverflow) {
1001 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1002 return EXIT;
1005 if (ev->state & ControlMask) {
1006 if (!strcmp(str, "")) /* C-u */
1007 return DEL_LINE;
1008 if (!strcmp(str, "")) /* C-w */
1009 return DEL_WORD;
1010 if (!strcmp(str, "")) /* C-h */
1011 return DEL_CHAR;
1012 if (!strcmp(str, "\r")) /* C-m */
1013 return CONFIRM_CONTINUE;
1014 if (!strcmp(str, "")) /* C-p */
1015 return PREV_COMPL;
1016 if (!strcmp(str, "")) /* C-n */
1017 return NEXT_COMPL;
1018 if (!strcmp(str, "")) /* C-c */
1019 return EXIT;
1020 if (!strcmp(str, "\t")) /* C-i */
1021 return TOGGLE_FIRST_SELECTED;
1024 *input = strdup(str);
1025 if (*input == NULL) {
1026 fprintf(stderr, "Error while allocating memory for key.\n");
1027 return EXIT;
1030 return ADD_CHAR;
1033 void
1034 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1036 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1037 /* if there is something selected expand it and return */
1038 int index = cs->selected == -1 ? 0 : cs->selected;
1039 struct completion *c = cs->completions;
1040 char *t;
1042 while (1) {
1043 if (index == 0)
1044 break;
1045 c++;
1046 index--;
1049 t = c->rcompletion;
1050 free(*text);
1051 *text = strdup(t);
1053 if (*text == NULL) {
1054 fprintf(stderr, "Memory allocation error\n");
1055 *status = ERR;
1058 *textlen = strlen(*text);
1059 return;
1062 if (!r->free_text) /* cannot accept arbitrary text */
1063 *status = LOOPING;
1066 /* event loop */
1067 enum state
1068 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1070 enum state status = LOOPING;
1072 while (status == LOOPING) {
1073 XEvent e;
1074 XNextEvent(r->d, &e);
1076 if (XFilterEvent(&e, r->w))
1077 continue;
1079 switch (e.type) {
1080 case KeymapNotify:
1081 XRefreshKeyboardMapping(&e.xmapping);
1082 break;
1084 case FocusIn:
1085 /* Re-grab focus */
1086 if (e.xfocus.window != r->w)
1087 grabfocus(r->d, r->w);
1088 break;
1090 case VisibilityNotify:
1091 if (e.xvisibility.state != VisibilityUnobscured)
1092 XRaiseWindow(r->d, r->w);
1093 break;
1095 case MapNotify:
1096 get_wh(r->d, &r->w, &r->width, &r->height);
1097 draw(r, *text, cs);
1098 break;
1100 case KeyPress: {
1101 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1102 char *input;
1104 switch (parse_event(r->d, ev, r->xic, &input)) {
1105 case EXIT:
1106 status = ERR;
1107 break;
1109 case CONFIRM: {
1110 status = OK;
1111 confirm(&status, r, cs, text, textlen);
1112 break;
1115 case CONFIRM_CONTINUE: {
1116 status = OK_LOOP;
1117 confirm(&status, r, cs, text, textlen);
1118 break;
1121 case PREV_COMPL: {
1122 complete(cs, r->first_selected, 1, text, textlen, &status);
1123 r->offset = cs->selected;
1124 break;
1127 case NEXT_COMPL: {
1128 complete(cs, r->first_selected, 0, text, textlen, &status);
1129 r->offset = cs->selected;
1130 break;
1133 case DEL_CHAR:
1134 popc(*text);
1135 update_completions(cs, *text, lines, vlines, r->first_selected);
1136 r->offset = 0;
1137 break;
1139 case DEL_WORD: {
1140 popw(*text);
1141 update_completions(cs, *text, lines, vlines, r->first_selected);
1142 break;
1145 case DEL_LINE: {
1146 int i;
1147 for (i = 0; i < *textlen; ++i)
1148 *(*text + i) = 0;
1149 update_completions(cs, *text, lines, vlines, r->first_selected);
1150 r->offset = 0;
1151 break;
1154 case ADD_CHAR: {
1155 int str_len, i;
1157 str_len = strlen(input);
1160 * sometimes a strange key is pressed
1161 * i.e. ctrl alone), so input will be
1162 * empty. Don't need to update
1163 * completion in that case
1165 if (str_len == 0)
1166 break;
1168 for (i = 0; i < str_len; ++i) {
1169 *textlen = pushc(text, *textlen, input[i]);
1170 if (*textlen == -1) {
1171 fprintf(stderr, "Memory allocation error\n");
1172 status = ERR;
1173 break;
1177 if (status != ERR) {
1178 update_completions(cs, *text, lines, vlines, r->first_selected);
1179 free(input);
1182 r->offset = 0;
1183 break;
1186 case TOGGLE_FIRST_SELECTED:
1187 r->first_selected = !r->first_selected;
1188 if (r->first_selected && cs->selected < 0)
1189 cs->selected = 0;
1190 if (!r->first_selected && cs->selected == 0)
1191 cs->selected = -1;
1192 break;
1196 case ButtonPress: {
1197 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1198 /* if (ev->button == Button1) { /\* click *\/ */
1199 /* int x = ev->x - r.border_w; */
1200 /* int y = ev->y - r.border_n; */
1201 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1202 /* } */
1204 if (ev->button == Button4) /* scroll up */
1205 r->offset = MAX((ssize_t)r->offset - 1, 0);
1207 if (ev->button == Button5) /* scroll down */
1208 r->offset = MIN(r->offset + 1, cs->length - 1);
1210 break;
1214 draw(r, *text, cs);
1217 return status;
1220 int
1221 load_font(struct rendering *r, const char *fontname)
1223 #ifdef USE_XFT
1224 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1225 return 0;
1226 #else
1227 char **missing_charset_list;
1228 int missing_charset_count;
1230 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1231 if (r->font != NULL)
1232 return 0;
1234 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1236 if (!strcmp(fontname, default_fontname))
1237 return -1;
1239 return load_font(r, default_fontname);
1240 #endif
1243 void
1244 xim_init(struct rendering *r, XrmDatabase *xdb)
1246 XIM xim;
1247 XIMStyle best_match_style;
1248 XIMStyles *xis;
1249 int i;
1251 /* Open the X input method */
1252 xim = XOpenIM(r->d, *xdb, resname, resclass);
1253 check_allocation(xim);
1255 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1256 fprintf(stderr, "Input Styles could not be retrieved\n");
1257 exit(EX_UNAVAILABLE);
1260 best_match_style = 0;
1261 for (i = 0; i < xis->count_styles; ++i) {
1262 XIMStyle ts = xis->supported_styles[i];
1263 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1264 best_match_style = ts;
1265 break;
1268 XFree(xis);
1270 if (!best_match_style)
1271 fprintf(stderr, "No matching input style could be determined\n");
1273 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1274 check_allocation(r->xic);
1277 void
1278 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1280 XSetWindowAttributes attr;
1282 /* Create the window */
1283 attr.colormap = cmap;
1284 attr.override_redirect = 1;
1285 attr.border_pixel = 0;
1286 attr.background_pixel = 0x80808080;
1287 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1289 r->w = XCreateWindow(r->d,
1290 parent_window,
1291 x + ox, y + oy,
1292 r->width, r->height,
1294 vinfo.depth,
1295 InputOutput,
1296 vinfo.visual,
1297 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1298 &attr);
1301 void
1302 ps1extents(struct rendering *r)
1304 char *dup;
1305 dup = strdupn(r->ps1);
1306 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1307 free(dup);
1310 void
1311 usage(char *prgname)
1313 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
1314 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
1315 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
1316 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
1319 int
1320 main(int argc, char **argv)
1322 struct completions *cs;
1323 struct rendering r;
1324 XVisualInfo vinfo;
1325 Colormap cmap;
1326 size_t nlines, i;
1327 Window parent_window;
1328 XrmDatabase xdb;
1329 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1330 unsigned long borders_bg[4]; /* N E S W */
1331 enum state status;
1332 int ch;
1333 int offset_x, offset_y, x, y;
1334 int textlen, d_width, d_height;
1335 short embed;
1336 char *sep, *parent_window_id;
1337 char **lines, *buf, **vlines;
1338 char *fontname, *text, *xrm;
1340 #ifdef __OpenBSD__
1341 /* stdio & rpath: to read/write stdio/stdout/stderr */
1342 /* unix: to connect to XOrg */
1343 pledge("stdio rpath unix", "");
1344 #endif
1346 sep = NULL;
1347 parent_window_id = NULL;
1349 r.first_selected = 0;
1350 r.free_text = 1;
1351 r.multiple_select = 0;
1352 r.offset = 0;
1354 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1355 switch (ch) {
1356 case 'h': /* help */
1357 usage(*argv);
1358 return 0;
1359 case 'v': /* version */
1360 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1361 return 0;
1362 case 'e': /* embed */
1363 parent_window_id = strdup(optarg);
1364 check_allocation(parent_window_id);
1365 break;
1366 case 'd':
1367 sep = strdup(optarg);
1368 check_allocation(sep);
1369 case 'A':
1370 r.free_text = 0;
1371 break;
1372 case 'm':
1373 r.multiple_select = 1;
1374 break;
1375 default:
1376 break;
1380 /* Read the completions */
1381 lines = NULL;
1382 buf = NULL;
1383 nlines = readlines(&lines, &buf);
1385 vlines = NULL;
1386 if (sep != NULL) {
1387 int l;
1388 l = strlen(sep);
1389 vlines = calloc(nlines, sizeof(char*));
1390 check_allocation(vlines);
1392 for (i = 0; i < nlines; i++) {
1393 char *t;
1394 t = strstr(lines[i], sep);
1395 if (t == NULL)
1396 vlines[i] = lines[i];
1397 else
1398 vlines[i] = t + l;
1402 setlocale(LC_ALL, getenv("LANG"));
1404 status = LOOPING;
1406 /* where the monitor start (used only with xinerama) */
1407 offset_x = offset_y = 0;
1409 /* default width and height */
1410 r.width = 400;
1411 r.height = 20;
1413 /* default position on the screen */
1414 x = y = 0;
1416 /* default padding */
1417 r.padding = 10;
1419 /* default borders */
1420 r.borders[0] = r.borders[1] = r.borders[2] = r.borders[3] = 0;
1422 /* the prompt. We duplicate the string so later is easy to
1423 * free (in the case it's been overwritten by the user) */
1424 r.ps1 = strdup("$ ");
1425 check_allocation(r.ps1);
1427 /* same for the font name */
1428 fontname = strdup(default_fontname);
1429 check_allocation(fontname);
1431 textlen = 10;
1432 text = malloc(textlen * sizeof(char));
1433 check_allocation(text);
1435 /* struct completions *cs = filter(text, lines); */
1436 cs = compls_new(nlines);
1437 check_allocation(cs);
1439 /* start talking to xorg */
1440 r.d = XOpenDisplay(NULL);
1441 if (r.d == NULL) {
1442 fprintf(stderr, "Could not open display!\n");
1443 return EX_UNAVAILABLE;
1446 embed = 1;
1447 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1448 parent_window = DefaultRootWindow(r.d);
1449 embed = 0;
1452 /* get display size */
1453 get_wh(r.d, &parent_window, &d_width, &d_height);
1455 #ifdef USE_XINERAMA
1456 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1457 XineramaScreenInfo *info;
1458 Window rr;
1459 Window root;
1460 int number_of_screens, monitors, i;
1461 int root_x, root_y, win_x, win_y;
1462 unsigned int mask;
1463 short res;
1465 number_of_screens = XScreenCount(r.d);
1466 for (i = 0; i < number_of_screens; ++i) {
1467 root = XRootWindow(r.d, i);
1468 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1469 if (res)
1470 break;
1473 if (!res) {
1474 fprintf(stderr, "No mouse found.\n");
1475 root_x = 0;
1476 root_y = 0;
1479 /* Now find in which monitor the mice is */
1480 info = XineramaQueryScreens(r.d, &monitors);
1481 if (info) {
1482 for (i = 0; i < monitors; ++i) {
1483 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1484 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1485 offset_x = info[i].x_org;
1486 offset_y = info[i].y_org;
1487 d_width = info[i].width;
1488 d_height = info[i].height;
1489 break;
1493 XFree(info);
1495 #endif
1497 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1498 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1500 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1501 fgs[2] = parse_color("#000", NULL);
1503 bgs[0] = bgs[1] = parse_color("#000", NULL);
1504 bgs[2] = parse_color("#fff", NULL);
1506 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1508 r.horizontal_layout = 1;
1510 /* Read the resources */
1511 XrmInitialize();
1512 xrm = XResourceManagerString(r.d);
1513 xdb = NULL;
1514 if (xrm != NULL) {
1515 XrmValue value;
1516 char *datatype[20];
1518 xdb = XrmGetStringDatabase(xrm);
1520 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1521 free(fontname);
1522 fontname = strdup(value.addr);
1523 check_allocation(fontname);
1524 } else {
1525 fprintf(stderr, "no font defined, using %s\n", fontname);
1528 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1529 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1530 else
1531 fprintf(stderr, "no layout defined, using horizontal\n");
1533 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1534 free(r.ps1);
1535 r.ps1 = normalize_str(value.addr);
1536 } else {
1537 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1540 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1541 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1542 else
1543 fprintf(stderr, "no width defined, using %d\n", r.width);
1545 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1546 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1547 else
1548 fprintf(stderr, "no height defined, using %d\n", r.height);
1550 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1551 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1552 else
1553 fprintf(stderr, "no x defined, using %d\n", x);
1555 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1556 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1557 else
1558 fprintf(stderr, "no y defined, using %d\n", y);
1560 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == 1)
1561 r.padding = parse_integer(value.addr, r.padding);
1562 else
1563 fprintf(stderr, "no padding defined, using %d\n", r.padding);
1565 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1566 char **borders;
1568 borders = parse_csslike(value.addr);
1569 if (borders != NULL) {
1570 r.borders[0] = parse_integer(borders[0], 0);
1571 r.borders[1] = parse_integer(borders[1], 0);
1572 r.borders[2] = parse_integer(borders[2], 0);
1573 r.borders[3] = parse_integer(borders[3], 0);
1574 } else
1575 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1576 } else
1577 fprintf(stderr, "no border defined, using 0.\n");
1579 /* Prompt */
1580 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1581 fgs[0] = parse_color(value.addr, "#fff");
1583 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1584 bgs[0] = parse_color(value.addr, "#000");
1586 /* Completions */
1587 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1588 fgs[1] = parse_color(value.addr, "#fff");
1590 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1591 bgs[1] = parse_color(value.addr, "#000");
1593 /* Completion Highlighted */
1594 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1595 fgs[2] = parse_color(value.addr, "#000");
1597 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1598 bgs[2] = parse_color(value.addr, "#fff");
1600 /* Border */
1601 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1602 char **colors;
1603 colors = parse_csslike(value.addr);
1604 if (colors != NULL) {
1605 borders_bg[0] = parse_color(colors[0], "#000");
1606 borders_bg[1] = parse_color(colors[1], "#000");
1607 borders_bg[2] = parse_color(colors[2], "#000");
1608 borders_bg[3] = parse_color(colors[3], "#000");
1609 } else
1610 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1614 /* Second round of args parsing */
1615 optind = 0; /* reset the option index */
1616 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1617 switch (ch) {
1618 case 'a':
1619 r.first_selected = 1;
1620 break;
1621 case 'A':
1622 /* free_text -- already catched */
1623 case 'd':
1624 /* separator -- this case was already catched */
1625 case 'e':
1626 /* embedding mymenu this case was already catched. */
1627 case 'm':
1628 /* multiple selection this case was already catched. */
1629 break;
1630 case 'p': {
1631 char *newprompt;
1632 newprompt = strdup(optarg);
1633 if (newprompt != NULL) {
1634 free(r.ps1);
1635 r.ps1 = newprompt;
1637 break;
1639 case 'x':
1640 x = parse_int_with_pos(optarg, x, d_width, r.width);
1641 break;
1642 case 'y':
1643 y = parse_int_with_pos(optarg, y, d_height, r.height);
1644 break;
1645 case 'P':
1646 r.padding = parse_integer(optarg, r.padding);
1647 break;
1648 case 'l':
1649 r.horizontal_layout = !strcmp(optarg, "horizontal");
1650 break;
1651 case 'f': {
1652 char *newfont;
1653 if ((newfont = strdup(optarg)) != NULL) {
1654 free(fontname);
1655 fontname = newfont;
1657 break;
1659 case 'W':
1660 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1661 break;
1662 case 'H':
1663 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1664 break;
1665 case 'b': {
1666 char **borders;
1667 if ((borders = parse_csslike(optarg)) != NULL) {
1668 r.borders[0] = parse_integer(borders[0], 0);
1669 r.borders[1] = parse_integer(borders[1], 0);
1670 r.borders[2] = parse_integer(borders[2], 0);
1671 r.borders[3] = parse_integer(borders[3], 0);
1672 } else
1673 fprintf(stderr, "Error parsing b option\n");
1674 break;
1676 case 'B': {
1677 char **colors;
1678 if ((colors = parse_csslike(optarg)) != NULL) {
1679 borders_bg[0] = parse_color(colors[0], "#000");
1680 borders_bg[1] = parse_color(colors[1], "#000");
1681 borders_bg[2] = parse_color(colors[2], "#000");
1682 borders_bg[3] = parse_color(colors[3], "#000");
1683 } else
1684 fprintf(stderr, "error while parsing B option\n");
1685 break;
1687 case 't':
1688 fgs[0] = parse_color(optarg, NULL);
1689 break;
1690 case 'T':
1691 bgs[0] = parse_color(optarg, NULL);
1692 break;
1693 case 'c':
1694 fgs[1] = parse_color(optarg, NULL);
1695 break;
1696 case 'C':
1697 bgs[1] = parse_color(optarg, NULL);
1698 break;
1699 case 's':
1700 fgs[2] = parse_color(optarg, NULL);
1701 break;
1702 case 'S':
1703 fgs[2] = parse_color(optarg, NULL);
1704 break;
1705 default:
1706 fprintf(stderr, "Unrecognized option %c\n", ch);
1707 status = ERR;
1708 break;
1712 /* since only now we know if the first should be selected,
1713 * update the completion here */
1714 update_completions(cs, text, lines, vlines, r.first_selected);
1716 /* update the prompt lenght, only now we surely know the length of it */
1717 r.ps1len = strlen(r.ps1);
1719 /* Create the window */
1720 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1721 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1722 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1723 XMapRaised(r.d, r.w);
1725 /* If embed, listen for other events as well */
1726 if (embed) {
1727 Window *children, parent, root;
1728 unsigned int children_no;
1730 XSelectInput(r.d, parent_window, FocusChangeMask);
1731 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1732 for (i = 0; i < children_no && children[i] != r.w; ++i)
1733 XSelectInput(r.d, children[i], FocusChangeMask);
1734 XFree(children);
1736 grabfocus(r.d, r.w);
1739 take_keyboard(r.d, r.w);
1741 r.x_zero = r.borders[3];
1742 r.y_zero = r.borders[0];
1745 XGCValues values;
1747 r.fgs[0] = XCreateGC(r.d, r.w, 0, &values),
1748 r.fgs[1] = XCreateGC(r.d, r.w, 0, &values),
1749 r.fgs[2] = XCreateGC(r.d, r.w, 0, &values),
1750 r.bgs[0] = XCreateGC(r.d, r.w, 0, &values),
1751 r.bgs[1] = XCreateGC(r.d, r.w, 0, &values),
1752 r.bgs[2] = XCreateGC(r.d, r.w, 0, &values),
1753 r.borders_bg[0] = XCreateGC(r.d, r.w, 0, &values);
1754 r.borders_bg[1] = XCreateGC(r.d, r.w, 0, &values);
1755 r.borders_bg[2] = XCreateGC(r.d, r.w, 0, &values);
1756 r.borders_bg[3] = XCreateGC(r.d, r.w, 0, &values);
1759 if (load_font(&r, fontname) == -1)
1760 status = ERR;
1762 #ifdef USE_XFT
1763 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, DefaultColormap(r.d, 0));
1766 rgba_t c;
1767 XRenderColor xrcolor;
1769 /* Prompt */
1770 c = *(rgba_t*)&fgs[0];
1771 xrcolor.red = EXPANDBITS(c.rgba.r);
1772 xrcolor.green = EXPANDBITS(c.rgba.g);
1773 xrcolor.blue = EXPANDBITS(c.rgba.b);
1774 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1775 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[0]);
1777 /* Completion */
1778 c = *(rgba_t*)&fgs[1];
1779 xrcolor.red = EXPANDBITS(c.rgba.r);
1780 xrcolor.green = EXPANDBITS(c.rgba.g);
1781 xrcolor.blue = EXPANDBITS(c.rgba.b);
1782 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1783 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[1]);
1785 /* Completion highlighted */
1786 c = *(rgba_t*)&fgs[2];
1787 xrcolor.red = EXPANDBITS(c.rgba.r);
1788 xrcolor.green = EXPANDBITS(c.rgba.g);
1789 xrcolor.blue = EXPANDBITS(c.rgba.b);
1790 xrcolor.alpha = EXPANDBITS(c.rgba.a);
1791 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[2]);
1793 #endif
1795 /* Load the colors in our GCs */
1796 XSetForeground(r.d, r.fgs[0], fgs[0]);
1797 XSetForeground(r.d, r.bgs[0], bgs[0]);
1798 XSetForeground(r.d, r.fgs[1], fgs[1]);
1799 XSetForeground(r.d, r.bgs[1], bgs[1]);
1800 XSetForeground(r.d, r.fgs[2], fgs[2]);
1801 XSetForeground(r.d, r.bgs[2], bgs[2]);
1802 XSetForeground(r.d, r.borders_bg[0], borders_bg[0]);
1803 XSetForeground(r.d, r.borders_bg[1], borders_bg[1]);
1804 XSetForeground(r.d, r.borders_bg[2], borders_bg[2]);
1805 XSetForeground(r.d, r.borders_bg[3], borders_bg[3]);
1807 /* compute prompt dimensions */
1808 ps1extents(&r);
1810 xim_init(&r, &xdb);
1812 #ifdef __OpenBSD__
1813 /* Now we need only the ability to write */
1814 pledge("stdio", "");
1815 #endif
1817 /* Draw the window for the first time */
1818 draw(&r, text, cs);
1820 /* Main loop */
1821 while (status == LOOPING || status == OK_LOOP) {
1822 status = loop(&r, &text, &textlen, cs, lines, vlines);
1824 if (status != ERR)
1825 printf("%s\n", text);
1827 if (!r.multiple_select && status == OK_LOOP)
1828 status = OK;
1831 XUngrabKeyboard(r.d, CurrentTime);
1833 #ifdef USE_XFT
1834 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[0]);
1835 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[1]);
1836 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[2]);
1837 #endif
1839 free(r.ps1);
1840 free(fontname);
1841 free(text);
1843 free(buf);
1844 free(lines);
1845 free(vlines);
1846 compls_delete(cs);
1848 XDestroyWindow(r.d, r.w);
1849 XCloseDisplay(r.d);
1851 return status != OK;