Blob


1 #include <ctype.h> /* isalnum */
2 #include <err.h>
3 #include <errno.h>
4 #include <limits.h>
5 #include <locale.h> /* setlocale */
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h> /* strdup, strlen */
10 #include <sysexits.h>
11 #include <unistd.h>
13 #include <X11/Xcms.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.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 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
64 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
66 /* The states of the event loop */
67 enum state { LOOPING, OK_LOOP, OK, ERR };
69 /*
70 * For the drawing-related function. The text to be rendere could be
71 * the prompt, a completion or a highlighted completion
72 */
73 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
75 /* These are the possible action to be performed after user input. */
76 enum action {
77 NO_OP,
78 EXIT,
79 CONFIRM,
80 CONFIRM_CONTINUE,
81 NEXT_COMPL,
82 PREV_COMPL,
83 DEL_CHAR,
84 DEL_WORD,
85 DEL_LINE,
86 ADD_CHAR,
87 TOGGLE_FIRST_SELECTED,
88 SCROLL_DOWN,
89 SCROLL_UP,
90 };
92 /* A big set of values that needs to be carried around for drawing. A
93 * big struct to rule them all */
94 struct rendering {
95 Display *d; /* Connection to xorg */
96 Window w;
97 XIM xim;
98 int width;
99 int height;
100 int p_padding[4];
101 int c_padding[4];
102 int ch_padding[4];
103 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
104 the borders) */
105 int y_zero; /* like x_zero but for the y axis */
107 int offset; /* scroll offset */
109 short free_text;
110 short first_selected;
111 short multiple_select;
113 /* four border width */
114 int borders[4];
115 int p_borders[4];
116 int c_borders[4];
117 int ch_borders[4];
119 short horizontal_layout;
121 /* prompt */
122 char *ps1;
123 int ps1len;
124 int ps1w; /* ps1 width */
125 int ps1h; /* ps1 height */
127 int text_height; /* cache for the vertical layout */
129 XIC xic;
131 /* colors */
132 GC fgs[4];
133 GC bgs[4];
134 GC borders_bg[4];
135 GC p_borders_bg[4];
136 GC c_borders_bg[4];
137 GC ch_borders_bg[4];
138 #ifdef USE_XFT
139 XftFont *font;
140 XftDraw *xftdraw;
141 XftColor xft_colors[3];
142 #else
143 XFontSet font;
144 #endif
145 };
147 struct completion {
148 char *completion;
149 char *rcompletion;
150 int offset; /* the x (or y, depending on the layout) coordinate at
151 which the item is rendered */
152 };
154 /* Wrap the linked list of completions */
155 struct completions {
156 struct completion *completions;
157 ssize_t selected;
158 size_t length;
159 };
161 /* idea stolen from lemonbar. ty lemonboy */
162 typedef union {
163 struct {
164 uint8_t b;
165 uint8_t g;
166 uint8_t r;
167 uint8_t a;
168 } rgba;
169 uint32_t v;
170 } rgba_t;
172 extern char *optarg;
173 extern int optind;
175 /* Return a newly allocated (and empty) completion list */
176 struct completions *
177 compls_new(size_t length)
179 struct completions *cs = malloc(sizeof(struct completions));
181 if (cs == NULL)
182 return cs;
184 cs->completions = calloc(length, sizeof(struct completion));
185 if (cs->completions == NULL) {
186 free(cs);
187 return NULL;
190 cs->selected = -1;
191 cs->length = length;
192 return cs;
195 /* Delete the wrapper and the whole list */
196 void
197 compls_delete(struct completions *cs)
199 if (cs == NULL)
200 return;
202 free(cs->completions);
203 free(cs);
206 /*
207 * Create a completion list from a text and the list of possible
208 * completions (null terminated). Expects a non-null `cs'. `lines' and
209 * `vlines' should have the same length OR `vlines' is NULL.
210 */
211 void
212 filter(struct completions *cs, char *text, char **lines, char **vlines)
214 size_t index = 0;
215 size_t matching = 0;
216 char *l;
218 if (vlines == NULL)
219 vlines = lines;
221 while (1) {
222 if (lines[index] == NULL)
223 break;
225 l = vlines[index] != NULL ? vlines[index] : lines[index];
227 if (strcasestr(l, text) != NULL) {
228 struct completion *c = &cs->completions[matching];
229 c->completion = l;
230 c->rcompletion = lines[index];
231 matching++;
234 index++;
236 cs->length = matching;
237 cs->selected = -1;
240 /* Update the given completion */
241 void
242 update_completions(
243 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,
258 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 && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
271 && !p) {
272 free(*text);
273 *text = strdup(cs->completions->completion);
274 if (text == NULL) {
275 *status = ERR;
276 return;
278 *textlen = strlen(*text);
279 return;
282 index = cs->selected;
284 if (index == -1 && p)
285 index = 0;
286 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
288 n = &cs->completions[cs->selected];
290 free(*text);
291 *text = strdup(n->completion);
292 if (text == NULL) {
293 fprintf(stderr, "Memory allocation error!\n");
294 *status = ERR;
295 return;
297 *textlen = strlen(*text);
300 /* Push the character c at the end of the string pointed by p */
301 int
302 pushc(char **p, int maxlen, char c)
304 int len;
306 len = strnlen(*p, maxlen);
307 if (!(len < maxlen - 2)) {
308 char *newptr;
310 maxlen += maxlen >> 1;
311 newptr = realloc(*p, maxlen);
312 if (newptr == NULL) /* bad */
313 return -1;
314 *p = newptr;
317 (*p)[len] = c;
318 (*p)[len + 1] = '\0';
319 return maxlen;
322 /*
323 * Remove the last rune from the *UTF-8* string! This is different
324 * from just setting the last byte to 0 (in some cases ofc). Return a
325 * pointer (e) to the last nonzero char. If e < p then p is empty!
326 */
327 char *
328 popc(char *p)
330 int len = strlen(p);
331 char *e;
333 if (len == 0)
334 return p;
336 e = p + len - 1;
338 do {
339 char c = *e;
341 *e = '\0';
342 e -= 1;
344 /*
345 * If c is a starting byte (11......) or is under
346 * U+007F we're done.
347 */
348 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
349 break;
350 } while (e >= p);
352 return e;
355 /* Remove the last word plus trailing white spaces from the given string */
356 void
357 popw(char *w)
359 int len;
360 short in_word = 1;
362 if ((len = strlen(w)) == 0)
363 return;
365 while (1) {
366 char *e = popc(w);
368 if (e < w)
369 return;
371 if (in_word && isspace(*e))
372 in_word = 0;
374 if (!in_word && !isspace(*e))
375 return;
379 /*
380 * If the string is surrounded by quates (`"') remove them and replace
381 * every `\"' in the string with a single double-quote.
382 */
383 char *
384 normalize_str(const char *str)
386 int len, p;
387 char *s;
389 if ((len = strlen(str)) == 0)
390 return NULL;
392 if ((s = calloc(len, sizeof(char))) == NULL)
393 err(1, "calloc");
394 p = 0;
396 while (*str) {
397 char c = *str;
399 if (*str == '\\') {
400 if (*(str + 1)) {
401 s[p] = *(str + 1);
402 p++;
403 str += 2; /* skip this and the next char */
404 continue;
405 } else
406 break;
408 if (c == '"') {
409 str++; /* skip only this char */
410 continue;
412 s[p] = c;
413 p++;
414 str++;
417 return s;
420 size_t
421 read_stdin(char **buf)
423 size_t offset = 0;
424 size_t len = STDIN_CHUNKS;
426 *buf = malloc(len * sizeof(char));
427 if (*buf == NULL)
428 goto err;
430 while (1) {
431 ssize_t r;
432 size_t i;
434 r = read(0, *buf + offset, STDIN_CHUNKS);
436 if (r < 1)
437 return len;
439 offset += r;
441 len += STDIN_CHUNKS;
442 *buf = realloc(*buf, len);
443 if (*buf == NULL)
444 goto err;
446 for (i = offset; i < len; ++i)
447 (*buf)[i] = '\0';
450 err:
451 fprintf(stderr, "Error in allocating memory for stdin.\n");
452 exit(EX_UNAVAILABLE);
455 size_t
456 readlines(char ***lns, char **buf)
458 size_t i, len, ll, lines;
459 short in_line = 0;
461 lines = 0;
463 *buf = NULL;
464 len = read_stdin(buf);
466 ll = LINES_CHUNK;
467 *lns = malloc(ll * sizeof(char *));
469 if (*lns == NULL)
470 goto err;
472 for (i = 0; i < len; i++) {
473 char c = (*buf)[i];
475 if (c == '\0')
476 break;
478 if (c == '\n')
479 (*buf)[i] = '\0';
481 if (in_line && c == '\n')
482 in_line = 0;
484 if (!in_line && c != '\n') {
485 in_line = 1;
486 (*lns)[lines] = (*buf) + i;
487 lines++;
489 if (lines == ll) { /* resize */
490 ll += LINES_CHUNK;
491 *lns = realloc(*lns, ll * sizeof(char *));
492 if (*lns == NULL)
493 goto err;
498 (*lns)[lines] = NULL;
500 return lines;
502 err:
503 fprintf(stderr, "Error in memory allocation.\n");
504 exit(EX_UNAVAILABLE);
507 /*
508 * Compute the dimensions of the string str once rendered.
509 * It'll return the width and set ret_width and ret_height if not NULL
510 */
511 int
512 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
514 int height, width;
515 #ifdef USE_XFT
516 XGlyphInfo gi;
517 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
518 height = r->font->ascent - r->font->descent;
519 width = gi.width - gi.x;
520 #else
521 XRectangle rect;
522 XmbTextExtents(r->font, str, len, NULL, &rect);
523 height = rect.height;
524 width = rect.width;
525 #endif
526 if (ret_width != NULL)
527 *ret_width = width;
528 if (ret_height != NULL)
529 *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)
539 xftcolor = r->xft_colors[0];
540 if (tt == COMPL)
541 xftcolor = r->xft_colors[1];
542 if (tt == COMPL_HIGH)
543 xftcolor = r->xft_colors[2];
545 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
546 #else
547 GC gc;
548 if (tt == PROMPT)
549 gc = r->fgs[0];
550 if (tt == COMPL)
551 gc = r->fgs[1];
552 if (tt == COMPL_HIGH)
553 gc = r->fgs[2];
554 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
555 #endif
558 /* Duplicate the string and substitute every space with a 'n` */
559 char *
560 strdupn(char *str)
562 int len, i;
563 char *dup;
565 len = strlen(str);
567 if (str == NULL || len == 0)
568 return NULL;
570 if ((dup = strdup(str)) == NULL)
571 return NULL;
573 for (i = 0; i < len; ++i)
574 if (dup[i] == ' ')
575 dup[i] = 'n';
577 return dup;
580 int
581 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
583 GC *border_color, bg;
584 int *padding, *borders;
585 int ret = 0, inner_width, inner_height, x;
587 switch (t) {
588 case PROMPT:
589 border_color = r->p_borders_bg;
590 padding = r->p_padding;
591 borders = r->p_borders;
592 bg = r->bgs[0];
593 break;
594 case COMPL:
595 border_color = r->c_borders_bg;
596 padding = r->c_padding;
597 borders = r->c_borders;
598 bg = r->bgs[1];
599 break;
600 case COMPL_HIGH:
601 border_color = r->ch_borders_bg;
602 padding = r->ch_padding;
603 borders = r->ch_borders;
604 bg = r->bgs[2];
605 break;
608 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
610 inner_width = inner_width(r) - borders[1] - borders[3];
611 inner_height = padding[0] + r->text_height + padding[2];
613 /* Border top */
614 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
616 /* Border right */
617 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
618 borders[1], ret);
620 /* Border bottom */
621 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
622 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
624 /* Border left */
625 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
627 /* bg */
628 x = r->x_zero + borders[3];
629 y += borders[0];
630 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
632 /* content */
633 y += padding[0] + r->text_height;
634 x += padding[3];
635 if (prefix != NULL) {
636 draw_string(prefix, strlen(prefix), x, y, r, t);
637 x += prefix_width;
639 draw_string(text, strlen(text), x, y, r, t);
641 return ret;
644 int
645 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
647 GC *border_color, bg;
648 int *padding, *borders;
649 int ret = 0, inner_width, inner_height, y, text_width;
651 switch (t) {
652 case PROMPT:
653 border_color = r->p_borders_bg;
654 padding = r->p_padding;
655 borders = r->p_borders;
656 bg = r->bgs[0];
657 break;
658 case COMPL:
659 border_color = r->c_borders_bg;
660 padding = r->c_padding;
661 borders = r->c_borders;
662 bg = r->bgs[1];
663 break;
664 case COMPL_HIGH:
665 border_color = r->ch_borders_bg;
666 padding = r->ch_padding;
667 borders = r->ch_borders;
668 bg = r->bgs[2];
669 break;
672 if (padding[0] < 0 || padding[2] < 0)
673 padding[0] = padding[2]
674 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
676 /* If they are still lesser than 0, set 'em to 0 */
677 if (padding[0] < 0 || padding[2] < 0)
678 padding[0] = padding[2] = 0;
680 /* Get the text width */
681 text_extents(text, strlen(text), r, &text_width, NULL);
682 if (prefix != NULL)
683 text_width += prefix_width;
685 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
687 inner_width = padding[3] + text_width + padding[1];
688 inner_height = inner_height(r) - borders[0] - borders[2];
690 /* Border top */
691 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
693 /* Border right */
694 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
695 borders[1], inner_height(r));
697 /* Border bottom */
698 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
699 ret, borders[2]);
701 /* Border left */
702 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
704 /* bg */
705 x += borders[3];
706 y = r->y_zero + borders[0];
707 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
709 /* content */
710 y += padding[0] + r->text_height;
711 x += padding[3];
712 if (prefix != NULL) {
713 draw_string(prefix, strlen(prefix), x, y, r, t);
714 x += prefix_width;
716 draw_string(text, strlen(text), x, y, r, t);
718 return ret;
721 /* ,-----------------------------------------------------------------, */
722 /* | 20 char text | completion | completion | completion | compl | */
723 /* `-----------------------------------------------------------------' */
724 void
725 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
727 size_t i;
728 int x = r->x_zero;
730 /* Draw the prompt */
731 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
733 for (i = r->offset; i < cs->length; ++i) {
734 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
736 cs->completions[i].offset = x;
738 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
740 if (x > inner_width(r))
741 break;
744 for (i += 1; i < cs->length; ++i)
745 cs->completions[i].offset = -1;
748 /* ,-----------------------------------------------------------------, */
749 /* | prompt | */
750 /* |-----------------------------------------------------------------| */
751 /* | completion | */
752 /* |-----------------------------------------------------------------| */
753 /* | completion | */
754 /* `-----------------------------------------------------------------' */
755 void
756 draw_vertically(struct rendering *r, char *text, struct completions *cs)
758 size_t i;
759 int y = r->y_zero;
761 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
763 for (i = r->offset; i < cs->length; ++i) {
764 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
766 cs->completions[i].offset = y;
768 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
770 if (y > inner_height(r))
771 break;
774 for (i += 1; i < cs->length; ++i)
775 cs->completions[i].offset = -1;
778 void
779 draw(struct rendering *r, char *text, struct completions *cs)
781 /* Draw the background */
782 XFillRectangle(
783 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
785 /* Draw the contents */
786 if (r->horizontal_layout)
787 draw_horizontally(r, text, cs);
788 else
789 draw_vertically(r, text, cs);
791 /* Draw the borders */
792 if (r->borders[0] != 0)
793 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
795 if (r->borders[1] != 0)
796 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
797 r->borders[1], r->height);
799 if (r->borders[2] != 0)
800 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
801 r->borders[2]);
803 if (r->borders[3] != 0)
804 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
806 /* render! */
807 XFlush(r->d);
810 /* Set some WM stuff */
811 void
812 set_win_atoms_hints(Display *d, Window w, int width, int height)
814 Atom type;
815 XClassHint *class_hint;
816 XSizeHints *size_hint;
818 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
819 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
820 32, PropModeReplace, (unsigned char *)&type, 1);
822 /* some window managers honor this properties */
823 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
824 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
825 PropModeReplace, (unsigned char *)&type, 1);
827 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
828 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
829 PropModeAppend, (unsigned char *)&type, 1);
831 /* Setting window hints */
832 class_hint = XAllocClassHint();
833 if (class_hint == NULL) {
834 fprintf(stderr, "Could not allocate memory for class hint\n");
835 exit(EX_UNAVAILABLE);
838 class_hint->res_name = resname;
839 class_hint->res_class = resclass;
840 XSetClassHint(d, w, class_hint);
841 XFree(class_hint);
843 size_hint = XAllocSizeHints();
844 if (size_hint == NULL) {
845 fprintf(stderr, "Could not allocate memory for size hint\n");
846 exit(EX_UNAVAILABLE);
849 size_hint->flags = PMinSize | PBaseSize;
850 size_hint->min_width = width;
851 size_hint->base_width = width;
852 size_hint->min_height = height;
853 size_hint->base_height = height;
855 XFlush(d);
858 /* Get the width and height of the window `w' */
859 void
860 get_wh(Display *d, Window *w, int *width, int *height)
862 XWindowAttributes win_attr;
864 XGetWindowAttributes(d, *w, &win_attr);
865 *height = win_attr.height;
866 *width = win_attr.width;
869 int
870 grabfocus(Display *d, Window w)
872 int i;
873 for (i = 0; i < 100; ++i) {
874 Window focuswin;
875 int revert_to_win;
877 XGetInputFocus(d, &focuswin, &revert_to_win);
879 if (focuswin == w)
880 return 1;
882 XSetInputFocus(d, w, RevertToParent, CurrentTime);
883 usleep(1000);
885 return 0;
888 /*
889 * I know this may seem a little hackish BUT is the only way I managed
890 * to actually grab that goddam keyboard. Only one call to
891 * XGrabKeyboard does not always end up with the keyboard grabbed!
892 */
893 int
894 take_keyboard(Display *d, Window w)
896 int i;
897 for (i = 0; i < 100; i++) {
898 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
899 == GrabSuccess)
900 return 1;
901 usleep(1000);
903 fprintf(stderr, "Cannot grab keyboard\n");
904 return 0;
907 unsigned long
908 parse_color(const char *str, const char *def)
910 size_t len;
911 rgba_t tmp;
912 char *ep;
914 if (str == NULL)
915 goto invc;
917 len = strlen(str);
919 /* +1 for the # ath the start */
920 if (*str != '#' || len > 9 || len < 4)
921 goto invc;
922 ++str; /* skip the # */
924 errno = 0;
925 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
927 if (errno)
928 goto invc;
930 switch (len - 1) {
931 case 3:
932 /* expand #rgb -> #rrggbb */
933 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
934 | (tmp.v & 0x00f) * 0x0011;
935 case 6:
936 /* assume 0xff opacity */
937 tmp.rgba.a = 0xff;
938 break;
939 } /* colors in #aarrggbb need no adjustments */
941 /* premultiply the alpha */
942 if (tmp.rgba.a) {
943 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
944 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
945 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
946 return tmp.v;
949 return 0U;
951 invc:
952 fprintf(stderr, "Invalid color: \"%s\".\n", str);
953 if (def != NULL)
954 return parse_color(def, NULL);
955 else
956 return 0U;
959 /*
960 * Given a string try to parse it as a number or return `default_value'.
961 */
962 int
963 parse_integer(const char *str, int default_value)
965 long lval;
966 char *ep;
968 errno = 0;
969 lval = strtol(str, &ep, 10);
971 if (str[0] == '\0' || *ep != '\0') { /* NaN */
972 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str,
973 default_value);
974 return default_value;
977 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
978 || (lval > INT_MAX || lval < INT_MIN)) {
979 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
980 return default_value;
983 return lval;
986 /* Like parse_integer but recognize the percentages (i.e. strings ending with
987 * `%') */
988 int
989 parse_int_with_percentage(const char *str, int default_value, int max)
991 int len = strlen(str);
993 if (len > 0 && str[len - 1] == '%') {
994 int val;
995 char *cpy;
997 if ((cpy = strdup(str)) == NULL)
998 err(1, "strdup");
1000 cpy[len - 1] = '\0';
1001 val = parse_integer(cpy, default_value);
1002 free(cpy);
1003 return val * max / 100;
1006 return parse_integer(str, default_value);
1009 void
1010 get_mouse_coords(Display *d, int *x, int *y)
1012 Window w, root;
1013 int i;
1014 unsigned int u;
1016 *x = *y = 0;
1017 root = DefaultRootWindow(d);
1019 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1020 for (i = 0; i < ScreenCount(d); ++i) {
1021 if (root == RootWindow(d, i))
1022 break;
1028 * Like parse_int_with_percentage but understands some special values:
1029 * - middle that is (max-self)/2
1030 * - center = middle
1031 * - start that is 0
1032 * - end that is (max-self)
1033 * - mx x coordinate of the mouse
1034 * - my y coordinate of the mouse
1036 int
1037 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
1039 if (!strcmp(str, "start"))
1040 return 0;
1041 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1042 return (max - self) / 2;
1043 if (!strcmp(str, "end"))
1044 return max - self;
1045 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1046 int x, y;
1048 get_mouse_coords(d, &x, &y);
1049 if (!strcmp(str, "mx"))
1050 return x;
1051 else
1052 return y;
1054 return parse_int_with_percentage(str, default_value, max);
1057 /* Parse a string like a CSS value. */
1058 /* TODO: harden a bit this function */
1059 char **
1060 parse_csslike(const char *str)
1062 int i, j;
1063 char *s, *token, **ret;
1064 short any_null;
1066 s = strdup(str);
1067 if (s == NULL)
1068 return NULL;
1070 ret = malloc(4 * sizeof(char *));
1071 if (ret == NULL) {
1072 free(s);
1073 return NULL;
1076 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1077 ret[i] = strdup(token);
1079 if (i == 1)
1080 for (j = 1; j < 4; j++)
1081 ret[j] = strdup(ret[0]);
1083 if (i == 2) {
1084 ret[2] = strdup(ret[0]);
1085 ret[3] = strdup(ret[1]);
1088 if (i == 3)
1089 ret[3] = strdup(ret[1]);
1091 /* before we didn't check for the return type of strdup, here we will
1094 any_null = 0;
1095 for (i = 0; i < 4; ++i)
1096 any_null = ret[i] == NULL || any_null;
1098 if (any_null)
1099 for (i = 0; i < 4; ++i)
1100 if (ret[i] != NULL)
1101 free(ret[i]);
1103 if (i == 0 || any_null) {
1104 free(s);
1105 free(ret);
1106 return NULL;
1109 return ret;
1113 * Given an event, try to understand what the users wants. If the
1114 * return value is ADD_CHAR then `input' is a pointer to a string that
1115 * will need to be free'ed later.
1117 enum action
1118 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1120 char str[SYM_BUF_SIZE] = { 0 };
1121 Status s;
1123 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1124 return DEL_CHAR;
1126 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1127 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1129 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1130 return CONFIRM;
1132 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1133 return EXIT;
1135 /* Try to read what key was pressed */
1136 s = 0;
1137 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1138 if (s == XBufferOverflow) {
1139 fprintf(stderr,
1140 "Buffer overflow when trying to create keyboard "
1141 "symbol map.\n");
1142 return EXIT;
1145 if (ev->state & ControlMask) {
1146 if (!strcmp(str, "")) /* C-u */
1147 return DEL_LINE;
1148 if (!strcmp(str, "")) /* C-w */
1149 return DEL_WORD;
1150 if (!strcmp(str, "")) /* C-h */
1151 return DEL_CHAR;
1152 if (!strcmp(str, "\r")) /* C-m */
1153 return CONFIRM_CONTINUE;
1154 if (!strcmp(str, "")) /* C-p */
1155 return PREV_COMPL;
1156 if (!strcmp(str, "")) /* C-n */
1157 return NEXT_COMPL;
1158 if (!strcmp(str, "")) /* C-c */
1159 return EXIT;
1160 if (!strcmp(str, "\t")) /* C-i */
1161 return TOGGLE_FIRST_SELECTED;
1164 *input = strdup(str);
1165 if (*input == NULL) {
1166 fprintf(stderr, "Error while allocating memory for key.\n");
1167 return EXIT;
1170 return ADD_CHAR;
1173 void
1174 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1176 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1177 /* if there is something selected expand it and return */
1178 int index = cs->selected == -1 ? 0 : cs->selected;
1179 struct completion *c = cs->completions;
1180 char *t;
1182 while (1) {
1183 if (index == 0)
1184 break;
1185 c++;
1186 index--;
1189 t = c->rcompletion;
1190 free(*text);
1191 *text = strdup(t);
1193 if (*text == NULL) {
1194 fprintf(stderr, "Memory allocation error\n");
1195 *status = ERR;
1198 *textlen = strlen(*text);
1199 return;
1202 if (!r->free_text) /* cannot accept arbitrary text */
1203 *status = LOOPING;
1206 /* cs: completion list
1207 * offset: the offset of the click
1208 * first: the first (rendered) item
1209 * def: the default action
1211 enum action
1212 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1214 ssize_t selected = first;
1215 int set = 0;
1217 if (cs->length == 0)
1218 return NO_OP;
1220 if (offset < cs->completions[selected].offset)
1221 return EXIT;
1223 /* skip the first entry */
1224 for (selected += 1; selected < cs->length; ++selected) {
1225 if (cs->completions[selected].offset == -1)
1226 break;
1228 if (offset < cs->completions[selected].offset) {
1229 cs->selected = selected - 1;
1230 set = 1;
1231 break;
1235 if (!set)
1236 cs->selected = selected - 1;
1238 return def;
1241 enum action
1242 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1244 size_t off;
1246 if (r->horizontal_layout)
1247 off = e->x;
1248 else
1249 off = e->y;
1251 switch (e->button) {
1252 case Button1:
1253 return select_clicked(cs, off, r->offset, CONFIRM);
1255 case Button3:
1256 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1258 case Button4:
1259 return SCROLL_UP;
1261 case Button5:
1262 return SCROLL_DOWN;
1265 return NO_OP;
1268 /* event loop */
1269 enum state
1270 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1271 char **vlines)
1273 enum state status = LOOPING;
1275 while (status == LOOPING) {
1276 XEvent e;
1277 XNextEvent(r->d, &e);
1279 if (XFilterEvent(&e, r->w))
1280 continue;
1282 switch (e.type) {
1283 case KeymapNotify:
1284 XRefreshKeyboardMapping(&e.xmapping);
1285 break;
1287 case FocusIn:
1288 /* Re-grab focus */
1289 if (e.xfocus.window != r->w)
1290 grabfocus(r->d, r->w);
1291 break;
1293 case VisibilityNotify:
1294 if (e.xvisibility.state != VisibilityUnobscured)
1295 XRaiseWindow(r->d, r->w);
1296 break;
1298 case MapNotify:
1299 get_wh(r->d, &r->w, &r->width, &r->height);
1300 draw(r, *text, cs);
1301 break;
1303 case KeyPress:
1304 case ButtonPress: {
1305 enum action a;
1306 char *input = NULL;
1308 if (e.type == KeyPress)
1309 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1310 else
1311 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1313 switch (a) {
1314 case NO_OP:
1315 break;
1317 case EXIT:
1318 status = ERR;
1319 break;
1321 case CONFIRM: {
1322 status = OK;
1323 confirm(&status, r, cs, text, textlen);
1324 break;
1327 case CONFIRM_CONTINUE: {
1328 status = OK_LOOP;
1329 confirm(&status, r, cs, text, textlen);
1330 break;
1333 case PREV_COMPL: {
1334 complete(cs, r->first_selected, 1, text, textlen, &status);
1335 r->offset = cs->selected;
1336 break;
1339 case NEXT_COMPL: {
1340 complete(cs, r->first_selected, 0, text, textlen, &status);
1341 r->offset = cs->selected;
1342 break;
1345 case DEL_CHAR:
1346 popc(*text);
1347 update_completions(cs, *text, lines, vlines, r->first_selected);
1348 r->offset = 0;
1349 break;
1351 case DEL_WORD: {
1352 popw(*text);
1353 update_completions(cs, *text, lines, vlines, r->first_selected);
1354 break;
1357 case DEL_LINE: {
1358 int i;
1359 for (i = 0; i < *textlen; ++i)
1360 *(*text + i) = 0;
1361 update_completions(cs, *text, lines, vlines, r->first_selected);
1362 r->offset = 0;
1363 break;
1366 case ADD_CHAR: {
1367 int str_len, i;
1369 str_len = strlen(input);
1372 * sometimes a strange key is pressed
1373 * i.e. ctrl alone), so input will be
1374 * empty. Don't need to update
1375 * completion in that case
1377 if (str_len == 0)
1378 break;
1380 for (i = 0; i < str_len; ++i) {
1381 *textlen = pushc(text, *textlen, input[i]);
1382 if (*textlen == -1) {
1383 fprintf(stderr,
1384 "Memory allocation "
1385 "error\n");
1386 status = ERR;
1387 break;
1391 if (status != ERR) {
1392 update_completions(
1393 cs, *text, lines, vlines, r->first_selected);
1394 free(input);
1397 r->offset = 0;
1398 break;
1401 case TOGGLE_FIRST_SELECTED:
1402 r->first_selected = !r->first_selected;
1403 if (r->first_selected && cs->selected < 0)
1404 cs->selected = 0;
1405 if (!r->first_selected && cs->selected == 0)
1406 cs->selected = -1;
1407 break;
1409 case SCROLL_DOWN:
1410 r->offset = MIN(r->offset + 1, cs->length - 1);
1411 break;
1413 case SCROLL_UP:
1414 r->offset = MAX((ssize_t)r->offset - 1, 0);
1415 break;
1420 draw(r, *text, cs);
1423 return status;
1426 int
1427 load_font(struct rendering *r, const char *fontname)
1429 #ifdef USE_XFT
1430 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1431 return 0;
1432 #else
1433 char **missing_charset_list;
1434 int missing_charset_count;
1436 r->font = XCreateFontSet(
1437 r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1438 if (r->font != NULL)
1439 return 0;
1441 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1443 if (!strcmp(fontname, default_fontname))
1444 return -1;
1446 return load_font(r, default_fontname);
1447 #endif
1450 void
1451 xim_init(struct rendering *r, XrmDatabase *xdb)
1453 XIMStyle best_match_style;
1454 XIMStyles *xis;
1455 int i;
1457 /* Open the X input method */
1458 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1459 err(1, "XOpenIM");
1461 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1462 fprintf(stderr, "Input Styles could not be retrieved\n");
1463 exit(EX_UNAVAILABLE);
1466 best_match_style = 0;
1467 for (i = 0; i < xis->count_styles; ++i) {
1468 XIMStyle ts = xis->supported_styles[i];
1469 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1470 best_match_style = ts;
1471 break;
1474 XFree(xis);
1476 if (!best_match_style)
1477 fprintf(stderr, "No matching input style could be determined\n");
1479 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1480 XNFocusWindow, r->w, NULL);
1481 if (r->xic == NULL)
1482 err(1, "XCreateIC");
1485 void
1486 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1487 int y, int ox, int oy, unsigned long background_pixel)
1489 XSetWindowAttributes attr;
1491 /* Create the window */
1492 attr.colormap = cmap;
1493 attr.override_redirect = 1;
1494 attr.border_pixel = 0;
1495 attr.background_pixel = background_pixel;
1496 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1497 | ButtonPress | VisibilityChangeMask;
1499 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1500 vinfo.depth, InputOutput, vinfo.visual,
1501 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1504 void
1505 ps1extents(struct rendering *r)
1507 char *dup;
1508 dup = strdupn(r->ps1);
1509 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1510 free(dup);
1513 void
1514 usage(char *prgname)
1516 fprintf(stderr,
1517 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1518 " [-d separator] [-e window] [-f font] [-G color] [-g "
1519 "size]\n"
1520 " [-H height] [-I color] [-i size] [-J color] [-j "
1521 "size] [-l layout]\n"
1522 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1523 "color]\n"
1524 " [-t color] [-W width] [-x coord] [-y coord]\n",
1525 prgname);
1528 int
1529 main(int argc, char **argv)
1531 struct completions *cs;
1532 struct rendering r;
1533 XVisualInfo vinfo;
1534 Colormap cmap;
1535 size_t nlines, i;
1536 Window parent_window;
1537 XrmDatabase xdb;
1538 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1539 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1540 ch_borders_bg[4]; /* N E S W */
1541 enum state status;
1542 int ch;
1543 int offset_x, offset_y, x, y;
1544 int textlen, d_width, d_height;
1545 short embed;
1546 char *sep, *parent_window_id;
1547 char **lines, *buf, **vlines;
1548 char *fontname, *text, *xrm;
1550 #ifdef __OpenBSD__
1551 /* stdio & rpath: to read/write stdio/stdout/stderr */
1552 /* unix: to connect to XOrg */
1553 pledge("stdio rpath unix", "");
1554 #endif
1556 sep = NULL;
1557 parent_window_id = NULL;
1559 r.first_selected = 0;
1560 r.free_text = 1;
1561 r.multiple_select = 0;
1562 r.offset = 0;
1564 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1565 switch (ch) {
1566 case 'h': /* help */
1567 usage(*argv);
1568 return 0;
1569 case 'v': /* version */
1570 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1571 return 0;
1572 case 'e': /* embed */
1573 if ((parent_window_id = strdup(optarg)) == NULL)
1574 err(1, "strdup");
1575 break;
1576 case 'd':
1577 if ((sep = strdup(optarg)) == NULL)
1578 err(1, "strdup");
1579 break;
1580 case 'A':
1581 r.free_text = 0;
1582 break;
1583 case 'm':
1584 r.multiple_select = 1;
1585 break;
1586 default:
1587 break;
1591 /* Read the completions */
1592 lines = NULL;
1593 buf = NULL;
1594 nlines = readlines(&lines, &buf);
1596 vlines = NULL;
1597 if (sep != NULL) {
1598 int l;
1599 l = strlen(sep);
1600 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1601 err(1, "calloc");
1603 for (i = 0; i < nlines; i++) {
1604 char *t;
1605 t = strstr(lines[i], sep);
1606 if (t == NULL)
1607 vlines[i] = lines[i];
1608 else
1609 vlines[i] = t + l;
1613 setlocale(LC_ALL, getenv("LANG"));
1615 status = LOOPING;
1617 /* where the monitor start (used only with xinerama) */
1618 offset_x = offset_y = 0;
1620 /* default width and height */
1621 r.width = 400;
1622 r.height = 20;
1624 /* default position on the screen */
1625 x = y = 0;
1627 for (i = 0; i < 4; ++i) {
1628 /* default paddings */
1629 r.p_padding[i] = 10;
1630 r.c_padding[i] = 10;
1631 r.ch_padding[i] = 10;
1633 /* default borders */
1634 r.borders[i] = 0;
1635 r.p_borders[i] = 0;
1636 r.c_borders[i] = 0;
1637 r.ch_borders[i] = 0;
1640 /* the prompt. We duplicate the string so later is easy to
1641 * free (in the case it's been overwritten by the user) */
1642 if ((r.ps1 = strdup("$ ")) == NULL)
1643 err(1, "strdup");
1645 /* same for the font name */
1646 if ((fontname = strdup(default_fontname)) == NULL)
1647 err(1, "strdup");
1649 textlen = 10;
1650 if ((text = malloc(textlen * sizeof(char))) == NULL)
1651 err(1, "malloc");
1653 /* struct completions *cs = filter(text, lines); */
1654 if ((cs = compls_new(nlines)) == NULL)
1655 err(1, "compls_new");
1657 /* start talking to xorg */
1658 r.d = XOpenDisplay(NULL);
1659 if (r.d == NULL) {
1660 fprintf(stderr, "Could not open display!\n");
1661 return EX_UNAVAILABLE;
1664 embed = 1;
1665 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1666 parent_window = DefaultRootWindow(r.d);
1667 embed = 0;
1670 /* get display size */
1671 get_wh(r.d, &parent_window, &d_width, &d_height);
1673 #ifdef USE_XINERAMA
1674 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1675 XineramaScreenInfo *info;
1676 Window rr;
1677 Window root;
1678 int number_of_screens, monitors, i;
1679 int root_x, root_y, win_x, win_y;
1680 unsigned int mask;
1681 short res;
1683 number_of_screens = XScreenCount(r.d);
1684 for (i = 0; i < number_of_screens; ++i) {
1685 root = XRootWindow(r.d, i);
1686 res = XQueryPointer(
1687 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1688 if (res)
1689 break;
1692 if (!res) {
1693 fprintf(stderr, "No mouse found.\n");
1694 root_x = 0;
1695 root_y = 0;
1698 /* Now find in which monitor the mice is */
1699 info = XineramaQueryScreens(r.d, &monitors);
1700 if (info) {
1701 for (i = 0; i < monitors; ++i) {
1702 if (info[i].x_org <= root_x
1703 && root_x <= (info[i].x_org + info[i].width)
1704 && info[i].y_org <= root_y
1705 && root_y <= (info[i].y_org + info[i].height)) {
1706 offset_x = info[i].x_org;
1707 offset_y = info[i].y_org;
1708 d_width = info[i].width;
1709 d_height = info[i].height;
1710 break;
1714 XFree(info);
1716 #endif
1718 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1719 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1721 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1722 fgs[2] = parse_color("#000", NULL);
1724 bgs[0] = bgs[1] = parse_color("#000", NULL);
1725 bgs[2] = parse_color("#fff", NULL);
1727 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1729 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1730 = parse_color("#000", NULL);
1731 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1732 = parse_color("#000", NULL);
1733 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1734 = parse_color("#000", NULL);
1736 r.horizontal_layout = 1;
1738 /* Read the resources */
1739 XrmInitialize();
1740 xrm = XResourceManagerString(r.d);
1741 xdb = NULL;
1742 if (xrm != NULL) {
1743 XrmValue value;
1744 char *datatype[20];
1746 xdb = XrmGetStringDatabase(xrm);
1748 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1749 free(fontname);
1750 if ((fontname = strdup(value.addr)) == NULL)
1751 err(1, "strdup");
1752 } else {
1753 fprintf(stderr, "no font defined, using %s\n", fontname);
1756 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1757 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1758 else
1759 fprintf(stderr, "no layout defined, using horizontal\n");
1761 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1762 free(r.ps1);
1763 r.ps1 = normalize_str(value.addr);
1764 } else {
1765 fprintf(stderr,
1766 "no prompt defined, using \"%s\" as "
1767 "default\n",
1768 r.ps1);
1771 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1772 char **sizes;
1773 sizes = parse_csslike(value.addr);
1774 if (sizes != NULL)
1775 for (i = 0; i < 4; ++i)
1776 r.p_borders[i] = parse_integer(sizes[i], 0);
1777 else
1778 fprintf(stderr,
1779 "error while parsing "
1780 "MyMenu.prompt.border.size");
1783 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1784 char **colors;
1785 colors = parse_csslike(value.addr);
1786 if (colors != NULL)
1787 for (i = 0; i < 4; ++i)
1788 p_borders_bg[i] = parse_color(colors[i], "#000");
1789 else
1790 fprintf(stderr,
1791 "error while parsing "
1792 "MyMenu.prompt.border.color");
1795 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1796 char **colors;
1797 colors = parse_csslike(value.addr);
1798 if (colors != NULL)
1799 for (i = 0; i < 4; ++i)
1800 r.p_padding[i] = parse_integer(colors[i], 0);
1801 else
1802 fprintf(stderr,
1803 "error while parsing "
1804 "MyMenu.prompt.padding");
1807 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1808 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1809 else
1810 fprintf(stderr, "no width defined, using %d\n", r.width);
1812 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1813 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1814 else
1815 fprintf(stderr, "no height defined, using %d\n", r.height);
1817 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1818 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1820 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1821 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1823 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1824 char **borders;
1825 borders = parse_csslike(value.addr);
1826 if (borders != NULL)
1827 for (i = 0; i < 4; ++i)
1828 r.borders[i] = parse_int_with_percentage(
1829 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1830 else
1831 fprintf(stderr,
1832 "error while parsing "
1833 "MyMenu.border.size\n");
1836 /* Prompt */
1837 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1838 fgs[0] = parse_color(value.addr, "#fff");
1840 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1841 bgs[0] = parse_color(value.addr, "#000");
1843 /* Completions */
1844 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1845 fgs[1] = parse_color(value.addr, "#fff");
1847 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1848 bgs[1] = parse_color(value.addr, "#000");
1850 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1851 char **paddings;
1852 paddings = parse_csslike(value.addr);
1853 if (paddings != NULL)
1854 for (i = 0; i < 4; ++i)
1855 r.c_padding[i] = parse_integer(paddings[i], 0);
1856 else
1857 fprintf(stderr,
1858 "Error while parsing "
1859 "MyMenu.completion.padding");
1862 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1863 char **sizes;
1864 sizes = parse_csslike(value.addr);
1865 if (sizes != NULL)
1866 for (i = 0; i < 4; ++i)
1867 r.c_borders[i] = parse_integer(sizes[i], 0);
1868 else
1869 fprintf(stderr,
1870 "Error while parsing "
1871 "MyMenu.completion.border.size");
1874 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1875 char **sizes;
1876 sizes = parse_csslike(value.addr);
1877 if (sizes != NULL)
1878 for (i = 0; i < 4; ++i)
1879 c_borders_bg[i] = parse_color(sizes[i], "#000");
1880 else
1881 fprintf(stderr,
1882 "Error while parsing "
1883 "MyMenu.completion.border.color");
1886 /* Completion Highlighted */
1887 if (XrmGetResource(
1888 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1889 fgs[2] = parse_color(value.addr, "#000");
1891 if (XrmGetResource(
1892 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1893 bgs[2] = parse_color(value.addr, "#fff");
1895 if (XrmGetResource(
1896 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1897 char **paddings;
1898 paddings = parse_csslike(value.addr);
1899 if (paddings != NULL)
1900 for (i = 0; i < 4; ++i)
1901 r.ch_padding[i] = parse_integer(paddings[i], 0);
1902 else
1903 fprintf(stderr,
1904 "Error while parsing "
1905 "MyMenu.completion_highlighted."
1906 "padding");
1909 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1910 &value)) {
1911 char **sizes;
1912 sizes = parse_csslike(value.addr);
1913 if (sizes != NULL)
1914 for (i = 0; i < 4; ++i)
1915 r.ch_borders[i] = parse_integer(sizes[i], 0);
1916 else
1917 fprintf(stderr,
1918 "Error while parsing "
1919 "MyMenu.completion_highlighted."
1920 "border.size");
1923 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1924 &value)) {
1925 char **colors;
1926 colors = parse_csslike(value.addr);
1927 if (colors != NULL)
1928 for (i = 0; i < 4; ++i)
1929 ch_borders_bg[i] = parse_color(colors[i], "#000");
1930 else
1931 fprintf(stderr,
1932 "Error while parsing "
1933 "MyMenu.completion_highlighted."
1934 "border.color");
1937 /* Border */
1938 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1939 char **colors;
1940 colors = parse_csslike(value.addr);
1941 if (colors != NULL)
1942 for (i = 0; i < 4; ++i)
1943 borders_bg[i] = parse_color(colors[i], "#000");
1944 else
1945 fprintf(stderr,
1946 "error while parsing "
1947 "MyMenu.border.color\n");
1951 /* Second round of args parsing */
1952 optind = 0; /* reset the option index */
1953 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1954 switch (ch) {
1955 case 'a':
1956 r.first_selected = 1;
1957 break;
1958 case 'A':
1959 /* free_text -- already catched */
1960 case 'd':
1961 /* separator -- this case was already catched */
1962 case 'e':
1963 /* embedding mymenu this case was already catched. */
1964 case 'm':
1965 /* multiple selection this case was already catched.
1967 break;
1968 case 'p': {
1969 char *newprompt;
1970 newprompt = strdup(optarg);
1971 if (newprompt != NULL) {
1972 free(r.ps1);
1973 r.ps1 = newprompt;
1975 break;
1977 case 'x':
1978 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1979 break;
1980 case 'y':
1981 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1982 break;
1983 case 'P': {
1984 char **paddings;
1985 if ((paddings = parse_csslike(optarg)) != NULL)
1986 for (i = 0; i < 4; ++i)
1987 r.p_padding[i] = parse_integer(paddings[i], 0);
1988 break;
1990 case 'G': {
1991 char **colors;
1992 if ((colors = parse_csslike(optarg)) != NULL)
1993 for (i = 0; i < 4; ++i)
1994 p_borders_bg[i] = parse_color(colors[i], "#000");
1995 break;
1997 case 'g': {
1998 char **sizes;
1999 if ((sizes = parse_csslike(optarg)) != NULL)
2000 for (i = 0; i < 4; ++i)
2001 r.p_borders[i] = parse_integer(sizes[i], 0);
2002 break;
2004 case 'I': {
2005 char **colors;
2006 if ((colors = parse_csslike(optarg)) != NULL)
2007 for (i = 0; i < 4; ++i)
2008 c_borders_bg[i] = parse_color(colors[i], "#000");
2009 break;
2011 case 'i': {
2012 char **sizes;
2013 if ((sizes = parse_csslike(optarg)) != NULL)
2014 for (i = 0; i < 4; ++i)
2015 r.c_borders[i] = parse_integer(sizes[i], 0);
2016 break;
2018 case 'J': {
2019 char **colors;
2020 if ((colors = parse_csslike(optarg)) != NULL)
2021 for (i = 0; i < 4; ++i)
2022 ch_borders_bg[i] = parse_color(colors[i], "#000");
2023 break;
2025 case 'j': {
2026 char **sizes;
2027 if ((sizes = parse_csslike(optarg)) != NULL)
2028 for (i = 0; i < 4; ++i)
2029 r.ch_borders[i] = parse_integer(sizes[i], 0);
2030 break;
2032 case 'l':
2033 r.horizontal_layout = !strcmp(optarg, "horizontal");
2034 break;
2035 case 'f': {
2036 char *newfont;
2037 if ((newfont = strdup(optarg)) != NULL) {
2038 free(fontname);
2039 fontname = newfont;
2041 break;
2043 case 'W':
2044 r.width = parse_int_with_percentage(optarg, r.width, d_width);
2045 break;
2046 case 'H':
2047 r.height = parse_int_with_percentage(optarg, r.height, d_height);
2048 break;
2049 case 'b': {
2050 char **borders;
2051 if ((borders = parse_csslike(optarg)) != NULL) {
2052 for (i = 0; i < 4; ++i)
2053 r.borders[i] = parse_integer(borders[i], 0);
2054 } else
2055 fprintf(stderr, "Error parsing b option\n");
2056 break;
2058 case 'B': {
2059 char **colors;
2060 if ((colors = parse_csslike(optarg)) != NULL) {
2061 for (i = 0; i < 4; ++i)
2062 borders_bg[i] = parse_color(colors[i], "#000");
2063 } else
2064 fprintf(stderr, "error while parsing B option\n");
2065 break;
2067 case 't':
2068 fgs[0] = parse_color(optarg, NULL);
2069 break;
2070 case 'T':
2071 bgs[0] = parse_color(optarg, NULL);
2072 break;
2073 case 'c':
2074 fgs[1] = parse_color(optarg, NULL);
2075 break;
2076 case 'C':
2077 bgs[1] = parse_color(optarg, NULL);
2078 break;
2079 case 's':
2080 fgs[2] = parse_color(optarg, NULL);
2081 break;
2082 case 'S':
2083 fgs[2] = parse_color(optarg, NULL);
2084 break;
2085 default:
2086 fprintf(stderr, "Unrecognized option %c\n", ch);
2087 status = ERR;
2088 break;
2092 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2093 fprintf(stderr, "height, width, x or y are lesser than 0.");
2094 status = ERR;
2097 /* since only now we know if the first should be selected,
2098 * update the completion here */
2099 update_completions(cs, text, lines, vlines, r.first_selected);
2101 /* update the prompt lenght, only now we surely know the length of it
2103 r.ps1len = strlen(r.ps1);
2105 /* Create the window */
2106 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2107 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2108 XMapRaised(r.d, r.w);
2110 /* If embed, listen for other events as well */
2111 if (embed) {
2112 Window *children, parent, root;
2113 unsigned int children_no;
2115 XSelectInput(r.d, parent_window, FocusChangeMask);
2116 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2117 && children) {
2118 for (i = 0; i < children_no && children[i] != r.w; ++i)
2119 XSelectInput(r.d, children[i], FocusChangeMask);
2120 XFree(children);
2122 grabfocus(r.d, r.w);
2125 take_keyboard(r.d, r.w);
2127 r.x_zero = r.borders[3];
2128 r.y_zero = r.borders[0];
2131 XGCValues values;
2133 for (i = 0; i < 3; ++i) {
2134 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2135 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2138 for (i = 0; i < 4; ++i) {
2139 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2140 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2141 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2142 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2146 /* Load the colors in our GCs */
2147 for (i = 0; i < 3; ++i) {
2148 XSetForeground(r.d, r.fgs[i], fgs[i]);
2149 XSetForeground(r.d, r.bgs[i], bgs[i]);
2152 for (i = 0; i < 4; ++i) {
2153 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2154 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2155 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2156 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2159 if (load_font(&r, fontname) == -1)
2160 status = ERR;
2162 #ifdef USE_XFT
2163 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2165 for (i = 0; i < 3; ++i) {
2166 rgba_t c;
2167 XRenderColor xrcolor;
2169 c = *(rgba_t *)&fgs[i];
2170 xrcolor.red = EXPANDBITS(c.rgba.r);
2171 xrcolor.green = EXPANDBITS(c.rgba.g);
2172 xrcolor.blue = EXPANDBITS(c.rgba.b);
2173 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2174 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2176 #endif
2178 /* compute prompt dimensions */
2179 ps1extents(&r);
2181 xim_init(&r, &xdb);
2183 #ifdef __OpenBSD__
2184 /* Now we need only the ability to write */
2185 pledge("stdio", "");
2186 #endif
2188 /* Cache text height */
2189 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2191 /* Draw the window for the first time */
2192 draw(&r, text, cs);
2194 /* Main loop */
2195 while (status == LOOPING || status == OK_LOOP) {
2196 status = loop(&r, &text, &textlen, cs, lines, vlines);
2198 if (status != ERR)
2199 printf("%s\n", text);
2201 if (!r.multiple_select && status == OK_LOOP)
2202 status = OK;
2205 XUngrabKeyboard(r.d, CurrentTime);
2207 #ifdef USE_XFT
2208 for (i = 0; i < 3; ++i)
2209 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2210 #endif
2212 for (i = 0; i < 3; ++i) {
2213 XFreeGC(r.d, r.fgs[i]);
2214 XFreeGC(r.d, r.bgs[i]);
2217 for (i = 0; i < 4; ++i) {
2218 XFreeGC(r.d, r.borders_bg[i]);
2219 XFreeGC(r.d, r.p_borders_bg[i]);
2220 XFreeGC(r.d, r.c_borders_bg[i]);
2221 XFreeGC(r.d, r.ch_borders_bg[i]);
2224 XDestroyIC(r.xic);
2225 XCloseIM(r.xim);
2227 #ifdef USE_XFT
2228 for (i = 0; i < 3; ++i)
2229 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2230 XftFontClose(r.d, r.font);
2231 XftDrawDestroy(r.xftdraw);
2232 #else
2233 XFreeFontSet(r.d, r.font);
2234 #endif
2236 free(r.ps1);
2237 free(fontname);
2238 free(text);
2240 free(buf);
2241 free(lines);
2242 free(vlines);
2243 compls_delete(cs);
2245 XFreeColormap(r.d, cmap);
2247 XDestroyWindow(r.d, r.w);
2248 XCloseDisplay(r.d);
2250 return status != OK;