Blob


1 #include <ctype.h> /* isalnum */
2 #include <errno.h>
3 #include <limits.h>
4 #include <locale.h> /* setlocale */
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h> /* strdup, strlen */
9 #include <sysexits.h>
10 #include <unistd.h>
12 #include <X11/Xcms.h>
13 #include <X11/Xlib.h>
14 #include <X11/Xresource.h>
15 #include <X11/Xutil.h>
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 #include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 #include <X11/Xft/Xft.h>
24 #endif
26 #ifndef VERSION
27 #define VERSION "unknown"
28 #endif
30 #define resname "MyMenu"
31 #define resclass "mymenu"
33 #define SYM_BUF_SIZE 4
35 #ifdef USE_XFT
36 #define default_fontname "monospace"
37 #else
38 #define default_fontname "fixed"
39 #endif
41 #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:"
43 #define MIN(a, b) ((a) < (b) ? (a) : (b))
44 #define MAX(a, b) ((a) > (b) ? (a) : (b))
46 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
48 /*
49 * If we don't have or we don't want an "ignore case" completion
50 * style, fall back to `strstr(3)`
51 */
52 #ifndef USE_STRCASESTR
53 #define strcasestr strstr
54 #endif
56 /* The number of char to read */
57 #define STDIN_CHUNKS 128
59 /* The number of lines to allocate in advance */
60 #define LINES_CHUNK 64
62 /* Abort on NULL */
63 #define check_allocation(a) \
64 { \
65 if (a == NULL) { \
66 fprintf(stderr, "Could not allocate memory\n"); \
67 abort(); \
68 } \
69 }
71 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
72 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
74 /* The states of the event loop */
75 enum state { LOOPING, OK_LOOP, OK, ERR };
77 /*
78 * For the drawing-related function. The text to be rendere could be
79 * the prompt, a completion or a highlighted completion
80 */
81 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
83 /* These are the possible action to be performed after user input. */
84 enum action {
85 EXIT,
86 CONFIRM,
87 CONFIRM_CONTINUE,
88 NEXT_COMPL,
89 PREV_COMPL,
90 DEL_CHAR,
91 DEL_WORD,
92 DEL_LINE,
93 ADD_CHAR,
94 TOGGLE_FIRST_SELECTED
95 };
97 /* A big set of values that needs to be carried around for drawing. A
98 big struct to rule them all */
99 struct rendering {
100 Display *d; /* Connection to xorg */
101 Window w;
102 XIM xim;
103 int width;
104 int height;
105 int p_padding[4];
106 int c_padding[4];
107 int ch_padding[4];
108 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
109 the borders) */
110 int y_zero; /* like x_zero but for the y axis */
112 size_t offset; /* scroll offset */
114 short free_text;
115 short first_selected;
116 short multiple_select;
118 /* four border width */
119 int borders[4];
120 int p_borders[4];
121 int c_borders[4];
122 int ch_borders[4];
124 short horizontal_layout;
126 /* prompt */
127 char *ps1;
128 int ps1len;
129 int ps1w; /* ps1 width */
130 int ps1h; /* ps1 height */
132 int text_height; /* cache for the vertical layout */
134 XIC xic;
136 /* colors */
137 GC fgs[4];
138 GC bgs[4];
139 GC borders_bg[4];
140 GC p_borders_bg[4];
141 GC c_borders_bg[4];
142 GC ch_borders_bg[4];
143 #ifdef USE_XFT
144 XftFont *font;
145 XftDraw *xftdraw;
146 XftColor xft_colors[3];
147 #else
148 XFontSet font;
149 #endif
150 };
152 struct completion {
153 char *completion;
154 char *rcompletion;
155 };
157 /* Wrap the linked list of completions */
158 struct completions {
159 struct completion *completions;
160 ssize_t selected;
161 size_t length;
162 };
164 /* idea stolen from lemonbar. ty lemonboy */
165 typedef union {
166 struct {
167 uint8_t b;
168 uint8_t g;
169 uint8_t r;
170 uint8_t a;
171 } rgba;
172 uint32_t v;
173 } rgba_t;
175 extern char *optarg;
176 extern int optind;
178 /* Return a newly allocated (and empty) completion list */
179 struct completions *
180 compls_new(size_t length)
182 struct completions *cs = malloc(sizeof(struct completions));
184 if (cs == NULL)
185 return cs;
187 cs->completions = calloc(length, sizeof(struct completion));
188 if (cs->completions == NULL) {
189 free(cs);
190 return NULL;
193 cs->selected = -1;
194 cs->length = length;
195 return cs;
198 /* Delete the wrapper and the whole list */
199 void
200 compls_delete(struct completions *cs)
202 if (cs == NULL)
203 return;
205 free(cs->completions);
206 free(cs);
209 /*
210 * Create a completion list from a text and the list of possible
211 * completions (null terminated). Expects a non-null `cs'. `lines' and
212 * `vlines' should have the same length OR `vlines' is NULL.
213 */
214 void
215 filter(struct completions *cs, char *text, char **lines, char **vlines)
217 size_t index = 0;
218 size_t matching = 0;
219 char *l;
221 if (vlines == NULL)
222 vlines = lines;
224 while (1) {
225 if (lines[index] == NULL)
226 break;
228 l = vlines[index] != NULL ? vlines[index] : lines[index];
230 if (strcasestr(l, text) != NULL) {
231 struct completion *c = &cs->completions[matching];
232 c->completion = l;
233 c->rcompletion = lines[index];
234 matching++;
237 index++;
239 cs->length = matching;
240 cs->selected = -1;
243 /* Update the given completion */
244 void
245 update_completions(struct completions *cs, char *text, char **lines,
246 char **vlines, short first_selected)
248 filter(cs, text, lines, vlines);
249 if (first_selected && cs->length > 0)
250 cs->selected = 0;
253 /*
254 * Select the next or previous selection and update some state. `text'
255 * will be updated with the text of the completion and `textlen' with
256 * the new length. If the memory cannot be allocated `status' will be
257 * set to `ERR'.
258 */
259 void
260 complete(struct completions *cs, short first_selected, short p, char **text,
261 int *textlen, enum state *status)
263 struct completion *n;
264 int index;
266 if (cs == NULL || cs->length == 0)
267 return;
269 /*
270 * If the first is always selected and the first entry is
271 * different from the text, expand the text and return
272 */
273 if (first_selected && cs->selected == 0
274 && strcmp(cs->completions->completion, *text) != 0 && !p) {
275 free(*text);
276 *text = strdup(cs->completions->completion);
277 if (text == NULL) {
278 *status = ERR;
279 return;
281 *textlen = strlen(*text);
282 return;
285 index = cs->selected;
287 if (index == -1 && p)
288 index = 0;
289 index = cs->selected
290 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
292 n = &cs->completions[cs->selected];
294 free(*text);
295 *text = strdup(n->completion);
296 if (text == NULL) {
297 fprintf(stderr, "Memory allocation error!\n");
298 *status = ERR;
299 return;
301 *textlen = strlen(*text);
304 /* Push the character c at the end of the string pointed by p */
305 int
306 pushc(char **p, int maxlen, char c)
308 int len;
310 len = strnlen(*p, maxlen);
311 if (!(len < maxlen - 2)) {
312 char *newptr;
314 maxlen += maxlen >> 1;
315 newptr = realloc(*p, maxlen);
316 if (newptr == NULL) /* bad */
317 return -1;
318 *p = newptr;
321 (*p)[len] = c;
322 (*p)[len + 1] = '\0';
323 return maxlen;
326 /*
327 * Remove the last rune from the *UTF-8* string! This is different
328 * from just setting the last byte to 0 (in some cases ofc). Return a
329 * pointer (e) to the last nonzero char. If e < p then p is empty!
330 */
331 char *
332 popc(char *p)
334 int len = strlen(p);
335 char *e;
337 if (len == 0)
338 return p;
340 e = p + len - 1;
342 do {
343 char c = *e;
345 *e = '\0';
346 e -= 1;
348 /*
349 * If c is a starting byte (11......) or is under
350 * U+007F we're done.
351 */
352 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
353 break;
354 } while (e >= p);
356 return e;
359 /* Remove the last word plus trailing white spaces from the given string */
360 void
361 popw(char *w)
363 int len;
364 short in_word = 1;
366 if ((len = strlen(w)) == 0)
367 return;
369 while (1) {
370 char *e = popc(w);
372 if (e < w)
373 return;
375 if (in_word && isspace(*e))
376 in_word = 0;
378 if (!in_word && !isspace(*e))
379 return;
383 /*
384 * If the string is surrounded by quates (`"') remove them and replace
385 * every `\"' in the string with a single double-quote.
386 */
387 char *
388 normalize_str(const char *str)
390 int len, p;
391 char *s;
393 if ((len = strlen(str)) == 0)
394 return NULL;
396 s = calloc(len, sizeof(char));
397 check_allocation(s);
398 p = 0;
400 while (*str) {
401 char c = *str;
403 if (*str == '\\') {
404 if (*(str + 1)) {
405 s[p] = *(str + 1);
406 p++;
407 str += 2; /* skip this and the next char */
408 continue;
409 } else
410 break;
412 if (c == '"') {
413 str++; /* skip only this char */
414 continue;
416 s[p] = c;
417 p++;
418 str++;
421 return s;
424 size_t
425 read_stdin(char **buf)
427 size_t offset = 0;
428 size_t len = STDIN_CHUNKS;
430 *buf = malloc(len * sizeof(char));
431 if (*buf == NULL)
432 goto err;
434 while (1) {
435 ssize_t r;
436 size_t i;
438 r = read(0, *buf + offset, STDIN_CHUNKS);
440 if (r < 1)
441 return len;
443 offset += r;
445 len += STDIN_CHUNKS;
446 *buf = realloc(*buf, len);
447 if (*buf == NULL)
448 goto err;
450 for (i = offset; i < len; ++i)
451 (*buf)[i] = '\0';
454 err:
455 fprintf(stderr, "Error in allocating memory for stdin.\n");
456 exit(EX_UNAVAILABLE);
459 size_t
460 readlines(char ***lns, char **buf)
462 size_t i, len, ll, lines;
463 short in_line = 0;
465 lines = 0;
467 *buf = NULL;
468 len = read_stdin(buf);
470 ll = LINES_CHUNK;
471 *lns = malloc(ll * sizeof(char *));
473 if (*lns == NULL)
474 goto err;
476 for (i = 0; i < len; i++) {
477 char c = (*buf)[i];
479 if (c == '\0')
480 break;
482 if (c == '\n')
483 (*buf)[i] = '\0';
485 if (in_line && c == '\n')
486 in_line = 0;
488 if (!in_line && c != '\n') {
489 in_line = 1;
490 (*lns)[lines] = (*buf) + i;
491 lines++;
493 if (lines == ll) { /* resize */
494 ll += LINES_CHUNK;
495 *lns = realloc(*lns, ll * sizeof(char *));
496 if (*lns == NULL)
497 goto err;
502 (*lns)[lines] = NULL;
504 return lines;
506 err:
507 fprintf(stderr, "Error in memory allocation.\n");
508 exit(EX_UNAVAILABLE);
511 /*
512 * Compute the dimensions of the string str once rendered.
513 * It'll return the width and set ret_width and ret_height if not NULL
514 */
515 int
516 text_extents(char *str, int len, struct rendering *r, int *ret_width,
517 int *ret_height)
519 int height, width;
520 #ifdef USE_XFT
521 XGlyphInfo gi;
522 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
523 height = r->font->ascent - r->font->descent;
524 width = gi.width - gi.x;
525 #else
526 XRectangle rect;
527 XmbTextExtents(r->font, str, len, NULL, &rect);
528 height = rect.height;
529 width = rect.width;
530 #endif
531 if (ret_width != NULL)
532 *ret_width = width;
533 if (ret_height != NULL)
534 *ret_height = height;
535 return width;
538 void
539 draw_string(char *str, int len, int x, int y, struct rendering *r,
540 enum obj_type tt)
542 #ifdef USE_XFT
543 XftColor xftcolor;
544 if (tt == PROMPT)
545 xftcolor = r->xft_colors[0];
546 if (tt == COMPL)
547 xftcolor = r->xft_colors[1];
548 if (tt == COMPL_HIGH)
549 xftcolor = r->xft_colors[2];
551 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
552 #else
553 GC gc;
554 if (tt == PROMPT)
555 gc = r->fgs[0];
556 if (tt == COMPL)
557 gc = r->fgs[1];
558 if (tt == COMPL_HIGH)
559 gc = r->fgs[2];
560 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
561 #endif
564 /* Duplicate the string and substitute every space with a 'n` */
565 char *
566 strdupn(char *str)
568 int len, i;
569 char *dup;
571 len = strlen(str);
573 if (str == NULL || len == 0)
574 return NULL;
576 if ((dup = strdup(str)) == NULL)
577 return NULL;
579 for (i = 0; i < len; ++i)
580 if (dup[i] == ' ')
581 dup[i] = 'n';
583 return dup;
586 int
587 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
588 enum obj_type t, char *text)
590 GC *border_color, bg;
591 int *padding, *borders;
592 int ret = 0, inner_width, inner_height, x;
594 switch (t) {
595 case PROMPT:
596 border_color = r->p_borders_bg;
597 padding = r->p_padding;
598 borders = r->p_borders;
599 bg = r->bgs[0];
600 break;
601 case COMPL:
602 border_color = r->c_borders_bg;
603 padding = r->c_padding;
604 borders = r->c_borders;
605 bg = r->bgs[1];
606 break;
607 case COMPL_HIGH:
608 border_color = r->ch_borders_bg;
609 padding = r->ch_padding;
610 borders = r->ch_borders;
611 bg = r->bgs[2];
612 break;
615 ret = borders[0] + padding[0] + r->text_height + padding[2]
616 + borders[2];
618 inner_width = inner_width(r) - borders[1] - borders[3];
619 inner_height = padding[0] + r->text_height + padding[2];
621 /* Border top */
622 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
623 borders[0]);
625 /* Border right */
626 XFillRectangle(r->d, r->w, border_color[1],
627 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
629 /* Border bottom */
630 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
631 y + borders[0] + padding[0] + r->text_height + padding[2],
632 r->width, borders[2]);
634 /* Border left */
635 XFillRectangle(
636 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
638 /* bg */
639 x = r->x_zero + borders[3];
640 y += borders[0];
641 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
643 /* content */
644 y += padding[0] + r->text_height;
645 x += padding[3];
646 if (prefix != NULL) {
647 draw_string(prefix, strlen(prefix), x, y, r, t);
648 x += prefix_width;
650 draw_string(text, strlen(text), x, y, r, t);
652 return ret;
655 int
656 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
657 enum obj_type t, char *text)
659 GC *border_color, bg;
660 int *padding, *borders;
661 int ret = 0, inner_width, inner_height, y, text_width;
663 switch (t) {
664 case PROMPT:
665 border_color = r->p_borders_bg;
666 padding = r->p_padding;
667 borders = r->p_borders;
668 bg = r->bgs[0];
669 break;
670 case COMPL:
671 border_color = r->c_borders_bg;
672 padding = r->c_padding;
673 borders = r->c_borders;
674 bg = r->bgs[1];
675 break;
676 case COMPL_HIGH:
677 border_color = r->ch_borders_bg;
678 padding = r->ch_padding;
679 borders = r->ch_borders;
680 bg = r->bgs[2];
681 break;
684 if (padding[0] < 0 || padding[2] < 0)
685 padding[0] = padding[2]
686 = (inner_height(r) - borders[0] - borders[2]
687 - r->text_height)
688 / 2;
690 /* If they are still lesser than 0, set 'em to 0 */
691 if (padding[0] < 0 || padding[2] < 0)
692 padding[0] = padding[2] = 0;
694 /* Get the text width */
695 text_extents(text, strlen(text), r, &text_width, NULL);
696 if (prefix != NULL)
697 text_width += prefix_width;
699 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
701 inner_width = padding[3] + text_width + padding[1];
702 inner_height = inner_height(r) - borders[0] - borders[2];
704 /* Border top */
705 XFillRectangle(
706 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
708 /* Border right */
709 XFillRectangle(r->d, r->w, border_color[1],
710 x + borders[3] + inner_width, r->y_zero, borders[1],
711 inner_height(r));
713 /* Border bottom */
714 XFillRectangle(r->d, r->w, border_color[2], x,
715 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
717 /* Border left */
718 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
719 inner_height(r));
721 /* bg */
722 x += borders[3];
723 y = r->y_zero + borders[0];
724 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
726 /* content */
727 y += padding[0] + r->text_height;
728 x += padding[3];
729 if (prefix != NULL) {
730 draw_string(prefix, strlen(prefix), x, y, r, t);
731 x += prefix_width;
733 draw_string(text, strlen(text), x, y, r, t);
735 return ret;
738 /* ,-----------------------------------------------------------------, */
739 /* | 20 char text | completion | completion | completion | compl | */
740 /* `-----------------------------------------------------------------' */
741 void
742 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
744 size_t i;
745 int x = r->x_zero;
747 /* Draw the prompt */
748 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
750 for (i = r->offset; i < cs->length; ++i) {
751 enum obj_type t
752 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
754 x += draw_h_box(
755 r, x, NULL, 0, t, cs->completions[i].completion);
757 if (x > inner_width(r))
758 break;
762 /* ,-----------------------------------------------------------------, */
763 /* | prompt | */
764 /* |-----------------------------------------------------------------| */
765 /* | completion | */
766 /* |-----------------------------------------------------------------| */
767 /* | completion | */
768 /* `-----------------------------------------------------------------' */
769 void
770 draw_vertically(struct rendering *r, char *text, struct completions *cs)
772 size_t i;
773 int y = r->y_zero;
775 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
777 for (i = r->offset; i < cs->length; ++i) {
778 enum obj_type t
779 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
781 y += draw_v_box(
782 r, y, NULL, 0, t, cs->completions[i].completion);
784 if (y > inner_height(r))
785 break;
789 void
790 draw(struct rendering *r, char *text, struct completions *cs)
792 /* Draw the background */
793 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
794 inner_width(r), inner_height(r));
796 /* Draw the contents */
797 if (r->horizontal_layout)
798 draw_horizontally(r, text, cs);
799 else
800 draw_vertically(r, text, cs);
802 /* Draw the borders */
803 if (r->borders[0] != 0)
804 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
805 r->borders[0]);
807 if (r->borders[1] != 0)
808 XFillRectangle(r->d, r->w, r->borders_bg[1],
809 r->width - r->borders[1], 0, r->borders[1],
810 r->height);
812 if (r->borders[2] != 0)
813 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
814 r->height - r->borders[2], r->width, r->borders[2]);
816 if (r->borders[3] != 0)
817 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
818 r->borders[3], r->height);
820 /* render! */
821 XFlush(r->d);
824 /* Set some WM stuff */
825 void
826 set_win_atoms_hints(Display *d, Window w, int width, int height)
828 Atom type;
829 XClassHint *class_hint;
830 XSizeHints *size_hint;
832 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
833 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
834 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
835 (unsigned char *)&type, 1);
837 /* some window managers honor this properties */
838 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
839 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
840 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
841 (unsigned char *)&type, 1);
843 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
844 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
845 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
846 (unsigned char *)&type, 1);
848 /* Setting window hints */
849 class_hint = XAllocClassHint();
850 if (class_hint == NULL) {
851 fprintf(stderr, "Could not allocate memory for class hint\n");
852 exit(EX_UNAVAILABLE);
855 class_hint->res_name = resname;
856 class_hint->res_class = resclass;
857 XSetClassHint(d, w, class_hint);
858 XFree(class_hint);
860 size_hint = XAllocSizeHints();
861 if (size_hint == NULL) {
862 fprintf(stderr, "Could not allocate memory for size hint\n");
863 exit(EX_UNAVAILABLE);
866 size_hint->flags = PMinSize | PBaseSize;
867 size_hint->min_width = width;
868 size_hint->base_width = width;
869 size_hint->min_height = height;
870 size_hint->base_height = height;
872 XFlush(d);
875 /* Get the width and height of the window `w' */
876 void
877 get_wh(Display *d, Window *w, int *width, int *height)
879 XWindowAttributes win_attr;
881 XGetWindowAttributes(d, *w, &win_attr);
882 *height = win_attr.height;
883 *width = win_attr.width;
886 int
887 grabfocus(Display *d, Window w)
889 int i;
890 for (i = 0; i < 100; ++i) {
891 Window focuswin;
892 int revert_to_win;
894 XGetInputFocus(d, &focuswin, &revert_to_win);
896 if (focuswin == w)
897 return 1;
899 XSetInputFocus(d, w, RevertToParent, CurrentTime);
900 usleep(1000);
902 return 0;
905 /*
906 * I know this may seem a little hackish BUT is the only way I managed
907 * to actually grab that goddam keyboard. Only one call to
908 * XGrabKeyboard does not always end up with the keyboard grabbed!
909 */
910 int
911 take_keyboard(Display *d, Window w)
913 int i;
914 for (i = 0; i < 100; i++) {
915 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
916 CurrentTime)
917 == GrabSuccess)
918 return 1;
919 usleep(1000);
921 fprintf(stderr, "Cannot grab keyboard\n");
922 return 0;
925 unsigned long
926 parse_color(const char *str, const char *def)
928 size_t len;
929 rgba_t tmp;
930 char *ep;
932 if (str == NULL)
933 goto invc;
935 len = strlen(str);
937 /* +1 for the # ath the start */
938 if (*str != '#' || len > 9 || len < 4)
939 goto invc;
940 ++str; /* skip the # */
942 errno = 0;
943 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
945 if (errno)
946 goto invc;
948 switch (len - 1) {
949 case 3:
950 /* expand #rgb -> #rrggbb */
951 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
952 | (tmp.v & 0x00f) * 0x0011;
953 case 6:
954 /* assume 0xff opacity */
955 tmp.rgba.a = 0xff;
956 break;
957 } /* colors in #aarrggbb need no adjustments */
959 /* premultiply the alpha */
960 if (tmp.rgba.a) {
961 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
962 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
963 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
964 return tmp.v;
967 return 0U;
969 invc:
970 fprintf(stderr, "Invalid color: \"%s\".\n", str);
971 if (def != NULL)
972 return parse_color(def, NULL);
973 else
974 return 0U;
977 /*
978 * Given a string try to parse it as a number or return `default_value'.
979 */
980 int
981 parse_integer(const char *str, int default_value)
983 long lval;
984 char *ep;
986 errno = 0;
987 lval = strtol(str, &ep, 10);
989 if (str[0] == '\0' || *ep != '\0') { /* NaN */
990 fprintf(stderr,
991 "'%s' is not a valid number! Using %d as default.\n",
992 str, default_value);
993 return default_value;
996 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
997 || (lval > INT_MAX || lval < INT_MIN)) {
998 fprintf(stderr, "%s out of range! Using %d as default.\n",
999 str, default_value);
1000 return default_value;
1003 return lval;
1006 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1007 * `%') */
1008 int
1009 parse_int_with_percentage(const char *str, int default_value, int max)
1011 int len = strlen(str);
1013 if (len > 0 && str[len - 1] == '%') {
1014 int val;
1015 char *cpy;
1017 cpy = strdup(str);
1018 check_allocation(cpy);
1019 cpy[len - 1] = '\0';
1020 val = parse_integer(cpy, default_value);
1021 free(cpy);
1022 return val * max / 100;
1025 return parse_integer(str, default_value);
1029 * Like parse_int_with_percentage but understands some special values:
1030 * - middle that is (max-self)/2
1031 * - start that is 0
1032 * - end that is (max-self)
1034 int
1035 parse_int_with_pos(const char *str, int default_value, int max, int self)
1037 if (!strcmp(str, "start"))
1038 return 0;
1039 if (!strcmp(str, "middle"))
1040 return (max - self) / 2;
1041 if (!strcmp(str, "end"))
1042 return max - self;
1043 return parse_int_with_percentage(str, default_value, max);
1046 /* Parse a string like a CSS value. */
1047 /* TODO: harden a bit this function */
1048 char **
1049 parse_csslike(const char *str)
1051 int i, j;
1052 char *s, *token, **ret;
1053 short any_null;
1055 s = strdup(str);
1056 if (s == NULL)
1057 return NULL;
1059 ret = malloc(4 * sizeof(char *));
1060 if (ret == NULL) {
1061 free(s);
1062 return NULL;
1065 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1066 ret[i] = strdup(token);
1068 if (i == 1)
1069 for (j = 1; j < 4; j++)
1070 ret[j] = strdup(ret[0]);
1072 if (i == 2) {
1073 ret[2] = strdup(ret[0]);
1074 ret[3] = strdup(ret[1]);
1077 if (i == 3)
1078 ret[3] = strdup(ret[1]);
1080 /* before we didn't check for the return type of strdup, here we will
1083 any_null = 0;
1084 for (i = 0; i < 4; ++i)
1085 any_null = ret[i] == NULL || any_null;
1087 if (any_null)
1088 for (i = 0; i < 4; ++i)
1089 if (ret[i] != NULL)
1090 free(ret[i]);
1092 if (i == 0 || any_null) {
1093 free(s);
1094 free(ret);
1095 return NULL;
1098 return ret;
1102 * Given an event, try to understand what the users wants. If the
1103 * return value is ADD_CHAR then `input' is a pointer to a string that
1104 * will need to be free'ed later.
1106 enum action
1107 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1109 char str[SYM_BUF_SIZE] = { 0 };
1110 Status s;
1112 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1113 return DEL_CHAR;
1115 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1116 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1118 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1119 return CONFIRM;
1121 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1122 return EXIT;
1124 /* Try to read what key was pressed */
1125 s = 0;
1126 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1127 if (s == XBufferOverflow) {
1128 fprintf(stderr,
1129 "Buffer overflow when trying to create keyboard "
1130 "symbol map.\n");
1131 return EXIT;
1134 if (ev->state & ControlMask) {
1135 if (!strcmp(str, "")) /* C-u */
1136 return DEL_LINE;
1137 if (!strcmp(str, "")) /* C-w */
1138 return DEL_WORD;
1139 if (!strcmp(str, "")) /* C-h */
1140 return DEL_CHAR;
1141 if (!strcmp(str, "\r")) /* C-m */
1142 return CONFIRM_CONTINUE;
1143 if (!strcmp(str, "")) /* C-p */
1144 return PREV_COMPL;
1145 if (!strcmp(str, "")) /* C-n */
1146 return NEXT_COMPL;
1147 if (!strcmp(str, "")) /* C-c */
1148 return EXIT;
1149 if (!strcmp(str, "\t")) /* C-i */
1150 return TOGGLE_FIRST_SELECTED;
1153 *input = strdup(str);
1154 if (*input == NULL) {
1155 fprintf(stderr, "Error while allocating memory for key.\n");
1156 return EXIT;
1159 return ADD_CHAR;
1162 void
1163 confirm(enum state *status, struct rendering *r, struct completions *cs,
1164 char **text, int *textlen)
1166 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1167 /* if there is something selected expand it and return */
1168 int index = cs->selected == -1 ? 0 : cs->selected;
1169 struct completion *c = cs->completions;
1170 char *t;
1172 while (1) {
1173 if (index == 0)
1174 break;
1175 c++;
1176 index--;
1179 t = c->rcompletion;
1180 free(*text);
1181 *text = strdup(t);
1183 if (*text == NULL) {
1184 fprintf(stderr, "Memory allocation error\n");
1185 *status = ERR;
1188 *textlen = strlen(*text);
1189 return;
1192 if (!r->free_text) /* cannot accept arbitrary text */
1193 *status = LOOPING;
1196 /* event loop */
1197 enum state
1198 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1199 char **lines, char **vlines)
1201 enum state status = LOOPING;
1203 while (status == LOOPING) {
1204 XEvent e;
1205 XNextEvent(r->d, &e);
1207 if (XFilterEvent(&e, r->w))
1208 continue;
1210 switch (e.type) {
1211 case KeymapNotify:
1212 XRefreshKeyboardMapping(&e.xmapping);
1213 break;
1215 case FocusIn:
1216 /* Re-grab focus */
1217 if (e.xfocus.window != r->w)
1218 grabfocus(r->d, r->w);
1219 break;
1221 case VisibilityNotify:
1222 if (e.xvisibility.state != VisibilityUnobscured)
1223 XRaiseWindow(r->d, r->w);
1224 break;
1226 case MapNotify:
1227 get_wh(r->d, &r->w, &r->width, &r->height);
1228 draw(r, *text, cs);
1229 break;
1231 case KeyPress: {
1232 XKeyPressedEvent *ev = (XKeyPressedEvent *)&e;
1233 char *input;
1235 switch (parse_event(r->d, ev, r->xic, &input)) {
1236 case EXIT:
1237 status = ERR;
1238 break;
1240 case CONFIRM: {
1241 status = OK;
1242 confirm(&status, r, cs, text, textlen);
1243 break;
1246 case CONFIRM_CONTINUE: {
1247 status = OK_LOOP;
1248 confirm(&status, r, cs, text, textlen);
1249 break;
1252 case PREV_COMPL: {
1253 complete(cs, r->first_selected, 1, text,
1254 textlen, &status);
1255 r->offset = cs->selected;
1256 break;
1259 case NEXT_COMPL: {
1260 complete(cs, r->first_selected, 0, text,
1261 textlen, &status);
1262 r->offset = cs->selected;
1263 break;
1266 case DEL_CHAR:
1267 popc(*text);
1268 update_completions(cs, *text, lines, vlines,
1269 r->first_selected);
1270 r->offset = 0;
1271 break;
1273 case DEL_WORD: {
1274 popw(*text);
1275 update_completions(cs, *text, lines, vlines,
1276 r->first_selected);
1277 break;
1280 case DEL_LINE: {
1281 int i;
1282 for (i = 0; i < *textlen; ++i)
1283 *(*text + i) = 0;
1284 update_completions(cs, *text, lines, vlines,
1285 r->first_selected);
1286 r->offset = 0;
1287 break;
1290 case ADD_CHAR: {
1291 int str_len, i;
1293 str_len = strlen(input);
1296 * sometimes a strange key is pressed
1297 * i.e. ctrl alone), so input will be
1298 * empty. Don't need to update
1299 * completion in that case
1301 if (str_len == 0)
1302 break;
1304 for (i = 0; i < str_len; ++i) {
1305 *textlen = pushc(
1306 text, *textlen, input[i]);
1307 if (*textlen == -1) {
1308 fprintf(stderr,
1309 "Memory allocation "
1310 "error\n");
1311 status = ERR;
1312 break;
1316 if (status != ERR) {
1317 update_completions(cs, *text, lines,
1318 vlines, r->first_selected);
1319 free(input);
1322 r->offset = 0;
1323 break;
1326 case TOGGLE_FIRST_SELECTED:
1327 r->first_selected = !r->first_selected;
1328 if (r->first_selected && cs->selected < 0)
1329 cs->selected = 0;
1330 if (!r->first_selected && cs->selected == 0)
1331 cs->selected = -1;
1332 break;
1336 case ButtonPress: {
1337 XButtonPressedEvent *ev = (XButtonPressedEvent *)&e;
1338 /* if (ev->button == Button1) { /\* click *\/ */
1339 /* int x = ev->x - r.border_w; */
1340 /* int y = ev->y - r.border_n; */
1341 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1342 /* } */
1344 if (ev->button == Button4) /* scroll up */
1345 r->offset = MAX((ssize_t)r->offset - 1, 0);
1347 if (ev->button == Button5) /* scroll down */
1348 r->offset
1349 = MIN(r->offset + 1, cs->length - 1);
1351 break;
1355 draw(r, *text, cs);
1358 return status;
1361 int
1362 load_font(struct rendering *r, const char *fontname)
1364 #ifdef USE_XFT
1365 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1366 return 0;
1367 #else
1368 char **missing_charset_list;
1369 int missing_charset_count;
1371 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1372 &missing_charset_count, NULL);
1373 if (r->font != NULL)
1374 return 0;
1376 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1378 if (!strcmp(fontname, default_fontname))
1379 return -1;
1381 return load_font(r, default_fontname);
1382 #endif
1385 void
1386 xim_init(struct rendering *r, XrmDatabase *xdb)
1388 XIMStyle best_match_style;
1389 XIMStyles *xis;
1390 int i;
1392 /* Open the X input method */
1393 r->xim = XOpenIM(r->d, *xdb, resname, resclass);
1394 check_allocation(r->xim);
1396 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1397 fprintf(stderr, "Input Styles could not be retrieved\n");
1398 exit(EX_UNAVAILABLE);
1401 best_match_style = 0;
1402 for (i = 0; i < xis->count_styles; ++i) {
1403 XIMStyle ts = xis->supported_styles[i];
1404 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1405 best_match_style = ts;
1406 break;
1409 XFree(xis);
1411 if (!best_match_style)
1412 fprintf(stderr,
1413 "No matching input style could be determined\n");
1415 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1416 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1417 check_allocation(r->xic);
1420 void
1421 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1422 XVisualInfo vinfo, int x, int y, int ox, int oy,
1423 unsigned long background_pixel)
1425 XSetWindowAttributes attr;
1427 /* Create the window */
1428 attr.colormap = cmap;
1429 attr.override_redirect = 1;
1430 attr.border_pixel = 0;
1431 attr.background_pixel = background_pixel;
1432 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1433 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1435 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1436 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1437 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1438 | CWOverrideRedirect,
1439 &attr);
1442 void
1443 ps1extents(struct rendering *r)
1445 char *dup;
1446 dup = strdupn(r->ps1);
1447 text_extents(
1448 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1449 free(dup);
1452 void
1453 usage(char *prgname)
1455 fprintf(stderr,
1456 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1457 " [-d separator] [-e window] [-f font] [-G color] [-g "
1458 "size]\n"
1459 " [-H height] [-I color] [-i size] [-J color] [-j "
1460 "size] [-l layout]\n"
1461 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1462 "color]\n"
1463 " [-t color] [-W width] [-x coord] [-y coord]\n",
1464 prgname);
1467 int
1468 main(int argc, char **argv)
1470 struct completions *cs;
1471 struct rendering r;
1472 XVisualInfo vinfo;
1473 Colormap cmap;
1474 size_t nlines, i;
1475 Window parent_window;
1476 XrmDatabase xdb;
1477 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1478 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1479 ch_borders_bg[4]; /* N E S W */
1480 enum state status;
1481 int ch;
1482 int offset_x, offset_y, x, y;
1483 int textlen, d_width, d_height;
1484 short embed;
1485 char *sep, *parent_window_id;
1486 char **lines, *buf, **vlines;
1487 char *fontname, *text, *xrm;
1489 #ifdef __OpenBSD__
1490 /* stdio & rpath: to read/write stdio/stdout/stderr */
1491 /* unix: to connect to XOrg */
1492 pledge("stdio rpath unix", "");
1493 #endif
1495 sep = NULL;
1496 parent_window_id = NULL;
1498 r.first_selected = 0;
1499 r.free_text = 1;
1500 r.multiple_select = 0;
1501 r.offset = 0;
1503 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1504 switch (ch) {
1505 case 'h': /* help */
1506 usage(*argv);
1507 return 0;
1508 case 'v': /* version */
1509 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1510 return 0;
1511 case 'e': /* embed */
1512 parent_window_id = strdup(optarg);
1513 check_allocation(parent_window_id);
1514 break;
1515 case 'd':
1516 sep = strdup(optarg);
1517 check_allocation(sep);
1518 case 'A':
1519 r.free_text = 0;
1520 break;
1521 case 'm':
1522 r.multiple_select = 1;
1523 break;
1524 default:
1525 break;
1529 /* Read the completions */
1530 lines = NULL;
1531 buf = NULL;
1532 nlines = readlines(&lines, &buf);
1534 vlines = NULL;
1535 if (sep != NULL) {
1536 int l;
1537 l = strlen(sep);
1538 vlines = calloc(nlines, sizeof(char *));
1539 check_allocation(vlines);
1541 for (i = 0; i < nlines; i++) {
1542 char *t;
1543 t = strstr(lines[i], sep);
1544 if (t == NULL)
1545 vlines[i] = lines[i];
1546 else
1547 vlines[i] = t + l;
1551 setlocale(LC_ALL, getenv("LANG"));
1553 status = LOOPING;
1555 /* where the monitor start (used only with xinerama) */
1556 offset_x = offset_y = 0;
1558 /* default width and height */
1559 r.width = 400;
1560 r.height = 20;
1562 /* default position on the screen */
1563 x = y = 0;
1565 for (i = 0; i < 4; ++i) {
1566 /* default paddings */
1567 r.p_padding[i] = 10;
1568 r.c_padding[i] = 10;
1569 r.ch_padding[i] = 10;
1571 /* default borders */
1572 r.borders[i] = 0;
1573 r.p_borders[i] = 0;
1574 r.c_borders[i] = 0;
1575 r.ch_borders[i] = 0;
1578 /* the prompt. We duplicate the string so later is easy to
1579 * free (in the case it's been overwritten by the user) */
1580 r.ps1 = strdup("$ ");
1581 check_allocation(r.ps1);
1583 /* same for the font name */
1584 fontname = strdup(default_fontname);
1585 check_allocation(fontname);
1587 textlen = 10;
1588 text = malloc(textlen * sizeof(char));
1589 check_allocation(text);
1591 /* struct completions *cs = filter(text, lines); */
1592 cs = compls_new(nlines);
1593 check_allocation(cs);
1595 /* start talking to xorg */
1596 r.d = XOpenDisplay(NULL);
1597 if (r.d == NULL) {
1598 fprintf(stderr, "Could not open display!\n");
1599 return EX_UNAVAILABLE;
1602 embed = 1;
1603 if (!(parent_window_id
1604 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1605 parent_window = DefaultRootWindow(r.d);
1606 embed = 0;
1609 /* get display size */
1610 get_wh(r.d, &parent_window, &d_width, &d_height);
1612 #ifdef USE_XINERAMA
1613 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1614 XineramaScreenInfo *info;
1615 Window rr;
1616 Window root;
1617 int number_of_screens, monitors, i;
1618 int root_x, root_y, win_x, win_y;
1619 unsigned int mask;
1620 short res;
1622 number_of_screens = XScreenCount(r.d);
1623 for (i = 0; i < number_of_screens; ++i) {
1624 root = XRootWindow(r.d, i);
1625 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1626 &root_y, &win_x, &win_y, &mask);
1627 if (res)
1628 break;
1631 if (!res) {
1632 fprintf(stderr, "No mouse found.\n");
1633 root_x = 0;
1634 root_y = 0;
1637 /* Now find in which monitor the mice is */
1638 info = XineramaQueryScreens(r.d, &monitors);
1639 if (info) {
1640 for (i = 0; i < monitors; ++i) {
1641 if (info[i].x_org <= root_x
1642 && root_x <= (info[i].x_org
1643 + info[i].width)
1644 && info[i].y_org <= root_y
1645 && root_y <= (info[i].y_org
1646 + info[i].height)) {
1647 offset_x = info[i].x_org;
1648 offset_y = info[i].y_org;
1649 d_width = info[i].width;
1650 d_height = info[i].height;
1651 break;
1655 XFree(info);
1657 #endif
1659 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1660 cmap = XCreateColormap(
1661 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1663 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1664 fgs[2] = parse_color("#000", NULL);
1666 bgs[0] = bgs[1] = parse_color("#000", NULL);
1667 bgs[2] = parse_color("#fff", NULL);
1669 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1670 = parse_color("#000", NULL);
1672 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1673 = parse_color("#000", NULL);
1674 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1675 = parse_color("#000", NULL);
1676 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1677 = ch_borders_bg[3] = parse_color("#000", NULL);
1679 r.horizontal_layout = 1;
1681 /* Read the resources */
1682 XrmInitialize();
1683 xrm = XResourceManagerString(r.d);
1684 xdb = NULL;
1685 if (xrm != NULL) {
1686 XrmValue value;
1687 char *datatype[20];
1689 xdb = XrmGetStringDatabase(xrm);
1691 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1692 == 1) {
1693 free(fontname);
1694 fontname = strdup(value.addr);
1695 check_allocation(fontname);
1696 } else {
1697 fprintf(stderr, "no font defined, using %s\n",
1698 fontname);
1701 if (XrmGetResource(
1702 xdb, "MyMenu.layout", "*", datatype, &value)
1703 == 1)
1704 r.horizontal_layout
1705 = !strcmp(value.addr, "horizontal");
1706 else
1707 fprintf(stderr,
1708 "no layout defined, using horizontal\n");
1710 if (XrmGetResource(
1711 xdb, "MyMenu.prompt", "*", datatype, &value)
1712 == 1) {
1713 free(r.ps1);
1714 r.ps1 = normalize_str(value.addr);
1715 } else {
1716 fprintf(stderr,
1717 "no prompt defined, using \"%s\" as "
1718 "default\n",
1719 r.ps1);
1722 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1723 datatype, &value)
1724 == 1) {
1725 char **sizes;
1726 sizes = parse_csslike(value.addr);
1727 if (sizes != NULL)
1728 for (i = 0; i < 4; ++i)
1729 r.p_borders[i]
1730 = parse_integer(sizes[i], 0);
1731 else
1732 fprintf(stderr,
1733 "error while parsing "
1734 "MyMenu.prompt.border.size");
1737 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1738 datatype, &value)
1739 == 1) {
1740 char **colors;
1741 colors = parse_csslike(value.addr);
1742 if (colors != NULL)
1743 for (i = 0; i < 4; ++i)
1744 p_borders_bg[i] = parse_color(
1745 colors[i], "#000");
1746 else
1747 fprintf(stderr,
1748 "error while parsing "
1749 "MyMenu.prompt.border.color");
1752 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1753 datatype, &value)
1754 == 1) {
1755 char **colors;
1756 colors = parse_csslike(value.addr);
1757 if (colors != NULL)
1758 for (i = 0; i < 4; ++i)
1759 r.p_padding[i]
1760 = parse_integer(colors[i], 0);
1761 else
1762 fprintf(stderr,
1763 "error while parsing "
1764 "MyMenu.prompt.padding");
1767 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1768 == 1)
1769 r.width = parse_int_with_percentage(
1770 value.addr, r.width, d_width);
1771 else
1772 fprintf(stderr, "no width defined, using %d\n",
1773 r.width);
1775 if (XrmGetResource(
1776 xdb, "MyMenu.height", "*", datatype, &value)
1777 == 1)
1778 r.height = parse_int_with_percentage(
1779 value.addr, r.height, d_height);
1780 else
1781 fprintf(stderr, "no height defined, using %d\n",
1782 r.height);
1784 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1785 == 1)
1786 x = parse_int_with_pos(
1787 value.addr, x, d_width, r.width);
1789 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1790 == 1)
1791 y = parse_int_with_pos(
1792 value.addr, y, d_height, r.height);
1794 if (XrmGetResource(
1795 xdb, "MyMenu.border.size", "*", datatype, &value)
1796 == 1) {
1797 char **borders;
1798 borders = parse_csslike(value.addr);
1799 if (borders != NULL)
1800 for (i = 0; i < 4; ++i)
1801 r.borders[i]
1802 = parse_int_with_percentage(
1803 borders[i], 0,
1804 (i % 2) == 0
1805 ? d_height
1806 : d_width);
1807 else
1808 fprintf(stderr,
1809 "error while parsing "
1810 "MyMenu.border.size\n");
1813 /* Prompt */
1814 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1815 datatype, &value)
1816 == 1)
1817 fgs[0] = parse_color(value.addr, "#fff");
1819 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1820 datatype, &value)
1821 == 1)
1822 bgs[0] = parse_color(value.addr, "#000");
1824 /* Completions */
1825 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1826 datatype, &value)
1827 == 1)
1828 fgs[1] = parse_color(value.addr, "#fff");
1830 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1831 datatype, &value)
1832 == 1)
1833 bgs[1] = parse_color(value.addr, "#000");
1835 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1836 datatype, &value)
1837 == 1) {
1838 char **paddings;
1839 paddings = parse_csslike(value.addr);
1840 if (paddings != NULL)
1841 for (i = 0; i < 4; ++i)
1842 r.c_padding[i] = parse_integer(
1843 paddings[i], 0);
1844 else
1845 fprintf(stderr,
1846 "Error while parsing "
1847 "MyMenu.completion.padding");
1850 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1851 datatype, &value)
1852 == 1) {
1853 char **sizes;
1854 sizes = parse_csslike(value.addr);
1855 if (sizes != NULL)
1856 for (i = 0; i < 4; ++i)
1857 r.c_borders[i]
1858 = parse_integer(sizes[i], 0);
1859 else
1860 fprintf(stderr,
1861 "Error while parsing "
1862 "MyMenu.completion.border.size");
1865 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1866 datatype, &value)
1867 == 1) {
1868 char **sizes;
1869 sizes = parse_csslike(value.addr);
1870 if (sizes != NULL)
1871 for (i = 0; i < 4; ++i)
1872 c_borders_bg[i] = parse_color(
1873 sizes[i], "#000");
1874 else
1875 fprintf(stderr,
1876 "Error while parsing "
1877 "MyMenu.completion.border.color");
1880 /* Completion Highlighted */
1881 if (XrmGetResource(xdb,
1882 "MyMenu.completion_highlighted.foreground", "*",
1883 datatype, &value)
1884 == 1)
1885 fgs[2] = parse_color(value.addr, "#000");
1887 if (XrmGetResource(xdb,
1888 "MyMenu.completion_highlighted.background", "*",
1889 datatype, &value)
1890 == 1)
1891 bgs[2] = parse_color(value.addr, "#fff");
1893 if (XrmGetResource(xdb,
1894 "MyMenu.completion_highlighted.padding", "*",
1895 datatype, &value)
1896 == 1) {
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(
1902 paddings[i], 0);
1903 else
1904 fprintf(stderr,
1905 "Error while parsing "
1906 "MyMenu.completion_highlighted."
1907 "padding");
1910 if (XrmGetResource(xdb,
1911 "MyMenu.completion_highlighted.border.size", "*",
1912 datatype, &value)
1913 == 1) {
1914 char **sizes;
1915 sizes = parse_csslike(value.addr);
1916 if (sizes != NULL)
1917 for (i = 0; i < 4; ++i)
1918 r.ch_borders[i]
1919 = parse_integer(sizes[i], 0);
1920 else
1921 fprintf(stderr,
1922 "Error while parsing "
1923 "MyMenu.completion_highlighted."
1924 "border.size");
1927 if (XrmGetResource(xdb,
1928 "MyMenu.completion_highlighted.border.color", "*",
1929 datatype, &value)
1930 == 1) {
1931 char **colors;
1932 colors = parse_csslike(value.addr);
1933 if (colors != NULL)
1934 for (i = 0; i < 4; ++i)
1935 ch_borders_bg[i] = parse_color(
1936 colors[i], "#000");
1937 else
1938 fprintf(stderr,
1939 "Error while parsing "
1940 "MyMenu.completion_highlighted."
1941 "border.color");
1944 /* Border */
1945 if (XrmGetResource(
1946 xdb, "MyMenu.border.color", "*", datatype, &value)
1947 == 1) {
1948 char **colors;
1949 colors = parse_csslike(value.addr);
1950 if (colors != NULL)
1951 for (i = 0; i < 4; ++i)
1952 borders_bg[i] = parse_color(
1953 colors[i], "#000");
1954 else
1955 fprintf(stderr,
1956 "error while parsing "
1957 "MyMenu.border.color\n");
1961 /* Second round of args parsing */
1962 optind = 0; /* reset the option index */
1963 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1964 switch (ch) {
1965 case 'a':
1966 r.first_selected = 1;
1967 break;
1968 case 'A':
1969 /* free_text -- already catched */
1970 case 'd':
1971 /* separator -- this case was already catched */
1972 case 'e':
1973 /* embedding mymenu this case was already catched. */
1974 case 'm':
1975 /* multiple selection this case was already catched.
1977 break;
1978 case 'p': {
1979 char *newprompt;
1980 newprompt = strdup(optarg);
1981 if (newprompt != NULL) {
1982 free(r.ps1);
1983 r.ps1 = newprompt;
1985 break;
1987 case 'x':
1988 x = parse_int_with_pos(optarg, x, d_width, r.width);
1989 break;
1990 case 'y':
1991 y = parse_int_with_pos(optarg, y, d_height, r.height);
1992 break;
1993 case 'P': {
1994 char **paddings;
1995 if ((paddings = parse_csslike(optarg)) != NULL)
1996 for (i = 0; i < 4; ++i)
1997 r.p_padding[i] = parse_integer(
1998 paddings[i], 0);
1999 break;
2001 case 'G': {
2002 char **colors;
2003 if ((colors = parse_csslike(optarg)) != NULL)
2004 for (i = 0; i < 4; ++i)
2005 p_borders_bg[i] = parse_color(
2006 colors[i], "#000");
2007 break;
2009 case 'g': {
2010 char **sizes;
2011 if ((sizes = parse_csslike(optarg)) != NULL)
2012 for (i = 0; i < 4; ++i)
2013 r.p_borders[i]
2014 = parse_integer(sizes[i], 0);
2015 break;
2017 case 'I': {
2018 char **colors;
2019 if ((colors = parse_csslike(optarg)) != NULL)
2020 for (i = 0; i < 4; ++i)
2021 c_borders_bg[i] = parse_color(
2022 colors[i], "#000");
2023 break;
2025 case 'i': {
2026 char **sizes;
2027 if ((sizes = parse_csslike(optarg)) != NULL)
2028 for (i = 0; i < 4; ++i)
2029 r.c_borders[i]
2030 = parse_integer(sizes[i], 0);
2031 break;
2033 case 'J': {
2034 char **colors;
2035 if ((colors = parse_csslike(optarg)) != NULL)
2036 for (i = 0; i < 4; ++i)
2037 ch_borders_bg[i] = parse_color(
2038 colors[i], "#000");
2039 break;
2041 case 'j': {
2042 char **sizes;
2043 if ((sizes = parse_csslike(optarg)) != NULL)
2044 for (i = 0; i < 4; ++i)
2045 r.ch_borders[i]
2046 = parse_integer(sizes[i], 0);
2047 break;
2049 case 'l':
2050 r.horizontal_layout = !strcmp(optarg, "horizontal");
2051 break;
2052 case 'f': {
2053 char *newfont;
2054 if ((newfont = strdup(optarg)) != NULL) {
2055 free(fontname);
2056 fontname = newfont;
2058 break;
2060 case 'W':
2061 r.width = parse_int_with_percentage(
2062 optarg, r.width, d_width);
2063 break;
2064 case 'H':
2065 r.height = parse_int_with_percentage(
2066 optarg, r.height, d_height);
2067 break;
2068 case 'b': {
2069 char **borders;
2070 if ((borders = parse_csslike(optarg)) != NULL) {
2071 for (i = 0; i < 4; ++i)
2072 r.borders[i] = parse_integer(
2073 borders[i], 0);
2074 } else
2075 fprintf(stderr, "Error parsing b option\n");
2076 break;
2078 case 'B': {
2079 char **colors;
2080 if ((colors = parse_csslike(optarg)) != NULL) {
2081 for (i = 0; i < 4; ++i)
2082 borders_bg[i] = parse_color(
2083 colors[i], "#000");
2084 } else
2085 fprintf(stderr,
2086 "error while parsing B option\n");
2087 break;
2089 case 't':
2090 fgs[0] = parse_color(optarg, NULL);
2091 break;
2092 case 'T':
2093 bgs[0] = parse_color(optarg, NULL);
2094 break;
2095 case 'c':
2096 fgs[1] = parse_color(optarg, NULL);
2097 break;
2098 case 'C':
2099 bgs[1] = parse_color(optarg, NULL);
2100 break;
2101 case 's':
2102 fgs[2] = parse_color(optarg, NULL);
2103 break;
2104 case 'S':
2105 fgs[2] = parse_color(optarg, NULL);
2106 break;
2107 default:
2108 fprintf(stderr, "Unrecognized option %c\n", ch);
2109 status = ERR;
2110 break;
2114 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2115 fprintf(stderr, "height, width, x or y are lesser than 0.");
2116 status = ERR;
2119 /* since only now we know if the first should be selected,
2120 * update the completion here */
2121 update_completions(cs, text, lines, vlines, r.first_selected);
2123 /* update the prompt lenght, only now we surely know the length of it
2125 r.ps1len = strlen(r.ps1);
2127 /* Create the window */
2128 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2129 offset_y, bgs[1]);
2130 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2131 XMapRaised(r.d, r.w);
2133 /* If embed, listen for other events as well */
2134 if (embed) {
2135 Window *children, parent, root;
2136 unsigned int children_no;
2138 XSelectInput(r.d, parent_window, FocusChangeMask);
2139 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2140 &children_no)
2141 && children) {
2142 for (i = 0; i < children_no && children[i] != r.w;
2143 ++i)
2144 XSelectInput(
2145 r.d, children[i], FocusChangeMask);
2146 XFree(children);
2148 grabfocus(r.d, r.w);
2151 take_keyboard(r.d, r.w);
2153 r.x_zero = r.borders[3];
2154 r.y_zero = r.borders[0];
2157 XGCValues values;
2159 for (i = 0; i < 3; ++i) {
2160 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2161 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2164 for (i = 0; i < 4; ++i) {
2165 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2166 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2167 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2168 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2172 /* Load the colors in our GCs */
2173 for (i = 0; i < 3; ++i) {
2174 XSetForeground(r.d, r.fgs[i], fgs[i]);
2175 XSetForeground(r.d, r.bgs[i], bgs[i]);
2178 for (i = 0; i < 4; ++i) {
2179 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2180 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2181 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2182 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2185 if (load_font(&r, fontname) == -1)
2186 status = ERR;
2188 #ifdef USE_XFT
2189 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2191 for (i = 0; i < 3; ++i) {
2192 rgba_t c;
2193 XRenderColor xrcolor;
2195 c = *(rgba_t *)&fgs[i];
2196 xrcolor.red = EXPANDBITS(c.rgba.r);
2197 xrcolor.green = EXPANDBITS(c.rgba.g);
2198 xrcolor.blue = EXPANDBITS(c.rgba.b);
2199 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2200 XftColorAllocValue(
2201 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2203 #endif
2205 /* compute prompt dimensions */
2206 ps1extents(&r);
2208 xim_init(&r, &xdb);
2210 #ifdef __OpenBSD__
2211 /* Now we need only the ability to write */
2212 pledge("stdio", "");
2213 #endif
2215 /* Cache text height */
2216 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2218 /* Draw the window for the first time */
2219 draw(&r, text, cs);
2221 /* Main loop */
2222 while (status == LOOPING || status == OK_LOOP) {
2223 status = loop(&r, &text, &textlen, cs, lines, vlines);
2225 if (status != ERR)
2226 printf("%s\n", text);
2228 if (!r.multiple_select && status == OK_LOOP)
2229 status = OK;
2232 XUngrabKeyboard(r.d, CurrentTime);
2234 #ifdef USE_XFT
2235 for (i = 0; i < 3; ++i)
2236 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2237 #endif
2239 for (i = 0; i < 3; ++i) {
2240 XFreeGC(r.d, r.fgs[i]);
2241 XFreeGC(r.d, r.bgs[i]);
2244 for (i = 0; i < 4; ++i) {
2245 XFreeGC(r.d, r.borders_bg[i]);
2246 XFreeGC(r.d, r.p_borders_bg[i]);
2247 XFreeGC(r.d, r.c_borders_bg[i]);
2248 XFreeGC(r.d, r.ch_borders_bg[i]);
2251 XDestroyIC(r.xic);
2252 XCloseIM(r.xim);
2254 #ifdef USE_XFT
2255 for (i = 0; i < 3; ++i)
2256 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2257 XftFontClose(r.d, r.font);
2258 XftDrawDestroy(r.xftdraw);
2259 #else
2260 XFreeFontSet(r.d, r.font);
2261 #endif
2263 free(r.ps1);
2264 free(fontname);
2265 free(text);
2267 free(buf);
2268 free(lines);
2269 free(vlines);
2270 compls_delete(cs);
2272 XFreeColormap(r.d, cmap);
2274 XDestroyWindow(r.d, r.w);
2275 XCloseDisplay(r.d);
2277 return status != OK;