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 int width;
103 int height;
104 int p_padding[4];
105 int c_padding[4];
106 int ch_padding[4];
107 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause the borders) */
108 int y_zero; /* like x_zero but for the y axis */
110 size_t offset; /* scroll offset */
112 short free_text;
113 short first_selected;
114 short multiple_select;
116 /* four border width */
117 int borders[4];
118 int p_borders[4];
119 int c_borders[4];
120 int ch_borders[4];
122 short horizontal_layout;
124 /* prompt */
125 char *ps1;
126 int ps1len;
127 int ps1w; /* ps1 width */
128 int ps1h; /* ps1 height */
130 int text_height; /* cache for the vertical layout */
132 XIC xic;
134 /* colors */
135 GC fgs[4];
136 GC bgs[4];
137 GC borders_bg[4];
138 GC p_borders_bg[4];
139 GC c_borders_bg[4];
140 GC ch_borders_bg[4];
141 #ifdef USE_XFT
142 XftFont *font;
143 XftDraw *xftdraw;
144 XftColor xft_colors[3];
145 #else
146 XFontSet font;
147 #endif
148 };
150 struct completion {
151 char *completion;
152 char *rcompletion;
153 };
155 /* Wrap the linked list of completions */
156 struct completions {
157 struct completion *completions;
158 ssize_t selected;
159 size_t length;
160 };
162 /* idea stolen from lemonbar. ty lemonboy */
163 typedef union {
164 struct {
165 uint8_t b;
166 uint8_t g;
167 uint8_t r;
168 uint8_t a;
169 } rgba;
170 uint32_t v;
171 } rgba_t;
173 extern char *optarg;
174 extern int optind;
176 /* Return a newly allocated (and empty) completion list */
177 struct completions *
178 compls_new(size_t length)
180 struct completions *cs = malloc(sizeof(struct completions));
182 if (cs == NULL)
183 return cs;
185 cs->completions = calloc(length, sizeof(struct completion));
186 if (cs->completions == NULL) {
187 free(cs);
188 return NULL;
191 cs->selected = -1;
192 cs->length = length;
193 return cs;
196 /* Delete the wrapper and the whole list */
197 void
198 compls_delete(struct completions *cs)
200 if (cs == NULL)
201 return;
203 free(cs->completions);
204 free(cs);
207 /*
208 * Create a completion list from a text and the list of possible
209 * completions (null terminated). Expects a non-null `cs'. `lines' and
210 * `vlines' should have the same length OR `vlines' is NULL.
211 */
212 void
213 filter(struct completions *cs, char *text, char **lines, char **vlines)
215 size_t index = 0;
216 size_t matching = 0;
217 char *l;
219 if (vlines == NULL)
220 vlines = lines;
222 while (1) {
223 if (lines[index] == NULL)
224 break;
226 l = vlines[index] != NULL ? vlines[index] : lines[index];
228 if (strcasestr(l, text) != NULL) {
229 struct completion *c = &cs->completions[matching];
230 c->completion = l;
231 c->rcompletion = lines[index];
232 matching++;
235 index++;
237 cs->length = matching;
238 cs->selected = -1;
241 /* Update the given completion */
242 void
243 update_completions(struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
245 filter(cs, text, lines, vlines);
246 if (first_selected && cs->length > 0)
247 cs->selected = 0;
250 /*
251 * Select the next or previous selection and update some state. `text'
252 * will be updated with the text of the completion and `textlen' with
253 * the new length. If the memory cannot be allocated `status' will be
254 * set to `ERR'.
255 */
256 void
257 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen, enum state *status)
259 struct completion *n;
260 int index;
262 if (cs == NULL || cs->length == 0)
263 return;
265 /*
266 * If the first is always selected and the first entry is
267 * different from the text, expand the text and return
268 */
269 if (first_selected
270 && cs->selected == 0
271 && strcmp(cs->completions->completion, *text) != 0
272 && !p) {
273 free(*text);
274 *text = strdup(cs->completions->completion);
275 if (text == NULL) {
276 *status = ERR;
277 return;
279 *textlen = strlen(*text);
280 return;
283 index = cs->selected;
285 if (index == -1 && p)
286 index = 0;
287 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
289 n = &cs->completions[cs->selected];
291 free(*text);
292 *text = strdup(n->completion);
293 if (text == NULL) {
294 fprintf(stderr, "Memory allocation error!\n");
295 *status = ERR;
296 return;
298 *textlen = strlen(*text);
301 /* Push the character c at the end of the string pointed by p */
302 int
303 pushc(char **p, int maxlen, char c)
305 int len;
307 len = strnlen(*p, maxlen);
308 if (!(len < maxlen -2)) {
309 char *newptr;
311 maxlen += maxlen >> 1;
312 newptr = realloc(*p, maxlen);
313 if (newptr == NULL) /* bad */
314 return -1;
315 *p = newptr;
318 (*p)[len] = c;
319 (*p)[len+1] = '\0';
320 return maxlen;
323 /*
324 * Remove the last rune from the *UTF-8* string! This is different
325 * from just setting the last byte to 0 (in some cases ofc). Return a
326 * pointer (e) to the last nonzero char. If e < p then p is empty!
327 */
328 char *
329 popc(char *p)
331 int len = strlen(p);
332 char *e;
334 if (len == 0)
335 return p;
337 e = p + len - 1;
339 do {
340 char c = *e;
342 *e = '\0';
343 e -= 1;
345 /*
346 * If c is a starting byte (11......) or is under
347 * U+007F we're done.
348 */
349 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
350 break;
351 } while (e >= p);
353 return e;
356 /* Remove the last word plus trailing white spaces from the given string */
357 void
358 popw(char *w)
360 int len;
361 short in_word = 1;
363 if ((len = strlen(w)) == 0)
364 return;
366 while (1) {
367 char *e = popc(w);
369 if (e < w)
370 return;
372 if (in_word && isspace(*e))
373 in_word = 0;
375 if (!in_word && !isspace(*e))
376 return;
380 /*
381 * If the string is surrounded by quates (`"') remove them and replace
382 * every `\"' in the string with a single double-quote.
383 */
384 char *
385 normalize_str(const char *str)
387 int len, p;
388 char *s;
390 if ((len = strlen(str)) == 0)
391 return NULL;
393 s = calloc(len, sizeof(char));
394 check_allocation(s);
395 p = 0;
397 while (*str) {
398 char c = *str;
400 if (*str == '\\') {
401 if (*(str + 1)) {
402 s[p] = *(str + 1);
403 p++;
404 str += 2; /* skip this and the next char */
405 continue;
406 } else
407 break;
409 if (c == '"') {
410 str++; /* skip only this char */
411 continue;
413 s[p] = c;
414 p++;
415 str++;
418 return s;
421 size_t
422 read_stdin(char **buf)
424 size_t offset = 0;
425 size_t len = STDIN_CHUNKS;
427 *buf = malloc(len * sizeof(char));
428 if (*buf == NULL)
429 goto err;
431 while (1) {
432 ssize_t r;
433 size_t i;
435 r = read(0, *buf + offset, STDIN_CHUNKS);
437 if (r < 1)
438 return len;
440 offset += r;
442 len += STDIN_CHUNKS;
443 *buf = realloc(*buf, len);
444 if (*buf == NULL)
445 goto err;
447 for (i = offset; i < len; ++i)
448 (*buf)[i] = '\0';
451 err:
452 fprintf(stderr, "Error in allocating memory for stdin.\n");
453 exit(EX_UNAVAILABLE);
456 size_t
457 readlines(char ***lns, char **buf)
459 size_t i, len, ll, lines;
460 short in_line = 0;
462 lines = 0;
464 *buf = NULL;
465 len = read_stdin(buf);
467 ll = LINES_CHUNK;
468 *lns = malloc(ll * sizeof(char*));
470 if (*lns == NULL)
471 goto err;
473 for (i = 0; i < len; i++) {
474 char c = (*buf)[i];
476 if (c == '\0')
477 break;
479 if (c == '\n')
480 (*buf)[i] = '\0';
482 if (in_line && c == '\n')
483 in_line = 0;
485 if (!in_line && c != '\n') {
486 in_line = 1;
487 (*lns)[lines] = (*buf) + i;
488 lines++;
490 if (lines == ll) { /* resize */
491 ll += LINES_CHUNK;
492 *lns = realloc(*lns, ll * sizeof(char*));
493 if (*lns == NULL)
494 goto err;
499 (*lns)[lines] = NULL;
501 return lines;
503 err:
504 fprintf(stderr, "Error in memory allocation.\n");
505 exit(EX_UNAVAILABLE);
508 /*
509 * Compute the dimensions of the string str once rendered.
510 * It'll return the width and set ret_width and ret_height if not NULL
511 */
512 int
513 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
515 int height;
516 int 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 XIM xim;
1348 XIMStyle best_match_style;
1349 XIMStyles *xis;
1350 int i;
1352 /* Open the X input method */
1353 xim = XOpenIM(r->d, *xdb, resname, resclass);
1354 check_allocation(xim);
1356 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1357 fprintf(stderr, "Input Styles could not be retrieved\n");
1358 exit(EX_UNAVAILABLE);
1361 best_match_style = 0;
1362 for (i = 0; i < xis->count_styles; ++i) {
1363 XIMStyle ts = xis->supported_styles[i];
1364 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1365 best_match_style = ts;
1366 break;
1369 XFree(xis);
1371 if (!best_match_style)
1372 fprintf(stderr, "No matching input style could be determined\n");
1374 r->xic = XCreateIC(xim, XNInputStyle, best_match_style, XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1375 check_allocation(r->xic);
1378 void
1379 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x, int y, int ox, int oy)
1381 XSetWindowAttributes attr;
1383 /* Create the window */
1384 attr.colormap = cmap;
1385 attr.override_redirect = 1;
1386 attr.border_pixel = 0;
1387 attr.background_pixel = 0x80808080;
1388 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1390 r->w = XCreateWindow(r->d,
1391 parent_window,
1392 x + ox, y + oy,
1393 r->width, r->height,
1395 vinfo.depth,
1396 InputOutput,
1397 vinfo.visual,
1398 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect,
1399 &attr);
1402 void
1403 ps1extents(struct rendering *r)
1405 char *dup;
1406 dup = strdupn(r->ps1);
1407 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1408 free(dup);
1411 void
1412 usage(char *prgname)
1414 fprintf(stderr,
1415 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1416 " [-d separator] [-e window] [-f font] [-G color] [-g size]\n"
1417 " [-H height] [-I color] [-i size] [-J color] [-j size] [-l layout]\n"
1418 " [-P padding] [-p prompt] [-S color] [-s color] [-T color]\n"
1419 " [-t color] [-W width] [-x coord] [-y coord]\n", prgname);
1422 int
1423 main(int argc, char **argv)
1425 struct completions *cs;
1426 struct rendering r;
1427 XVisualInfo vinfo;
1428 Colormap cmap;
1429 size_t nlines, i;
1430 Window parent_window;
1431 XrmDatabase xdb;
1432 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1433 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4], ch_borders_bg[4]; /* N E S W */
1434 enum state status;
1435 int ch;
1436 int offset_x, offset_y, x, y;
1437 int textlen, d_width, d_height;
1438 short embed;
1439 char *sep, *parent_window_id;
1440 char **lines, *buf, **vlines;
1441 char *fontname, *text, *xrm;
1443 #ifdef __OpenBSD__
1444 /* stdio & rpath: to read/write stdio/stdout/stderr */
1445 /* unix: to connect to XOrg */
1446 pledge("stdio rpath unix", "");
1447 #endif
1449 sep = NULL;
1450 parent_window_id = NULL;
1452 r.first_selected = 0;
1453 r.free_text = 1;
1454 r.multiple_select = 0;
1455 r.offset = 0;
1457 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1458 switch (ch) {
1459 case 'h': /* help */
1460 usage(*argv);
1461 return 0;
1462 case 'v': /* version */
1463 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1464 return 0;
1465 case 'e': /* embed */
1466 parent_window_id = strdup(optarg);
1467 check_allocation(parent_window_id);
1468 break;
1469 case 'd':
1470 sep = strdup(optarg);
1471 check_allocation(sep);
1472 case 'A':
1473 r.free_text = 0;
1474 break;
1475 case 'm':
1476 r.multiple_select = 1;
1477 break;
1478 default:
1479 break;
1483 /* Read the completions */
1484 lines = NULL;
1485 buf = NULL;
1486 nlines = readlines(&lines, &buf);
1488 vlines = NULL;
1489 if (sep != NULL) {
1490 int l;
1491 l = strlen(sep);
1492 vlines = calloc(nlines, sizeof(char*));
1493 check_allocation(vlines);
1495 for (i = 0; i < nlines; i++) {
1496 char *t;
1497 t = strstr(lines[i], sep);
1498 if (t == NULL)
1499 vlines[i] = lines[i];
1500 else
1501 vlines[i] = t + l;
1505 setlocale(LC_ALL, getenv("LANG"));
1507 status = LOOPING;
1509 /* where the monitor start (used only with xinerama) */
1510 offset_x = offset_y = 0;
1512 /* default width and height */
1513 r.width = 400;
1514 r.height = 20;
1516 /* default position on the screen */
1517 x = y = 0;
1519 for (i = 0; i < 4; ++i) {
1520 /* default paddings */
1521 r.p_padding[i] = 10;
1522 r.c_padding[i] = 10;
1523 r.ch_padding[i] = 10;
1525 /* default borders */
1526 r.borders[i] = 0;
1527 r.p_borders[i] = 0;
1528 r.c_borders[i] = 0;
1529 r.ch_borders[i] = 0;
1532 /* the prompt. We duplicate the string so later is easy to
1533 * free (in the case it's been overwritten by the user) */
1534 r.ps1 = strdup("$ ");
1535 check_allocation(r.ps1);
1537 /* same for the font name */
1538 fontname = strdup(default_fontname);
1539 check_allocation(fontname);
1541 textlen = 10;
1542 text = malloc(textlen * sizeof(char));
1543 check_allocation(text);
1545 /* struct completions *cs = filter(text, lines); */
1546 cs = compls_new(nlines);
1547 check_allocation(cs);
1549 /* start talking to xorg */
1550 r.d = XOpenDisplay(NULL);
1551 if (r.d == NULL) {
1552 fprintf(stderr, "Could not open display!\n");
1553 return EX_UNAVAILABLE;
1556 embed = 1;
1557 if (! (parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1558 parent_window = DefaultRootWindow(r.d);
1559 embed = 0;
1562 /* get display size */
1563 get_wh(r.d, &parent_window, &d_width, &d_height);
1565 #ifdef USE_XINERAMA
1566 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1567 XineramaScreenInfo *info;
1568 Window rr;
1569 Window root;
1570 int number_of_screens, monitors, i;
1571 int root_x, root_y, win_x, win_y;
1572 unsigned int mask;
1573 short res;
1575 number_of_screens = XScreenCount(r.d);
1576 for (i = 0; i < number_of_screens; ++i) {
1577 root = XRootWindow(r.d, i);
1578 res = XQueryPointer(r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1579 if (res)
1580 break;
1583 if (!res) {
1584 fprintf(stderr, "No mouse found.\n");
1585 root_x = 0;
1586 root_y = 0;
1589 /* Now find in which monitor the mice is */
1590 info = XineramaQueryScreens(r.d, &monitors);
1591 if (info) {
1592 for (i = 0; i < monitors; ++i) {
1593 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1594 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1595 offset_x = info[i].x_org;
1596 offset_y = info[i].y_org;
1597 d_width = info[i].width;
1598 d_height = info[i].height;
1599 break;
1603 XFree(info);
1605 #endif
1607 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1608 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1610 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1611 fgs[2] = parse_color("#000", NULL);
1613 bgs[0] = bgs[1] = parse_color("#000", NULL);
1614 bgs[2] = parse_color("#fff", NULL);
1616 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1618 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3] = parse_color("#000", NULL);
1619 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3] = parse_color("#000", NULL);
1620 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3] = parse_color("#000", NULL);
1622 r.horizontal_layout = 1;
1624 /* Read the resources */
1625 XrmInitialize();
1626 xrm = XResourceManagerString(r.d);
1627 xdb = NULL;
1628 if (xrm != NULL) {
1629 XrmValue value;
1630 char *datatype[20];
1632 xdb = XrmGetStringDatabase(xrm);
1634 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == 1) {
1635 free(fontname);
1636 fontname = strdup(value.addr);
1637 check_allocation(fontname);
1638 } else {
1639 fprintf(stderr, "no font defined, using %s\n", fontname);
1642 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == 1)
1643 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1644 else
1645 fprintf(stderr, "no layout defined, using horizontal\n");
1647 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == 1) {
1648 free(r.ps1);
1649 r.ps1 = normalize_str(value.addr);
1650 } else {
1651 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", r.ps1);
1654 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value) == 1) {
1655 char **sizes;
1656 sizes = parse_csslike(value.addr);
1657 if (sizes != NULL)
1658 for (i = 0; i < 4; ++i)
1659 r.p_borders[i] = parse_integer(sizes[i], 0);
1660 else
1661 fprintf(stderr, "error while parsing MyMenu.prompt.border.size");
1664 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value) == 1) {
1665 char **colors;
1666 colors = parse_csslike(value.addr);
1667 if (colors != NULL)
1668 for (i = 0; i < 4; ++i)
1669 p_borders_bg[i] = parse_color(colors[i], "#000");
1670 else
1671 fprintf(stderr, "error while parsing MyMenu.prompt.border.color");
1674 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value) == 1) {
1675 char **colors;
1676 colors = parse_csslike(value.addr);
1677 if (colors != NULL)
1678 for (i = 0; i < 4; ++i)
1679 r.p_padding[i] = parse_integer(colors[i], 0);
1680 else
1681 fprintf(stderr, "error while parsing MyMenu.prompt.padding");
1684 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == 1)
1685 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1686 else
1687 fprintf(stderr, "no width defined, using %d\n", r.width);
1689 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == 1)
1690 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1691 else
1692 fprintf(stderr, "no height defined, using %d\n", r.height);
1694 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == 1)
1695 x = parse_int_with_pos(value.addr, x, d_width, r.width);
1697 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == 1)
1698 y = parse_int_with_pos(value.addr, y, d_height, r.height);
1700 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == 1) {
1701 char **borders;
1702 borders = parse_csslike(value.addr);
1703 if (borders != NULL)
1704 for (i = 0; i < 4; ++i)
1705 r.borders[i] = parse_int_with_percentage(borders[i], 0, (i % 2) == 0 ? r.height : r.width);
1706 else
1707 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1710 /* Prompt */
1711 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == 1)
1712 fgs[0] = parse_color(value.addr, "#fff");
1714 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == 1)
1715 bgs[0] = parse_color(value.addr, "#000");
1717 /* Completions */
1718 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == 1)
1719 fgs[1] = parse_color(value.addr, "#fff");
1721 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == 1)
1722 bgs[1] = parse_color(value.addr, "#000");
1724 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value) == 1) {
1725 char **paddings;
1726 paddings = parse_csslike(value.addr);
1727 if (paddings != NULL)
1728 for (i = 0; i < 4; ++i)
1729 r.c_padding[i] = parse_integer(paddings[i], 0);
1730 else
1731 fprintf(stderr, "Error while parsing MyMenu.completion.padding");
1734 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value) == 1) {
1735 char **sizes;
1736 sizes = parse_csslike(value.addr);
1737 if (sizes != NULL)
1738 for (i = 0; i < 4; ++i)
1739 r.c_borders[i] = parse_integer(sizes[i], 0);
1740 else
1741 fprintf(stderr, "Error while parsing MyMenu.completion.border.size");
1744 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value) == 1) {
1745 char **sizes;
1746 sizes = parse_csslike(value.addr);
1747 if (sizes != NULL)
1748 for (i = 0; i < 4; ++i)
1749 c_borders_bg[i] = parse_color(sizes[i], "#000");
1750 else
1751 fprintf(stderr, "Error while parsing MyMenu.completion.border.color");
1754 /* Completion Highlighted */
1755 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == 1)
1756 fgs[2] = parse_color(value.addr, "#000");
1758 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == 1)
1759 bgs[2] = parse_color(value.addr, "#fff");
1761 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value) == 1) {
1762 char **paddings;
1763 paddings = parse_csslike(value.addr);
1764 if (paddings != NULL)
1765 for (i = 0; i < 4; ++i)
1766 r.ch_padding[i] = parse_integer(paddings[i], 0);
1767 else
1768 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.padding");
1771 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype, &value) == 1) {
1772 char **sizes;
1773 sizes = parse_csslike(value.addr);
1774 if (sizes != NULL)
1775 for (i = 0; i < 4; ++i)
1776 r.ch_borders[i] = parse_integer(sizes[i], 0);
1777 else
1778 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.size");
1781 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype, &value) == 1) {
1782 char **colors;
1783 colors = parse_csslike(value.addr);
1784 if (colors != NULL)
1785 for (i = 0; i < 4; ++i)
1786 ch_borders_bg[i] = parse_color(colors[i], "#000");
1787 else
1788 fprintf(stderr, "Error while parsing MyMenu.completion_highlighted.border.color");
1791 /* Border */
1792 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == 1) {
1793 char **colors;
1794 colors = parse_csslike(value.addr);
1795 if (colors != NULL)
1796 for (i = 0; i < 4; ++i)
1797 borders_bg[i] = parse_color(colors[i], "#000");
1798 else
1799 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1803 /* Second round of args parsing */
1804 optind = 0; /* reset the option index */
1805 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1806 switch (ch) {
1807 case 'a':
1808 r.first_selected = 1;
1809 break;
1810 case 'A':
1811 /* free_text -- already catched */
1812 case 'd':
1813 /* separator -- this case was already catched */
1814 case 'e':
1815 /* embedding mymenu this case was already catched. */
1816 case 'm':
1817 /* multiple selection this case was already catched. */
1818 break;
1819 case 'p': {
1820 char *newprompt;
1821 newprompt = strdup(optarg);
1822 if (newprompt != NULL) {
1823 free(r.ps1);
1824 r.ps1 = newprompt;
1826 break;
1828 case 'x':
1829 x = parse_int_with_pos(optarg, x, d_width, r.width);
1830 break;
1831 case 'y':
1832 y = parse_int_with_pos(optarg, y, d_height, r.height);
1833 break;
1834 case 'P': {
1835 char **paddings;
1836 if ((paddings = parse_csslike(optarg)) != NULL)
1837 for (i = 0; i < 4; ++i)
1838 r.p_padding[i] = parse_integer(paddings[i], 0);
1839 break;
1841 case 'G': {
1842 char **colors;
1843 if ((colors = parse_csslike(optarg)) != NULL)
1844 for (i = 0; i < 4; ++i)
1845 p_borders_bg[i] = parse_color(colors[i], "#000");
1846 break;
1848 case 'g': {
1849 char **sizes;
1850 if ((sizes = parse_csslike(optarg)) != NULL)
1851 for (i = 0; i < 4; ++i)
1852 r.p_borders[i] = parse_integer(sizes[i], 0);
1853 break;
1855 case 'I': {
1856 char **colors;
1857 if ((colors = parse_csslike(optarg)) != NULL)
1858 for (i = 0; i < 4; ++i)
1859 c_borders_bg[i] = parse_color(colors[i], "#000");
1860 break;
1862 case 'i': {
1863 char **sizes;
1864 if ((sizes = parse_csslike(optarg)) != NULL)
1865 for (i = 0; i < 4; ++i)
1866 r.c_borders[i] = parse_integer(sizes[i], 0);
1867 break;
1869 case 'J': {
1870 char **colors;
1871 if ((colors = parse_csslike(optarg)) != NULL)
1872 for (i = 0; i < 4; ++i)
1873 ch_borders_bg[i] = parse_color(colors[i], "#000");
1874 break;
1876 case 'j': {
1877 char **sizes;
1878 if ((sizes = parse_csslike(optarg)) != NULL)
1879 for (i = 0; i < 4; ++i)
1880 r.ch_borders[i] = parse_integer(sizes[i], 0);
1881 break;
1883 case 'l':
1884 r.horizontal_layout = !strcmp(optarg, "horizontal");
1885 break;
1886 case 'f': {
1887 char *newfont;
1888 if ((newfont = strdup(optarg)) != NULL) {
1889 free(fontname);
1890 fontname = newfont;
1892 break;
1894 case 'W':
1895 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1896 break;
1897 case 'H':
1898 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1899 break;
1900 case 'b': {
1901 char **borders;
1902 if ((borders = parse_csslike(optarg)) != NULL) {
1903 for (i = 0; i < 4; ++i)
1904 r.borders[i] = parse_integer(borders[i], 0);
1905 } else
1906 fprintf(stderr, "Error parsing b option\n");
1907 break;
1909 case 'B': {
1910 char **colors;
1911 if ((colors = parse_csslike(optarg)) != NULL) {
1912 for (i = 0; i < 4; ++i)
1913 borders_bg[i] = parse_color(colors[i], "#000");
1914 } else
1915 fprintf(stderr, "error while parsing B option\n");
1916 break;
1918 case 't':
1919 fgs[0] = parse_color(optarg, NULL);
1920 break;
1921 case 'T':
1922 bgs[0] = parse_color(optarg, NULL);
1923 break;
1924 case 'c':
1925 fgs[1] = parse_color(optarg, NULL);
1926 break;
1927 case 'C':
1928 bgs[1] = parse_color(optarg, NULL);
1929 break;
1930 case 's':
1931 fgs[2] = parse_color(optarg, NULL);
1932 break;
1933 case 'S':
1934 fgs[2] = parse_color(optarg, NULL);
1935 break;
1936 default:
1937 fprintf(stderr, "Unrecognized option %c\n", ch);
1938 status = ERR;
1939 break;
1943 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1944 fprintf(stderr, "height, width, x or y are lesser than 0.");
1945 status = ERR;
1948 /* since only now we know if the first should be selected,
1949 * update the completion here */
1950 update_completions(cs, text, lines, vlines, r.first_selected);
1952 /* update the prompt lenght, only now we surely know the length of it */
1953 r.ps1len = strlen(r.ps1);
1955 /* Create the window */
1956 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y);
1957 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1958 XSelectInput(r.d, r.w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1959 XMapRaised(r.d, r.w);
1961 /* If embed, listen for other events as well */
1962 if (embed) {
1963 Window *children, parent, root;
1964 unsigned int children_no;
1966 XSelectInput(r.d, parent_window, FocusChangeMask);
1967 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no) && children) {
1968 for (i = 0; i < children_no && children[i] != r.w; ++i)
1969 XSelectInput(r.d, children[i], FocusChangeMask);
1970 XFree(children);
1972 grabfocus(r.d, r.w);
1975 take_keyboard(r.d, r.w);
1977 r.x_zero = r.borders[3];
1978 r.y_zero = r.borders[0];
1981 XGCValues values;
1983 for (i = 0; i < 3; ++i) {
1984 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1985 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
1988 for (i = 0; i < 4; ++i) {
1989 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1990 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1991 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1992 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
1996 /* Load the colors in our GCs */
1997 for (i = 0; i < 3; ++i) {
1998 XSetForeground(r.d, r.fgs[i], fgs[i]);
1999 XSetForeground(r.d, r.bgs[i], bgs[i]);
2002 for (i = 0; i < 4; ++i) {
2003 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2004 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2005 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2006 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2009 if (load_font(&r, fontname) == -1)
2010 status = ERR;
2012 #ifdef USE_XFT
2013 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2016 rgba_t c;
2017 XRenderColor xrcolor;
2019 /* Prompt */
2020 c = *(rgba_t*)&fgs[0];
2021 xrcolor.red = EXPANDBITS(c.rgba.r);
2022 xrcolor.green = EXPANDBITS(c.rgba.g);
2023 xrcolor.blue = EXPANDBITS(c.rgba.b);
2024 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2025 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[0]);
2027 /* Completion */
2028 c = *(rgba_t*)&fgs[1];
2029 xrcolor.red = EXPANDBITS(c.rgba.r);
2030 xrcolor.green = EXPANDBITS(c.rgba.g);
2031 xrcolor.blue = EXPANDBITS(c.rgba.b);
2032 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2033 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[1]);
2035 /* Completion highlighted */
2036 c = *(rgba_t*)&fgs[2];
2037 xrcolor.red = EXPANDBITS(c.rgba.r);
2038 xrcolor.green = EXPANDBITS(c.rgba.g);
2039 xrcolor.blue = EXPANDBITS(c.rgba.b);
2040 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2041 XftColorAllocValue(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &xrcolor, &r.xft_colors[2]);
2043 #endif
2045 /* compute prompt dimensions */
2046 ps1extents(&r);
2048 xim_init(&r, &xdb);
2050 #ifdef __OpenBSD__
2051 /* Now we need only the ability to write */
2052 pledge("stdio", "");
2053 #endif
2055 /* Cache text height */
2056 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2058 /* Draw the window for the first time */
2059 draw(&r, text, cs);
2061 /* Main loop */
2062 while (status == LOOPING || status == OK_LOOP) {
2063 status = loop(&r, &text, &textlen, cs, lines, vlines);
2065 if (status != ERR)
2066 printf("%s\n", text);
2068 if (!r.multiple_select && status == OK_LOOP)
2069 status = OK;
2072 XUngrabKeyboard(r.d, CurrentTime);
2074 #ifdef USE_XFT
2075 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[0]);
2076 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[1]);
2077 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_colors[2]);
2078 #endif
2080 free(r.ps1);
2081 free(fontname);
2082 free(text);
2084 free(buf);
2085 free(lines);
2086 free(vlines);
2087 compls_delete(cs);
2089 XDestroyWindow(r.d, r.w);
2090 XCloseDisplay(r.d);
2092 return status != OK;