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(struct completions *cs, char *text, char **lines,
243 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,
258 int *textlen, enum state *status)
260 struct completion *n;
261 int index;
263 if (cs == NULL || cs->length == 0)
264 return;
266 /*
267 * If the first is always selected and the first entry is
268 * different from the text, expand the text and return
269 */
270 if (first_selected && cs->selected == 0
271 && strcmp(cs->completions->completion, *text) != 0 && !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
287 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
289 n = &cs->completions[cs->selected];
291 free(*text);
292 *text = strdup(n->completion);
293 if (text == NULL) {
294 fprintf(stderr, "Memory allocation error!\n");
295 *status = ERR;
296 return;
298 *textlen = strlen(*text);
301 /* Push the character c at the end of the string pointed by p */
302 int
303 pushc(char **p, int maxlen, char c)
305 int len;
307 len = strnlen(*p, maxlen);
308 if (!(len < maxlen - 2)) {
309 char *newptr;
311 maxlen += maxlen >> 1;
312 newptr = realloc(*p, maxlen);
313 if (newptr == NULL) /* bad */
314 return -1;
315 *p = newptr;
318 (*p)[len] = c;
319 (*p)[len + 1] = '\0';
320 return maxlen;
323 /*
324 * Remove the last rune from the *UTF-8* string! This is different
325 * from just setting the last byte to 0 (in some cases ofc). Return a
326 * pointer (e) to the last nonzero char. If e < p then p is empty!
327 */
328 char *
329 popc(char *p)
331 int len = strlen(p);
332 char *e;
334 if (len == 0)
335 return p;
337 e = p + len - 1;
339 do {
340 char c = *e;
342 *e = '\0';
343 e -= 1;
345 /*
346 * If c is a starting byte (11......) or is under
347 * U+007F we're done.
348 */
349 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
350 break;
351 } while (e >= p);
353 return e;
356 /* Remove the last word plus trailing white spaces from the given string */
357 void
358 popw(char *w)
360 int len;
361 short in_word = 1;
363 if ((len = strlen(w)) == 0)
364 return;
366 while (1) {
367 char *e = popc(w);
369 if (e < w)
370 return;
372 if (in_word && isspace(*e))
373 in_word = 0;
375 if (!in_word && !isspace(*e))
376 return;
380 /*
381 * If the string is surrounded by quates (`"') remove them and replace
382 * every `\"' in the string with a single double-quote.
383 */
384 char *
385 normalize_str(const char *str)
387 int len, p;
388 char *s;
390 if ((len = strlen(str)) == 0)
391 return NULL;
393 if ((s = calloc(len, sizeof(char))) == NULL)
394 err(1, "calloc");
395 p = 0;
397 while (*str) {
398 char c = *str;
400 if (*str == '\\') {
401 if (*(str + 1)) {
402 s[p] = *(str + 1);
403 p++;
404 str += 2; /* skip this and the next char */
405 continue;
406 } else
407 break;
409 if (c == '"') {
410 str++; /* skip only this char */
411 continue;
413 s[p] = c;
414 p++;
415 str++;
418 return s;
421 size_t
422 read_stdin(char **buf)
424 size_t offset = 0;
425 size_t len = STDIN_CHUNKS;
427 *buf = malloc(len * sizeof(char));
428 if (*buf == NULL)
429 goto err;
431 while (1) {
432 ssize_t r;
433 size_t i;
435 r = read(0, *buf + offset, STDIN_CHUNKS);
437 if (r < 1)
438 return len;
440 offset += r;
442 len += STDIN_CHUNKS;
443 *buf = realloc(*buf, len);
444 if (*buf == NULL)
445 goto err;
447 for (i = offset; i < len; ++i)
448 (*buf)[i] = '\0';
451 err:
452 fprintf(stderr, "Error in allocating memory for stdin.\n");
453 exit(EX_UNAVAILABLE);
456 size_t
457 readlines(char ***lns, char **buf)
459 size_t i, len, ll, lines;
460 short in_line = 0;
462 lines = 0;
464 *buf = NULL;
465 len = read_stdin(buf);
467 ll = LINES_CHUNK;
468 *lns = malloc(ll * sizeof(char *));
470 if (*lns == NULL)
471 goto err;
473 for (i = 0; i < len; i++) {
474 char c = (*buf)[i];
476 if (c == '\0')
477 break;
479 if (c == '\n')
480 (*buf)[i] = '\0';
482 if (in_line && c == '\n')
483 in_line = 0;
485 if (!in_line && c != '\n') {
486 in_line = 1;
487 (*lns)[lines] = (*buf) + i;
488 lines++;
490 if (lines == ll) { /* resize */
491 ll += LINES_CHUNK;
492 *lns = realloc(*lns, ll * sizeof(char *));
493 if (*lns == NULL)
494 goto err;
499 (*lns)[lines] = NULL;
501 return lines;
503 err:
504 fprintf(stderr, "Error in memory allocation.\n");
505 exit(EX_UNAVAILABLE);
508 /*
509 * Compute the dimensions of the string str once rendered.
510 * It'll return the width and set ret_width and ret_height if not NULL
511 */
512 int
513 text_extents(char *str, int len, struct rendering *r, int *ret_width,
514 int *ret_height)
516 int height, width;
517 #ifdef USE_XFT
518 XGlyphInfo gi;
519 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
520 height = r->font->ascent - r->font->descent;
521 width = gi.width - gi.x;
522 #else
523 XRectangle rect;
524 XmbTextExtents(r->font, str, len, NULL, &rect);
525 height = rect.height;
526 width = rect.width;
527 #endif
528 if (ret_width != NULL)
529 *ret_width = width;
530 if (ret_height != NULL)
531 *ret_height = height;
532 return width;
535 void
536 draw_string(char *str, int len, int x, int y, struct rendering *r,
537 enum obj_type tt)
539 #ifdef USE_XFT
540 XftColor xftcolor;
541 if (tt == PROMPT)
542 xftcolor = r->xft_colors[0];
543 if (tt == COMPL)
544 xftcolor = r->xft_colors[1];
545 if (tt == COMPL_HIGH)
546 xftcolor = r->xft_colors[2];
548 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
549 #else
550 GC gc;
551 if (tt == PROMPT)
552 gc = r->fgs[0];
553 if (tt == COMPL)
554 gc = r->fgs[1];
555 if (tt == COMPL_HIGH)
556 gc = r->fgs[2];
557 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
558 #endif
561 /* Duplicate the string and substitute every space with a 'n` */
562 char *
563 strdupn(char *str)
565 int len, i;
566 char *dup;
568 len = strlen(str);
570 if (str == NULL || len == 0)
571 return NULL;
573 if ((dup = strdup(str)) == NULL)
574 return NULL;
576 for (i = 0; i < len; ++i)
577 if (dup[i] == ' ')
578 dup[i] = 'n';
580 return dup;
583 int
584 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
585 enum obj_type t, char *text)
587 GC *border_color, bg;
588 int *padding, *borders;
589 int ret = 0, inner_width, inner_height, x;
591 switch (t) {
592 case PROMPT:
593 border_color = r->p_borders_bg;
594 padding = r->p_padding;
595 borders = r->p_borders;
596 bg = r->bgs[0];
597 break;
598 case COMPL:
599 border_color = r->c_borders_bg;
600 padding = r->c_padding;
601 borders = r->c_borders;
602 bg = r->bgs[1];
603 break;
604 case COMPL_HIGH:
605 border_color = r->ch_borders_bg;
606 padding = r->ch_padding;
607 borders = r->ch_borders;
608 bg = r->bgs[2];
609 break;
612 ret = borders[0] + padding[0] + r->text_height + padding[2]
613 + borders[2];
615 inner_width = inner_width(r) - borders[1] - borders[3];
616 inner_height = padding[0] + r->text_height + padding[2];
618 /* Border top */
619 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
620 borders[0]);
622 /* Border right */
623 XFillRectangle(r->d, r->w, border_color[1],
624 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
626 /* Border bottom */
627 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
628 y + borders[0] + padding[0] + r->text_height + padding[2],
629 r->width, borders[2]);
631 /* Border left */
632 XFillRectangle(
633 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
635 /* bg */
636 x = r->x_zero + borders[3];
637 y += borders[0];
638 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
640 /* content */
641 y += padding[0] + r->text_height;
642 x += padding[3];
643 if (prefix != NULL) {
644 draw_string(prefix, strlen(prefix), x, y, r, t);
645 x += prefix_width;
647 draw_string(text, strlen(text), x, y, r, t);
649 return ret;
652 int
653 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
654 enum obj_type t, char *text)
656 GC *border_color, bg;
657 int *padding, *borders;
658 int ret = 0, inner_width, inner_height, y, text_width;
660 switch (t) {
661 case PROMPT:
662 border_color = r->p_borders_bg;
663 padding = r->p_padding;
664 borders = r->p_borders;
665 bg = r->bgs[0];
666 break;
667 case COMPL:
668 border_color = r->c_borders_bg;
669 padding = r->c_padding;
670 borders = r->c_borders;
671 bg = r->bgs[1];
672 break;
673 case COMPL_HIGH:
674 border_color = r->ch_borders_bg;
675 padding = r->ch_padding;
676 borders = r->ch_borders;
677 bg = r->bgs[2];
678 break;
681 if (padding[0] < 0 || padding[2] < 0)
682 padding[0] = padding[2]
683 = (inner_height(r) - borders[0] - borders[2]
684 - r->text_height)
685 / 2;
687 /* If they are still lesser than 0, set 'em to 0 */
688 if (padding[0] < 0 || padding[2] < 0)
689 padding[0] = padding[2] = 0;
691 /* Get the text width */
692 text_extents(text, strlen(text), r, &text_width, NULL);
693 if (prefix != NULL)
694 text_width += prefix_width;
696 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
698 inner_width = padding[3] + text_width + padding[1];
699 inner_height = inner_height(r) - borders[0] - borders[2];
701 /* Border top */
702 XFillRectangle(
703 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
705 /* Border right */
706 XFillRectangle(r->d, r->w, border_color[1],
707 x + borders[3] + inner_width, r->y_zero, borders[1],
708 inner_height(r));
710 /* Border bottom */
711 XFillRectangle(r->d, r->w, border_color[2], x,
712 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
714 /* Border left */
715 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
716 inner_height(r));
718 /* bg */
719 x += borders[3];
720 y = r->y_zero + borders[0];
721 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
723 /* content */
724 y += padding[0] + r->text_height;
725 x += padding[3];
726 if (prefix != NULL) {
727 draw_string(prefix, strlen(prefix), x, y, r, t);
728 x += prefix_width;
730 draw_string(text, strlen(text), x, y, r, t);
732 return ret;
735 /* ,-----------------------------------------------------------------, */
736 /* | 20 char text | completion | completion | completion | compl | */
737 /* `-----------------------------------------------------------------' */
738 void
739 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
741 size_t i;
742 int x = r->x_zero;
744 /* Draw the prompt */
745 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
747 for (i = r->offset; i < cs->length; ++i) {
748 enum obj_type t
749 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
751 cs->completions[i].offset = x;
753 x += draw_h_box(
754 r, x, NULL, 0, t, cs->completions[i].completion);
756 if (x > inner_width(r))
757 break;
760 for (i += 1; i < cs->length; ++i)
761 cs->completions[i].offset = -1;
764 /* ,-----------------------------------------------------------------, */
765 /* | prompt | */
766 /* |-----------------------------------------------------------------| */
767 /* | completion | */
768 /* |-----------------------------------------------------------------| */
769 /* | completion | */
770 /* `-----------------------------------------------------------------' */
771 void
772 draw_vertically(struct rendering *r, char *text, struct completions *cs)
774 size_t i;
775 int y = r->y_zero;
777 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
779 for (i = r->offset; i < cs->length; ++i) {
780 enum obj_type t
781 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
783 cs->completions[i].offset = y;
785 y += draw_v_box(
786 r, y, NULL, 0, t, cs->completions[i].completion);
788 if (y > inner_height(r))
789 break;
792 for (i += 1; i < cs->length; ++i)
793 cs->completions[i].offset = -1;
796 void
797 draw(struct rendering *r, char *text, struct completions *cs)
799 /* Draw the background */
800 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
801 inner_width(r), inner_height(r));
803 /* Draw the contents */
804 if (r->horizontal_layout)
805 draw_horizontally(r, text, cs);
806 else
807 draw_vertically(r, text, cs);
809 /* Draw the borders */
810 if (r->borders[0] != 0)
811 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
812 r->borders[0]);
814 if (r->borders[1] != 0)
815 XFillRectangle(r->d, r->w, r->borders_bg[1],
816 r->width - r->borders[1], 0, r->borders[1],
817 r->height);
819 if (r->borders[2] != 0)
820 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
821 r->height - r->borders[2], r->width, r->borders[2]);
823 if (r->borders[3] != 0)
824 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
825 r->borders[3], r->height);
827 /* render! */
828 XFlush(r->d);
831 /* Set some WM stuff */
832 void
833 set_win_atoms_hints(Display *d, Window w, int width, int height)
835 Atom type;
836 XClassHint *class_hint;
837 XSizeHints *size_hint;
839 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
840 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
841 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
842 (unsigned char *)&type, 1);
844 /* some window managers honor this properties */
845 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
846 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
847 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
848 (unsigned char *)&type, 1);
850 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
851 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
852 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
853 (unsigned char *)&type, 1);
855 /* Setting window hints */
856 class_hint = XAllocClassHint();
857 if (class_hint == NULL) {
858 fprintf(stderr, "Could not allocate memory for class hint\n");
859 exit(EX_UNAVAILABLE);
862 class_hint->res_name = resname;
863 class_hint->res_class = resclass;
864 XSetClassHint(d, w, class_hint);
865 XFree(class_hint);
867 size_hint = XAllocSizeHints();
868 if (size_hint == NULL) {
869 fprintf(stderr, "Could not allocate memory for size hint\n");
870 exit(EX_UNAVAILABLE);
873 size_hint->flags = PMinSize | PBaseSize;
874 size_hint->min_width = width;
875 size_hint->base_width = width;
876 size_hint->min_height = height;
877 size_hint->base_height = height;
879 XFlush(d);
882 /* Get the width and height of the window `w' */
883 void
884 get_wh(Display *d, Window *w, int *width, int *height)
886 XWindowAttributes win_attr;
888 XGetWindowAttributes(d, *w, &win_attr);
889 *height = win_attr.height;
890 *width = win_attr.width;
893 int
894 grabfocus(Display *d, Window w)
896 int i;
897 for (i = 0; i < 100; ++i) {
898 Window focuswin;
899 int revert_to_win;
901 XGetInputFocus(d, &focuswin, &revert_to_win);
903 if (focuswin == w)
904 return 1;
906 XSetInputFocus(d, w, RevertToParent, CurrentTime);
907 usleep(1000);
909 return 0;
912 /*
913 * I know this may seem a little hackish BUT is the only way I managed
914 * to actually grab that goddam keyboard. Only one call to
915 * XGrabKeyboard does not always end up with the keyboard grabbed!
916 */
917 int
918 take_keyboard(Display *d, Window w)
920 int i;
921 for (i = 0; i < 100; i++) {
922 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
923 CurrentTime)
924 == GrabSuccess)
925 return 1;
926 usleep(1000);
928 fprintf(stderr, "Cannot grab keyboard\n");
929 return 0;
932 unsigned long
933 parse_color(const char *str, const char *def)
935 size_t len;
936 rgba_t tmp;
937 char *ep;
939 if (str == NULL)
940 goto invc;
942 len = strlen(str);
944 /* +1 for the # ath the start */
945 if (*str != '#' || len > 9 || len < 4)
946 goto invc;
947 ++str; /* skip the # */
949 errno = 0;
950 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
952 if (errno)
953 goto invc;
955 switch (len - 1) {
956 case 3:
957 /* expand #rgb -> #rrggbb */
958 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
959 | (tmp.v & 0x00f) * 0x0011;
960 case 6:
961 /* assume 0xff opacity */
962 tmp.rgba.a = 0xff;
963 break;
964 } /* colors in #aarrggbb need no adjustments */
966 /* premultiply the alpha */
967 if (tmp.rgba.a) {
968 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
969 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
970 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
971 return tmp.v;
974 return 0U;
976 invc:
977 fprintf(stderr, "Invalid color: \"%s\".\n", str);
978 if (def != NULL)
979 return parse_color(def, NULL);
980 else
981 return 0U;
984 /*
985 * Given a string try to parse it as a number or return `default_value'.
986 */
987 int
988 parse_integer(const char *str, int default_value)
990 long lval;
991 char *ep;
993 errno = 0;
994 lval = strtol(str, &ep, 10);
996 if (str[0] == '\0' || *ep != '\0') { /* NaN */
997 fprintf(stderr,
998 "'%s' is not a valid number! Using %d as default.\n",
999 str, default_value);
1000 return default_value;
1003 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
1004 || (lval > INT_MAX || lval < INT_MIN)) {
1005 fprintf(stderr, "%s out of range! Using %d as default.\n",
1006 str, default_value);
1007 return default_value;
1010 return lval;
1013 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1014 * `%') */
1015 int
1016 parse_int_with_percentage(const char *str, int default_value, int max)
1018 int len = strlen(str);
1020 if (len > 0 && str[len - 1] == '%') {
1021 int val;
1022 char *cpy;
1024 if ((cpy = strdup(str)) == NULL)
1025 err(1, "strdup");
1027 cpy[len - 1] = '\0';
1028 val = parse_integer(cpy, default_value);
1029 free(cpy);
1030 return val * max / 100;
1033 return parse_integer(str, default_value);
1037 * Like parse_int_with_percentage but understands some special values:
1038 * - middle that is (max-self)/2
1039 * - start that is 0
1040 * - end that is (max-self)
1042 int
1043 parse_int_with_pos(const char *str, int default_value, int max, int self)
1045 if (!strcmp(str, "start"))
1046 return 0;
1047 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1048 return (max - self) / 2;
1049 if (!strcmp(str, "end"))
1050 return max - self;
1051 return parse_int_with_percentage(str, default_value, max);
1054 /* Parse a string like a CSS value. */
1055 /* TODO: harden a bit this function */
1056 char **
1057 parse_csslike(const char *str)
1059 int i, j;
1060 char *s, *token, **ret;
1061 short any_null;
1063 s = strdup(str);
1064 if (s == NULL)
1065 return NULL;
1067 ret = malloc(4 * sizeof(char *));
1068 if (ret == NULL) {
1069 free(s);
1070 return NULL;
1073 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1074 ret[i] = strdup(token);
1076 if (i == 1)
1077 for (j = 1; j < 4; j++)
1078 ret[j] = strdup(ret[0]);
1080 if (i == 2) {
1081 ret[2] = strdup(ret[0]);
1082 ret[3] = strdup(ret[1]);
1085 if (i == 3)
1086 ret[3] = strdup(ret[1]);
1088 /* before we didn't check for the return type of strdup, here we will
1091 any_null = 0;
1092 for (i = 0; i < 4; ++i)
1093 any_null = ret[i] == NULL || any_null;
1095 if (any_null)
1096 for (i = 0; i < 4; ++i)
1097 if (ret[i] != NULL)
1098 free(ret[i]);
1100 if (i == 0 || any_null) {
1101 free(s);
1102 free(ret);
1103 return NULL;
1106 return ret;
1110 * Given an event, try to understand what the users wants. If the
1111 * return value is ADD_CHAR then `input' is a pointer to a string that
1112 * will need to be free'ed later.
1114 enum action
1115 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1117 char str[SYM_BUF_SIZE] = { 0 };
1118 Status s;
1120 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1121 return DEL_CHAR;
1123 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1124 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1126 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1127 return CONFIRM;
1129 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1130 return EXIT;
1132 /* Try to read what key was pressed */
1133 s = 0;
1134 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1135 if (s == XBufferOverflow) {
1136 fprintf(stderr,
1137 "Buffer overflow when trying to create keyboard "
1138 "symbol map.\n");
1139 return EXIT;
1142 if (ev->state & ControlMask) {
1143 if (!strcmp(str, "")) /* C-u */
1144 return DEL_LINE;
1145 if (!strcmp(str, "")) /* C-w */
1146 return DEL_WORD;
1147 if (!strcmp(str, "")) /* C-h */
1148 return DEL_CHAR;
1149 if (!strcmp(str, "\r")) /* C-m */
1150 return CONFIRM_CONTINUE;
1151 if (!strcmp(str, "")) /* C-p */
1152 return PREV_COMPL;
1153 if (!strcmp(str, "")) /* C-n */
1154 return NEXT_COMPL;
1155 if (!strcmp(str, "")) /* C-c */
1156 return EXIT;
1157 if (!strcmp(str, "\t")) /* C-i */
1158 return TOGGLE_FIRST_SELECTED;
1161 *input = strdup(str);
1162 if (*input == NULL) {
1163 fprintf(stderr, "Error while allocating memory for key.\n");
1164 return EXIT;
1167 return ADD_CHAR;
1170 void
1171 confirm(enum state *status, struct rendering *r, struct completions *cs,
1172 char **text, int *textlen)
1174 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1175 /* if there is something selected expand it and return */
1176 int index = cs->selected == -1 ? 0 : cs->selected;
1177 struct completion *c = cs->completions;
1178 char *t;
1180 while (1) {
1181 if (index == 0)
1182 break;
1183 c++;
1184 index--;
1187 t = c->rcompletion;
1188 free(*text);
1189 *text = strdup(t);
1191 if (*text == NULL) {
1192 fprintf(stderr, "Memory allocation error\n");
1193 *status = ERR;
1196 *textlen = strlen(*text);
1197 return;
1200 if (!r->free_text) /* cannot accept arbitrary text */
1201 *status = LOOPING;
1204 /* cs: completion list
1205 * offset: the offset of the click
1206 * first: the first (rendered) item
1207 * def: the default action
1209 enum action
1210 select_clicked(
1211 struct completions *cs, size_t offset, size_t first, enum action def)
1213 ssize_t selected = first;
1214 int set = 0;
1216 if (cs->length == 0)
1217 return NO_OP;
1219 if (offset < cs->completions[selected].offset)
1220 return NO_OP;
1222 /* skip the first entry */
1223 for (selected += 1; selected < cs->length; ++selected) {
1224 if (cs->completions[selected].offset == -1) {
1225 printf("caught -1\n");
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(
1243 struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1245 size_t off;
1247 if (r->horizontal_layout)
1248 off = e->x;
1249 else
1250 off = e->y;
1252 switch (e->button) {
1253 case Button1:
1254 return select_clicked(cs, off, r->offset, CONFIRM);
1256 case Button3:
1257 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1259 case Button4:
1260 return SCROLL_UP;
1262 case Button5:
1263 return SCROLL_DOWN;
1266 return NO_OP;
1269 /* event loop */
1270 enum state
1271 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1272 char **lines, char **vlines)
1274 enum state status = LOOPING;
1276 while (status == LOOPING) {
1277 XEvent e;
1278 XNextEvent(r->d, &e);
1280 if (XFilterEvent(&e, r->w))
1281 continue;
1283 switch (e.type) {
1284 case KeymapNotify:
1285 XRefreshKeyboardMapping(&e.xmapping);
1286 break;
1288 case FocusIn:
1289 /* Re-grab focus */
1290 if (e.xfocus.window != r->w)
1291 grabfocus(r->d, r->w);
1292 break;
1294 case VisibilityNotify:
1295 if (e.xvisibility.state != VisibilityUnobscured)
1296 XRaiseWindow(r->d, r->w);
1297 break;
1299 case MapNotify:
1300 get_wh(r->d, &r->w, &r->width, &r->height);
1301 draw(r, *text, cs);
1302 break;
1304 case KeyPress:
1305 case ButtonPress: {
1306 enum action a;
1307 char *input = NULL;
1309 if (e.type == KeyPress)
1310 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1311 r->xic, &input);
1312 else
1313 a = handle_mouse(
1314 r, cs, (XButtonPressedEvent *)&e);
1316 switch (a) {
1317 case NO_OP:
1318 break;
1320 case EXIT:
1321 status = ERR;
1322 break;
1324 case CONFIRM: {
1325 status = OK;
1326 confirm(&status, r, cs, text, textlen);
1327 break;
1330 case CONFIRM_CONTINUE: {
1331 status = OK_LOOP;
1332 confirm(&status, r, cs, text, textlen);
1333 break;
1336 case PREV_COMPL: {
1337 complete(cs, r->first_selected, 1, text,
1338 textlen, &status);
1339 r->offset = cs->selected;
1340 break;
1343 case NEXT_COMPL: {
1344 complete(cs, r->first_selected, 0, text,
1345 textlen, &status);
1346 r->offset = cs->selected;
1347 break;
1350 case DEL_CHAR:
1351 popc(*text);
1352 update_completions(cs, *text, lines, vlines,
1353 r->first_selected);
1354 r->offset = 0;
1355 break;
1357 case DEL_WORD: {
1358 popw(*text);
1359 update_completions(cs, *text, lines, vlines,
1360 r->first_selected);
1361 break;
1364 case DEL_LINE: {
1365 int i;
1366 for (i = 0; i < *textlen; ++i)
1367 *(*text + i) = 0;
1368 update_completions(cs, *text, lines, vlines,
1369 r->first_selected);
1370 r->offset = 0;
1371 break;
1374 case ADD_CHAR: {
1375 int str_len, i;
1377 str_len = strlen(input);
1380 * sometimes a strange key is pressed
1381 * i.e. ctrl alone), so input will be
1382 * empty. Don't need to update
1383 * completion in that case
1385 if (str_len == 0)
1386 break;
1388 for (i = 0; i < str_len; ++i) {
1389 *textlen = pushc(
1390 text, *textlen, input[i]);
1391 if (*textlen == -1) {
1392 fprintf(stderr,
1393 "Memory allocation "
1394 "error\n");
1395 status = ERR;
1396 break;
1400 if (status != ERR) {
1401 update_completions(cs, *text, lines,
1402 vlines, r->first_selected);
1403 free(input);
1406 r->offset = 0;
1407 break;
1410 case TOGGLE_FIRST_SELECTED:
1411 r->first_selected = !r->first_selected;
1412 if (r->first_selected && cs->selected < 0)
1413 cs->selected = 0;
1414 if (!r->first_selected && cs->selected == 0)
1415 cs->selected = -1;
1416 break;
1418 case SCROLL_DOWN:
1419 r->offset
1420 = MIN(r->offset + 1, cs->length - 1);
1421 break;
1423 case SCROLL_UP:
1424 r->offset = MAX((ssize_t)r->offset - 1, 0);
1425 break;
1430 draw(r, *text, cs);
1433 return status;
1436 int
1437 load_font(struct rendering *r, const char *fontname)
1439 #ifdef USE_XFT
1440 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1441 return 0;
1442 #else
1443 char **missing_charset_list;
1444 int missing_charset_count;
1446 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1447 &missing_charset_count, NULL);
1448 if (r->font != NULL)
1449 return 0;
1451 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1453 if (!strcmp(fontname, default_fontname))
1454 return -1;
1456 return load_font(r, default_fontname);
1457 #endif
1460 void
1461 xim_init(struct rendering *r, XrmDatabase *xdb)
1463 XIMStyle best_match_style;
1464 XIMStyles *xis;
1465 int i;
1467 /* Open the X input method */
1468 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1469 err(1, "XOpenIM");
1471 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1472 fprintf(stderr, "Input Styles could not be retrieved\n");
1473 exit(EX_UNAVAILABLE);
1476 best_match_style = 0;
1477 for (i = 0; i < xis->count_styles; ++i) {
1478 XIMStyle ts = xis->supported_styles[i];
1479 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1480 best_match_style = ts;
1481 break;
1484 XFree(xis);
1486 if (!best_match_style)
1487 fprintf(stderr,
1488 "No matching input style could be determined\n");
1490 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1491 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1492 if (r->xic == NULL)
1493 err(1, "XCreateIC");
1496 void
1497 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1498 XVisualInfo vinfo, int x, int y, int ox, int oy,
1499 unsigned long background_pixel)
1501 XSetWindowAttributes attr;
1503 /* Create the window */
1504 attr.colormap = cmap;
1505 attr.override_redirect = 1;
1506 attr.border_pixel = 0;
1507 attr.background_pixel = background_pixel;
1508 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1509 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1511 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1512 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1513 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1514 | CWOverrideRedirect,
1515 &attr);
1518 void
1519 ps1extents(struct rendering *r)
1521 char *dup;
1522 dup = strdupn(r->ps1);
1523 text_extents(
1524 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1525 free(dup);
1528 void
1529 usage(char *prgname)
1531 fprintf(stderr,
1532 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1533 " [-d separator] [-e window] [-f font] [-G color] [-g "
1534 "size]\n"
1535 " [-H height] [-I color] [-i size] [-J color] [-j "
1536 "size] [-l layout]\n"
1537 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1538 "color]\n"
1539 " [-t color] [-W width] [-x coord] [-y coord]\n",
1540 prgname);
1543 int
1544 main(int argc, char **argv)
1546 struct completions *cs;
1547 struct rendering r;
1548 XVisualInfo vinfo;
1549 Colormap cmap;
1550 size_t nlines, i;
1551 Window parent_window;
1552 XrmDatabase xdb;
1553 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1554 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1555 ch_borders_bg[4]; /* N E S W */
1556 enum state status;
1557 int ch;
1558 int offset_x, offset_y, x, y;
1559 int textlen, d_width, d_height;
1560 short embed;
1561 char *sep, *parent_window_id;
1562 char **lines, *buf, **vlines;
1563 char *fontname, *text, *xrm;
1565 #ifdef __OpenBSD__
1566 /* stdio & rpath: to read/write stdio/stdout/stderr */
1567 /* unix: to connect to XOrg */
1568 pledge("stdio rpath unix", "");
1569 #endif
1571 sep = NULL;
1572 parent_window_id = NULL;
1574 r.first_selected = 0;
1575 r.free_text = 1;
1576 r.multiple_select = 0;
1577 r.offset = 0;
1579 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1580 switch (ch) {
1581 case 'h': /* help */
1582 usage(*argv);
1583 return 0;
1584 case 'v': /* version */
1585 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1586 return 0;
1587 case 'e': /* embed */
1588 if ((parent_window_id = strdup(optarg)) == NULL)
1589 err(1, "strdup");
1590 break;
1591 case 'd':
1592 if ((sep = strdup(optarg)) == NULL)
1593 err(1, "strdup");
1594 break;
1595 case 'A':
1596 r.free_text = 0;
1597 break;
1598 case 'm':
1599 r.multiple_select = 1;
1600 break;
1601 default:
1602 break;
1606 /* Read the completions */
1607 lines = NULL;
1608 buf = NULL;
1609 nlines = readlines(&lines, &buf);
1611 vlines = NULL;
1612 if (sep != NULL) {
1613 int l;
1614 l = strlen(sep);
1615 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1616 err(1, "calloc");
1618 for (i = 0; i < nlines; i++) {
1619 char *t;
1620 t = strstr(lines[i], sep);
1621 if (t == NULL)
1622 vlines[i] = lines[i];
1623 else
1624 vlines[i] = t + l;
1628 setlocale(LC_ALL, getenv("LANG"));
1630 status = LOOPING;
1632 /* where the monitor start (used only with xinerama) */
1633 offset_x = offset_y = 0;
1635 /* default width and height */
1636 r.width = 400;
1637 r.height = 20;
1639 /* default position on the screen */
1640 x = y = 0;
1642 for (i = 0; i < 4; ++i) {
1643 /* default paddings */
1644 r.p_padding[i] = 10;
1645 r.c_padding[i] = 10;
1646 r.ch_padding[i] = 10;
1648 /* default borders */
1649 r.borders[i] = 0;
1650 r.p_borders[i] = 0;
1651 r.c_borders[i] = 0;
1652 r.ch_borders[i] = 0;
1655 /* the prompt. We duplicate the string so later is easy to
1656 * free (in the case it's been overwritten by the user) */
1657 if ((r.ps1 = strdup("$ ")) == NULL)
1658 err(1, "strdup");
1660 /* same for the font name */
1661 if ((fontname = strdup(default_fontname)) == NULL)
1662 err(1, "strdup");
1664 textlen = 10;
1665 if ((text = malloc(textlen * sizeof(char))) == NULL)
1666 err(1, "malloc");
1668 /* struct completions *cs = filter(text, lines); */
1669 if ((cs = compls_new(nlines)) == NULL)
1670 err(1, "compls_new");
1672 /* start talking to xorg */
1673 r.d = XOpenDisplay(NULL);
1674 if (r.d == NULL) {
1675 fprintf(stderr, "Could not open display!\n");
1676 return EX_UNAVAILABLE;
1679 embed = 1;
1680 if (!(parent_window_id
1681 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1682 parent_window = DefaultRootWindow(r.d);
1683 embed = 0;
1686 /* get display size */
1687 get_wh(r.d, &parent_window, &d_width, &d_height);
1689 #ifdef USE_XINERAMA
1690 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1691 XineramaScreenInfo *info;
1692 Window rr;
1693 Window root;
1694 int number_of_screens, monitors, i;
1695 int root_x, root_y, win_x, win_y;
1696 unsigned int mask;
1697 short res;
1699 number_of_screens = XScreenCount(r.d);
1700 for (i = 0; i < number_of_screens; ++i) {
1701 root = XRootWindow(r.d, i);
1702 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1703 &root_y, &win_x, &win_y, &mask);
1704 if (res)
1705 break;
1708 if (!res) {
1709 fprintf(stderr, "No mouse found.\n");
1710 root_x = 0;
1711 root_y = 0;
1714 /* Now find in which monitor the mice is */
1715 info = XineramaQueryScreens(r.d, &monitors);
1716 if (info) {
1717 for (i = 0; i < monitors; ++i) {
1718 if (info[i].x_org <= root_x
1719 && root_x <= (info[i].x_org
1720 + info[i].width)
1721 && info[i].y_org <= root_y
1722 && root_y <= (info[i].y_org
1723 + info[i].height)) {
1724 offset_x = info[i].x_org;
1725 offset_y = info[i].y_org;
1726 d_width = info[i].width;
1727 d_height = info[i].height;
1728 break;
1732 XFree(info);
1734 #endif
1736 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1737 cmap = XCreateColormap(
1738 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1740 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1741 fgs[2] = parse_color("#000", NULL);
1743 bgs[0] = bgs[1] = parse_color("#000", NULL);
1744 bgs[2] = parse_color("#fff", NULL);
1746 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1747 = parse_color("#000", NULL);
1749 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1750 = parse_color("#000", NULL);
1751 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1752 = parse_color("#000", NULL);
1753 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1754 = ch_borders_bg[3] = parse_color("#000", NULL);
1756 r.horizontal_layout = 1;
1758 /* Read the resources */
1759 XrmInitialize();
1760 xrm = XResourceManagerString(r.d);
1761 xdb = NULL;
1762 if (xrm != NULL) {
1763 XrmValue value;
1764 char *datatype[20];
1766 xdb = XrmGetStringDatabase(xrm);
1768 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1769 == 1) {
1770 free(fontname);
1771 if ((fontname = strdup(value.addr)) == NULL)
1772 err(1, "strdup");
1773 } else {
1774 fprintf(stderr, "no font defined, using %s\n",
1775 fontname);
1778 if (XrmGetResource(
1779 xdb, "MyMenu.layout", "*", datatype, &value)
1780 == 1)
1781 r.horizontal_layout
1782 = !strcmp(value.addr, "horizontal");
1783 else
1784 fprintf(stderr,
1785 "no layout defined, using horizontal\n");
1787 if (XrmGetResource(
1788 xdb, "MyMenu.prompt", "*", datatype, &value)
1789 == 1) {
1790 free(r.ps1);
1791 r.ps1 = normalize_str(value.addr);
1792 } else {
1793 fprintf(stderr,
1794 "no prompt defined, using \"%s\" as "
1795 "default\n",
1796 r.ps1);
1799 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1800 datatype, &value)
1801 == 1) {
1802 char **sizes;
1803 sizes = parse_csslike(value.addr);
1804 if (sizes != NULL)
1805 for (i = 0; i < 4; ++i)
1806 r.p_borders[i]
1807 = parse_integer(sizes[i], 0);
1808 else
1809 fprintf(stderr,
1810 "error while parsing "
1811 "MyMenu.prompt.border.size");
1814 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1815 datatype, &value)
1816 == 1) {
1817 char **colors;
1818 colors = parse_csslike(value.addr);
1819 if (colors != NULL)
1820 for (i = 0; i < 4; ++i)
1821 p_borders_bg[i] = parse_color(
1822 colors[i], "#000");
1823 else
1824 fprintf(stderr,
1825 "error while parsing "
1826 "MyMenu.prompt.border.color");
1829 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1830 datatype, &value)
1831 == 1) {
1832 char **colors;
1833 colors = parse_csslike(value.addr);
1834 if (colors != NULL)
1835 for (i = 0; i < 4; ++i)
1836 r.p_padding[i]
1837 = parse_integer(colors[i], 0);
1838 else
1839 fprintf(stderr,
1840 "error while parsing "
1841 "MyMenu.prompt.padding");
1844 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1845 == 1)
1846 r.width = parse_int_with_percentage(
1847 value.addr, r.width, d_width);
1848 else
1849 fprintf(stderr, "no width defined, using %d\n",
1850 r.width);
1852 if (XrmGetResource(
1853 xdb, "MyMenu.height", "*", datatype, &value)
1854 == 1)
1855 r.height = parse_int_with_percentage(
1856 value.addr, r.height, d_height);
1857 else
1858 fprintf(stderr, "no height defined, using %d\n",
1859 r.height);
1861 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1862 == 1)
1863 x = parse_int_with_pos(
1864 value.addr, x, d_width, r.width);
1866 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1867 == 1)
1868 y = parse_int_with_pos(
1869 value.addr, y, d_height, r.height);
1871 if (XrmGetResource(
1872 xdb, "MyMenu.border.size", "*", datatype, &value)
1873 == 1) {
1874 char **borders;
1875 borders = parse_csslike(value.addr);
1876 if (borders != NULL)
1877 for (i = 0; i < 4; ++i)
1878 r.borders[i]
1879 = parse_int_with_percentage(
1880 borders[i], 0,
1881 (i % 2) == 0
1882 ? d_height
1883 : d_width);
1884 else
1885 fprintf(stderr,
1886 "error while parsing "
1887 "MyMenu.border.size\n");
1890 /* Prompt */
1891 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1892 datatype, &value)
1893 == 1)
1894 fgs[0] = parse_color(value.addr, "#fff");
1896 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1897 datatype, &value)
1898 == 1)
1899 bgs[0] = parse_color(value.addr, "#000");
1901 /* Completions */
1902 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1903 datatype, &value)
1904 == 1)
1905 fgs[1] = parse_color(value.addr, "#fff");
1907 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1908 datatype, &value)
1909 == 1)
1910 bgs[1] = parse_color(value.addr, "#000");
1912 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1913 datatype, &value)
1914 == 1) {
1915 char **paddings;
1916 paddings = parse_csslike(value.addr);
1917 if (paddings != NULL)
1918 for (i = 0; i < 4; ++i)
1919 r.c_padding[i] = parse_integer(
1920 paddings[i], 0);
1921 else
1922 fprintf(stderr,
1923 "Error while parsing "
1924 "MyMenu.completion.padding");
1927 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1928 datatype, &value)
1929 == 1) {
1930 char **sizes;
1931 sizes = parse_csslike(value.addr);
1932 if (sizes != NULL)
1933 for (i = 0; i < 4; ++i)
1934 r.c_borders[i]
1935 = parse_integer(sizes[i], 0);
1936 else
1937 fprintf(stderr,
1938 "Error while parsing "
1939 "MyMenu.completion.border.size");
1942 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1943 datatype, &value)
1944 == 1) {
1945 char **sizes;
1946 sizes = parse_csslike(value.addr);
1947 if (sizes != NULL)
1948 for (i = 0; i < 4; ++i)
1949 c_borders_bg[i] = parse_color(
1950 sizes[i], "#000");
1951 else
1952 fprintf(stderr,
1953 "Error while parsing "
1954 "MyMenu.completion.border.color");
1957 /* Completion Highlighted */
1958 if (XrmGetResource(xdb,
1959 "MyMenu.completion_highlighted.foreground", "*",
1960 datatype, &value)
1961 == 1)
1962 fgs[2] = parse_color(value.addr, "#000");
1964 if (XrmGetResource(xdb,
1965 "MyMenu.completion_highlighted.background", "*",
1966 datatype, &value)
1967 == 1)
1968 bgs[2] = parse_color(value.addr, "#fff");
1970 if (XrmGetResource(xdb,
1971 "MyMenu.completion_highlighted.padding", "*",
1972 datatype, &value)
1973 == 1) {
1974 char **paddings;
1975 paddings = parse_csslike(value.addr);
1976 if (paddings != NULL)
1977 for (i = 0; i < 4; ++i)
1978 r.ch_padding[i] = parse_integer(
1979 paddings[i], 0);
1980 else
1981 fprintf(stderr,
1982 "Error while parsing "
1983 "MyMenu.completion_highlighted."
1984 "padding");
1987 if (XrmGetResource(xdb,
1988 "MyMenu.completion_highlighted.border.size", "*",
1989 datatype, &value)
1990 == 1) {
1991 char **sizes;
1992 sizes = parse_csslike(value.addr);
1993 if (sizes != NULL)
1994 for (i = 0; i < 4; ++i)
1995 r.ch_borders[i]
1996 = parse_integer(sizes[i], 0);
1997 else
1998 fprintf(stderr,
1999 "Error while parsing "
2000 "MyMenu.completion_highlighted."
2001 "border.size");
2004 if (XrmGetResource(xdb,
2005 "MyMenu.completion_highlighted.border.color", "*",
2006 datatype, &value)
2007 == 1) {
2008 char **colors;
2009 colors = parse_csslike(value.addr);
2010 if (colors != NULL)
2011 for (i = 0; i < 4; ++i)
2012 ch_borders_bg[i] = parse_color(
2013 colors[i], "#000");
2014 else
2015 fprintf(stderr,
2016 "Error while parsing "
2017 "MyMenu.completion_highlighted."
2018 "border.color");
2021 /* Border */
2022 if (XrmGetResource(
2023 xdb, "MyMenu.border.color", "*", datatype, &value)
2024 == 1) {
2025 char **colors;
2026 colors = parse_csslike(value.addr);
2027 if (colors != NULL)
2028 for (i = 0; i < 4; ++i)
2029 borders_bg[i] = parse_color(
2030 colors[i], "#000");
2031 else
2032 fprintf(stderr,
2033 "error while parsing "
2034 "MyMenu.border.color\n");
2038 /* Second round of args parsing */
2039 optind = 0; /* reset the option index */
2040 while ((ch = getopt(argc, argv, ARGS)) != -1) {
2041 switch (ch) {
2042 case 'a':
2043 r.first_selected = 1;
2044 break;
2045 case 'A':
2046 /* free_text -- already catched */
2047 case 'd':
2048 /* separator -- this case was already catched */
2049 case 'e':
2050 /* embedding mymenu this case was already catched. */
2051 case 'm':
2052 /* multiple selection this case was already catched.
2054 break;
2055 case 'p': {
2056 char *newprompt;
2057 newprompt = strdup(optarg);
2058 if (newprompt != NULL) {
2059 free(r.ps1);
2060 r.ps1 = newprompt;
2062 break;
2064 case 'x':
2065 x = parse_int_with_pos(optarg, x, d_width, r.width);
2066 break;
2067 case 'y':
2068 y = parse_int_with_pos(optarg, y, d_height, r.height);
2069 break;
2070 case 'P': {
2071 char **paddings;
2072 if ((paddings = parse_csslike(optarg)) != NULL)
2073 for (i = 0; i < 4; ++i)
2074 r.p_padding[i] = parse_integer(
2075 paddings[i], 0);
2076 break;
2078 case 'G': {
2079 char **colors;
2080 if ((colors = parse_csslike(optarg)) != NULL)
2081 for (i = 0; i < 4; ++i)
2082 p_borders_bg[i] = parse_color(
2083 colors[i], "#000");
2084 break;
2086 case 'g': {
2087 char **sizes;
2088 if ((sizes = parse_csslike(optarg)) != NULL)
2089 for (i = 0; i < 4; ++i)
2090 r.p_borders[i]
2091 = parse_integer(sizes[i], 0);
2092 break;
2094 case 'I': {
2095 char **colors;
2096 if ((colors = parse_csslike(optarg)) != NULL)
2097 for (i = 0; i < 4; ++i)
2098 c_borders_bg[i] = parse_color(
2099 colors[i], "#000");
2100 break;
2102 case 'i': {
2103 char **sizes;
2104 if ((sizes = parse_csslike(optarg)) != NULL)
2105 for (i = 0; i < 4; ++i)
2106 r.c_borders[i]
2107 = parse_integer(sizes[i], 0);
2108 break;
2110 case 'J': {
2111 char **colors;
2112 if ((colors = parse_csslike(optarg)) != NULL)
2113 for (i = 0; i < 4; ++i)
2114 ch_borders_bg[i] = parse_color(
2115 colors[i], "#000");
2116 break;
2118 case 'j': {
2119 char **sizes;
2120 if ((sizes = parse_csslike(optarg)) != NULL)
2121 for (i = 0; i < 4; ++i)
2122 r.ch_borders[i]
2123 = parse_integer(sizes[i], 0);
2124 break;
2126 case 'l':
2127 r.horizontal_layout = !strcmp(optarg, "horizontal");
2128 break;
2129 case 'f': {
2130 char *newfont;
2131 if ((newfont = strdup(optarg)) != NULL) {
2132 free(fontname);
2133 fontname = newfont;
2135 break;
2137 case 'W':
2138 r.width = parse_int_with_percentage(
2139 optarg, r.width, d_width);
2140 break;
2141 case 'H':
2142 r.height = parse_int_with_percentage(
2143 optarg, r.height, d_height);
2144 break;
2145 case 'b': {
2146 char **borders;
2147 if ((borders = parse_csslike(optarg)) != NULL) {
2148 for (i = 0; i < 4; ++i)
2149 r.borders[i] = parse_integer(
2150 borders[i], 0);
2151 } else
2152 fprintf(stderr, "Error parsing b option\n");
2153 break;
2155 case 'B': {
2156 char **colors;
2157 if ((colors = parse_csslike(optarg)) != NULL) {
2158 for (i = 0; i < 4; ++i)
2159 borders_bg[i] = parse_color(
2160 colors[i], "#000");
2161 } else
2162 fprintf(stderr,
2163 "error while parsing B option\n");
2164 break;
2166 case 't':
2167 fgs[0] = parse_color(optarg, NULL);
2168 break;
2169 case 'T':
2170 bgs[0] = parse_color(optarg, NULL);
2171 break;
2172 case 'c':
2173 fgs[1] = parse_color(optarg, NULL);
2174 break;
2175 case 'C':
2176 bgs[1] = parse_color(optarg, NULL);
2177 break;
2178 case 's':
2179 fgs[2] = parse_color(optarg, NULL);
2180 break;
2181 case 'S':
2182 fgs[2] = parse_color(optarg, NULL);
2183 break;
2184 default:
2185 fprintf(stderr, "Unrecognized option %c\n", ch);
2186 status = ERR;
2187 break;
2191 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2192 fprintf(stderr, "height, width, x or y are lesser than 0.");
2193 status = ERR;
2196 /* since only now we know if the first should be selected,
2197 * update the completion here */
2198 update_completions(cs, text, lines, vlines, r.first_selected);
2200 /* update the prompt lenght, only now we surely know the length of it
2202 r.ps1len = strlen(r.ps1);
2204 /* Create the window */
2205 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2206 offset_y, bgs[1]);
2207 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2208 XMapRaised(r.d, r.w);
2210 /* If embed, listen for other events as well */
2211 if (embed) {
2212 Window *children, parent, root;
2213 unsigned int children_no;
2215 XSelectInput(r.d, parent_window, FocusChangeMask);
2216 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2217 &children_no)
2218 && children) {
2219 for (i = 0; i < children_no && children[i] != r.w;
2220 ++i)
2221 XSelectInput(
2222 r.d, children[i], FocusChangeMask);
2223 XFree(children);
2225 grabfocus(r.d, r.w);
2228 take_keyboard(r.d, r.w);
2230 r.x_zero = r.borders[3];
2231 r.y_zero = r.borders[0];
2234 XGCValues values;
2236 for (i = 0; i < 3; ++i) {
2237 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2238 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2241 for (i = 0; i < 4; ++i) {
2242 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2243 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2244 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2245 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2249 /* Load the colors in our GCs */
2250 for (i = 0; i < 3; ++i) {
2251 XSetForeground(r.d, r.fgs[i], fgs[i]);
2252 XSetForeground(r.d, r.bgs[i], bgs[i]);
2255 for (i = 0; i < 4; ++i) {
2256 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2257 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2258 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2259 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2262 if (load_font(&r, fontname) == -1)
2263 status = ERR;
2265 #ifdef USE_XFT
2266 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2268 for (i = 0; i < 3; ++i) {
2269 rgba_t c;
2270 XRenderColor xrcolor;
2272 c = *(rgba_t *)&fgs[i];
2273 xrcolor.red = EXPANDBITS(c.rgba.r);
2274 xrcolor.green = EXPANDBITS(c.rgba.g);
2275 xrcolor.blue = EXPANDBITS(c.rgba.b);
2276 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2277 XftColorAllocValue(
2278 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2280 #endif
2282 /* compute prompt dimensions */
2283 ps1extents(&r);
2285 xim_init(&r, &xdb);
2287 #ifdef __OpenBSD__
2288 /* Now we need only the ability to write */
2289 pledge("stdio", "");
2290 #endif
2292 /* Cache text height */
2293 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2295 /* Draw the window for the first time */
2296 draw(&r, text, cs);
2298 /* Main loop */
2299 while (status == LOOPING || status == OK_LOOP) {
2300 status = loop(&r, &text, &textlen, cs, lines, vlines);
2302 if (status != ERR)
2303 printf("%s\n", text);
2305 if (!r.multiple_select && status == OK_LOOP)
2306 status = OK;
2309 XUngrabKeyboard(r.d, CurrentTime);
2311 #ifdef USE_XFT
2312 for (i = 0; i < 3; ++i)
2313 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2314 #endif
2316 for (i = 0; i < 3; ++i) {
2317 XFreeGC(r.d, r.fgs[i]);
2318 XFreeGC(r.d, r.bgs[i]);
2321 for (i = 0; i < 4; ++i) {
2322 XFreeGC(r.d, r.borders_bg[i]);
2323 XFreeGC(r.d, r.p_borders_bg[i]);
2324 XFreeGC(r.d, r.c_borders_bg[i]);
2325 XFreeGC(r.d, r.ch_borders_bg[i]);
2328 XDestroyIC(r.xic);
2329 XCloseIM(r.xim);
2331 #ifdef USE_XFT
2332 for (i = 0; i < 3; ++i)
2333 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2334 XftFontClose(r.d, r.font);
2335 XftDrawDestroy(r.xftdraw);
2336 #else
2337 XFreeFontSet(r.d, r.font);
2338 #endif
2340 free(r.ps1);
2341 free(fontname);
2342 free(text);
2344 free(buf);
2345 free(lines);
2346 free(vlines);
2347 compls_delete(cs);
2349 XFreeColormap(r.d, cmap);
2351 XDestroyWindow(r.d, r.w);
2352 XCloseDisplay(r.d);
2354 return status != OK;