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 break;
1227 if (offset < cs->completions[selected].offset) {
1228 cs->selected = selected - 1;
1229 set = 1;
1230 break;
1234 if (!set)
1235 cs->selected = selected - 1;
1237 return def;
1240 enum action
1241 handle_mouse(
1242 struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1244 size_t off;
1246 if (r->horizontal_layout)
1247 off = e->x;
1248 else
1249 off = e->y;
1251 switch (e->button) {
1252 case Button1:
1253 return select_clicked(cs, off, r->offset, CONFIRM);
1255 case Button3:
1256 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1258 case Button4:
1259 return SCROLL_UP;
1261 case Button5:
1262 return SCROLL_DOWN;
1265 return NO_OP;
1268 /* event loop */
1269 enum state
1270 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1271 char **lines, char **vlines)
1273 enum state status = LOOPING;
1275 while (status == LOOPING) {
1276 XEvent e;
1277 XNextEvent(r->d, &e);
1279 if (XFilterEvent(&e, r->w))
1280 continue;
1282 switch (e.type) {
1283 case KeymapNotify:
1284 XRefreshKeyboardMapping(&e.xmapping);
1285 break;
1287 case FocusIn:
1288 /* Re-grab focus */
1289 if (e.xfocus.window != r->w)
1290 grabfocus(r->d, r->w);
1291 break;
1293 case VisibilityNotify:
1294 if (e.xvisibility.state != VisibilityUnobscured)
1295 XRaiseWindow(r->d, r->w);
1296 break;
1298 case MapNotify:
1299 get_wh(r->d, &r->w, &r->width, &r->height);
1300 draw(r, *text, cs);
1301 break;
1303 case KeyPress:
1304 case ButtonPress: {
1305 enum action a;
1306 char *input = NULL;
1308 if (e.type == KeyPress)
1309 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1310 r->xic, &input);
1311 else
1312 a = handle_mouse(
1313 r, cs, (XButtonPressedEvent *)&e);
1315 switch (a) {
1316 case NO_OP:
1317 break;
1319 case EXIT:
1320 status = ERR;
1321 break;
1323 case CONFIRM: {
1324 status = OK;
1325 confirm(&status, r, cs, text, textlen);
1326 break;
1329 case CONFIRM_CONTINUE: {
1330 status = OK_LOOP;
1331 confirm(&status, r, cs, text, textlen);
1332 break;
1335 case PREV_COMPL: {
1336 complete(cs, r->first_selected, 1, text,
1337 textlen, &status);
1338 r->offset = cs->selected;
1339 break;
1342 case NEXT_COMPL: {
1343 complete(cs, r->first_selected, 0, text,
1344 textlen, &status);
1345 r->offset = cs->selected;
1346 break;
1349 case DEL_CHAR:
1350 popc(*text);
1351 update_completions(cs, *text, lines, vlines,
1352 r->first_selected);
1353 r->offset = 0;
1354 break;
1356 case DEL_WORD: {
1357 popw(*text);
1358 update_completions(cs, *text, lines, vlines,
1359 r->first_selected);
1360 break;
1363 case DEL_LINE: {
1364 int i;
1365 for (i = 0; i < *textlen; ++i)
1366 *(*text + i) = 0;
1367 update_completions(cs, *text, lines, vlines,
1368 r->first_selected);
1369 r->offset = 0;
1370 break;
1373 case ADD_CHAR: {
1374 int str_len, i;
1376 str_len = strlen(input);
1379 * sometimes a strange key is pressed
1380 * i.e. ctrl alone), so input will be
1381 * empty. Don't need to update
1382 * completion in that case
1384 if (str_len == 0)
1385 break;
1387 for (i = 0; i < str_len; ++i) {
1388 *textlen = pushc(
1389 text, *textlen, input[i]);
1390 if (*textlen == -1) {
1391 fprintf(stderr,
1392 "Memory allocation "
1393 "error\n");
1394 status = ERR;
1395 break;
1399 if (status != ERR) {
1400 update_completions(cs, *text, lines,
1401 vlines, r->first_selected);
1402 free(input);
1405 r->offset = 0;
1406 break;
1409 case TOGGLE_FIRST_SELECTED:
1410 r->first_selected = !r->first_selected;
1411 if (r->first_selected && cs->selected < 0)
1412 cs->selected = 0;
1413 if (!r->first_selected && cs->selected == 0)
1414 cs->selected = -1;
1415 break;
1417 case SCROLL_DOWN:
1418 r->offset
1419 = MIN(r->offset + 1, cs->length - 1);
1420 break;
1422 case SCROLL_UP:
1423 r->offset = MAX((ssize_t)r->offset - 1, 0);
1424 break;
1429 draw(r, *text, cs);
1432 return status;
1435 int
1436 load_font(struct rendering *r, const char *fontname)
1438 #ifdef USE_XFT
1439 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1440 return 0;
1441 #else
1442 char **missing_charset_list;
1443 int missing_charset_count;
1445 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1446 &missing_charset_count, NULL);
1447 if (r->font != NULL)
1448 return 0;
1450 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1452 if (!strcmp(fontname, default_fontname))
1453 return -1;
1455 return load_font(r, default_fontname);
1456 #endif
1459 void
1460 xim_init(struct rendering *r, XrmDatabase *xdb)
1462 XIMStyle best_match_style;
1463 XIMStyles *xis;
1464 int i;
1466 /* Open the X input method */
1467 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1468 err(1, "XOpenIM");
1470 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1471 fprintf(stderr, "Input Styles could not be retrieved\n");
1472 exit(EX_UNAVAILABLE);
1475 best_match_style = 0;
1476 for (i = 0; i < xis->count_styles; ++i) {
1477 XIMStyle ts = xis->supported_styles[i];
1478 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1479 best_match_style = ts;
1480 break;
1483 XFree(xis);
1485 if (!best_match_style)
1486 fprintf(stderr,
1487 "No matching input style could be determined\n");
1489 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1490 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1491 if (r->xic == NULL)
1492 err(1, "XCreateIC");
1495 void
1496 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1497 XVisualInfo vinfo, int x, int y, int ox, int oy,
1498 unsigned long background_pixel)
1500 XSetWindowAttributes attr;
1502 /* Create the window */
1503 attr.colormap = cmap;
1504 attr.override_redirect = 1;
1505 attr.border_pixel = 0;
1506 attr.background_pixel = background_pixel;
1507 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1508 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1510 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1511 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1512 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1513 | CWOverrideRedirect,
1514 &attr);
1517 void
1518 ps1extents(struct rendering *r)
1520 char *dup;
1521 dup = strdupn(r->ps1);
1522 text_extents(
1523 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1524 free(dup);
1527 void
1528 usage(char *prgname)
1530 fprintf(stderr,
1531 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1532 " [-d separator] [-e window] [-f font] [-G color] [-g "
1533 "size]\n"
1534 " [-H height] [-I color] [-i size] [-J color] [-j "
1535 "size] [-l layout]\n"
1536 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1537 "color]\n"
1538 " [-t color] [-W width] [-x coord] [-y coord]\n",
1539 prgname);
1542 int
1543 main(int argc, char **argv)
1545 struct completions *cs;
1546 struct rendering r;
1547 XVisualInfo vinfo;
1548 Colormap cmap;
1549 size_t nlines, i;
1550 Window parent_window;
1551 XrmDatabase xdb;
1552 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1553 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1554 ch_borders_bg[4]; /* N E S W */
1555 enum state status;
1556 int ch;
1557 int offset_x, offset_y, x, y;
1558 int textlen, d_width, d_height;
1559 short embed;
1560 char *sep, *parent_window_id;
1561 char **lines, *buf, **vlines;
1562 char *fontname, *text, *xrm;
1564 #ifdef __OpenBSD__
1565 /* stdio & rpath: to read/write stdio/stdout/stderr */
1566 /* unix: to connect to XOrg */
1567 pledge("stdio rpath unix", "");
1568 #endif
1570 sep = NULL;
1571 parent_window_id = NULL;
1573 r.first_selected = 0;
1574 r.free_text = 1;
1575 r.multiple_select = 0;
1576 r.offset = 0;
1578 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1579 switch (ch) {
1580 case 'h': /* help */
1581 usage(*argv);
1582 return 0;
1583 case 'v': /* version */
1584 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1585 return 0;
1586 case 'e': /* embed */
1587 if ((parent_window_id = strdup(optarg)) == NULL)
1588 err(1, "strdup");
1589 break;
1590 case 'd':
1591 if ((sep = strdup(optarg)) == NULL)
1592 err(1, "strdup");
1593 break;
1594 case 'A':
1595 r.free_text = 0;
1596 break;
1597 case 'm':
1598 r.multiple_select = 1;
1599 break;
1600 default:
1601 break;
1605 /* Read the completions */
1606 lines = NULL;
1607 buf = NULL;
1608 nlines = readlines(&lines, &buf);
1610 vlines = NULL;
1611 if (sep != NULL) {
1612 int l;
1613 l = strlen(sep);
1614 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1615 err(1, "calloc");
1617 for (i = 0; i < nlines; i++) {
1618 char *t;
1619 t = strstr(lines[i], sep);
1620 if (t == NULL)
1621 vlines[i] = lines[i];
1622 else
1623 vlines[i] = t + l;
1627 setlocale(LC_ALL, getenv("LANG"));
1629 status = LOOPING;
1631 /* where the monitor start (used only with xinerama) */
1632 offset_x = offset_y = 0;
1634 /* default width and height */
1635 r.width = 400;
1636 r.height = 20;
1638 /* default position on the screen */
1639 x = y = 0;
1641 for (i = 0; i < 4; ++i) {
1642 /* default paddings */
1643 r.p_padding[i] = 10;
1644 r.c_padding[i] = 10;
1645 r.ch_padding[i] = 10;
1647 /* default borders */
1648 r.borders[i] = 0;
1649 r.p_borders[i] = 0;
1650 r.c_borders[i] = 0;
1651 r.ch_borders[i] = 0;
1654 /* the prompt. We duplicate the string so later is easy to
1655 * free (in the case it's been overwritten by the user) */
1656 if ((r.ps1 = strdup("$ ")) == NULL)
1657 err(1, "strdup");
1659 /* same for the font name */
1660 if ((fontname = strdup(default_fontname)) == NULL)
1661 err(1, "strdup");
1663 textlen = 10;
1664 if ((text = malloc(textlen * sizeof(char))) == NULL)
1665 err(1, "malloc");
1667 /* struct completions *cs = filter(text, lines); */
1668 if ((cs = compls_new(nlines)) == NULL)
1669 err(1, "compls_new");
1671 /* start talking to xorg */
1672 r.d = XOpenDisplay(NULL);
1673 if (r.d == NULL) {
1674 fprintf(stderr, "Could not open display!\n");
1675 return EX_UNAVAILABLE;
1678 embed = 1;
1679 if (!(parent_window_id
1680 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1681 parent_window = DefaultRootWindow(r.d);
1682 embed = 0;
1685 /* get display size */
1686 get_wh(r.d, &parent_window, &d_width, &d_height);
1688 #ifdef USE_XINERAMA
1689 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1690 XineramaScreenInfo *info;
1691 Window rr;
1692 Window root;
1693 int number_of_screens, monitors, i;
1694 int root_x, root_y, win_x, win_y;
1695 unsigned int mask;
1696 short res;
1698 number_of_screens = XScreenCount(r.d);
1699 for (i = 0; i < number_of_screens; ++i) {
1700 root = XRootWindow(r.d, i);
1701 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1702 &root_y, &win_x, &win_y, &mask);
1703 if (res)
1704 break;
1707 if (!res) {
1708 fprintf(stderr, "No mouse found.\n");
1709 root_x = 0;
1710 root_y = 0;
1713 /* Now find in which monitor the mice is */
1714 info = XineramaQueryScreens(r.d, &monitors);
1715 if (info) {
1716 for (i = 0; i < monitors; ++i) {
1717 if (info[i].x_org <= root_x
1718 && root_x <= (info[i].x_org
1719 + info[i].width)
1720 && info[i].y_org <= root_y
1721 && root_y <= (info[i].y_org
1722 + info[i].height)) {
1723 offset_x = info[i].x_org;
1724 offset_y = info[i].y_org;
1725 d_width = info[i].width;
1726 d_height = info[i].height;
1727 break;
1731 XFree(info);
1733 #endif
1735 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1736 cmap = XCreateColormap(
1737 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1739 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1740 fgs[2] = parse_color("#000", NULL);
1742 bgs[0] = bgs[1] = parse_color("#000", NULL);
1743 bgs[2] = parse_color("#fff", NULL);
1745 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1746 = parse_color("#000", NULL);
1748 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1749 = parse_color("#000", NULL);
1750 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1751 = parse_color("#000", NULL);
1752 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1753 = ch_borders_bg[3] = parse_color("#000", NULL);
1755 r.horizontal_layout = 1;
1757 /* Read the resources */
1758 XrmInitialize();
1759 xrm = XResourceManagerString(r.d);
1760 xdb = NULL;
1761 if (xrm != NULL) {
1762 XrmValue value;
1763 char *datatype[20];
1765 xdb = XrmGetStringDatabase(xrm);
1767 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1768 == 1) {
1769 free(fontname);
1770 if ((fontname = strdup(value.addr)) == NULL)
1771 err(1, "strdup");
1772 } else {
1773 fprintf(stderr, "no font defined, using %s\n",
1774 fontname);
1777 if (XrmGetResource(
1778 xdb, "MyMenu.layout", "*", datatype, &value)
1779 == 1)
1780 r.horizontal_layout
1781 = !strcmp(value.addr, "horizontal");
1782 else
1783 fprintf(stderr,
1784 "no layout defined, using horizontal\n");
1786 if (XrmGetResource(
1787 xdb, "MyMenu.prompt", "*", datatype, &value)
1788 == 1) {
1789 free(r.ps1);
1790 r.ps1 = normalize_str(value.addr);
1791 } else {
1792 fprintf(stderr,
1793 "no prompt defined, using \"%s\" as "
1794 "default\n",
1795 r.ps1);
1798 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1799 datatype, &value)
1800 == 1) {
1801 char **sizes;
1802 sizes = parse_csslike(value.addr);
1803 if (sizes != NULL)
1804 for (i = 0; i < 4; ++i)
1805 r.p_borders[i]
1806 = parse_integer(sizes[i], 0);
1807 else
1808 fprintf(stderr,
1809 "error while parsing "
1810 "MyMenu.prompt.border.size");
1813 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1814 datatype, &value)
1815 == 1) {
1816 char **colors;
1817 colors = parse_csslike(value.addr);
1818 if (colors != NULL)
1819 for (i = 0; i < 4; ++i)
1820 p_borders_bg[i] = parse_color(
1821 colors[i], "#000");
1822 else
1823 fprintf(stderr,
1824 "error while parsing "
1825 "MyMenu.prompt.border.color");
1828 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1829 datatype, &value)
1830 == 1) {
1831 char **colors;
1832 colors = parse_csslike(value.addr);
1833 if (colors != NULL)
1834 for (i = 0; i < 4; ++i)
1835 r.p_padding[i]
1836 = parse_integer(colors[i], 0);
1837 else
1838 fprintf(stderr,
1839 "error while parsing "
1840 "MyMenu.prompt.padding");
1843 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1844 == 1)
1845 r.width = parse_int_with_percentage(
1846 value.addr, r.width, d_width);
1847 else
1848 fprintf(stderr, "no width defined, using %d\n",
1849 r.width);
1851 if (XrmGetResource(
1852 xdb, "MyMenu.height", "*", datatype, &value)
1853 == 1)
1854 r.height = parse_int_with_percentage(
1855 value.addr, r.height, d_height);
1856 else
1857 fprintf(stderr, "no height defined, using %d\n",
1858 r.height);
1860 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1861 == 1)
1862 x = parse_int_with_pos(
1863 value.addr, x, d_width, r.width);
1865 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1866 == 1)
1867 y = parse_int_with_pos(
1868 value.addr, y, d_height, r.height);
1870 if (XrmGetResource(
1871 xdb, "MyMenu.border.size", "*", datatype, &value)
1872 == 1) {
1873 char **borders;
1874 borders = parse_csslike(value.addr);
1875 if (borders != NULL)
1876 for (i = 0; i < 4; ++i)
1877 r.borders[i]
1878 = parse_int_with_percentage(
1879 borders[i], 0,
1880 (i % 2) == 0
1881 ? d_height
1882 : d_width);
1883 else
1884 fprintf(stderr,
1885 "error while parsing "
1886 "MyMenu.border.size\n");
1889 /* Prompt */
1890 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1891 datatype, &value)
1892 == 1)
1893 fgs[0] = parse_color(value.addr, "#fff");
1895 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1896 datatype, &value)
1897 == 1)
1898 bgs[0] = parse_color(value.addr, "#000");
1900 /* Completions */
1901 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1902 datatype, &value)
1903 == 1)
1904 fgs[1] = parse_color(value.addr, "#fff");
1906 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1907 datatype, &value)
1908 == 1)
1909 bgs[1] = parse_color(value.addr, "#000");
1911 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1912 datatype, &value)
1913 == 1) {
1914 char **paddings;
1915 paddings = parse_csslike(value.addr);
1916 if (paddings != NULL)
1917 for (i = 0; i < 4; ++i)
1918 r.c_padding[i] = parse_integer(
1919 paddings[i], 0);
1920 else
1921 fprintf(stderr,
1922 "Error while parsing "
1923 "MyMenu.completion.padding");
1926 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1927 datatype, &value)
1928 == 1) {
1929 char **sizes;
1930 sizes = parse_csslike(value.addr);
1931 if (sizes != NULL)
1932 for (i = 0; i < 4; ++i)
1933 r.c_borders[i]
1934 = parse_integer(sizes[i], 0);
1935 else
1936 fprintf(stderr,
1937 "Error while parsing "
1938 "MyMenu.completion.border.size");
1941 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1942 datatype, &value)
1943 == 1) {
1944 char **sizes;
1945 sizes = parse_csslike(value.addr);
1946 if (sizes != NULL)
1947 for (i = 0; i < 4; ++i)
1948 c_borders_bg[i] = parse_color(
1949 sizes[i], "#000");
1950 else
1951 fprintf(stderr,
1952 "Error while parsing "
1953 "MyMenu.completion.border.color");
1956 /* Completion Highlighted */
1957 if (XrmGetResource(xdb,
1958 "MyMenu.completion_highlighted.foreground", "*",
1959 datatype, &value)
1960 == 1)
1961 fgs[2] = parse_color(value.addr, "#000");
1963 if (XrmGetResource(xdb,
1964 "MyMenu.completion_highlighted.background", "*",
1965 datatype, &value)
1966 == 1)
1967 bgs[2] = parse_color(value.addr, "#fff");
1969 if (XrmGetResource(xdb,
1970 "MyMenu.completion_highlighted.padding", "*",
1971 datatype, &value)
1972 == 1) {
1973 char **paddings;
1974 paddings = parse_csslike(value.addr);
1975 if (paddings != NULL)
1976 for (i = 0; i < 4; ++i)
1977 r.ch_padding[i] = parse_integer(
1978 paddings[i], 0);
1979 else
1980 fprintf(stderr,
1981 "Error while parsing "
1982 "MyMenu.completion_highlighted."
1983 "padding");
1986 if (XrmGetResource(xdb,
1987 "MyMenu.completion_highlighted.border.size", "*",
1988 datatype, &value)
1989 == 1) {
1990 char **sizes;
1991 sizes = parse_csslike(value.addr);
1992 if (sizes != NULL)
1993 for (i = 0; i < 4; ++i)
1994 r.ch_borders[i]
1995 = parse_integer(sizes[i], 0);
1996 else
1997 fprintf(stderr,
1998 "Error while parsing "
1999 "MyMenu.completion_highlighted."
2000 "border.size");
2003 if (XrmGetResource(xdb,
2004 "MyMenu.completion_highlighted.border.color", "*",
2005 datatype, &value)
2006 == 1) {
2007 char **colors;
2008 colors = parse_csslike(value.addr);
2009 if (colors != NULL)
2010 for (i = 0; i < 4; ++i)
2011 ch_borders_bg[i] = parse_color(
2012 colors[i], "#000");
2013 else
2014 fprintf(stderr,
2015 "Error while parsing "
2016 "MyMenu.completion_highlighted."
2017 "border.color");
2020 /* Border */
2021 if (XrmGetResource(
2022 xdb, "MyMenu.border.color", "*", datatype, &value)
2023 == 1) {
2024 char **colors;
2025 colors = parse_csslike(value.addr);
2026 if (colors != NULL)
2027 for (i = 0; i < 4; ++i)
2028 borders_bg[i] = parse_color(
2029 colors[i], "#000");
2030 else
2031 fprintf(stderr,
2032 "error while parsing "
2033 "MyMenu.border.color\n");
2037 /* Second round of args parsing */
2038 optind = 0; /* reset the option index */
2039 while ((ch = getopt(argc, argv, ARGS)) != -1) {
2040 switch (ch) {
2041 case 'a':
2042 r.first_selected = 1;
2043 break;
2044 case 'A':
2045 /* free_text -- already catched */
2046 case 'd':
2047 /* separator -- this case was already catched */
2048 case 'e':
2049 /* embedding mymenu this case was already catched. */
2050 case 'm':
2051 /* multiple selection this case was already catched.
2053 break;
2054 case 'p': {
2055 char *newprompt;
2056 newprompt = strdup(optarg);
2057 if (newprompt != NULL) {
2058 free(r.ps1);
2059 r.ps1 = newprompt;
2061 break;
2063 case 'x':
2064 x = parse_int_with_pos(optarg, x, d_width, r.width);
2065 break;
2066 case 'y':
2067 y = parse_int_with_pos(optarg, y, d_height, r.height);
2068 break;
2069 case 'P': {
2070 char **paddings;
2071 if ((paddings = parse_csslike(optarg)) != NULL)
2072 for (i = 0; i < 4; ++i)
2073 r.p_padding[i] = parse_integer(
2074 paddings[i], 0);
2075 break;
2077 case 'G': {
2078 char **colors;
2079 if ((colors = parse_csslike(optarg)) != NULL)
2080 for (i = 0; i < 4; ++i)
2081 p_borders_bg[i] = parse_color(
2082 colors[i], "#000");
2083 break;
2085 case 'g': {
2086 char **sizes;
2087 if ((sizes = parse_csslike(optarg)) != NULL)
2088 for (i = 0; i < 4; ++i)
2089 r.p_borders[i]
2090 = parse_integer(sizes[i], 0);
2091 break;
2093 case 'I': {
2094 char **colors;
2095 if ((colors = parse_csslike(optarg)) != NULL)
2096 for (i = 0; i < 4; ++i)
2097 c_borders_bg[i] = parse_color(
2098 colors[i], "#000");
2099 break;
2101 case 'i': {
2102 char **sizes;
2103 if ((sizes = parse_csslike(optarg)) != NULL)
2104 for (i = 0; i < 4; ++i)
2105 r.c_borders[i]
2106 = parse_integer(sizes[i], 0);
2107 break;
2109 case 'J': {
2110 char **colors;
2111 if ((colors = parse_csslike(optarg)) != NULL)
2112 for (i = 0; i < 4; ++i)
2113 ch_borders_bg[i] = parse_color(
2114 colors[i], "#000");
2115 break;
2117 case 'j': {
2118 char **sizes;
2119 if ((sizes = parse_csslike(optarg)) != NULL)
2120 for (i = 0; i < 4; ++i)
2121 r.ch_borders[i]
2122 = parse_integer(sizes[i], 0);
2123 break;
2125 case 'l':
2126 r.horizontal_layout = !strcmp(optarg, "horizontal");
2127 break;
2128 case 'f': {
2129 char *newfont;
2130 if ((newfont = strdup(optarg)) != NULL) {
2131 free(fontname);
2132 fontname = newfont;
2134 break;
2136 case 'W':
2137 r.width = parse_int_with_percentage(
2138 optarg, r.width, d_width);
2139 break;
2140 case 'H':
2141 r.height = parse_int_with_percentage(
2142 optarg, r.height, d_height);
2143 break;
2144 case 'b': {
2145 char **borders;
2146 if ((borders = parse_csslike(optarg)) != NULL) {
2147 for (i = 0; i < 4; ++i)
2148 r.borders[i] = parse_integer(
2149 borders[i], 0);
2150 } else
2151 fprintf(stderr, "Error parsing b option\n");
2152 break;
2154 case 'B': {
2155 char **colors;
2156 if ((colors = parse_csslike(optarg)) != NULL) {
2157 for (i = 0; i < 4; ++i)
2158 borders_bg[i] = parse_color(
2159 colors[i], "#000");
2160 } else
2161 fprintf(stderr,
2162 "error while parsing B option\n");
2163 break;
2165 case 't':
2166 fgs[0] = parse_color(optarg, NULL);
2167 break;
2168 case 'T':
2169 bgs[0] = parse_color(optarg, NULL);
2170 break;
2171 case 'c':
2172 fgs[1] = parse_color(optarg, NULL);
2173 break;
2174 case 'C':
2175 bgs[1] = parse_color(optarg, NULL);
2176 break;
2177 case 's':
2178 fgs[2] = parse_color(optarg, NULL);
2179 break;
2180 case 'S':
2181 fgs[2] = parse_color(optarg, NULL);
2182 break;
2183 default:
2184 fprintf(stderr, "Unrecognized option %c\n", ch);
2185 status = ERR;
2186 break;
2190 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2191 fprintf(stderr, "height, width, x or y are lesser than 0.");
2192 status = ERR;
2195 /* since only now we know if the first should be selected,
2196 * update the completion here */
2197 update_completions(cs, text, lines, vlines, r.first_selected);
2199 /* update the prompt lenght, only now we surely know the length of it
2201 r.ps1len = strlen(r.ps1);
2203 /* Create the window */
2204 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2205 offset_y, bgs[1]);
2206 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2207 XMapRaised(r.d, r.w);
2209 /* If embed, listen for other events as well */
2210 if (embed) {
2211 Window *children, parent, root;
2212 unsigned int children_no;
2214 XSelectInput(r.d, parent_window, FocusChangeMask);
2215 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2216 &children_no)
2217 && children) {
2218 for (i = 0; i < children_no && children[i] != r.w;
2219 ++i)
2220 XSelectInput(
2221 r.d, children[i], FocusChangeMask);
2222 XFree(children);
2224 grabfocus(r.d, r.w);
2227 take_keyboard(r.d, r.w);
2229 r.x_zero = r.borders[3];
2230 r.y_zero = r.borders[0];
2233 XGCValues values;
2235 for (i = 0; i < 3; ++i) {
2236 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2237 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2240 for (i = 0; i < 4; ++i) {
2241 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2242 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2243 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2244 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2248 /* Load the colors in our GCs */
2249 for (i = 0; i < 3; ++i) {
2250 XSetForeground(r.d, r.fgs[i], fgs[i]);
2251 XSetForeground(r.d, r.bgs[i], bgs[i]);
2254 for (i = 0; i < 4; ++i) {
2255 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2256 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2257 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2258 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2261 if (load_font(&r, fontname) == -1)
2262 status = ERR;
2264 #ifdef USE_XFT
2265 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2267 for (i = 0; i < 3; ++i) {
2268 rgba_t c;
2269 XRenderColor xrcolor;
2271 c = *(rgba_t *)&fgs[i];
2272 xrcolor.red = EXPANDBITS(c.rgba.r);
2273 xrcolor.green = EXPANDBITS(c.rgba.g);
2274 xrcolor.blue = EXPANDBITS(c.rgba.b);
2275 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2276 XftColorAllocValue(
2277 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2279 #endif
2281 /* compute prompt dimensions */
2282 ps1extents(&r);
2284 xim_init(&r, &xdb);
2286 #ifdef __OpenBSD__
2287 /* Now we need only the ability to write */
2288 pledge("stdio", "");
2289 #endif
2291 /* Cache text height */
2292 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2294 /* Draw the window for the first time */
2295 draw(&r, text, cs);
2297 /* Main loop */
2298 while (status == LOOPING || status == OK_LOOP) {
2299 status = loop(&r, &text, &textlen, cs, lines, vlines);
2301 if (status != ERR)
2302 printf("%s\n", text);
2304 if (!r.multiple_select && status == OK_LOOP)
2305 status = OK;
2308 XUngrabKeyboard(r.d, CurrentTime);
2310 #ifdef USE_XFT
2311 for (i = 0; i < 3; ++i)
2312 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2313 #endif
2315 for (i = 0; i < 3; ++i) {
2316 XFreeGC(r.d, r.fgs[i]);
2317 XFreeGC(r.d, r.bgs[i]);
2320 for (i = 0; i < 4; ++i) {
2321 XFreeGC(r.d, r.borders_bg[i]);
2322 XFreeGC(r.d, r.p_borders_bg[i]);
2323 XFreeGC(r.d, r.c_borders_bg[i]);
2324 XFreeGC(r.d, r.ch_borders_bg[i]);
2327 XDestroyIC(r.xic);
2328 XCloseIM(r.xim);
2330 #ifdef USE_XFT
2331 for (i = 0; i < 3; ++i)
2332 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2333 XftFontClose(r.d, r.font);
2334 XftDrawDestroy(r.xftdraw);
2335 #else
2336 XFreeFontSet(r.d, r.font);
2337 #endif
2339 free(r.ps1);
2340 free(fontname);
2341 free(text);
2343 free(buf);
2344 free(lines);
2345 free(vlines);
2346 compls_delete(cs);
2348 XFreeColormap(r.d, cmap);
2350 XDestroyWindow(r.d, r.w);
2351 XCloseDisplay(r.d);
2353 return status != OK;