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>
18 #include <X11/Xft/Xft.h>
20 #include <X11/extensions/Xinerama.h>
22 #ifndef VERSION
23 #define VERSION "unknown"
24 #endif
26 #define resname "MyMenu"
27 #define resclass "mymenu"
29 #define SYM_BUF_SIZE 4
31 #define default_fontname "monospace"
33 #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:"
35 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 #define MAX(a, b) ((a) > (b) ? (a) : (b))
38 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
40 /*
41 * If we don't have or we don't want an "ignore case" completion
42 * style, fall back to `strstr(3)`
43 */
44 #ifndef USE_STRCASESTR
45 #define strcasestr strstr
46 #endif
48 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
49 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
51 /* The states of the event loop */
52 enum state { LOOPING, OK_LOOP, OK, ERR };
54 /*
55 * For the drawing-related function. The text to be rendere could be
56 * the prompt, a completion or a highlighted completion
57 */
58 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
60 /* These are the possible action to be performed after user input. */
61 enum action {
62 NO_OP,
63 EXIT,
64 CONFIRM,
65 CONFIRM_CONTINUE,
66 NEXT_COMPL,
67 PREV_COMPL,
68 DEL_CHAR,
69 DEL_WORD,
70 DEL_LINE,
71 ADD_CHAR,
72 TOGGLE_FIRST_SELECTED,
73 SCROLL_DOWN,
74 SCROLL_UP,
75 };
77 /* A big set of values that needs to be carried around for drawing. A
78 * big struct to rule them all */
79 struct rendering {
80 Display *d; /* Connection to xorg */
81 Window w;
82 XIM xim;
83 int width;
84 int height;
85 int p_padding[4];
86 int c_padding[4];
87 int ch_padding[4];
88 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
89 the borders) */
90 int y_zero; /* like x_zero but for the y axis */
92 int offset; /* scroll offset */
94 short free_text;
95 short first_selected;
96 short multiple_select;
98 /* four border width */
99 int borders[4];
100 int p_borders[4];
101 int c_borders[4];
102 int ch_borders[4];
104 short horizontal_layout;
106 /* prompt */
107 char *ps1;
108 int ps1len;
109 int ps1w; /* ps1 width */
110 int ps1h; /* ps1 height */
112 int text_height; /* cache for the vertical layout */
114 XIC xic;
116 /* colors */
117 GC fgs[4];
118 GC bgs[4];
119 GC borders_bg[4];
120 GC p_borders_bg[4];
121 GC c_borders_bg[4];
122 GC ch_borders_bg[4];
123 XftFont *font;
124 XftDraw *xftdraw;
125 XftColor xft_colors[3];
126 };
128 struct completion {
129 char *completion;
130 char *rcompletion;
131 int offset; /* the x (or y, depending on the layout) coordinate at
132 which the item is rendered */
133 };
135 /* Wrap the linked list of completions */
136 struct completions {
137 struct completion *completions;
138 ssize_t selected;
139 size_t length;
140 };
142 /* idea stolen from lemonbar. ty lemonboy */
143 typedef union {
144 struct {
145 uint8_t b;
146 uint8_t g;
147 uint8_t r;
148 uint8_t a;
149 } rgba;
150 uint32_t v;
151 } rgba_t;
153 extern char *optarg;
154 extern int optind;
156 /* Return a newly allocated (and empty) completion list */
157 struct completions *
158 compls_new(size_t length)
160 struct completions *cs = malloc(sizeof(struct completions));
162 if (cs == NULL)
163 return cs;
165 cs->completions = calloc(length, sizeof(struct completion));
166 if (cs->completions == NULL) {
167 free(cs);
168 return NULL;
171 cs->selected = -1;
172 cs->length = length;
173 return cs;
176 /* Delete the wrapper and the whole list */
177 void
178 compls_delete(struct completions *cs)
180 if (cs == NULL)
181 return;
183 free(cs->completions);
184 free(cs);
187 /*
188 * Create a completion list from a text and the list of possible
189 * completions (null terminated). Expects a non-null `cs'. `lines' and
190 * `vlines' should have the same length OR `vlines' is NULL.
191 */
192 void
193 filter(struct completions *cs, char *text, char **lines, char **vlines)
195 size_t index = 0;
196 size_t matching = 0;
197 char *l;
199 if (vlines == NULL)
200 vlines = lines;
202 while (1) {
203 if (lines[index] == NULL)
204 break;
206 l = vlines[index] != NULL ? vlines[index] : lines[index];
208 if (strcasestr(l, text) != NULL) {
209 struct completion *c = &cs->completions[matching];
210 c->completion = l;
211 c->rcompletion = lines[index];
212 matching++;
215 index++;
217 cs->length = matching;
218 cs->selected = -1;
221 /* Update the given completion */
222 void
223 update_completions(
224 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
226 filter(cs, text, lines, vlines);
227 if (first_selected && cs->length > 0)
228 cs->selected = 0;
231 /*
232 * Select the next or previous selection and update some state. `text'
233 * will be updated with the text of the completion and `textlen' with
234 * the new length. If the memory cannot be allocated `status' will be
235 * set to `ERR'.
236 */
237 void
238 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
239 enum state *status)
241 struct completion *n;
242 int index;
244 if (cs == NULL || cs->length == 0)
245 return;
247 /*
248 * If the first is always selected and the first entry is
249 * different from the text, expand the text and return
250 */
251 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
252 && !p) {
253 free(*text);
254 *text = strdup(cs->completions->completion);
255 if (text == NULL) {
256 *status = ERR;
257 return;
259 *textlen = strlen(*text);
260 return;
263 index = cs->selected;
265 if (index == -1 && p)
266 index = 0;
267 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
269 n = &cs->completions[cs->selected];
271 free(*text);
272 *text = strdup(n->completion);
273 if (text == NULL) {
274 fprintf(stderr, "Memory allocation error!\n");
275 *status = ERR;
276 return;
278 *textlen = strlen(*text);
281 /* Push the character c at the end of the string pointed by p */
282 int
283 pushc(char **p, int maxlen, char c)
285 int len;
287 len = strnlen(*p, maxlen);
288 if (!(len < maxlen - 2)) {
289 char *newptr;
291 maxlen += maxlen >> 1;
292 newptr = realloc(*p, maxlen);
293 if (newptr == NULL) /* bad */
294 return -1;
295 *p = newptr;
298 (*p)[len] = c;
299 (*p)[len + 1] = '\0';
300 return maxlen;
303 /*
304 * Remove the last rune from the *UTF-8* string! This is different
305 * from just setting the last byte to 0 (in some cases ofc). Return a
306 * pointer (e) to the last nonzero char. If e < p then p is empty!
307 */
308 char *
309 popc(char *p)
311 int len = strlen(p);
312 char *e;
314 if (len == 0)
315 return p;
317 e = p + len - 1;
319 do {
320 char c = *e;
322 *e = '\0';
323 e -= 1;
325 /*
326 * If c is a starting byte (11......) or is under
327 * U+007F we're done.
328 */
329 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
330 break;
331 } while (e >= p);
333 return e;
336 /* Remove the last word plus trailing white spaces from the given string */
337 void
338 popw(char *w)
340 int len;
341 short in_word = 1;
343 if ((len = strlen(w)) == 0)
344 return;
346 while (1) {
347 char *e = popc(w);
349 if (e < w)
350 return;
352 if (in_word && isspace(*e))
353 in_word = 0;
355 if (!in_word && !isspace(*e))
356 return;
360 /*
361 * If the string is surrounded by quates (`"') remove them and replace
362 * every `\"' in the string with a single double-quote.
363 */
364 char *
365 normalize_str(const char *str)
367 int len, p;
368 char *s;
370 if ((len = strlen(str)) == 0)
371 return NULL;
373 if ((s = calloc(len, sizeof(char))) == NULL)
374 err(1, "calloc");
375 p = 0;
377 while (*str) {
378 char c = *str;
380 if (*str == '\\') {
381 if (*(str + 1)) {
382 s[p] = *(str + 1);
383 p++;
384 str += 2; /* skip this and the next char */
385 continue;
386 } else
387 break;
389 if (c == '"') {
390 str++; /* skip only this char */
391 continue;
393 s[p] = c;
394 p++;
395 str++;
398 return s;
401 char **
402 readlines(size_t *lineslen)
404 size_t len = 0, cap = 0;
405 size_t linesize = 0;
406 ssize_t linelen;
407 char *line = NULL, **lines = NULL;
409 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
410 if (linelen != 0 && line[linelen-1] == '\n')
411 line[linelen-1] = '\0';
413 if (len == cap) {
414 size_t newcap;
415 void *t;
417 newcap = MAX(cap * 1.5, 32);
418 t = recallocarray(lines, cap, newcap, sizeof(char *));
419 if (t == NULL)
420 err(1, "recallocarray");
421 cap = newcap;
422 lines = t;
425 if ((lines[len++] = strdup(line)) == NULL)
426 err(1, "strdup");
429 if (ferror(stdin))
430 err(1, "getline");
431 free(line);
433 *lineslen = len;
434 return lines;
437 /*
438 * Compute the dimensions of the string str once rendered.
439 * It'll return the width and set ret_width and ret_height if not NULL
440 */
441 int
442 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
444 int height, width;
445 XGlyphInfo gi;
446 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
447 height = r->font->ascent - r->font->descent;
448 width = gi.width - gi.x;
450 if (ret_width != NULL)
451 *ret_width = width;
452 if (ret_height != NULL)
453 *ret_height = height;
454 return width;
457 void
458 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
460 XftColor xftcolor;
461 if (tt == PROMPT)
462 xftcolor = r->xft_colors[0];
463 if (tt == COMPL)
464 xftcolor = r->xft_colors[1];
465 if (tt == COMPL_HIGH)
466 xftcolor = r->xft_colors[2];
468 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
471 /* Duplicate the string and substitute every space with a 'n` */
472 char *
473 strdupn(char *str)
475 int len, i;
476 char *dup;
478 len = strlen(str);
480 if (str == NULL || len == 0)
481 return NULL;
483 if ((dup = strdup(str)) == NULL)
484 return NULL;
486 for (i = 0; i < len; ++i)
487 if (dup[i] == ' ')
488 dup[i] = 'n';
490 return dup;
493 int
494 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
496 GC *border_color, bg;
497 int *padding, *borders;
498 int ret = 0, inner_width, inner_height, x;
500 switch (t) {
501 case PROMPT:
502 border_color = r->p_borders_bg;
503 padding = r->p_padding;
504 borders = r->p_borders;
505 bg = r->bgs[0];
506 break;
507 case COMPL:
508 border_color = r->c_borders_bg;
509 padding = r->c_padding;
510 borders = r->c_borders;
511 bg = r->bgs[1];
512 break;
513 case COMPL_HIGH:
514 border_color = r->ch_borders_bg;
515 padding = r->ch_padding;
516 borders = r->ch_borders;
517 bg = r->bgs[2];
518 break;
521 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
523 inner_width = inner_width(r) - borders[1] - borders[3];
524 inner_height = padding[0] + r->text_height + padding[2];
526 /* Border top */
527 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
529 /* Border right */
530 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
531 borders[1], ret);
533 /* Border bottom */
534 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
535 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
537 /* Border left */
538 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
540 /* bg */
541 x = r->x_zero + borders[3];
542 y += borders[0];
543 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
545 /* content */
546 y += padding[0] + r->text_height;
547 x += padding[3];
548 if (prefix != NULL) {
549 draw_string(prefix, strlen(prefix), x, y, r, t);
550 x += prefix_width;
552 draw_string(text, strlen(text), x, y, r, t);
554 return ret;
557 int
558 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
560 GC *border_color, bg;
561 int *padding, *borders;
562 int ret = 0, inner_width, inner_height, y, text_width;
564 switch (t) {
565 case PROMPT:
566 border_color = r->p_borders_bg;
567 padding = r->p_padding;
568 borders = r->p_borders;
569 bg = r->bgs[0];
570 break;
571 case COMPL:
572 border_color = r->c_borders_bg;
573 padding = r->c_padding;
574 borders = r->c_borders;
575 bg = r->bgs[1];
576 break;
577 case COMPL_HIGH:
578 border_color = r->ch_borders_bg;
579 padding = r->ch_padding;
580 borders = r->ch_borders;
581 bg = r->bgs[2];
582 break;
585 if (padding[0] < 0 || padding[2] < 0)
586 padding[0] = padding[2]
587 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
589 /* If they are still lesser than 0, set 'em to 0 */
590 if (padding[0] < 0 || padding[2] < 0)
591 padding[0] = padding[2] = 0;
593 /* Get the text width */
594 text_extents(text, strlen(text), r, &text_width, NULL);
595 if (prefix != NULL)
596 text_width += prefix_width;
598 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
600 inner_width = padding[3] + text_width + padding[1];
601 inner_height = inner_height(r) - borders[0] - borders[2];
603 /* Border top */
604 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
606 /* Border right */
607 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
608 borders[1], inner_height(r));
610 /* Border bottom */
611 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
612 ret, borders[2]);
614 /* Border left */
615 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
617 /* bg */
618 x += borders[3];
619 y = r->y_zero + borders[0];
620 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
622 /* content */
623 y += padding[0] + r->text_height;
624 x += padding[3];
625 if (prefix != NULL) {
626 draw_string(prefix, strlen(prefix), x, y, r, t);
627 x += prefix_width;
629 draw_string(text, strlen(text), x, y, r, t);
631 return ret;
634 /* ,-----------------------------------------------------------------, */
635 /* | 20 char text | completion | completion | completion | compl | */
636 /* `-----------------------------------------------------------------' */
637 void
638 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
640 size_t i;
641 int x = r->x_zero;
643 /* Draw the prompt */
644 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
646 for (i = r->offset; i < cs->length; ++i) {
647 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
649 cs->completions[i].offset = x;
651 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
653 if (x > inner_width(r))
654 break;
657 for (i += 1; i < cs->length; ++i)
658 cs->completions[i].offset = -1;
661 /* ,-----------------------------------------------------------------, */
662 /* | prompt | */
663 /* |-----------------------------------------------------------------| */
664 /* | completion | */
665 /* |-----------------------------------------------------------------| */
666 /* | completion | */
667 /* `-----------------------------------------------------------------' */
668 void
669 draw_vertically(struct rendering *r, char *text, struct completions *cs)
671 size_t i;
672 int y = r->y_zero;
674 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
676 for (i = r->offset; i < cs->length; ++i) {
677 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
679 cs->completions[i].offset = y;
681 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
683 if (y > inner_height(r))
684 break;
687 for (i += 1; i < cs->length; ++i)
688 cs->completions[i].offset = -1;
691 void
692 draw(struct rendering *r, char *text, struct completions *cs)
694 /* Draw the background */
695 XFillRectangle(
696 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
698 /* Draw the contents */
699 if (r->horizontal_layout)
700 draw_horizontally(r, text, cs);
701 else
702 draw_vertically(r, text, cs);
704 /* Draw the borders */
705 if (r->borders[0] != 0)
706 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
708 if (r->borders[1] != 0)
709 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
710 r->borders[1], r->height);
712 if (r->borders[2] != 0)
713 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
714 r->borders[2]);
716 if (r->borders[3] != 0)
717 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
719 /* render! */
720 XFlush(r->d);
723 /* Set some WM stuff */
724 void
725 set_win_atoms_hints(Display *d, Window w, int width, int height)
727 Atom type;
728 XClassHint *class_hint;
729 XSizeHints *size_hint;
731 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
732 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
733 32, PropModeReplace, (unsigned char *)&type, 1);
735 /* some window managers honor this properties */
736 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
737 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
738 PropModeReplace, (unsigned char *)&type, 1);
740 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
741 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
742 PropModeAppend, (unsigned char *)&type, 1);
744 /* Setting window hints */
745 class_hint = XAllocClassHint();
746 if (class_hint == NULL) {
747 fprintf(stderr, "Could not allocate memory for class hint\n");
748 exit(EX_UNAVAILABLE);
751 class_hint->res_name = resname;
752 class_hint->res_class = resclass;
753 XSetClassHint(d, w, class_hint);
754 XFree(class_hint);
756 size_hint = XAllocSizeHints();
757 if (size_hint == NULL) {
758 fprintf(stderr, "Could not allocate memory for size hint\n");
759 exit(EX_UNAVAILABLE);
762 size_hint->flags = PMinSize | PBaseSize;
763 size_hint->min_width = width;
764 size_hint->base_width = width;
765 size_hint->min_height = height;
766 size_hint->base_height = height;
768 XFlush(d);
771 /* Get the width and height of the window `w' */
772 void
773 get_wh(Display *d, Window *w, int *width, int *height)
775 XWindowAttributes win_attr;
777 XGetWindowAttributes(d, *w, &win_attr);
778 *height = win_attr.height;
779 *width = win_attr.width;
782 int
783 grabfocus(Display *d, Window w)
785 int i;
786 for (i = 0; i < 100; ++i) {
787 Window focuswin;
788 int revert_to_win;
790 XGetInputFocus(d, &focuswin, &revert_to_win);
792 if (focuswin == w)
793 return 1;
795 XSetInputFocus(d, w, RevertToParent, CurrentTime);
796 usleep(1000);
798 return 0;
801 /*
802 * I know this may seem a little hackish BUT is the only way I managed
803 * to actually grab that goddam keyboard. Only one call to
804 * XGrabKeyboard does not always end up with the keyboard grabbed!
805 */
806 int
807 take_keyboard(Display *d, Window w)
809 int i;
810 for (i = 0; i < 100; i++) {
811 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
812 == GrabSuccess)
813 return 1;
814 usleep(1000);
816 fprintf(stderr, "Cannot grab keyboard\n");
817 return 0;
820 unsigned long
821 parse_color(const char *str, const char *def)
823 size_t len;
824 rgba_t tmp;
825 char *ep;
827 if (str == NULL)
828 goto invc;
830 len = strlen(str);
832 /* +1 for the # ath the start */
833 if (*str != '#' || len > 9 || len < 4)
834 goto invc;
835 ++str; /* skip the # */
837 errno = 0;
838 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
840 if (errno)
841 goto invc;
843 switch (len - 1) {
844 case 3:
845 /* expand #rgb -> #rrggbb */
846 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
847 | (tmp.v & 0x00f) * 0x0011;
848 case 6:
849 /* assume 0xff opacity */
850 tmp.rgba.a = 0xff;
851 break;
852 } /* colors in #aarrggbb need no adjustments */
854 /* premultiply the alpha */
855 if (tmp.rgba.a) {
856 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
857 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
858 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
859 return tmp.v;
862 return 0U;
864 invc:
865 fprintf(stderr, "Invalid color: \"%s\".\n", str);
866 if (def != NULL)
867 return parse_color(def, NULL);
868 else
869 return 0U;
872 /*
873 * Given a string try to parse it as a number or return `default_value'.
874 */
875 int
876 parse_integer(const char *str, int default_value)
878 long lval;
879 char *ep;
881 errno = 0;
882 lval = strtol(str, &ep, 10);
884 if (str[0] == '\0' || *ep != '\0') { /* NaN */
885 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str,
886 default_value);
887 return default_value;
890 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
891 || (lval > INT_MAX || lval < INT_MIN)) {
892 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
893 return default_value;
896 return lval;
899 /* Like parse_integer but recognize the percentages (i.e. strings ending with
900 * `%') */
901 int
902 parse_int_with_percentage(const char *str, int default_value, int max)
904 int len = strlen(str);
906 if (len > 0 && str[len - 1] == '%') {
907 int val;
908 char *cpy;
910 if ((cpy = strdup(str)) == NULL)
911 err(1, "strdup");
913 cpy[len - 1] = '\0';
914 val = parse_integer(cpy, default_value);
915 free(cpy);
916 return val * max / 100;
919 return parse_integer(str, default_value);
922 void
923 get_mouse_coords(Display *d, int *x, int *y)
925 Window w, root;
926 int i;
927 unsigned int u;
929 *x = *y = 0;
930 root = DefaultRootWindow(d);
932 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
933 for (i = 0; i < ScreenCount(d); ++i) {
934 if (root == RootWindow(d, i))
935 break;
940 /*
941 * Like parse_int_with_percentage but understands some special values:
942 * - middle that is (max-self)/2
943 * - center = middle
944 * - start that is 0
945 * - end that is (max-self)
946 * - mx x coordinate of the mouse
947 * - my y coordinate of the mouse
948 */
949 int
950 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
952 if (!strcmp(str, "start"))
953 return 0;
954 if (!strcmp(str, "middle") || !strcmp(str, "center"))
955 return (max - self) / 2;
956 if (!strcmp(str, "end"))
957 return max - self;
958 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
959 int x, y;
961 get_mouse_coords(d, &x, &y);
962 if (!strcmp(str, "mx"))
963 return x - 1;
964 else
965 return y - 1;
967 return parse_int_with_percentage(str, default_value, max);
970 /* Parse a string like a CSS value. */
971 /* TODO: harden a bit this function */
972 char **
973 parse_csslike(const char *str)
975 int i, j;
976 char *s, *token, **ret;
977 short any_null;
979 s = strdup(str);
980 if (s == NULL)
981 return NULL;
983 ret = malloc(4 * sizeof(char *));
984 if (ret == NULL) {
985 free(s);
986 return NULL;
989 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
990 ret[i] = strdup(token);
992 if (i == 1)
993 for (j = 1; j < 4; j++)
994 ret[j] = strdup(ret[0]);
996 if (i == 2) {
997 ret[2] = strdup(ret[0]);
998 ret[3] = strdup(ret[1]);
1001 if (i == 3)
1002 ret[3] = strdup(ret[1]);
1004 /* before we didn't check for the return type of strdup, here we will
1007 any_null = 0;
1008 for (i = 0; i < 4; ++i)
1009 any_null = ret[i] == NULL || any_null;
1011 if (any_null)
1012 for (i = 0; i < 4; ++i)
1013 if (ret[i] != NULL)
1014 free(ret[i]);
1016 if (i == 0 || any_null) {
1017 free(s);
1018 free(ret);
1019 return NULL;
1022 return ret;
1026 * Given an event, try to understand what the users wants. If the
1027 * return value is ADD_CHAR then `input' is a pointer to a string that
1028 * will need to be free'ed later.
1030 enum action
1031 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1033 char str[SYM_BUF_SIZE] = { 0 };
1034 Status s;
1036 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1037 return DEL_CHAR;
1039 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1040 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1042 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1043 return CONFIRM;
1045 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1046 return EXIT;
1048 /* Try to read what key was pressed */
1049 s = 0;
1050 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1051 if (s == XBufferOverflow) {
1052 fprintf(stderr,
1053 "Buffer overflow when trying to create keyboard "
1054 "symbol map.\n");
1055 return EXIT;
1058 if (ev->state & ControlMask) {
1059 if (!strcmp(str, "")) /* C-u */
1060 return DEL_LINE;
1061 if (!strcmp(str, "")) /* C-w */
1062 return DEL_WORD;
1063 if (!strcmp(str, "")) /* C-h */
1064 return DEL_CHAR;
1065 if (!strcmp(str, "\r")) /* C-m */
1066 return CONFIRM_CONTINUE;
1067 if (!strcmp(str, "")) /* C-p */
1068 return PREV_COMPL;
1069 if (!strcmp(str, "")) /* C-n */
1070 return NEXT_COMPL;
1071 if (!strcmp(str, "")) /* C-c */
1072 return EXIT;
1073 if (!strcmp(str, "\t")) /* C-i */
1074 return TOGGLE_FIRST_SELECTED;
1077 *input = strdup(str);
1078 if (*input == NULL) {
1079 fprintf(stderr, "Error while allocating memory for key.\n");
1080 return EXIT;
1083 return ADD_CHAR;
1086 void
1087 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1089 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1090 /* if there is something selected expand it and return */
1091 int index = cs->selected == -1 ? 0 : cs->selected;
1092 struct completion *c = cs->completions;
1093 char *t;
1095 while (1) {
1096 if (index == 0)
1097 break;
1098 c++;
1099 index--;
1102 t = c->rcompletion;
1103 free(*text);
1104 *text = strdup(t);
1106 if (*text == NULL) {
1107 fprintf(stderr, "Memory allocation error\n");
1108 *status = ERR;
1111 *textlen = strlen(*text);
1112 return;
1115 if (!r->free_text) /* cannot accept arbitrary text */
1116 *status = LOOPING;
1119 /* cs: completion list
1120 * offset: the offset of the click
1121 * first: the first (rendered) item
1122 * def: the default action
1124 enum action
1125 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1127 ssize_t selected = first;
1128 int set = 0;
1130 if (cs->length == 0)
1131 return NO_OP;
1133 if (offset < cs->completions[selected].offset)
1134 return EXIT;
1136 /* skip the first entry */
1137 for (selected += 1; selected < cs->length; ++selected) {
1138 if (cs->completions[selected].offset == -1)
1139 break;
1141 if (offset < cs->completions[selected].offset) {
1142 cs->selected = selected - 1;
1143 set = 1;
1144 break;
1148 if (!set)
1149 cs->selected = selected - 1;
1151 return def;
1154 enum action
1155 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1157 size_t off;
1159 if (r->horizontal_layout)
1160 off = e->x;
1161 else
1162 off = e->y;
1164 switch (e->button) {
1165 case Button1:
1166 return select_clicked(cs, off, r->offset, CONFIRM);
1168 case Button3:
1169 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1171 case Button4:
1172 return SCROLL_UP;
1174 case Button5:
1175 return SCROLL_DOWN;
1178 return NO_OP;
1181 /* event loop */
1182 enum state
1183 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1184 char **vlines)
1186 enum state status = LOOPING;
1188 while (status == LOOPING) {
1189 XEvent e;
1190 XNextEvent(r->d, &e);
1192 if (XFilterEvent(&e, r->w))
1193 continue;
1195 switch (e.type) {
1196 case KeymapNotify:
1197 XRefreshKeyboardMapping(&e.xmapping);
1198 break;
1200 case FocusIn:
1201 /* Re-grab focus */
1202 if (e.xfocus.window != r->w)
1203 grabfocus(r->d, r->w);
1204 break;
1206 case VisibilityNotify:
1207 if (e.xvisibility.state != VisibilityUnobscured)
1208 XRaiseWindow(r->d, r->w);
1209 break;
1211 case MapNotify:
1212 get_wh(r->d, &r->w, &r->width, &r->height);
1213 draw(r, *text, cs);
1214 break;
1216 case KeyPress:
1217 case ButtonPress: {
1218 enum action a;
1219 char *input = NULL;
1221 if (e.type == KeyPress)
1222 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1223 else
1224 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1226 switch (a) {
1227 case NO_OP:
1228 break;
1230 case EXIT:
1231 status = ERR;
1232 break;
1234 case CONFIRM: {
1235 status = OK;
1236 confirm(&status, r, cs, text, textlen);
1237 break;
1240 case CONFIRM_CONTINUE: {
1241 status = OK_LOOP;
1242 confirm(&status, r, cs, text, textlen);
1243 break;
1246 case PREV_COMPL: {
1247 complete(cs, r->first_selected, 1, text, textlen, &status);
1248 r->offset = cs->selected;
1249 break;
1252 case NEXT_COMPL: {
1253 complete(cs, r->first_selected, 0, text, textlen, &status);
1254 r->offset = cs->selected;
1255 break;
1258 case DEL_CHAR:
1259 popc(*text);
1260 update_completions(cs, *text, lines, vlines, r->first_selected);
1261 r->offset = 0;
1262 break;
1264 case DEL_WORD: {
1265 popw(*text);
1266 update_completions(cs, *text, lines, vlines, r->first_selected);
1267 break;
1270 case DEL_LINE: {
1271 int i;
1272 for (i = 0; i < *textlen; ++i)
1273 *(*text + i) = 0;
1274 update_completions(cs, *text, lines, vlines, r->first_selected);
1275 r->offset = 0;
1276 break;
1279 case ADD_CHAR: {
1280 int str_len, i;
1282 str_len = strlen(input);
1285 * sometimes a strange key is pressed
1286 * i.e. ctrl alone), so input will be
1287 * empty. Don't need to update
1288 * completion in that case
1290 if (str_len == 0)
1291 break;
1293 for (i = 0; i < str_len; ++i) {
1294 *textlen = pushc(text, *textlen, input[i]);
1295 if (*textlen == -1) {
1296 fprintf(stderr,
1297 "Memory allocation "
1298 "error\n");
1299 status = ERR;
1300 break;
1304 if (status != ERR) {
1305 update_completions(
1306 cs, *text, lines, vlines, r->first_selected);
1307 free(input);
1310 r->offset = 0;
1311 break;
1314 case TOGGLE_FIRST_SELECTED:
1315 r->first_selected = !r->first_selected;
1316 if (r->first_selected && cs->selected < 0)
1317 cs->selected = 0;
1318 if (!r->first_selected && cs->selected == 0)
1319 cs->selected = -1;
1320 break;
1322 case SCROLL_DOWN:
1323 r->offset = MIN(r->offset + 1, cs->length - 1);
1324 break;
1326 case SCROLL_UP:
1327 r->offset = MAX((ssize_t)r->offset - 1, 0);
1328 break;
1333 draw(r, *text, cs);
1336 return status;
1339 int
1340 load_font(struct rendering *r, const char *fontname)
1342 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1343 return 0;
1346 void
1347 xim_init(struct rendering *r, XrmDatabase *xdb)
1349 XIMStyle best_match_style;
1350 XIMStyles *xis;
1351 int i;
1353 /* Open the X input method */
1354 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1355 err(1, "XOpenIM");
1357 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1358 fprintf(stderr, "Input Styles could not be retrieved\n");
1359 exit(EX_UNAVAILABLE);
1362 best_match_style = 0;
1363 for (i = 0; i < xis->count_styles; ++i) {
1364 XIMStyle ts = xis->supported_styles[i];
1365 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1366 best_match_style = ts;
1367 break;
1370 XFree(xis);
1372 if (!best_match_style)
1373 fprintf(stderr, "No matching input style could be determined\n");
1375 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1376 XNFocusWindow, r->w, NULL);
1377 if (r->xic == NULL)
1378 err(1, "XCreateIC");
1381 void
1382 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1383 int y, int ox, int oy, unsigned long background_pixel)
1385 XSetWindowAttributes attr;
1387 /* Create the window */
1388 attr.colormap = cmap;
1389 attr.override_redirect = 1;
1390 attr.border_pixel = 0;
1391 attr.background_pixel = background_pixel;
1392 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1393 | ButtonPress | VisibilityChangeMask;
1395 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1396 vinfo.depth, InputOutput, vinfo.visual,
1397 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1400 void
1401 ps1extents(struct rendering *r)
1403 char *dup;
1404 dup = strdupn(r->ps1);
1405 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1406 free(dup);
1409 void
1410 usage(char *prgname)
1412 fprintf(stderr,
1413 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1414 " [-d separator] [-e window] [-f font] [-G color] [-g "
1415 "size]\n"
1416 " [-H height] [-I color] [-i size] [-J color] [-j "
1417 "size] [-l layout]\n"
1418 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1419 "color]\n"
1420 " [-t color] [-W width] [-x coord] [-y coord]\n",
1421 prgname);
1424 int
1425 main(int argc, char **argv)
1427 struct completions *cs;
1428 struct rendering r;
1429 XVisualInfo vinfo;
1430 Colormap cmap;
1431 size_t nlines, i;
1432 Window parent_window;
1433 XrmDatabase xdb;
1434 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1435 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1436 ch_borders_bg[4]; /* N E S W */
1437 enum state status;
1438 int ch;
1439 int offset_x, offset_y, x, y;
1440 int textlen, d_width, d_height;
1441 short embed;
1442 char *sep, *parent_window_id;
1443 char **lines, **vlines;
1444 char *fontname, *text, *xrm;
1446 sep = NULL;
1447 parent_window_id = NULL;
1449 r.first_selected = 0;
1450 r.free_text = 1;
1451 r.multiple_select = 0;
1452 r.offset = 0;
1454 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1455 switch (ch) {
1456 case 'h': /* help */
1457 usage(*argv);
1458 return 0;
1459 case 'v': /* version */
1460 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1461 return 0;
1462 case 'e': /* embed */
1463 if ((parent_window_id = strdup(optarg)) == NULL)
1464 err(1, "strdup");
1465 break;
1466 case 'd':
1467 if ((sep = strdup(optarg)) == NULL)
1468 err(1, "strdup");
1469 break;
1470 case 'A':
1471 r.free_text = 0;
1472 break;
1473 case 'm':
1474 r.multiple_select = 1;
1475 break;
1476 default:
1477 break;
1481 lines = readlines(&nlines);
1483 vlines = NULL;
1484 if (sep != NULL) {
1485 int l;
1486 l = strlen(sep);
1487 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1488 err(1, "calloc");
1490 for (i = 0; i < nlines; i++) {
1491 char *t;
1492 t = strstr(lines[i], sep);
1493 if (t == NULL)
1494 vlines[i] = lines[i];
1495 else
1496 vlines[i] = t + l;
1500 setlocale(LC_ALL, getenv("LANG"));
1502 status = LOOPING;
1504 /* where the monitor start (used only with xinerama) */
1505 offset_x = offset_y = 0;
1507 /* default width and height */
1508 r.width = 400;
1509 r.height = 20;
1511 /* default position on the screen */
1512 x = y = 0;
1514 for (i = 0; i < 4; ++i) {
1515 /* default paddings */
1516 r.p_padding[i] = 10;
1517 r.c_padding[i] = 10;
1518 r.ch_padding[i] = 10;
1520 /* default borders */
1521 r.borders[i] = 0;
1522 r.p_borders[i] = 0;
1523 r.c_borders[i] = 0;
1524 r.ch_borders[i] = 0;
1527 /* the prompt. We duplicate the string so later is easy to
1528 * free (in the case it's been overwritten by the user) */
1529 if ((r.ps1 = strdup("$ ")) == NULL)
1530 err(1, "strdup");
1532 /* same for the font name */
1533 if ((fontname = strdup(default_fontname)) == NULL)
1534 err(1, "strdup");
1536 textlen = 10;
1537 if ((text = malloc(textlen * sizeof(char))) == NULL)
1538 err(1, "malloc");
1540 /* struct completions *cs = filter(text, lines); */
1541 if ((cs = compls_new(nlines)) == NULL)
1542 err(1, "compls_new");
1544 /* start talking to xorg */
1545 r.d = XOpenDisplay(NULL);
1546 if (r.d == NULL) {
1547 fprintf(stderr, "Could not open display!\n");
1548 return EX_UNAVAILABLE;
1551 embed = 1;
1552 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1553 parent_window = DefaultRootWindow(r.d);
1554 embed = 0;
1557 /* get display size */
1558 get_wh(r.d, &parent_window, &d_width, &d_height);
1560 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1561 XineramaScreenInfo *info;
1562 Window rr;
1563 Window root;
1564 int number_of_screens, monitors, i;
1565 int root_x, root_y, win_x, win_y;
1566 unsigned int mask;
1567 short res;
1569 number_of_screens = XScreenCount(r.d);
1570 for (i = 0; i < number_of_screens; ++i) {
1571 root = XRootWindow(r.d, i);
1572 res = XQueryPointer(
1573 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1574 if (res)
1575 break;
1578 if (!res) {
1579 fprintf(stderr, "No mouse found.\n");
1580 root_x = 0;
1581 root_y = 0;
1584 /* Now find in which monitor the mice is */
1585 info = XineramaQueryScreens(r.d, &monitors);
1586 if (info) {
1587 for (i = 0; i < monitors; ++i) {
1588 if (info[i].x_org <= root_x
1589 && root_x <= (info[i].x_org + info[i].width)
1590 && info[i].y_org <= root_y
1591 && root_y <= (info[i].y_org + info[i].height)) {
1592 offset_x = info[i].x_org;
1593 offset_y = info[i].y_org;
1594 d_width = info[i].width;
1595 d_height = info[i].height;
1596 break;
1600 XFree(info);
1603 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1604 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1606 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1607 fgs[2] = parse_color("#000", NULL);
1609 bgs[0] = bgs[1] = parse_color("#000", NULL);
1610 bgs[2] = parse_color("#fff", NULL);
1612 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1614 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1615 = parse_color("#000", NULL);
1616 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1617 = parse_color("#000", NULL);
1618 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1619 = parse_color("#000", NULL);
1621 r.horizontal_layout = 1;
1623 /* Read the resources */
1624 XrmInitialize();
1625 xrm = XResourceManagerString(r.d);
1626 xdb = NULL;
1627 if (xrm != NULL) {
1628 XrmValue value;
1629 char *datatype[20];
1631 xdb = XrmGetStringDatabase(xrm);
1633 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1634 free(fontname);
1635 if ((fontname = strdup(value.addr)) == NULL)
1636 err(1, "strdup");
1637 } else {
1638 fprintf(stderr, "no font defined, using %s\n", fontname);
1641 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1642 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1643 else
1644 fprintf(stderr, "no layout defined, using horizontal\n");
1646 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1647 free(r.ps1);
1648 r.ps1 = normalize_str(value.addr);
1649 } else {
1650 fprintf(stderr,
1651 "no prompt defined, using \"%s\" as "
1652 "default\n",
1653 r.ps1);
1656 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1657 char **sizes;
1658 sizes = parse_csslike(value.addr);
1659 if (sizes != NULL)
1660 for (i = 0; i < 4; ++i)
1661 r.p_borders[i] = parse_integer(sizes[i], 0);
1662 else
1663 fprintf(stderr,
1664 "error while parsing "
1665 "MyMenu.prompt.border.size");
1668 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1669 char **colors;
1670 colors = parse_csslike(value.addr);
1671 if (colors != NULL)
1672 for (i = 0; i < 4; ++i)
1673 p_borders_bg[i] = parse_color(colors[i], "#000");
1674 else
1675 fprintf(stderr,
1676 "error while parsing "
1677 "MyMenu.prompt.border.color");
1680 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1681 char **colors;
1682 colors = parse_csslike(value.addr);
1683 if (colors != NULL)
1684 for (i = 0; i < 4; ++i)
1685 r.p_padding[i] = parse_integer(colors[i], 0);
1686 else
1687 fprintf(stderr,
1688 "error while parsing "
1689 "MyMenu.prompt.padding");
1692 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1693 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1694 else
1695 fprintf(stderr, "no width defined, using %d\n", r.width);
1697 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1698 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1699 else
1700 fprintf(stderr, "no height defined, using %d\n", r.height);
1702 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1703 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1705 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1706 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1708 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1709 char **borders;
1710 borders = parse_csslike(value.addr);
1711 if (borders != NULL)
1712 for (i = 0; i < 4; ++i)
1713 r.borders[i] = parse_int_with_percentage(
1714 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1715 else
1716 fprintf(stderr,
1717 "error while parsing "
1718 "MyMenu.border.size\n");
1721 /* Prompt */
1722 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1723 fgs[0] = parse_color(value.addr, "#fff");
1725 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1726 bgs[0] = parse_color(value.addr, "#000");
1728 /* Completions */
1729 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1730 fgs[1] = parse_color(value.addr, "#fff");
1732 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1733 bgs[1] = parse_color(value.addr, "#000");
1735 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1736 char **paddings;
1737 paddings = parse_csslike(value.addr);
1738 if (paddings != NULL)
1739 for (i = 0; i < 4; ++i)
1740 r.c_padding[i] = parse_integer(paddings[i], 0);
1741 else
1742 fprintf(stderr,
1743 "Error while parsing "
1744 "MyMenu.completion.padding");
1747 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1748 char **sizes;
1749 sizes = parse_csslike(value.addr);
1750 if (sizes != NULL)
1751 for (i = 0; i < 4; ++i)
1752 r.c_borders[i] = parse_integer(sizes[i], 0);
1753 else
1754 fprintf(stderr,
1755 "Error while parsing "
1756 "MyMenu.completion.border.size");
1759 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1760 char **sizes;
1761 sizes = parse_csslike(value.addr);
1762 if (sizes != NULL)
1763 for (i = 0; i < 4; ++i)
1764 c_borders_bg[i] = parse_color(sizes[i], "#000");
1765 else
1766 fprintf(stderr,
1767 "Error while parsing "
1768 "MyMenu.completion.border.color");
1771 /* Completion Highlighted */
1772 if (XrmGetResource(
1773 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1774 fgs[2] = parse_color(value.addr, "#000");
1776 if (XrmGetResource(
1777 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1778 bgs[2] = parse_color(value.addr, "#fff");
1780 if (XrmGetResource(
1781 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1782 char **paddings;
1783 paddings = parse_csslike(value.addr);
1784 if (paddings != NULL)
1785 for (i = 0; i < 4; ++i)
1786 r.ch_padding[i] = parse_integer(paddings[i], 0);
1787 else
1788 fprintf(stderr,
1789 "Error while parsing "
1790 "MyMenu.completion_highlighted."
1791 "padding");
1794 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1795 &value)) {
1796 char **sizes;
1797 sizes = parse_csslike(value.addr);
1798 if (sizes != NULL)
1799 for (i = 0; i < 4; ++i)
1800 r.ch_borders[i] = parse_integer(sizes[i], 0);
1801 else
1802 fprintf(stderr,
1803 "Error while parsing "
1804 "MyMenu.completion_highlighted."
1805 "border.size");
1808 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1809 &value)) {
1810 char **colors;
1811 colors = parse_csslike(value.addr);
1812 if (colors != NULL)
1813 for (i = 0; i < 4; ++i)
1814 ch_borders_bg[i] = parse_color(colors[i], "#000");
1815 else
1816 fprintf(stderr,
1817 "Error while parsing "
1818 "MyMenu.completion_highlighted."
1819 "border.color");
1822 /* Border */
1823 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1824 char **colors;
1825 colors = parse_csslike(value.addr);
1826 if (colors != NULL)
1827 for (i = 0; i < 4; ++i)
1828 borders_bg[i] = parse_color(colors[i], "#000");
1829 else
1830 fprintf(stderr,
1831 "error while parsing "
1832 "MyMenu.border.color\n");
1836 /* Second round of args parsing */
1837 optind = 0; /* reset the option index */
1838 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1839 switch (ch) {
1840 case 'a':
1841 r.first_selected = 1;
1842 break;
1843 case 'A':
1844 /* free_text -- already catched */
1845 case 'd':
1846 /* separator -- this case was already catched */
1847 case 'e':
1848 /* embedding mymenu this case was already catched. */
1849 case 'm':
1850 /* multiple selection this case was already catched.
1852 break;
1853 case 'p': {
1854 char *newprompt;
1855 newprompt = strdup(optarg);
1856 if (newprompt != NULL) {
1857 free(r.ps1);
1858 r.ps1 = newprompt;
1860 break;
1862 case 'x':
1863 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1864 break;
1865 case 'y':
1866 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1867 break;
1868 case 'P': {
1869 char **paddings;
1870 if ((paddings = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 r.p_padding[i] = parse_integer(paddings[i], 0);
1873 break;
1875 case 'G': {
1876 char **colors;
1877 if ((colors = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 p_borders_bg[i] = parse_color(colors[i], "#000");
1880 break;
1882 case 'g': {
1883 char **sizes;
1884 if ((sizes = parse_csslike(optarg)) != NULL)
1885 for (i = 0; i < 4; ++i)
1886 r.p_borders[i] = parse_integer(sizes[i], 0);
1887 break;
1889 case 'I': {
1890 char **colors;
1891 if ((colors = parse_csslike(optarg)) != NULL)
1892 for (i = 0; i < 4; ++i)
1893 c_borders_bg[i] = parse_color(colors[i], "#000");
1894 break;
1896 case 'i': {
1897 char **sizes;
1898 if ((sizes = parse_csslike(optarg)) != NULL)
1899 for (i = 0; i < 4; ++i)
1900 r.c_borders[i] = parse_integer(sizes[i], 0);
1901 break;
1903 case 'J': {
1904 char **colors;
1905 if ((colors = parse_csslike(optarg)) != NULL)
1906 for (i = 0; i < 4; ++i)
1907 ch_borders_bg[i] = parse_color(colors[i], "#000");
1908 break;
1910 case 'j': {
1911 char **sizes;
1912 if ((sizes = parse_csslike(optarg)) != NULL)
1913 for (i = 0; i < 4; ++i)
1914 r.ch_borders[i] = parse_integer(sizes[i], 0);
1915 break;
1917 case 'l':
1918 r.horizontal_layout = !strcmp(optarg, "horizontal");
1919 break;
1920 case 'f': {
1921 char *newfont;
1922 if ((newfont = strdup(optarg)) != NULL) {
1923 free(fontname);
1924 fontname = newfont;
1926 break;
1928 case 'W':
1929 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1930 break;
1931 case 'H':
1932 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1933 break;
1934 case 'b': {
1935 char **borders;
1936 if ((borders = parse_csslike(optarg)) != NULL) {
1937 for (i = 0; i < 4; ++i)
1938 r.borders[i] = parse_integer(borders[i], 0);
1939 } else
1940 fprintf(stderr, "Error parsing b option\n");
1941 break;
1943 case 'B': {
1944 char **colors;
1945 if ((colors = parse_csslike(optarg)) != NULL) {
1946 for (i = 0; i < 4; ++i)
1947 borders_bg[i] = parse_color(colors[i], "#000");
1948 } else
1949 fprintf(stderr, "error while parsing B option\n");
1950 break;
1952 case 't':
1953 fgs[0] = parse_color(optarg, NULL);
1954 break;
1955 case 'T':
1956 bgs[0] = parse_color(optarg, NULL);
1957 break;
1958 case 'c':
1959 fgs[1] = parse_color(optarg, NULL);
1960 break;
1961 case 'C':
1962 bgs[1] = parse_color(optarg, NULL);
1963 break;
1964 case 's':
1965 fgs[2] = parse_color(optarg, NULL);
1966 break;
1967 case 'S':
1968 bgs[2] = parse_color(optarg, NULL);
1969 break;
1970 default:
1971 fprintf(stderr, "Unrecognized option %c\n", ch);
1972 status = ERR;
1973 break;
1977 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1978 fprintf(stderr, "height, width, x or y are lesser than 0.");
1979 status = ERR;
1982 /* since only now we know if the first should be selected,
1983 * update the completion here */
1984 update_completions(cs, text, lines, vlines, r.first_selected);
1986 /* update the prompt lenght, only now we surely know the length of it
1988 r.ps1len = strlen(r.ps1);
1990 /* Create the window */
1991 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1992 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1993 XMapRaised(r.d, r.w);
1995 /* If embed, listen for other events as well */
1996 if (embed) {
1997 Window *children, parent, root;
1998 unsigned int children_no;
2000 XSelectInput(r.d, parent_window, FocusChangeMask);
2001 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2002 && children) {
2003 for (i = 0; i < children_no && children[i] != r.w; ++i)
2004 XSelectInput(r.d, children[i], FocusChangeMask);
2005 XFree(children);
2007 grabfocus(r.d, r.w);
2010 take_keyboard(r.d, r.w);
2012 r.x_zero = r.borders[3];
2013 r.y_zero = r.borders[0];
2016 XGCValues values;
2018 for (i = 0; i < 3; ++i) {
2019 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2020 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2023 for (i = 0; i < 4; ++i) {
2024 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2025 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2026 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2027 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2031 /* Load the colors in our GCs */
2032 for (i = 0; i < 3; ++i) {
2033 XSetForeground(r.d, r.fgs[i], fgs[i]);
2034 XSetForeground(r.d, r.bgs[i], bgs[i]);
2037 for (i = 0; i < 4; ++i) {
2038 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2039 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2040 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2041 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2044 if (load_font(&r, fontname) == -1)
2045 status = ERR;
2047 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2049 for (i = 0; i < 3; ++i) {
2050 rgba_t c;
2051 XRenderColor xrcolor;
2053 c = *(rgba_t *)&fgs[i];
2054 xrcolor.red = EXPANDBITS(c.rgba.r);
2055 xrcolor.green = EXPANDBITS(c.rgba.g);
2056 xrcolor.blue = EXPANDBITS(c.rgba.b);
2057 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2058 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2061 /* compute prompt dimensions */
2062 ps1extents(&r);
2064 xim_init(&r, &xdb);
2066 #ifdef __OpenBSD__
2067 if (pledge("stdio", "") == -1)
2068 err(1, "pledge");
2069 #endif
2071 /* Cache text height */
2072 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2074 /* Draw the window for the first time */
2075 draw(&r, text, cs);
2077 /* Main loop */
2078 while (status == LOOPING || status == OK_LOOP) {
2079 status = loop(&r, &text, &textlen, cs, lines, vlines);
2081 if (status != ERR)
2082 printf("%s\n", text);
2084 if (!r.multiple_select && status == OK_LOOP)
2085 status = OK;
2088 XUngrabKeyboard(r.d, CurrentTime);
2090 for (i = 0; i < 3; ++i)
2091 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2093 for (i = 0; i < 3; ++i) {
2094 XFreeGC(r.d, r.fgs[i]);
2095 XFreeGC(r.d, r.bgs[i]);
2098 for (i = 0; i < 4; ++i) {
2099 XFreeGC(r.d, r.borders_bg[i]);
2100 XFreeGC(r.d, r.p_borders_bg[i]);
2101 XFreeGC(r.d, r.c_borders_bg[i]);
2102 XFreeGC(r.d, r.ch_borders_bg[i]);
2105 XDestroyIC(r.xic);
2106 XCloseIM(r.xim);
2108 for (i = 0; i < 3; ++i)
2109 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2110 XftFontClose(r.d, r.font);
2111 XftDrawDestroy(r.xftdraw);
2113 free(r.ps1);
2114 free(fontname);
2115 free(text);
2117 free(lines);
2118 free(vlines);
2119 compls_delete(cs);
2121 XFreeColormap(r.d, cmap);
2123 XDestroyWindow(r.d, r.w);
2124 XCloseDisplay(r.d);
2126 return status != OK;