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:G:g:I:i:J:j:"
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 obj_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 XIM xim;
103 int width;
104 int height;
105 int p_padding[4];
106 int c_padding[4];
107 int ch_padding[4];
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];
119 int p_borders[4];
120 int c_borders[4];
121 int ch_borders[4];
123 short horizontal_layout;
125 /* prompt */
126 char *ps1;
127 int ps1len;
128 int ps1w; /* ps1 width */
129 int ps1h; /* ps1 height */
131 int text_height; /* cache for the vertical layout */
133 XIC xic;
135 /* colors */
136 GC fgs[4];
137 GC bgs[4];
138 GC borders_bg[4];
139 GC p_borders_bg[4];
140 GC c_borders_bg[4];
141 GC ch_borders_bg[4];
142 #ifdef USE_XFT
143 XftFont *font;
144 XftDraw *xftdraw;
145 XftColor xft_colors[3];
146 #else
147 XFontSet font;
148 #endif
149 };
151 struct completion {
152 char *completion;
153 char *rcompletion;
154 };
156 /* Wrap the linked list of completions */
157 struct completions {
158 struct completion *completions;
159 ssize_t selected;
160 size_t length;
161 };
163 /* idea stolen from lemonbar. ty lemonboy */
164 typedef union {
165 struct {
166 uint8_t b;
167 uint8_t g;
168 uint8_t r;
169 uint8_t a;
170 } rgba;
171 uint32_t v;
172 } rgba_t;
174 extern char *optarg;
175 extern int optind;
177 /* Return a newly allocated (and empty) completion list */
178 struct completions *
179 compls_new(size_t length)
181 struct completions *cs = malloc(sizeof(struct completions));
183 if (cs == NULL)
184 return cs;
186 cs->completions = calloc(length, sizeof(struct completion));
187 if (cs->completions == NULL) {
188 free(cs);
189 return NULL;
192 cs->selected = -1;
193 cs->length = length;
194 return cs;
197 /* Delete the wrapper and the whole list */
198 void
199 compls_delete(struct completions *cs)
201 if (cs == NULL)
202 return;
204 free(cs->completions);
205 free(cs);
208 /*
209 * Create a completion list from a text and the list of possible
210 * completions (null terminated). Expects a non-null `cs'. `lines' and
211 * `vlines' should have the same length OR `vlines' is NULL.
212 */
213 void
214 filter(struct completions *cs, char *text, char **lines, char **vlines)
216 size_t index = 0;
217 size_t matching = 0;
218 char *l;
220 if (vlines == NULL)
221 vlines = lines;
223 while (1) {
224 if (lines[index] == NULL)
225 break;
227 l = vlines[index] != NULL ? vlines[index] : lines[index];
229 if (strcasestr(l, text) != NULL) {
230 struct completion *c = &cs->completions[matching];
231 c->completion = l;
232 c->rcompletion = lines[index];
233 matching++;
236 index++;
238 cs->length = matching;
239 cs->selected = -1;
242 /* Update the given completion */
243 void
244 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
246 filter(cs, text, lines, vlines);
247 if (first_selected && cs->length > 0)
248 cs->selected = 0;
251 /*
252 * Select the next or previous selection and update some state. `text'
253 * will be updated with the text of the completion and `textlen' with
254 * the new length. If the memory cannot be allocated `status' will be
255 * set to `ERR'.
256 */
257 void
258 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
260 struct completion *n;
261 int index;
263 if (cs == NULL || cs->length == 0)
264 return;
266 /*
267 * If the first is always selected and the first entry is
268 * different from the text, expand the text and return
269 */
270 if (first_selected
271 && cs->selected == 0
272 && strcmp(cs->completions->completion, *text) != 0
273 && !p) {
274 free(*text);
275 *text = strdup(cs->completions->completion);
276 if (text == NULL) {
277 *status = ERR;
278 return;
280 *textlen = strlen(*text);
281 return;
284 index = cs->selected;
286 if (index == -1 && p)
287 index = 0;
288 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
290 n = &cs->completions[cs->selected];
292 free(*text);
293 *text = strdup(n->completion);
294 if (text == NULL) {
295 fprintf(stderr, "Memory allocation error!\n");
296 *status = ERR;
297 return;
299 *textlen = strlen(*text);
302 /* Push the character c at the end of the string pointed by p */
303 int
304 pushc(char **p, int maxlen, char c)
306 int len;
308 len = strnlen(*p, maxlen);
309 if (!(len < maxlen -2)) {
310 char *newptr;
312 maxlen += maxlen >> 1;
313 newptr = realloc(*p, maxlen);
314 if (newptr == NULL) /* bad */
315 return -1;
316 *p = newptr;
319 (*p)[len] = c;
320 (*p)[len+1] = '\0';
321 return maxlen;
324 /*
325 * Remove the last rune from the *UTF-8* string! This is different
326 * from just setting the last byte to 0 (in some cases ofc). Return a
327 * pointer (e) to the last nonzero char. If e < p then p is empty!
328 */
329 char *
330 popc(char *p)
332 int len = strlen(p);
333 char *e;
335 if (len == 0)
336 return p;
338 e = p + len - 1;
340 do {
341 char c = *e;
343 *e = '\0';
344 e -= 1;
346 /*
347 * If c is a starting byte (11......) or is under
348 * U+007F we're done.
349 */
350 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
351 break;
352 } while (e >= p);
354 return e;
357 /* Remove the last word plus trailing white spaces from the given string */
358 void
359 popw(char *w)
361 int len;
362 short in_word = 1;
364 if ((len = strlen(w)) == 0)
365 return;
367 while (1) {
368 char *e = popc(w);
370 if (e < w)
371 return;
373 if (in_word && isspace(*e))
374 in_word = 0;
376 if (!in_word && !isspace(*e))
377 return;
381 /*
382 * If the string is surrounded by quates (`"') remove them and replace
383 * every `\"' in the string with a single double-quote.
384 */
385 char *
386 normalize_str(const char *str)
388 int len, p;
389 char *s;
391 if ((len = strlen(str)) == 0)
392 return NULL;
394 s = calloc(len, sizeof(char));
395 check_allocation(s);
396 p = 0;
398 while (*str) {
399 char c = *str;
401 if (*str == '\\') {
402 if (*(str + 1)) {
403 s[p] = *(str + 1);
404 p++;
405 str += 2; /* skip this and the next char */
406 continue;
407 } else
408 break;
410 if (c == '"') {
411 str++; /* skip only this char */
412 continue;
414 s[p] = c;
415 p++;
416 str++;
419 return s;
422 size_t
423 read_stdin(char **buf)
425 size_t offset = 0;
426 size_t len = STDIN_CHUNKS;
428 *buf = malloc(len * sizeof(char));
429 if (*buf == NULL)
430 goto err;
432 while (1) {
433 ssize_t r;
434 size_t i;
436 r = read(0, *buf + offset, STDIN_CHUNKS);
438 if (r < 1)
439 return len;
441 offset += r;
443 len += STDIN_CHUNKS;
444 *buf = realloc(*buf, len);
445 if (*buf == NULL)
446 goto err;
448 for (i = offset; i < len; ++i)
449 (*buf)[i] = '\0';
452 err:
453 fprintf(stderr, "Error in allocating memory for stdin.\n");
454 exit(EX_UNAVAILABLE);
457 size_t
458 readlines(char ***lns, char **buf)
460 size_t i, len, ll, lines;
461 short in_line = 0;
463 lines = 0;
465 *buf = NULL;
466 len = read_stdin(buf);
468 ll = LINES_CHUNK;
469 *lns = malloc(ll * sizeof(char*));
471 if (*lns == NULL)
472 goto err;
474 for (i = 0; i < len; i++) {
475 char c = (*buf)[i];
477 if (c == '\0')
478 break;
480 if (c == '\n')
481 (*buf)[i] = '\0';
483 if (in_line && c == '\n')
484 in_line = 0;
486 if (!in_line && c != '\n') {
487 in_line = 1;
488 (*lns)[lines] = (*buf) + i;
489 lines++;
491 if (lines == ll) { /* resize */
492 ll += LINES_CHUNK;
493 *lns = realloc(*lns, ll * sizeof(char*));
494 if (*lns == NULL)
495 goto err;
500 (*lns)[lines] = NULL;
502 return lines;
504 err:
505 fprintf(stderr, "Error in memory allocation.\n");
506 exit(EX_UNAVAILABLE);
509 /*
510 * Compute the dimensions of the string str once rendered.
511 * It'll return the width and set ret_width and ret_height if not NULL
512 */
513 int
514 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
516 int height, width;
517 #ifdef USE_XFT
518 XGlyphInfo gi;
519 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
520 height = r->font->ascent - r->font->descent;
521 width = gi.width - gi.x;
522 #else
523 XRectangle rect;
524 XmbTextExtents(r->font, str, len, NULL, &rect);
525 height = rect.height;
526 width = rect.width;
527 #endif
528 if (ret_width != NULL) *ret_width = width;
529 if (ret_height != NULL) *ret_height = height;
530 return width;
533 void
534 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
536 #ifdef USE_XFT
537 XftColor xftcolor;
538 if (tt == PROMPT) xftcolor = r->xft_colors[0];
539 if (tt == COMPL) xftcolor = r->xft_colors[1];
540 if (tt == COMPL_HIGH) xftcolor = r->xft_colors[2];
542 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
543 #else
544 GC gc;
545 if (tt == PROMPT) gc = r->fgs[0];
546 if (tt == COMPL) gc = r->fgs[1];
547 if (tt == COMPL_HIGH) gc = r->fgs[2];
548 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
549 #endif
552 /* Duplicate the string and substitute every space with a 'n` */
553 char *
554 strdupn(char *str)
556 int len, i;
557 char *dup;
559 len = strlen(str);
561 if (str == NULL || len == 0)
562 return NULL;
564 if ((dup = strdup(str)) == NULL)
565 return NULL;
567 for (i = 0; i < len; ++i)
568 if (dup[i] == ' ')
569 dup[i] = 'n';
571 return dup;
574 int
575 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
577 GC *border_color, bg;
578 int *padding, *borders;
579 int ret = 0, inner_width, inner_height, x;
581 switch (t) {
582 case PROMPT:
583 border_color = r->p_borders_bg;
584 padding = r->p_padding;
585 borders = r->p_borders;
586 bg = r->bgs[0];
587 break;
588 case COMPL:
589 border_color = r->c_borders_bg;
590 padding = r->c_padding;
591 borders = r->c_borders;
592 bg = r->bgs[1];
593 break;
594 case COMPL_HIGH:
595 border_color = r->ch_borders_bg;
596 padding = r->ch_padding;
597 borders = r->ch_borders;
598 bg = r->bgs[2];
599 break;
602 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
604 inner_width = inner_width(r) - borders[1] - borders[3];
605 inner_height = padding[0] + r->text_height + padding[2];
607 /* Border top */
608 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
610 /* Border right */
611 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1] , y, borders[1], ret);
613 /* Border bottom */
614 XFillRectangle(r->d, r->w, border_color[2], r->x_zero, y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
616 /* Border left */
617 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
619 /* bg */
620 x = r->x_zero + borders[3];
621 y += borders[0];
622 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
624 /* content */
625 y += padding[0] + r->text_height;
626 x += padding[3];
627 if (prefix != NULL) {
628 draw_string(prefix, strlen(prefix), x, y, r, t);
629 x += prefix_width;
631 draw_string(text, strlen(text), x, y, r, t);
633 return ret;
636 int
637 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
639 GC *border_color, bg;
640 int *padding, *borders;
641 int ret = 0, inner_width, inner_height, y, text_width;
643 switch (t) {
644 case PROMPT:
645 border_color = r->p_borders_bg;
646 padding = r->p_padding;
647 borders = r->p_borders;
648 bg = r->bgs[0];
649 break;
650 case COMPL:
651 border_color = r->c_borders_bg;
652 padding = r->c_padding;
653 borders = r->c_borders;
654 bg = r->bgs[1];
655 break;
656 case COMPL_HIGH:
657 border_color = r->ch_borders_bg;
658 padding = r->ch_padding;
659 borders = r->ch_borders;
660 bg = r->bgs[2];
661 break;
664 if (padding[0] < 0 || padding[2] < 0)
665 padding[0] = padding[2] = (inner_height(r) - borders[0] - borders[2] - r->text_height)/2;
667 /* If they are still lesser than 0, set 'em to 0 */
668 if (padding[0] < 0 || padding[2] < 0)
669 padding[0] = padding[2] = 0;
671 /* Get the text width */
672 text_extents(text, strlen(text), r, &text_width, NULL);
673 if (prefix != NULL)
674 text_width += prefix_width;
676 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
678 inner_width = padding[3] + text_width + padding[1];
679 inner_height = inner_height(r) - borders[0] - borders[2];
681 /* Border top */
682 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
684 /* Border right */
685 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero, borders[1], inner_height(r));
687 /* Border bottom */
688 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
690 /* Border left */
691 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
693 /* bg */
694 x += borders[3];
695 y = r->y_zero + borders[0];
696 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
698 /* content */
699 y += padding[0] + r->text_height;
700 x += padding[3];
701 if (prefix != NULL) {
702 draw_string(prefix, strlen(prefix), x, y, r, t);
703 x += prefix_width;
705 draw_string(text, strlen(text), x, y, r, t);
707 return ret;
710 /* ,-----------------------------------------------------------------, */
711 /* | 20 char text | completion | completion | completion | compl | */
712 /* `-----------------------------------------------------------------' */
713 void
714 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
716 size_t i;
717 int x = r->x_zero;
719 /* Draw the prompt */
720 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
722 for (i = r->offset; i < cs->length; ++i) {
723 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
725 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
727 if (x > inner_width(r))
728 break;
732 /* ,-----------------------------------------------------------------, */
733 /* | prompt | */
734 /* |-----------------------------------------------------------------| */
735 /* | completion | */
736 /* |-----------------------------------------------------------------| */
737 /* | completion | */
738 /* `-----------------------------------------------------------------' */
739 void
740 draw_vertically(struct rendering *r, char *text, struct completions *cs)
742 size_t i;
743 int y = r->y_zero;
745 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
747 for (i = r->offset; i < cs->length; ++i) {
748 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
750 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
752 if (y > inner_height(r))
753 break;
757 void
758 draw(struct rendering *r, char *text, struct completions *cs)
760 /* Draw the background */
761 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
763 /* Draw the contents */
764 if (r->horizontal_layout)
765 draw_horizontally(r, text, cs);
766 else
767 draw_vertically(r, text, cs);
769 /* Draw the borders */
770 if (r->borders[0] != 0)
771 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
773 if (r->borders[1] != 0)
774 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0, r->borders[1], r->height);
776 if (r->borders[2] != 0)
777 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width, r->borders[2]);
779 if (r->borders[3] != 0)
780 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
782 /* render! */
783 XFlush(r->d);
786 /* Set some WM stuff */
787 void
788 set_win_atoms_hints(Display *d, Window w, int width, int height)
790 Atom type;
791 XClassHint *class_hint;
792 XSizeHints *size_hint;
794 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
795 XChangeProperty(d,
796 w,
797 XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
798 XInternAtom(d, "ATOM", 0),
799 32,
800 PropModeReplace,
801 (unsigned char *)&type,
803 );
805 /* some window managers honor this properties */
806 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
807 XChangeProperty(d,
808 w,
809 XInternAtom(d, "_NET_WM_STATE", 0),
810 XInternAtom(d, "ATOM", 0),
811 32,
812 PropModeReplace,
813 (unsigned char *)&type,
815 );
817 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
818 XChangeProperty(d,
819 w,
820 XInternAtom(d, "_NET_WM_STATE", 0),
821 XInternAtom(d, "ATOM", 0),
822 32,
823 PropModeAppend,
824 (unsigned char *)&type,
826 );
828 /* Setting window hints */
829 class_hint = XAllocClassHint();
830 if (class_hint == NULL) {
831 fprintf(stderr, "Could not allocate memory for class hint\n");
832 exit(EX_UNAVAILABLE);
835 class_hint->res_name = resname;
836 class_hint->res_class = resclass;
837 XSetClassHint(d, w, class_hint);
838 XFree(class_hint);
840 size_hint = XAllocSizeHints();
841 if (size_hint == NULL) {
842 fprintf(stderr, "Could not allocate memory for size hint\n");
843 exit(EX_UNAVAILABLE);
846 size_hint->flags = PMinSize | PBaseSize;
847 size_hint->min_width = width;
848 size_hint->base_width = width;
849 size_hint->min_height = height;
850 size_hint->base_height = height;
852 XFlush(d);
855 /* Get the width and height of the window `w' */
856 void
857 get_wh(Display *d, Window *w, int *width, int *height)
859 XWindowAttributes win_attr;
861 XGetWindowAttributes(d, *w, &win_attr);
862 *height = win_attr.height;
863 *width = win_attr.width;
866 int
867 grabfocus(Display *d, Window w)
869 int i;
870 for (i = 0; i < 100; ++i) {
871 Window focuswin;
872 int revert_to_win;
874 XGetInputFocus(d, &focuswin, &revert_to_win);
876 if (focuswin == w)
877 return 1;
879 XSetInputFocus(d, w, RevertToParent, CurrentTime);
880 usleep(1000);
882 return 0;
885 /*
886 * I know this may seem a little hackish BUT is the only way I managed
887 * to actually grab that goddam keyboard. Only one call to
888 * XGrabKeyboard does not always end up with the keyboard grabbed!
889 */
890 int
891 take_keyboard(Display *d, Window w)
893 int i;
894 for (i = 0; i < 100; i++) {
895 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
896 return 1;
897 usleep(1000);
899 fprintf(stderr, "Cannot grab keyboard\n");
900 return 0;
903 unsigned long
904 parse_color(const char *str, const char *def)
906 size_t len;
907 rgba_t tmp;
908 char *ep;
910 if (str == NULL)
911 goto invc;
913 len = strlen(str);
915 /* +1 for the # ath the start */
916 if (*str != '#' || len > 9 || len < 4)
917 goto invc;
918 ++str; /* skip the # */
920 errno = 0;
921 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
923 if (errno)
924 goto invc;
926 switch (len-1) {
927 case 3:
928 /* expand #rgb -> #rrggbb */
929 tmp.v = (tmp.v & 0xf00) * 0x1100
930 | (tmp.v & 0x0f0) * 0x0110
931 | (tmp.v & 0x00f) * 0x0011;
932 case 6:
933 /* assume 0xff opacity */
934 tmp.rgba.a = 0xff;
935 break;
936 } /* colors in #aarrggbb need no adjustments */
938 /* premultiply the alpha */
939 if (tmp.rgba.a) {
940 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
941 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
942 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
943 return tmp.v;
946 return 0U;
948 invc:
949 fprintf(stderr, "Invalid color: \"%s\".\n", str);
950 if (def != NULL)
951 return parse_color(def, NULL);
952 else
953 return 0U;
956 /*
957 * Given a string try to parse it as a number or return `default_value'.
958 */
959 int
960 parse_integer(const char *str, int default_value)
962 long lval;
963 char *ep;
965 errno = 0;
966 lval = strtol(str, &ep, 10);
968 if (str[0] == '\0' || *ep != '\0') { /* NaN */
969 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
970 return default_value;
973 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
974 (lval > INT_MAX || lval < INT_MIN)) {
975 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
976 return default_value;
979 return lval;
982 /* Like parse_integer but recognize the percentages (i.e. strings ending with `%') */
983 int
984 parse_int_with_percentage(const char *str, int default_value, int max)
986 int len = strlen(str);
988 if (len > 0 && str[len-1] == '%') {
989 int val;
990 char *cpy;
992 cpy = strdup(str);
993 check_allocation(cpy);
994 cpy[len-1] = '\0';
995 val = parse_integer(cpy, default_value);
996 free(cpy);
997 return val * max / 100;
1000 return parse_integer(str, default_value);
1004 * Like parse_int_with_percentage but understands some special values:
1005 * - middle that is (max-self)/2
1006 * - start that is 0
1007 * - end that is (max-self)
1009 int
1010 parse_int_with_pos(const char *str, int default_value, int max, int self)
1012 if (!strcmp(str, "start"))
1013 return 0;
1014 if (!strcmp(str, "middle"))
1015 return (max - self)/2;
1016 if (!strcmp(str, "end"))
1017 return max-self;
1018 return parse_int_with_percentage(str, default_value, max);
1021 /* Parse a string like a CSS value. */
1022 /* TODO: harden a bit this function */
1023 char **
1024 parse_csslike(const char *str)
1026 int i, j;
1027 char *s, *token, **ret;
1028 short any_null;
1030 s = strdup(str);
1031 if (s == NULL)
1032 return NULL;
1034 ret = malloc(4 * sizeof(char*));
1035 if (ret == NULL) {
1036 free(s);
1037 return NULL;
1040 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1041 ret[i] = strdup(token);
1043 if (i == 1)
1044 for (j = 1; j < 4; j++)
1045 ret[j] = strdup(ret[0]);
1047 if (i == 2) {
1048 ret[2] = strdup(ret[0]);
1049 ret[3] = strdup(ret[1]);
1052 if (i == 3)
1053 ret[3] = strdup(ret[1]);
1055 /* before we didn't check for the return type of strdup, here we will */
1057 any_null = 0;
1058 for (i = 0; i < 4; ++i)
1059 any_null = ret[i] == NULL || any_null;
1061 if (any_null)
1062 for (i = 0; i < 4; ++i)
1063 if (ret[i] != NULL)
1064 free(ret[i]);
1066 if (i == 0 || any_null) {
1067 free(s);
1068 free(ret);
1069 return NULL;
1072 return ret;
1076 * Given an event, try to understand what the users wants. If the
1077 * return value is ADD_CHAR then `input' is a pointer to a string that
1078 * will need to be free'ed later.
1080 enum
1081 action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1083 char str[SYM_BUF_SIZE] = {0};
1084 Status s;
1086 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1087 return DEL_CHAR;
1089 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1090 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1092 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1093 return CONFIRM;
1095 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1096 return EXIT;
1098 /* Try to read what key was pressed */
1099 s = 0;
1100 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1101 if (s == XBufferOverflow) {
1102 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1103 return EXIT;
1106 if (ev->state & ControlMask) {
1107 if (!strcmp(str, "")) /* C-u */
1108 return DEL_LINE;
1109 if (!strcmp(str, "")) /* C-w */
1110 return DEL_WORD;
1111 if (!strcmp(str, "")) /* C-h */
1112 return DEL_CHAR;
1113 if (!strcmp(str, "\r")) /* C-m */
1114 return CONFIRM_CONTINUE;
1115 if (!strcmp(str, "")) /* C-p */
1116 return PREV_COMPL;
1117 if (!strcmp(str, "")) /* C-n */
1118 return NEXT_COMPL;
1119 if (!strcmp(str, "")) /* C-c */
1120 return EXIT;
1121 if (!strcmp(str, "\t")) /* C-i */
1122 return TOGGLE_FIRST_SELECTED;
1125 *input = strdup(str);
1126 if (*input == NULL) {
1127 fprintf(stderr, "Error while allocating memory for key.\n");
1128 return EXIT;
1131 return ADD_CHAR;
1134 void
1135 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1137 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1138 /* if there is something selected expand it and return */
1139 int index = cs->selected == -1 ? 0 : cs->selected;
1140 struct completion *c = cs->completions;
1141 char *t;
1143 while (1) {
1144 if (index == 0)
1145 break;
1146 c++;
1147 index--;
1150 t = c->rcompletion;
1151 free(*text);
1152 *text = strdup(t);
1154 if (*text == NULL) {
1155 fprintf(stderr, "Memory allocation error\n");
1156 *status = ERR;
1159 *textlen = strlen(*text);
1160 return;
1163 if (!r->free_text) /* cannot accept arbitrary text */
1164 *status = LOOPING;
1167 /* event loop */
1168 enum state
1169 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines)
1171 enum state status = LOOPING;
1173 while (status == LOOPING) {
1174 XEvent e;
1175 XNextEvent(r->d, &e);
1177 if (XFilterEvent(&e, r->w))
1178 continue;
1180 switch (e.type) {
1181 case KeymapNotify:
1182 XRefreshKeyboardMapping(&e.xmapping);
1183 break;
1185 case FocusIn:
1186 /* Re-grab focus */
1187 if (e.xfocus.window != r->w)
1188 grabfocus(r->d, r->w);
1189 break;
1191 case VisibilityNotify:
1192 if (e.xvisibility.state != VisibilityUnobscured)
1193 XRaiseWindow(r->d, r->w);
1194 break;
1196 case MapNotify:
1197 get_wh(r->d, &r->w, &r->width, &r->height);
1198 draw(r, *text, cs);
1199 break;
1201 case KeyPress: {
1202 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1203 char *input;
1205 switch (parse_event(r->d, ev, r->xic, &input)) {
1206 case EXIT:
1207 status = ERR;
1208 break;
1210 case CONFIRM: {
1211 status = OK;
1212 confirm(&status, r, cs, text, textlen);
1213 break;
1216 case CONFIRM_CONTINUE: {
1217 status = OK_LOOP;
1218 confirm(&status, r, cs, text, textlen);
1219 break;
1222 case PREV_COMPL: {
1223 complete(cs, r->first_selected, 1, text, textlen, &status);
1224 r->offset = cs->selected;
1225 break;
1228 case NEXT_COMPL: {
1229 complete(cs, r->first_selected, 0, text, textlen, &status);
1230 r->offset = cs->selected;
1231 break;
1234 case DEL_CHAR:
1235 popc(*text);
1236 update_completions(cs, *text, lines, vlines, r->first_selected);
1237 r->offset = 0;
1238 break;
1240 case DEL_WORD: {
1241 popw(*text);
1242 update_completions(cs, *text, lines, vlines, r->first_selected);
1243 break;
1246 case DEL_LINE: {
1247 int i;
1248 for (i = 0; i < *textlen; ++i)
1249 *(*text + i) = 0;
1250 update_completions(cs, *text, lines, vlines, r->first_selected);
1251 r->offset = 0;
1252 break;
1255 case ADD_CHAR: {
1256 int str_len, i;
1258 str_len = strlen(input);
1261 * sometimes a strange key is pressed
1262 * i.e. ctrl alone), so input will be
1263 * empty. Don't need to update
1264 * completion in that case
1266 if (str_len == 0)
1267 break;
1269 for (i = 0; i < str_len; ++i) {
1270 *textlen = pushc(text, *textlen, input[i]);
1271 if (*textlen == -1) {
1272 fprintf(stderr, "Memory allocation error\n");
1273 status = ERR;
1274 break;
1278 if (status != ERR) {
1279 update_completions(cs, *text, lines, vlines, r->first_selected);
1280 free(input);
1283 r->offset = 0;
1284 break;
1287 case TOGGLE_FIRST_SELECTED:
1288 r->first_selected = !r->first_selected;
1289 if (r->first_selected && cs->selected < 0)
1290 cs->selected = 0;
1291 if (!r->first_selected && cs->selected == 0)
1292 cs->selected = -1;
1293 break;
1297 case ButtonPress: {
1298 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1299 /* if (ev->button == Button1) { /\* click *\/ */
1300 /* int x = ev->x - r.border_w; */
1301 /* int y = ev->y - r.border_n; */
1302 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1303 /* } */
1305 if (ev->button == Button4) /* scroll up */
1306 r->offset = MAX((ssize_t)r->offset - 1, 0);
1308 if (ev->button == Button5) /* scroll down */
1309 r->offset = MIN(r->offset + 1, cs->length - 1);
1311 break;
1315 draw(r, *text, cs);
1318 return status;
1321 int
1322 load_font(struct rendering *r, const char *fontname)
1324 #ifdef USE_XFT
1325 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1326 return 0;
1327 #else
1328 char **missing_charset_list;
1329 int missing_charset_count;
1331 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1332 if (r->font != NULL)
1333 return 0;
1335 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1337 if (!strcmp(fontname, default_fontname))
1338 return -1;
1340 return load_font(r, default_fontname);
1341 #endif
1344 void
1345 xim_init(struct rendering *r, XrmDatabase *xdb)
1347 XIMStyle best_match_style;
1348 XIMStyles *xis;
1349 int i;
1351 /* Open the X input method */
1352 r->xim = XOpenIM(r->d, *xdb, resname, resclass);
1353 check_allocation(r->xim);
1355 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1356 fprintf(stderr, "Input Styles could not be retrieved\n");
1357 exit(EX_UNAVAILABLE);
1360 best_match_style = 0;
1361 for (i = 0; i < xis->count_styles; ++i) {
1362 XIMStyle ts = xis->supported_styles[i];
1363 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1364 best_match_style = ts;
1365 break;
1368 XFree(xis);
1370 if (!best_match_style)
1371 fprintf(stderr, "No matching input style could be determined\n");
1373 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1374 check_allocation(r->xic);
1377 void
1378 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy, unsigned long background_pixel)
1380 XSetWindowAttributes attr;
1382 /* Create the window */
1383 attr.colormap = cmap;
1384 attr.override_redirect = 1;
1385 attr.border_pixel = 0;
1386 attr.background_pixel = background_pixel;
1387 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1389 r->w = XCreateWindow(r->d,
1390 parent_window,
1391 x + ox, y + oy,
1392 r->width, r->height,
1394 vinfo.depth,
1395 InputOutput,
1396 vinfo.visual,
1397 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1398 &attr);
1401 void
1402 ps1extents(struct rendering *r)
1404 char *dup;
1405 dup = strdupn(r->ps1);
1406 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1407 free(dup);
1410 void
1411 usage(char *prgname)
1413 fprintf(stderr,
1414 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1415 " [-d separator] [-e window] [-f font] [-G color] [-g size]\n"
1416 " [-H height] [-I color] [-i size] [-J color] [-j size] [-l layout]\n"
1417 " [-P padding] [-p prompt] [-S color] [-s color] [-T color]\n"
1418 " [-t color] [-W width] [-x coord] [-y coord]\n", prgname);
1421 int
1422 main(int argc, char **argv)
1424 struct completions *cs;
1425 struct rendering r;
1426 XVisualInfo vinfo;
1427 Colormap cmap;
1428 size_t nlines, i;
1429 Window parent_window;
1430 XrmDatabase xdb;
1431 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1432 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4], ch_borders_bg[4]; /* N E S W */
1433 enum state status;
1434 int ch;
1435 int offset_x, offset_y, x, y;
1436 int textlen, d_width, d_height;
1437 short embed;
1438 char *sep, *parent_window_id;
1439 char **lines, *buf, **vlines;
1440 char *fontname, *text, *xrm;
1442 #ifdef __OpenBSD__
1443 /* stdio & rpath: to read/write stdio/stdout/stderr */
1444 /* unix: to connect to XOrg */
1445 pledge("stdio rpath unix", "");
1446 #endif
1448 sep = NULL;
1449 parent_window_id = NULL;
1451 r.first_selected = 0;
1452 r.free_text = 1;
1453 r.multiple_select = 0;
1454 r.offset = 0;
1456 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1457 switch (ch) {
1458 case 'h': /* help */
1459 usage(*argv);
1460 return 0;
1461 case 'v': /* version */
1462 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1463 return 0;
1464 case 'e': /* embed */
1465 parent_window_id = strdup(optarg);
1466 check_allocation(parent_window_id);
1467 break;
1468 case 'd':
1469 sep = strdup(optarg);
1470 check_allocation(sep);
1471 case 'A':
1472 r.free_text = 0;
1473 break;
1474 case 'm':
1475 r.multiple_select = 1;
1476 break;
1477 default:
1478 break;
1482 /* Read the completions */
1483 lines = NULL;
1484 buf = NULL;
1485 nlines = readlines(&lines, &buf);
1487 vlines = NULL;
1488 if (sep != NULL) {
1489 int l;
1490 l = strlen(sep);
1491 vlines = calloc(nlines, sizeof(char*));
1492 check_allocation(vlines);
1494 for (i = 0; i < nlines; i++) {
1495 char *t;
1496 t = strstr(lines[i], sep);
1497 if (t == NULL)
1498 vlines[i] = lines[i];
1499 else
1500 vlines[i] = t + l;
1504 setlocale(LC_ALL, getenv("LANG"));
1506 status = LOOPING;
1508 /* where the monitor start (used only with xinerama) */
1509 offset_x = offset_y = 0;
1511 /* default width and height */
1512 r.width = 400;
1513 r.height = 20;
1515 /* default position on the screen */
1516 x = y = 0;
1518 for (i = 0; i < 4; ++i) {
1519 /* default paddings */
1520 r.p_padding[i] = 10;
1521 r.c_padding[i] = 10;
1522 r.ch_padding[i] = 10;
1524 /* default borders */
1525 r.borders[i] = 0;
1526 r.p_borders[i] = 0;
1527 r.c_borders[i] = 0;
1528 r.ch_borders[i] = 0;
1531 /* the prompt. We duplicate the string so later is easy to
1532 * free (in the case it's been overwritten by the user) */
1533 r.ps1 = strdup("$ ");
1534 check_allocation(r.ps1);
1536 /* same for the font name */
1537 fontname = strdup(default_fontname);
1538 check_allocation(fontname);
1540 textlen = 10;
1541 text = malloc(textlen * sizeof(char));
1542 check_allocation(text);
1544 /* struct completions *cs = filter(text, lines); */
1545 cs = compls_new(nlines);
1546 check_allocation(cs);
1548 /* start talking to xorg */
1549 r.d = XOpenDisplay(NULL);
1550 if (r.d == NULL) {
1551 fprintf(stderr, "Could not open display!\n");
1552 return EX_UNAVAILABLE;
1555 embed = 1;
1556 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1557 parent_window = DefaultRootWindow(r.d);
1558 embed = 0;
1561 /* get display size */
1562 get_wh(r.d, &parent_window, &d_width, &d_height);
1564 #ifdef USE_XINERAMA
1565 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1566 XineramaScreenInfo *info;
1567 Window rr;
1568 Window root;
1569 int number_of_screens, monitors, i;
1570 int root_x, root_y, win_x, win_y;
1571 unsigned int mask;
1572 short res;
1574 number_of_screens = XScreenCount(r.d);
1575 for (i = 0; i < number_of_screens; ++i) {
1576 root = XRootWindow(r.d, i);
1577 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1578 if (res)
1579 break;
1582 if (!res) {
1583 fprintf(stderr, "No mouse found.\n");
1584 root_x = 0;
1585 root_y = 0;
1588 /* Now find in which monitor the mice is */
1589 info = XineramaQueryScreens(r.d, &monitors);
1590 if (info) {
1591 for (i = 0; i < monitors; ++i) {
1592 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1593 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1594 offset_x = info[i].x_org;
1595 offset_y = info[i].y_org;
1596 d_width = info[i].width;
1597 d_height = info[i].height;
1598 break;
1602 XFree(info);
1604 #endif
1606 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1607 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1609 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1610 fgs[2] = parse_color("#000", NULL);
1612 bgs[0] = bgs[1] = parse_color("#000", NULL);
1613 bgs[2] = parse_color("#fff", NULL);
1615 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1617 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3] = parse_color("#000", NULL);
1618 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3] = parse_color("#000", NULL);
1619 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3] = parse_color("#000", NULL);
1621 r.horizontal_layout = 1;
1623 /* Read the resources */
1624 XrmInitialize();
1625 xrm = XResourceManagerString(r.d);
1626 xdb = NULL;
1627 if (xrm != NULL) {
1628 XrmValue value;
1629 char *datatype[20];
1631 xdb = XrmGetStringDatabase(xrm);
1633 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1634 free(fontname);
1635 fontname = strdup(value.addr);
1636 check_allocation(fontname);
1637 } else {
1638 fprintf(stderr, "no font defined, using %s\n", fontname);
1641 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1642 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1643 else
1644 fprintf(stderr, "no layout defined, using horizontal\n");
1646 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1647 free(r.ps1);
1648 r.ps1 = normalize_str(value.addr);
1649 } else {
1650 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1653 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value) == 1) {
1654 char **sizes;
1655 sizes = parse_csslike(value.addr);
1656 if (sizes != NULL)
1657 for (i = 0; i < 4; ++i)
1658 r.p_borders[i] = parse_integer(sizes[i], 0);
1659 else
1660 fprintf(stderr, "error while parsing MyMenu.prompt.border.size");
1663 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value) == 1) {
1664 char **colors;
1665 colors = parse_csslike(value.addr);
1666 if (colors != NULL)
1667 for (i = 0; i < 4; ++i)
1668 p_borders_bg[i] = parse_color(colors[i], "#000");
1669 else
1670 fprintf(stderr, "error while parsing MyMenu.prompt.border.color");
1673 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value) == 1) {
1674 char **colors;
1675 colors = parse_csslike(value.addr);
1676 if (colors != NULL)
1677 for (i = 0; i < 4; ++i)
1678 r.p_padding[i] = parse_integer(colors[i], 0);
1679 else
1680 fprintf(stderr, "error while parsing MyMenu.prompt.padding");
1683 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1684 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1685 else
1686 fprintf(stderr, "no width defined, using %d\n", r.width);
1688 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1689 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1690 else
1691 fprintf(stderr, "no height defined, using %d\n", r.height);
1693 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1694 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1696 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1697 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1699 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1700 char **borders;
1701 borders = parse_csslike(value.addr);
1702 if (borders != NULL)
1703 for (i = 0; i < 4; ++i)
1704 r.borders[i] = parse_int_with_percentage(borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1705 else
1706 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1709 /* Prompt */
1710 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1711 fgs[0] = parse_color(value.addr, "#fff");
1713 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1714 bgs[0] = parse_color(value.addr, "#000");
1716 /* Completions */
1717 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1718 fgs[1] = parse_color(value.addr, "#fff");
1720 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1721 bgs[1] = parse_color(value.addr, "#000");
1723 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value) == 1) {
1724 char **paddings;
1725 paddings = parse_csslike(value.addr);
1726 if (paddings != NULL)
1727 for (i = 0; i < 4; ++i)
1728 r.c_padding[i] = parse_integer(paddings[i], 0);
1729 else
1730 fprintf(stderr, "Error while parsing MyMenu.completion.padding");
1733 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value) == 1) {
1734 char **sizes;
1735 sizes = parse_csslike(value.addr);
1736 if (sizes != NULL)
1737 for (i = 0; i < 4; ++i)
1738 r.c_borders[i] = parse_integer(sizes[i], 0);
1739 else
1740 fprintf(stderr, "Error while parsing MyMenu.completion.border.size");
1743 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value) == 1) {
1744 char **sizes;
1745 sizes = parse_csslike(value.addr);
1746 if (sizes != NULL)
1747 for (i = 0; i < 4; ++i)
1748 c_borders_bg[i] = parse_color(sizes[i], "#000");
1749 else
1750 fprintf(stderr, "Error while parsing MyMenu.completion.border.color");
1753 /* Completion Highlighted */
1754 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1755 fgs[2] = parse_color(value.addr, "#000");
1757 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1758 bgs[2] = parse_color(value.addr, "#fff");
1760 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value) == 1) {
1761 char **paddings;
1762 paddings = parse_csslike(value.addr);
1763 if (paddings != NULL)
1764 for (i = 0; i < 4; ++i)
1765 r.ch_padding[i] = parse_integer(paddings[i], 0);
1766 else
1767 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.padding");
1770 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype, &value) == 1) {
1771 char **sizes;
1772 sizes = parse_csslike(value.addr);
1773 if (sizes != NULL)
1774 for (i = 0; i < 4; ++i)
1775 r.ch_borders[i] = parse_integer(sizes[i], 0);
1776 else
1777 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.size");
1780 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype, &value) == 1) {
1781 char **colors;
1782 colors = parse_csslike(value.addr);
1783 if (colors != NULL)
1784 for (i = 0; i < 4; ++i)
1785 ch_borders_bg[i] = parse_color(colors[i], "#000");
1786 else
1787 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.color");
1790 /* Border */
1791 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1792 char **colors;
1793 colors = parse_csslike(value.addr);
1794 if (colors != NULL)
1795 for (i = 0; i < 4; ++i)
1796 borders_bg[i] = parse_color(colors[i], "#000");
1797 else
1798 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1802 /* Second round of args parsing */
1803 optind = 0; /* reset the option index */
1804 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1805 switch (ch) {
1806 case 'a':
1807 r.first_selected = 1;
1808 break;
1809 case 'A':
1810 /* free_text -- already catched */
1811 case 'd':
1812 /* separator -- this case was already catched */
1813 case 'e':
1814 /* embedding mymenu this case was already catched. */
1815 case 'm':
1816 /* multiple selection this case was already catched. */
1817 break;
1818 case 'p': {
1819 char *newprompt;
1820 newprompt = strdup(optarg);
1821 if (newprompt != NULL) {
1822 free(r.ps1);
1823 r.ps1 = newprompt;
1825 break;
1827 case 'x':
1828 x = parse_int_with_pos(optarg, x, d_width, r.width);
1829 break;
1830 case 'y':
1831 y = parse_int_with_pos(optarg, y, d_height, r.height);
1832 break;
1833 case 'P': {
1834 char **paddings;
1835 if ((paddings = parse_csslike(optarg)) != NULL)
1836 for (i = 0; i < 4; ++i)
1837 r.p_padding[i] = parse_integer(paddings[i], 0);
1838 break;
1840 case 'G': {
1841 char **colors;
1842 if ((colors = parse_csslike(optarg)) != NULL)
1843 for (i = 0; i < 4; ++i)
1844 p_borders_bg[i] = parse_color(colors[i], "#000");
1845 break;
1847 case 'g': {
1848 char **sizes;
1849 if ((sizes = parse_csslike(optarg)) != NULL)
1850 for (i = 0; i < 4; ++i)
1851 r.p_borders[i] = parse_integer(sizes[i], 0);
1852 break;
1854 case 'I': {
1855 char **colors;
1856 if ((colors = parse_csslike(optarg)) != NULL)
1857 for (i = 0; i < 4; ++i)
1858 c_borders_bg[i] = parse_color(colors[i], "#000");
1859 break;
1861 case 'i': {
1862 char **sizes;
1863 if ((sizes = parse_csslike(optarg)) != NULL)
1864 for (i = 0; i < 4; ++i)
1865 r.c_borders[i] = parse_integer(sizes[i], 0);
1866 break;
1868 case 'J': {
1869 char **colors;
1870 if ((colors = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 ch_borders_bg[i] = parse_color(colors[i], "#000");
1873 break;
1875 case 'j': {
1876 char **sizes;
1877 if ((sizes = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 r.ch_borders[i] = parse_integer(sizes[i], 0);
1880 break;
1882 case 'l':
1883 r.horizontal_layout = !strcmp(optarg, "horizontal");
1884 break;
1885 case 'f': {
1886 char *newfont;
1887 if ((newfont = strdup(optarg)) != NULL) {
1888 free(fontname);
1889 fontname = newfont;
1891 break;
1893 case 'W':
1894 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1895 break;
1896 case 'H':
1897 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1898 break;
1899 case 'b': {
1900 char **borders;
1901 if ((borders = parse_csslike(optarg)) != NULL) {
1902 for (i = 0; i < 4; ++i)
1903 r.borders[i] = parse_integer(borders[i], 0);
1904 } else
1905 fprintf(stderr, "Error parsing b option\n");
1906 break;
1908 case 'B': {
1909 char **colors;
1910 if ((colors = parse_csslike(optarg)) != NULL) {
1911 for (i = 0; i < 4; ++i)
1912 borders_bg[i] = parse_color(colors[i], "#000");
1913 } else
1914 fprintf(stderr, "error while parsing B option\n");
1915 break;
1917 case 't':
1918 fgs[0] = parse_color(optarg, NULL);
1919 break;
1920 case 'T':
1921 bgs[0] = parse_color(optarg, NULL);
1922 break;
1923 case 'c':
1924 fgs[1] = parse_color(optarg, NULL);
1925 break;
1926 case 'C':
1927 bgs[1] = parse_color(optarg, NULL);
1928 break;
1929 case 's':
1930 fgs[2] = parse_color(optarg, NULL);
1931 break;
1932 case 'S':
1933 fgs[2] = parse_color(optarg, NULL);
1934 break;
1935 default:
1936 fprintf(stderr, "Unrecognized option %c\n", ch);
1937 status = ERR;
1938 break;
1942 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1943 fprintf(stderr, "height, width, x or y are lesser than 0.");
1944 status = ERR;
1947 /* since only now we know if the first should be selected,
1948 * update the completion here */
1949 update_completions(cs, text, lines, vlines, r.first_selected);
1951 /* update the prompt lenght, only now we surely know the length of it */
1952 r.ps1len = strlen(r.ps1);
1954 /* Create the window */
1955 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1956 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1957 XMapRaised(r.d, r.w);
1959 /* If embed, listen for other events as well */
1960 if (embed) {
1961 Window *children, parent, root;
1962 unsigned int children_no;
1964 XSelectInput(r.d, parent_window, FocusChangeMask);
1965 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1966 for (i = 0; i < children_no && children[i] != r.w; ++i)
1967 XSelectInput(r.d, children[i], FocusChangeMask);
1968 XFree(children);
1970 grabfocus(r.d, r.w);
1973 take_keyboard(r.d, r.w);
1975 r.x_zero = r.borders[3];
1976 r.y_zero = r.borders[0];
1979 XGCValues values;
1981 for (i = 0; i < 3; ++i) {
1982 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1983 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
1986 for (i = 0; i < 4; ++i) {
1987 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1988 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1989 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1990 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1994 /* Load the colors in our GCs */
1995 for (i = 0; i < 3; ++i) {
1996 XSetForeground(r.d, r.fgs[i], fgs[i]);
1997 XSetForeground(r.d, r.bgs[i], bgs[i]);
2000 for (i = 0; i < 4; ++i) {
2001 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2002 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2003 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2004 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2007 if (load_font(&r, fontname) == -1)
2008 status = ERR;
2010 #ifdef USE_XFT
2011 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2013 for (i = 0; i < 3; ++i) {
2014 rgba_t c;
2015 XRenderColor xrcolor;
2017 c = *(rgba_t*)&fgs[i];
2018 xrcolor.red = EXPANDBITS(c.rgba.r);
2019 xrcolor.green = EXPANDBITS(c.rgba.g);
2020 xrcolor.blue = EXPANDBITS(c.rgba.b);
2021 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2022 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2024 #endif
2026 /* compute prompt dimensions */
2027 ps1extents(&r);
2029 xim_init(&r, &xdb);
2031 #ifdef __OpenBSD__
2032 /* Now we need only the ability to write */
2033 pledge("stdio", "");
2034 #endif
2036 /* Cache text height */
2037 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2039 /* Draw the window for the first time */
2040 draw(&r, text, cs);
2042 /* Main loop */
2043 while (status == LOOPING || status == OK_LOOP) {
2044 status = loop(&r, &text, &textlen, cs, lines, vlines);
2046 if (status != ERR)
2047 printf("%s\n", text);
2049 if (!r.multiple_select && status == OK_LOOP)
2050 status = OK;
2053 XUngrabKeyboard(r.d, CurrentTime);
2055 #ifdef USE_XFT
2056 for (i = 0; i < 3; ++i)
2057 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2058 #endif
2060 for (i = 0; i < 3; ++i) {
2061 XFreeGC(r.d, r.fgs[i]);
2062 XFreeGC(r.d, r.bgs[i]);
2065 for (i = 0; i < 4; ++i) {
2066 XFreeGC(r.d, r.borders_bg[i]);
2067 XFreeGC(r.d, r.p_borders_bg[i]);
2068 XFreeGC(r.d, r.c_borders_bg[i]);
2069 XFreeGC(r.d, r.ch_borders_bg[i]);
2072 XDestroyIC(r.xic);
2073 XCloseIM(r.xim);
2075 #ifdef USE_XFT
2076 for (i = 0; i < 3; ++i)
2077 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2078 XftFontClose(r.d, r.font);
2079 XftDrawDestroy(r.xftdraw);
2080 #else
2081 XFreeFontSet(r.d, r.font);
2082 #endif
2084 free(r.ps1);
2085 free(fontname);
2086 free(text);
2088 free(buf);
2089 free(lines);
2090 free(vlines);
2091 compls_delete(cs);
2093 XFreeColormap(r.d, cmap);
2095 XDestroyWindow(r.d, r.w);
2096 XCloseDisplay(r.d);
2098 return status != OK;