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 #define RESNAME "MyMenu"
23 #define RESCLASS "mymenu"
25 #define SYM_BUF_SIZE 4
27 #define DEFFONT "monospace"
29 #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:"
31 #define MIN(a, b) ((a) < (b) ? (a) : (b))
32 #define MAX(a, b) ((a) > (b) ? (a) : (b))
34 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
36 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
37 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
39 /* The states of the event loop */
40 enum state { LOOPING, OK_LOOP, OK, ERR };
42 /*
43 * For the drawing-related function. The text to be rendere could be
44 * the prompt, a completion or a highlighted completion
45 */
46 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
48 /* These are the possible action to be performed after user input. */
49 enum action {
50 NO_OP,
51 EXIT,
52 CONFIRM,
53 CONFIRM_CONTINUE,
54 NEXT_COMPL,
55 PREV_COMPL,
56 DEL_CHAR,
57 DEL_WORD,
58 DEL_LINE,
59 ADD_CHAR,
60 TOGGLE_FIRST_SELECTED,
61 SCROLL_DOWN,
62 SCROLL_UP,
63 };
65 /* A big set of values that needs to be carried around for drawing. A
66 * big struct to rule them all */
67 struct rendering {
68 Display *d; /* Connection to xorg */
69 Window w;
70 XIM xim;
71 int width;
72 int height;
73 int p_padding[4];
74 int c_padding[4];
75 int ch_padding[4];
76 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
77 the borders) */
78 int y_zero; /* like x_zero but for the y axis */
80 int offset; /* scroll offset */
82 short free_text;
83 short first_selected;
84 short multiple_select;
86 /* four border width */
87 int borders[4];
88 int p_borders[4];
89 int c_borders[4];
90 int ch_borders[4];
92 short horizontal_layout;
94 /* prompt */
95 char *ps1;
96 int ps1len;
97 int ps1w; /* ps1 width */
98 int ps1h; /* ps1 height */
100 int text_height; /* cache for the vertical layout */
102 XIC xic;
104 /* colors */
105 GC fgs[4];
106 GC bgs[4];
107 GC borders_bg[4];
108 GC p_borders_bg[4];
109 GC c_borders_bg[4];
110 GC ch_borders_bg[4];
111 XftFont *font;
112 XftDraw *xftdraw;
113 XftColor xft_colors[3];
114 };
116 struct completion {
117 char *completion;
118 char *rcompletion;
119 int offset; /* the x (or y, depending on the layout) coordinate at
120 which the item is rendered */
121 };
123 /* Wrap the linked list of completions */
124 struct completions {
125 struct completion *completions;
126 ssize_t selected;
127 size_t length;
128 };
130 /* idea stolen from lemonbar. ty lemonboy */
131 typedef union {
132 struct {
133 uint8_t b;
134 uint8_t g;
135 uint8_t r;
136 uint8_t a;
137 } rgba;
138 uint32_t v;
139 } rgba_t;
141 extern char *optarg;
142 extern int optind;
144 /* Return a newly allocated (and empty) completion list */
145 struct completions *
146 compls_new(size_t length)
148 struct completions *cs = malloc(sizeof(struct completions));
150 if (cs == NULL)
151 return cs;
153 cs->completions = calloc(length, sizeof(struct completion));
154 if (cs->completions == NULL) {
155 free(cs);
156 return NULL;
159 cs->selected = -1;
160 cs->length = length;
161 return cs;
164 /* Delete the wrapper and the whole list */
165 void
166 compls_delete(struct completions *cs)
168 if (cs == NULL)
169 return;
171 free(cs->completions);
172 free(cs);
175 /*
176 * Create a completion list from a text and the list of possible
177 * completions (null terminated). Expects a non-null `cs'. `lines' and
178 * `vlines' should have the same length OR `vlines' is NULL.
179 */
180 void
181 filter(struct completions *cs, char *text, char **lines, char **vlines)
183 size_t index = 0;
184 size_t matching = 0;
185 char *l;
187 if (vlines == NULL)
188 vlines = lines;
190 while (1) {
191 if (lines[index] == NULL)
192 break;
194 l = vlines[index] != NULL ? vlines[index] : lines[index];
196 if (strcasestr(l, text) != NULL) {
197 struct completion *c = &cs->completions[matching];
198 c->completion = l;
199 c->rcompletion = lines[index];
200 matching++;
203 index++;
205 cs->length = matching;
206 cs->selected = -1;
209 /* Update the given completion */
210 void
211 update_completions(
212 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
214 filter(cs, text, lines, vlines);
215 if (first_selected && cs->length > 0)
216 cs->selected = 0;
219 /*
220 * Select the next or previous selection and update some state. `text'
221 * will be updated with the text of the completion and `textlen' with
222 * the new length. If the memory cannot be allocated `status' will be
223 * set to `ERR'.
224 */
225 void
226 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
227 enum state *status)
229 struct completion *n;
230 int index;
232 if (cs == NULL || cs->length == 0)
233 return;
235 /*
236 * If the first is always selected and the first entry is
237 * different from the text, expand the text and return
238 */
239 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
240 && !p) {
241 free(*text);
242 *text = strdup(cs->completions->completion);
243 if (text == NULL) {
244 *status = ERR;
245 return;
247 *textlen = strlen(*text);
248 return;
251 index = cs->selected;
253 if (index == -1 && p)
254 index = 0;
255 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
257 n = &cs->completions[cs->selected];
259 free(*text);
260 *text = strdup(n->completion);
261 if (text == NULL) {
262 fprintf(stderr, "Memory allocation error!\n");
263 *status = ERR;
264 return;
266 *textlen = strlen(*text);
269 /* Push the character c at the end of the string pointed by p */
270 int
271 pushc(char **p, int maxlen, char c)
273 int len;
275 len = strnlen(*p, maxlen);
276 if (!(len < maxlen - 2)) {
277 char *newptr;
279 maxlen += maxlen >> 1;
280 newptr = realloc(*p, maxlen);
281 if (newptr == NULL) /* bad */
282 return -1;
283 *p = newptr;
286 (*p)[len] = c;
287 (*p)[len + 1] = '\0';
288 return maxlen;
291 /*
292 * Remove the last rune from the *UTF-8* string! This is different
293 * from just setting the last byte to 0 (in some cases ofc). Return a
294 * pointer (e) to the last nonzero char. If e < p then p is empty!
295 */
296 char *
297 popc(char *p)
299 int len = strlen(p);
300 char *e;
302 if (len == 0)
303 return p;
305 e = p + len - 1;
307 do {
308 char c = *e;
310 *e = '\0';
311 e -= 1;
313 /*
314 * If c is a starting byte (11......) or is under
315 * U+007F we're done.
316 */
317 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
318 break;
319 } while (e >= p);
321 return e;
324 /* Remove the last word plus trailing white spaces from the given string */
325 void
326 popw(char *w)
328 int len;
329 short in_word = 1;
331 if ((len = strlen(w)) == 0)
332 return;
334 while (1) {
335 char *e = popc(w);
337 if (e < w)
338 return;
340 if (in_word && isspace(*e))
341 in_word = 0;
343 if (!in_word && !isspace(*e))
344 return;
348 /*
349 * If the string is surrounded by quates (`"') remove them and replace
350 * every `\"' in the string with a single double-quote.
351 */
352 char *
353 normalize_str(const char *str)
355 int len, p;
356 char *s;
358 if ((len = strlen(str)) == 0)
359 return NULL;
361 if ((s = calloc(len, sizeof(char))) == NULL)
362 err(1, "calloc");
363 p = 0;
365 while (*str) {
366 char c = *str;
368 if (*str == '\\') {
369 if (*(str + 1)) {
370 s[p] = *(str + 1);
371 p++;
372 str += 2; /* skip this and the next char */
373 continue;
374 } else
375 break;
377 if (c == '"') {
378 str++; /* skip only this char */
379 continue;
381 s[p] = c;
382 p++;
383 str++;
386 return s;
389 char **
390 readlines(size_t *lineslen)
392 size_t len = 0, cap = 0;
393 size_t linesize = 0;
394 ssize_t linelen;
395 char *line = NULL, **lines = NULL;
397 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
398 if (linelen != 0 && line[linelen-1] == '\n')
399 line[linelen-1] = '\0';
401 if (len == cap) {
402 size_t newcap;
403 void *t;
405 newcap = MAX(cap * 1.5, 32);
406 t = recallocarray(lines, cap, newcap, sizeof(char *));
407 if (t == NULL)
408 err(1, "recallocarray");
409 cap = newcap;
410 lines = t;
413 if ((lines[len++] = strdup(line)) == NULL)
414 err(1, "strdup");
417 if (ferror(stdin))
418 err(1, "getline");
419 free(line);
421 *lineslen = len;
422 return lines;
425 /*
426 * Compute the dimensions of the string str once rendered.
427 * It'll return the width and set ret_width and ret_height if not NULL
428 */
429 int
430 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
432 int height, width;
433 XGlyphInfo gi;
434 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
435 height = r->font->ascent - r->font->descent;
436 width = gi.width - gi.x;
438 if (ret_width != NULL)
439 *ret_width = width;
440 if (ret_height != NULL)
441 *ret_height = height;
442 return width;
445 void
446 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
448 XftColor xftcolor;
449 if (tt == PROMPT)
450 xftcolor = r->xft_colors[0];
451 if (tt == COMPL)
452 xftcolor = r->xft_colors[1];
453 if (tt == COMPL_HIGH)
454 xftcolor = r->xft_colors[2];
456 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
459 /* Duplicate the string and substitute every space with a 'n` */
460 char *
461 strdupn(char *str)
463 int len, i;
464 char *t, *dup;
466 if (str == NULL || len == 0)
467 return NULL;
469 if ((dup = strdup(str)) == NULL)
470 return NULL;
472 for (t = dup; *t; ++t) {
473 if (*t == ' ')
474 *t = 'n';
477 return dup;
480 int
481 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
483 GC *border_color, bg;
484 int *padding, *borders;
485 int ret = 0, inner_width, inner_height, x;
487 switch (t) {
488 case PROMPT:
489 border_color = r->p_borders_bg;
490 padding = r->p_padding;
491 borders = r->p_borders;
492 bg = r->bgs[0];
493 break;
494 case COMPL:
495 border_color = r->c_borders_bg;
496 padding = r->c_padding;
497 borders = r->c_borders;
498 bg = r->bgs[1];
499 break;
500 case COMPL_HIGH:
501 border_color = r->ch_borders_bg;
502 padding = r->ch_padding;
503 borders = r->ch_borders;
504 bg = r->bgs[2];
505 break;
508 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
510 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
511 inner_height = padding[0] + r->text_height + padding[2];
513 /* Border top */
514 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
516 /* Border right */
517 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
518 borders[1], ret);
520 /* Border bottom */
521 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
522 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
524 /* Border left */
525 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
527 /* bg */
528 x = r->x_zero + borders[3];
529 y += borders[0];
530 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
532 /* content */
533 y += padding[0] + r->text_height;
534 x += padding[3];
535 if (prefix != NULL) {
536 draw_string(prefix, strlen(prefix), x, y, r, t);
537 x += prefix_width;
539 draw_string(text, strlen(text), x, y, r, t);
541 return ret;
544 int
545 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
547 GC *border_color, bg;
548 int *padding, *borders;
549 int ret = 0, inner_width, inner_height, y, text_width;
551 switch (t) {
552 case PROMPT:
553 border_color = r->p_borders_bg;
554 padding = r->p_padding;
555 borders = r->p_borders;
556 bg = r->bgs[0];
557 break;
558 case COMPL:
559 border_color = r->c_borders_bg;
560 padding = r->c_padding;
561 borders = r->c_borders;
562 bg = r->bgs[1];
563 break;
564 case COMPL_HIGH:
565 border_color = r->ch_borders_bg;
566 padding = r->ch_padding;
567 borders = r->ch_borders;
568 bg = r->bgs[2];
569 break;
572 if (padding[0] < 0 || padding[2] < 0)
573 padding[0] = padding[2]
574 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
576 /* If they are still lesser than 0, set 'em to 0 */
577 if (padding[0] < 0 || padding[2] < 0)
578 padding[0] = padding[2] = 0;
580 /* Get the text width */
581 text_extents(text, strlen(text), r, &text_width, NULL);
582 if (prefix != NULL)
583 text_width += prefix_width;
585 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
587 inner_width = padding[3] + text_width + padding[1];
588 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
590 /* Border top */
591 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
593 /* Border right */
594 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
595 borders[1], INNER_HEIGHT(r));
597 /* Border bottom */
598 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
599 ret, borders[2]);
601 /* Border left */
602 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
604 /* bg */
605 x += borders[3];
606 y = r->y_zero + borders[0];
607 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
609 /* content */
610 y += padding[0] + r->text_height;
611 x += padding[3];
612 if (prefix != NULL) {
613 draw_string(prefix, strlen(prefix), x, y, r, t);
614 x += prefix_width;
616 draw_string(text, strlen(text), x, y, r, t);
618 return ret;
621 /* ,-----------------------------------------------------------------, */
622 /* | 20 char text | completion | completion | completion | compl | */
623 /* `-----------------------------------------------------------------' */
624 void
625 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
627 size_t i;
628 int x = r->x_zero;
630 /* Draw the prompt */
631 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
633 for (i = r->offset; i < cs->length; ++i) {
634 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
636 cs->completions[i].offset = x;
638 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
640 if (x > INNER_WIDTH(r))
641 break;
644 for (i += 1; i < cs->length; ++i)
645 cs->completions[i].offset = -1;
648 /* ,-----------------------------------------------------------------, */
649 /* | prompt | */
650 /* |-----------------------------------------------------------------| */
651 /* | completion | */
652 /* |-----------------------------------------------------------------| */
653 /* | completion | */
654 /* `-----------------------------------------------------------------' */
655 void
656 draw_vertically(struct rendering *r, char *text, struct completions *cs)
658 size_t i;
659 int y = r->y_zero;
661 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
663 for (i = r->offset; i < cs->length; ++i) {
664 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
666 cs->completions[i].offset = y;
668 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
670 if (y > INNER_HEIGHT(r))
671 break;
674 for (i += 1; i < cs->length; ++i)
675 cs->completions[i].offset = -1;
678 void
679 draw(struct rendering *r, char *text, struct completions *cs)
681 /* Draw the background */
682 XFillRectangle(
683 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
685 /* Draw the contents */
686 if (r->horizontal_layout)
687 draw_horizontally(r, text, cs);
688 else
689 draw_vertically(r, text, cs);
691 /* Draw the borders */
692 if (r->borders[0] != 0)
693 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
695 if (r->borders[1] != 0)
696 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
697 r->borders[1], r->height);
699 if (r->borders[2] != 0)
700 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
701 r->borders[2]);
703 if (r->borders[3] != 0)
704 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
706 /* render! */
707 XFlush(r->d);
710 /* Set some WM stuff */
711 void
712 set_win_atoms_hints(Display *d, Window w, int width, int height)
714 Atom type;
715 XClassHint *class_hint;
716 XSizeHints *size_hint;
718 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
719 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
720 32, PropModeReplace, (unsigned char *)&type, 1);
722 /* some window managers honor this properties */
723 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
724 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
725 PropModeReplace, (unsigned char *)&type, 1);
727 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
728 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
729 PropModeAppend, (unsigned char *)&type, 1);
731 /* Setting window hints */
732 class_hint = XAllocClassHint();
733 if (class_hint == NULL) {
734 fprintf(stderr, "Could not allocate memory for class hint\n");
735 exit(EX_UNAVAILABLE);
738 class_hint->res_name = RESNAME;
739 class_hint->res_class = RESCLASS;
740 XSetClassHint(d, w, class_hint);
741 XFree(class_hint);
743 size_hint = XAllocSizeHints();
744 if (size_hint == NULL) {
745 fprintf(stderr, "Could not allocate memory for size hint\n");
746 exit(EX_UNAVAILABLE);
749 size_hint->flags = PMinSize | PBaseSize;
750 size_hint->min_width = width;
751 size_hint->base_width = width;
752 size_hint->min_height = height;
753 size_hint->base_height = height;
755 XFlush(d);
758 /* Get the width and height of the window `w' */
759 void
760 get_wh(Display *d, Window *w, int *width, int *height)
762 XWindowAttributes win_attr;
764 XGetWindowAttributes(d, *w, &win_attr);
765 *height = win_attr.height;
766 *width = win_attr.width;
769 int
770 grabfocus(Display *d, Window w)
772 int i;
773 for (i = 0; i < 100; ++i) {
774 Window focuswin;
775 int revert_to_win;
777 XGetInputFocus(d, &focuswin, &revert_to_win);
779 if (focuswin == w)
780 return 1;
782 XSetInputFocus(d, w, RevertToParent, CurrentTime);
783 usleep(1000);
785 return 0;
788 /*
789 * I know this may seem a little hackish BUT is the only way I managed
790 * to actually grab that goddam keyboard. Only one call to
791 * XGrabKeyboard does not always end up with the keyboard grabbed!
792 */
793 int
794 take_keyboard(Display *d, Window w)
796 int i;
797 for (i = 0; i < 100; i++) {
798 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
799 == GrabSuccess)
800 return 1;
801 usleep(1000);
803 fprintf(stderr, "Cannot grab keyboard\n");
804 return 0;
807 unsigned long
808 parse_color(const char *str, const char *def)
810 size_t len;
811 rgba_t tmp;
812 char *ep;
814 if (str == NULL)
815 goto invc;
817 len = strlen(str);
819 /* +1 for the # ath the start */
820 if (*str != '#' || len > 9 || len < 4)
821 goto invc;
822 ++str; /* skip the # */
824 errno = 0;
825 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
827 if (errno)
828 goto invc;
830 switch (len - 1) {
831 case 3:
832 /* expand #rgb -> #rrggbb */
833 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
834 | (tmp.v & 0x00f) * 0x0011;
835 case 6:
836 /* assume 0xff opacity */
837 tmp.rgba.a = 0xff;
838 break;
839 } /* colors in #aarrggbb need no adjustments */
841 /* premultiply the alpha */
842 if (tmp.rgba.a) {
843 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
844 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
845 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
846 return tmp.v;
849 return 0U;
851 invc:
852 fprintf(stderr, "Invalid color: \"%s\".\n", str);
853 if (def != NULL)
854 return parse_color(def, NULL);
855 else
856 return 0U;
859 /*
860 * Given a string try to parse it as a number or return `def'.
861 */
862 int
863 parse_integer(const char *str, int def)
865 const char *errstr;
866 int i;
868 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
869 if (errstr != NULL) {
870 warnx("'%s' is %s; using %d as default", str, errstr, def);
871 return def;
874 return i;
877 /* Like parse_integer but recognize the percentages (i.e. strings ending with
878 * `%') */
879 int
880 parse_int_with_percentage(const char *str, int default_value, int max)
882 int len = strlen(str);
884 if (len > 0 && str[len - 1] == '%') {
885 int val;
886 char *cpy;
888 if ((cpy = strdup(str)) == NULL)
889 err(1, "strdup");
891 cpy[len - 1] = '\0';
892 val = parse_integer(cpy, default_value);
893 free(cpy);
894 return val * max / 100;
897 return parse_integer(str, default_value);
900 void
901 get_mouse_coords(Display *d, int *x, int *y)
903 Window w, root;
904 int i;
905 unsigned int u;
907 *x = *y = 0;
908 root = DefaultRootWindow(d);
910 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
911 for (i = 0; i < ScreenCount(d); ++i) {
912 if (root == RootWindow(d, i))
913 break;
918 /*
919 * Like parse_int_with_percentage but understands some special values:
920 * - middle that is (max-self)/2
921 * - center = middle
922 * - start that is 0
923 * - end that is (max-self)
924 * - mx x coordinate of the mouse
925 * - my y coordinate of the mouse
926 */
927 int
928 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
930 if (!strcmp(str, "start"))
931 return 0;
932 if (!strcmp(str, "middle") || !strcmp(str, "center"))
933 return (max - self) / 2;
934 if (!strcmp(str, "end"))
935 return max - self;
936 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
937 int x, y;
939 get_mouse_coords(d, &x, &y);
940 if (!strcmp(str, "mx"))
941 return x - 1;
942 else
943 return y - 1;
945 return parse_int_with_percentage(str, default_value, max);
948 /* Parse a string like a CSS value. */
949 /* TODO: harden a bit this function */
950 char **
951 parse_csslike(const char *str)
953 int i, j;
954 char *s, *token, **ret;
955 short any_null;
957 s = strdup(str);
958 if (s == NULL)
959 return NULL;
961 ret = malloc(4 * sizeof(char *));
962 if (ret == NULL) {
963 free(s);
964 return NULL;
967 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
968 ret[i] = strdup(token);
970 if (i == 1)
971 for (j = 1; j < 4; j++)
972 ret[j] = strdup(ret[0]);
974 if (i == 2) {
975 ret[2] = strdup(ret[0]);
976 ret[3] = strdup(ret[1]);
979 if (i == 3)
980 ret[3] = strdup(ret[1]);
982 /* before we didn't check for the return type of strdup, here we will
983 */
985 any_null = 0;
986 for (i = 0; i < 4; ++i)
987 any_null = ret[i] == NULL || any_null;
989 if (any_null)
990 for (i = 0; i < 4; ++i)
991 if (ret[i] != NULL)
992 free(ret[i]);
994 if (i == 0 || any_null) {
995 free(s);
996 free(ret);
997 return NULL;
1000 return ret;
1004 * Given an event, try to understand what the users wants. If the
1005 * return value is ADD_CHAR then `input' is a pointer to a string that
1006 * will need to be free'ed later.
1008 enum action
1009 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1011 char str[SYM_BUF_SIZE] = { 0 };
1012 Status s;
1014 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1015 return DEL_CHAR;
1017 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1018 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1020 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1021 return CONFIRM;
1023 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1024 return EXIT;
1026 /* Try to read what key was pressed */
1027 s = 0;
1028 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1029 if (s == XBufferOverflow) {
1030 fprintf(stderr,
1031 "Buffer overflow when trying to create keyboard "
1032 "symbol map.\n");
1033 return EXIT;
1036 if (ev->state & ControlMask) {
1037 if (!strcmp(str, "")) /* C-u */
1038 return DEL_LINE;
1039 if (!strcmp(str, "")) /* C-w */
1040 return DEL_WORD;
1041 if (!strcmp(str, "")) /* C-h */
1042 return DEL_CHAR;
1043 if (!strcmp(str, "\r")) /* C-m */
1044 return CONFIRM_CONTINUE;
1045 if (!strcmp(str, "")) /* C-p */
1046 return PREV_COMPL;
1047 if (!strcmp(str, "")) /* C-n */
1048 return NEXT_COMPL;
1049 if (!strcmp(str, "")) /* C-c */
1050 return EXIT;
1051 if (!strcmp(str, "\t")) /* C-i */
1052 return TOGGLE_FIRST_SELECTED;
1055 *input = strdup(str);
1056 if (*input == NULL) {
1057 fprintf(stderr, "Error while allocating memory for key.\n");
1058 return EXIT;
1061 return ADD_CHAR;
1064 void
1065 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1067 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1068 /* if there is something selected expand it and return */
1069 int index = cs->selected == -1 ? 0 : cs->selected;
1070 struct completion *c = cs->completions;
1071 char *t;
1073 while (1) {
1074 if (index == 0)
1075 break;
1076 c++;
1077 index--;
1080 t = c->rcompletion;
1081 free(*text);
1082 *text = strdup(t);
1084 if (*text == NULL) {
1085 fprintf(stderr, "Memory allocation error\n");
1086 *status = ERR;
1089 *textlen = strlen(*text);
1090 return;
1093 if (!r->free_text) /* cannot accept arbitrary text */
1094 *status = LOOPING;
1097 /* cs: completion list
1098 * offset: the offset of the click
1099 * first: the first (rendered) item
1100 * def: the default action
1102 enum action
1103 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1105 ssize_t selected = first;
1106 int set = 0;
1108 if (cs->length == 0)
1109 return NO_OP;
1111 if (offset < cs->completions[selected].offset)
1112 return EXIT;
1114 /* skip the first entry */
1115 for (selected += 1; selected < cs->length; ++selected) {
1116 if (cs->completions[selected].offset == -1)
1117 break;
1119 if (offset < cs->completions[selected].offset) {
1120 cs->selected = selected - 1;
1121 set = 1;
1122 break;
1126 if (!set)
1127 cs->selected = selected - 1;
1129 return def;
1132 enum action
1133 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1135 size_t off;
1137 if (r->horizontal_layout)
1138 off = e->x;
1139 else
1140 off = e->y;
1142 switch (e->button) {
1143 case Button1:
1144 return select_clicked(cs, off, r->offset, CONFIRM);
1146 case Button3:
1147 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1149 case Button4:
1150 return SCROLL_UP;
1152 case Button5:
1153 return SCROLL_DOWN;
1156 return NO_OP;
1159 /* event loop */
1160 enum state
1161 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1162 char **vlines)
1164 enum state status = LOOPING;
1166 while (status == LOOPING) {
1167 XEvent e;
1168 XNextEvent(r->d, &e);
1170 if (XFilterEvent(&e, r->w))
1171 continue;
1173 switch (e.type) {
1174 case KeymapNotify:
1175 XRefreshKeyboardMapping(&e.xmapping);
1176 break;
1178 case FocusIn:
1179 /* Re-grab focus */
1180 if (e.xfocus.window != r->w)
1181 grabfocus(r->d, r->w);
1182 break;
1184 case VisibilityNotify:
1185 if (e.xvisibility.state != VisibilityUnobscured)
1186 XRaiseWindow(r->d, r->w);
1187 break;
1189 case MapNotify:
1190 get_wh(r->d, &r->w, &r->width, &r->height);
1191 draw(r, *text, cs);
1192 break;
1194 case KeyPress:
1195 case ButtonPress: {
1196 enum action a;
1197 char *input = NULL;
1199 if (e.type == KeyPress)
1200 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1201 else
1202 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1204 switch (a) {
1205 case NO_OP:
1206 break;
1208 case EXIT:
1209 status = ERR;
1210 break;
1212 case CONFIRM: {
1213 status = OK;
1214 confirm(&status, r, cs, text, textlen);
1215 break;
1218 case CONFIRM_CONTINUE: {
1219 status = OK_LOOP;
1220 confirm(&status, r, cs, text, textlen);
1221 break;
1224 case PREV_COMPL: {
1225 complete(cs, r->first_selected, 1, text, textlen, &status);
1226 r->offset = cs->selected;
1227 break;
1230 case NEXT_COMPL: {
1231 complete(cs, r->first_selected, 0, text, textlen, &status);
1232 r->offset = cs->selected;
1233 break;
1236 case DEL_CHAR:
1237 popc(*text);
1238 update_completions(cs, *text, lines, vlines, r->first_selected);
1239 r->offset = 0;
1240 break;
1242 case DEL_WORD: {
1243 popw(*text);
1244 update_completions(cs, *text, lines, vlines, r->first_selected);
1245 break;
1248 case DEL_LINE: {
1249 int i;
1250 for (i = 0; i < *textlen; ++i)
1251 *(*text + i) = 0;
1252 update_completions(cs, *text, lines, vlines, r->first_selected);
1253 r->offset = 0;
1254 break;
1257 case ADD_CHAR: {
1258 int str_len, i;
1260 str_len = strlen(input);
1263 * sometimes a strange key is pressed
1264 * i.e. ctrl alone), so input will be
1265 * empty. Don't need to update
1266 * completion in that case
1268 if (str_len == 0)
1269 break;
1271 for (i = 0; i < str_len; ++i) {
1272 *textlen = pushc(text, *textlen, input[i]);
1273 if (*textlen == -1) {
1274 fprintf(stderr,
1275 "Memory allocation "
1276 "error\n");
1277 status = ERR;
1278 break;
1282 if (status != ERR) {
1283 update_completions(
1284 cs, *text, lines, vlines, r->first_selected);
1285 free(input);
1288 r->offset = 0;
1289 break;
1292 case TOGGLE_FIRST_SELECTED:
1293 r->first_selected = !r->first_selected;
1294 if (r->first_selected && cs->selected < 0)
1295 cs->selected = 0;
1296 if (!r->first_selected && cs->selected == 0)
1297 cs->selected = -1;
1298 break;
1300 case SCROLL_DOWN:
1301 r->offset = MIN(r->offset + 1, cs->length - 1);
1302 break;
1304 case SCROLL_UP:
1305 r->offset = MAX((ssize_t)r->offset - 1, 0);
1306 break;
1311 draw(r, *text, cs);
1314 return status;
1317 int
1318 load_font(struct rendering *r, const char *fontname)
1320 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1321 return 0;
1324 void
1325 xim_init(struct rendering *r, XrmDatabase *xdb)
1327 XIMStyle best_match_style;
1328 XIMStyles *xis;
1329 int i;
1331 /* Open the X input method */
1332 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1333 err(1, "XOpenIM");
1335 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1336 fprintf(stderr, "Input Styles could not be retrieved\n");
1337 exit(EX_UNAVAILABLE);
1340 best_match_style = 0;
1341 for (i = 0; i < xis->count_styles; ++i) {
1342 XIMStyle ts = xis->supported_styles[i];
1343 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1344 best_match_style = ts;
1345 break;
1348 XFree(xis);
1350 if (!best_match_style)
1351 fprintf(stderr, "No matching input style could be determined\n");
1353 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1354 XNFocusWindow, r->w, NULL);
1355 if (r->xic == NULL)
1356 err(1, "XCreateIC");
1359 void
1360 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1361 int y, int ox, int oy, unsigned long background_pixel)
1363 XSetWindowAttributes attr;
1365 /* Create the window */
1366 attr.colormap = cmap;
1367 attr.override_redirect = 1;
1368 attr.border_pixel = 0;
1369 attr.background_pixel = background_pixel;
1370 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1371 | ButtonPress | VisibilityChangeMask;
1373 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1374 vinfo.depth, InputOutput, vinfo.visual,
1375 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1378 void
1379 ps1extents(struct rendering *r)
1381 char *dup;
1382 dup = strdupn(r->ps1);
1383 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1384 free(dup);
1387 void
1388 usage(char *prgname)
1390 fprintf(stderr,
1391 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1392 " [-d separator] [-e window] [-f font] [-G color] [-g "
1393 "size]\n"
1394 " [-H height] [-I color] [-i size] [-J color] [-j "
1395 "size] [-l layout]\n"
1396 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1397 "color]\n"
1398 " [-t color] [-W width] [-x coord] [-y coord]\n",
1399 prgname);
1402 int
1403 main(int argc, char **argv)
1405 struct completions *cs;
1406 struct rendering r;
1407 XVisualInfo vinfo;
1408 Colormap cmap;
1409 size_t nlines, i;
1410 Window parent_window;
1411 XrmDatabase xdb;
1412 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1413 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1414 ch_borders_bg[4]; /* N E S W */
1415 enum state status;
1416 int ch;
1417 int offset_x, offset_y, x, y;
1418 int textlen, d_width, d_height;
1419 short embed;
1420 char *sep, *parent_window_id;
1421 char **lines, **vlines;
1422 char *fontname, *text, *xrm;
1424 sep = NULL;
1425 parent_window_id = NULL;
1427 r.first_selected = 0;
1428 r.free_text = 1;
1429 r.multiple_select = 0;
1430 r.offset = 0;
1432 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1433 switch (ch) {
1434 case 'h': /* help */
1435 usage(*argv);
1436 return 0;
1437 case 'v': /* version */
1438 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1439 return 0;
1440 case 'e': /* embed */
1441 if ((parent_window_id = strdup(optarg)) == NULL)
1442 err(1, "strdup");
1443 break;
1444 case 'd':
1445 if ((sep = strdup(optarg)) == NULL)
1446 err(1, "strdup");
1447 break;
1448 case 'A':
1449 r.free_text = 0;
1450 break;
1451 case 'm':
1452 r.multiple_select = 1;
1453 break;
1454 default:
1455 break;
1459 lines = readlines(&nlines);
1461 vlines = NULL;
1462 if (sep != NULL) {
1463 int l;
1464 l = strlen(sep);
1465 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1466 err(1, "calloc");
1468 for (i = 0; i < nlines; i++) {
1469 char *t;
1470 t = strstr(lines[i], sep);
1471 if (t == NULL)
1472 vlines[i] = lines[i];
1473 else
1474 vlines[i] = t + l;
1478 setlocale(LC_ALL, getenv("LANG"));
1480 status = LOOPING;
1482 /* where the monitor start (used only with xinerama) */
1483 offset_x = offset_y = 0;
1485 /* default width and height */
1486 r.width = 400;
1487 r.height = 20;
1489 /* default position on the screen */
1490 x = y = 0;
1492 for (i = 0; i < 4; ++i) {
1493 /* default paddings */
1494 r.p_padding[i] = 10;
1495 r.c_padding[i] = 10;
1496 r.ch_padding[i] = 10;
1498 /* default borders */
1499 r.borders[i] = 0;
1500 r.p_borders[i] = 0;
1501 r.c_borders[i] = 0;
1502 r.ch_borders[i] = 0;
1505 /* the prompt. We duplicate the string so later is easy to
1506 * free (in the case it's been overwritten by the user) */
1507 if ((r.ps1 = strdup("$ ")) == NULL)
1508 err(1, "strdup");
1510 /* same for the font name */
1511 if ((fontname = strdup(DEFFONT)) == NULL)
1512 err(1, "strdup");
1514 textlen = 10;
1515 if ((text = malloc(textlen * sizeof(char))) == NULL)
1516 err(1, "malloc");
1518 /* struct completions *cs = filter(text, lines); */
1519 if ((cs = compls_new(nlines)) == NULL)
1520 err(1, "compls_new");
1522 /* start talking to xorg */
1523 r.d = XOpenDisplay(NULL);
1524 if (r.d == NULL) {
1525 fprintf(stderr, "Could not open display!\n");
1526 return EX_UNAVAILABLE;
1529 embed = 1;
1530 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1531 parent_window = DefaultRootWindow(r.d);
1532 embed = 0;
1535 /* get display size */
1536 get_wh(r.d, &parent_window, &d_width, &d_height);
1538 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1539 XineramaScreenInfo *info;
1540 Window rr;
1541 Window root;
1542 int number_of_screens, monitors, i;
1543 int root_x, root_y, win_x, win_y;
1544 unsigned int mask;
1545 short res;
1547 number_of_screens = XScreenCount(r.d);
1548 for (i = 0; i < number_of_screens; ++i) {
1549 root = XRootWindow(r.d, i);
1550 res = XQueryPointer(
1551 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1552 if (res)
1553 break;
1556 if (!res) {
1557 fprintf(stderr, "No mouse found.\n");
1558 root_x = 0;
1559 root_y = 0;
1562 /* Now find in which monitor the mice is */
1563 info = XineramaQueryScreens(r.d, &monitors);
1564 if (info) {
1565 for (i = 0; i < monitors; ++i) {
1566 if (info[i].x_org <= root_x
1567 && root_x <= (info[i].x_org + info[i].width)
1568 && info[i].y_org <= root_y
1569 && root_y <= (info[i].y_org + info[i].height)) {
1570 offset_x = info[i].x_org;
1571 offset_y = info[i].y_org;
1572 d_width = info[i].width;
1573 d_height = info[i].height;
1574 break;
1578 XFree(info);
1581 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1582 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1584 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1585 fgs[2] = parse_color("#000", NULL);
1587 bgs[0] = bgs[1] = parse_color("#000", NULL);
1588 bgs[2] = parse_color("#fff", NULL);
1590 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1592 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1593 = parse_color("#000", NULL);
1594 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1595 = parse_color("#000", NULL);
1596 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1597 = parse_color("#000", NULL);
1599 r.horizontal_layout = 1;
1601 /* Read the resources */
1602 XrmInitialize();
1603 xrm = XResourceManagerString(r.d);
1604 xdb = NULL;
1605 if (xrm != NULL) {
1606 XrmValue value;
1607 char *datatype[20];
1609 xdb = XrmGetStringDatabase(xrm);
1611 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1612 free(fontname);
1613 if ((fontname = strdup(value.addr)) == NULL)
1614 err(1, "strdup");
1615 } else {
1616 fprintf(stderr, "no font defined, using %s\n", fontname);
1619 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1620 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1621 else
1622 fprintf(stderr, "no layout defined, using horizontal\n");
1624 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1625 free(r.ps1);
1626 r.ps1 = normalize_str(value.addr);
1627 } else {
1628 fprintf(stderr,
1629 "no prompt defined, using \"%s\" as "
1630 "default\n",
1631 r.ps1);
1634 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1635 char **sizes;
1636 sizes = parse_csslike(value.addr);
1637 if (sizes != NULL)
1638 for (i = 0; i < 4; ++i)
1639 r.p_borders[i] = parse_integer(sizes[i], 0);
1640 else
1641 fprintf(stderr,
1642 "error while parsing "
1643 "MyMenu.prompt.border.size");
1646 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1647 char **colors;
1648 colors = parse_csslike(value.addr);
1649 if (colors != NULL)
1650 for (i = 0; i < 4; ++i)
1651 p_borders_bg[i] = parse_color(colors[i], "#000");
1652 else
1653 fprintf(stderr,
1654 "error while parsing "
1655 "MyMenu.prompt.border.color");
1658 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1659 char **colors;
1660 colors = parse_csslike(value.addr);
1661 if (colors != NULL)
1662 for (i = 0; i < 4; ++i)
1663 r.p_padding[i] = parse_integer(colors[i], 0);
1664 else
1665 fprintf(stderr,
1666 "error while parsing "
1667 "MyMenu.prompt.padding");
1670 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1671 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1672 else
1673 fprintf(stderr, "no width defined, using %d\n", r.width);
1675 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1676 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1677 else
1678 fprintf(stderr, "no height defined, using %d\n", r.height);
1680 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1681 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1683 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1684 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1686 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1687 char **borders;
1688 borders = parse_csslike(value.addr);
1689 if (borders != NULL)
1690 for (i = 0; i < 4; ++i)
1691 r.borders[i] = parse_int_with_percentage(
1692 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1693 else
1694 fprintf(stderr,
1695 "error while parsing "
1696 "MyMenu.border.size\n");
1699 /* Prompt */
1700 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1701 fgs[0] = parse_color(value.addr, "#fff");
1703 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1704 bgs[0] = parse_color(value.addr, "#000");
1706 /* Completions */
1707 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1708 fgs[1] = parse_color(value.addr, "#fff");
1710 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1711 bgs[1] = parse_color(value.addr, "#000");
1713 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1714 char **paddings;
1715 paddings = parse_csslike(value.addr);
1716 if (paddings != NULL)
1717 for (i = 0; i < 4; ++i)
1718 r.c_padding[i] = parse_integer(paddings[i], 0);
1719 else
1720 fprintf(stderr,
1721 "Error while parsing "
1722 "MyMenu.completion.padding");
1725 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1726 char **sizes;
1727 sizes = parse_csslike(value.addr);
1728 if (sizes != NULL)
1729 for (i = 0; i < 4; ++i)
1730 r.c_borders[i] = parse_integer(sizes[i], 0);
1731 else
1732 fprintf(stderr,
1733 "Error while parsing "
1734 "MyMenu.completion.border.size");
1737 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1738 char **sizes;
1739 sizes = parse_csslike(value.addr);
1740 if (sizes != NULL)
1741 for (i = 0; i < 4; ++i)
1742 c_borders_bg[i] = parse_color(sizes[i], "#000");
1743 else
1744 fprintf(stderr,
1745 "Error while parsing "
1746 "MyMenu.completion.border.color");
1749 /* Completion Highlighted */
1750 if (XrmGetResource(
1751 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1752 fgs[2] = parse_color(value.addr, "#000");
1754 if (XrmGetResource(
1755 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1756 bgs[2] = parse_color(value.addr, "#fff");
1758 if (XrmGetResource(
1759 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1760 char **paddings;
1761 paddings = parse_csslike(value.addr);
1762 if (paddings != NULL)
1763 for (i = 0; i < 4; ++i)
1764 r.ch_padding[i] = parse_integer(paddings[i], 0);
1765 else
1766 fprintf(stderr,
1767 "Error while parsing "
1768 "MyMenu.completion_highlighted."
1769 "padding");
1772 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1773 &value)) {
1774 char **sizes;
1775 sizes = parse_csslike(value.addr);
1776 if (sizes != NULL)
1777 for (i = 0; i < 4; ++i)
1778 r.ch_borders[i] = parse_integer(sizes[i], 0);
1779 else
1780 fprintf(stderr,
1781 "Error while parsing "
1782 "MyMenu.completion_highlighted."
1783 "border.size");
1786 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1787 &value)) {
1788 char **colors;
1789 colors = parse_csslike(value.addr);
1790 if (colors != NULL)
1791 for (i = 0; i < 4; ++i)
1792 ch_borders_bg[i] = parse_color(colors[i], "#000");
1793 else
1794 fprintf(stderr,
1795 "Error while parsing "
1796 "MyMenu.completion_highlighted."
1797 "border.color");
1800 /* Border */
1801 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1802 char **colors;
1803 colors = parse_csslike(value.addr);
1804 if (colors != NULL)
1805 for (i = 0; i < 4; ++i)
1806 borders_bg[i] = parse_color(colors[i], "#000");
1807 else
1808 fprintf(stderr,
1809 "error while parsing "
1810 "MyMenu.border.color\n");
1814 /* Second round of args parsing */
1815 optind = 0; /* reset the option index */
1816 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1817 switch (ch) {
1818 case 'a':
1819 r.first_selected = 1;
1820 break;
1821 case 'A':
1822 /* free_text -- already catched */
1823 case 'd':
1824 /* separator -- this case was already catched */
1825 case 'e':
1826 /* embedding mymenu this case was already catched. */
1827 case 'm':
1828 /* multiple selection this case was already catched.
1830 break;
1831 case 'p': {
1832 char *newprompt;
1833 newprompt = strdup(optarg);
1834 if (newprompt != NULL) {
1835 free(r.ps1);
1836 r.ps1 = newprompt;
1838 break;
1840 case 'x':
1841 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1842 break;
1843 case 'y':
1844 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1845 break;
1846 case 'P': {
1847 char **paddings;
1848 if ((paddings = parse_csslike(optarg)) != NULL)
1849 for (i = 0; i < 4; ++i)
1850 r.p_padding[i] = parse_integer(paddings[i], 0);
1851 break;
1853 case 'G': {
1854 char **colors;
1855 if ((colors = parse_csslike(optarg)) != NULL)
1856 for (i = 0; i < 4; ++i)
1857 p_borders_bg[i] = parse_color(colors[i], "#000");
1858 break;
1860 case 'g': {
1861 char **sizes;
1862 if ((sizes = parse_csslike(optarg)) != NULL)
1863 for (i = 0; i < 4; ++i)
1864 r.p_borders[i] = parse_integer(sizes[i], 0);
1865 break;
1867 case 'I': {
1868 char **colors;
1869 if ((colors = parse_csslike(optarg)) != NULL)
1870 for (i = 0; i < 4; ++i)
1871 c_borders_bg[i] = parse_color(colors[i], "#000");
1872 break;
1874 case 'i': {
1875 char **sizes;
1876 if ((sizes = parse_csslike(optarg)) != NULL)
1877 for (i = 0; i < 4; ++i)
1878 r.c_borders[i] = parse_integer(sizes[i], 0);
1879 break;
1881 case 'J': {
1882 char **colors;
1883 if ((colors = parse_csslike(optarg)) != NULL)
1884 for (i = 0; i < 4; ++i)
1885 ch_borders_bg[i] = parse_color(colors[i], "#000");
1886 break;
1888 case 'j': {
1889 char **sizes;
1890 if ((sizes = parse_csslike(optarg)) != NULL)
1891 for (i = 0; i < 4; ++i)
1892 r.ch_borders[i] = parse_integer(sizes[i], 0);
1893 break;
1895 case 'l':
1896 r.horizontal_layout = !strcmp(optarg, "horizontal");
1897 break;
1898 case 'f': {
1899 char *newfont;
1900 if ((newfont = strdup(optarg)) != NULL) {
1901 free(fontname);
1902 fontname = newfont;
1904 break;
1906 case 'W':
1907 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1908 break;
1909 case 'H':
1910 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1911 break;
1912 case 'b': {
1913 char **borders;
1914 if ((borders = parse_csslike(optarg)) != NULL) {
1915 for (i = 0; i < 4; ++i)
1916 r.borders[i] = parse_integer(borders[i], 0);
1917 } else
1918 fprintf(stderr, "Error parsing b option\n");
1919 break;
1921 case 'B': {
1922 char **colors;
1923 if ((colors = parse_csslike(optarg)) != NULL) {
1924 for (i = 0; i < 4; ++i)
1925 borders_bg[i] = parse_color(colors[i], "#000");
1926 } else
1927 fprintf(stderr, "error while parsing B option\n");
1928 break;
1930 case 't':
1931 fgs[0] = parse_color(optarg, NULL);
1932 break;
1933 case 'T':
1934 bgs[0] = parse_color(optarg, NULL);
1935 break;
1936 case 'c':
1937 fgs[1] = parse_color(optarg, NULL);
1938 break;
1939 case 'C':
1940 bgs[1] = parse_color(optarg, NULL);
1941 break;
1942 case 's':
1943 fgs[2] = parse_color(optarg, NULL);
1944 break;
1945 case 'S':
1946 bgs[2] = parse_color(optarg, NULL);
1947 break;
1948 default:
1949 fprintf(stderr, "Unrecognized option %c\n", ch);
1950 status = ERR;
1951 break;
1955 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1956 fprintf(stderr, "height, width, x or y are lesser than 0.");
1957 status = ERR;
1960 /* since only now we know if the first should be selected,
1961 * update the completion here */
1962 update_completions(cs, text, lines, vlines, r.first_selected);
1964 /* update the prompt lenght, only now we surely know the length of it
1966 r.ps1len = strlen(r.ps1);
1968 /* Create the window */
1969 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1970 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1971 XMapRaised(r.d, r.w);
1973 /* If embed, listen for other events as well */
1974 if (embed) {
1975 Window *children, parent, root;
1976 unsigned int children_no;
1978 XSelectInput(r.d, parent_window, FocusChangeMask);
1979 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1980 && children) {
1981 for (i = 0; i < children_no && children[i] != r.w; ++i)
1982 XSelectInput(r.d, children[i], FocusChangeMask);
1983 XFree(children);
1985 grabfocus(r.d, r.w);
1988 take_keyboard(r.d, r.w);
1990 r.x_zero = r.borders[3];
1991 r.y_zero = r.borders[0];
1994 XGCValues values;
1996 for (i = 0; i < 3; ++i) {
1997 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1998 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2001 for (i = 0; i < 4; ++i) {
2002 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2005 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2009 /* Load the colors in our GCs */
2010 for (i = 0; i < 3; ++i) {
2011 XSetForeground(r.d, r.fgs[i], fgs[i]);
2012 XSetForeground(r.d, r.bgs[i], bgs[i]);
2015 for (i = 0; i < 4; ++i) {
2016 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2017 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2018 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2019 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2022 if (load_font(&r, fontname) == -1)
2023 status = ERR;
2025 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2027 for (i = 0; i < 3; ++i) {
2028 rgba_t c;
2029 XRenderColor xrcolor;
2031 c = *(rgba_t *)&fgs[i];
2032 xrcolor.red = EXPANDBITS(c.rgba.r);
2033 xrcolor.green = EXPANDBITS(c.rgba.g);
2034 xrcolor.blue = EXPANDBITS(c.rgba.b);
2035 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2036 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2039 /* compute prompt dimensions */
2040 ps1extents(&r);
2042 xim_init(&r, &xdb);
2044 #ifdef __OpenBSD__
2045 if (pledge("stdio", "") == -1)
2046 err(1, "pledge");
2047 #endif
2049 /* Cache text height */
2050 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2052 /* Draw the window for the first time */
2053 draw(&r, text, cs);
2055 /* Main loop */
2056 while (status == LOOPING || status == OK_LOOP) {
2057 status = loop(&r, &text, &textlen, cs, lines, vlines);
2059 if (status != ERR)
2060 printf("%s\n", text);
2062 if (!r.multiple_select && status == OK_LOOP)
2063 status = OK;
2066 XUngrabKeyboard(r.d, CurrentTime);
2068 for (i = 0; i < 3; ++i)
2069 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2071 for (i = 0; i < 3; ++i) {
2072 XFreeGC(r.d, r.fgs[i]);
2073 XFreeGC(r.d, r.bgs[i]);
2076 for (i = 0; i < 4; ++i) {
2077 XFreeGC(r.d, r.borders_bg[i]);
2078 XFreeGC(r.d, r.p_borders_bg[i]);
2079 XFreeGC(r.d, r.c_borders_bg[i]);
2080 XFreeGC(r.d, r.ch_borders_bg[i]);
2083 XDestroyIC(r.xic);
2084 XCloseIM(r.xim);
2086 for (i = 0; i < 3; ++i)
2087 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2088 XftFontClose(r.d, r.font);
2089 XftDrawDestroy(r.xftdraw);
2091 free(r.ps1);
2092 free(fontname);
2093 free(text);
2095 free(lines);
2096 free(vlines);
2097 compls_delete(cs);
2099 XFreeColormap(r.d, cmap);
2101 XDestroyWindow(r.d, r.w);
2102 XCloseDisplay(r.d);
2104 return status != OK;