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 char *t, *dup;
465 if (str == NULL || *str == '\0')
466 return NULL;
468 if ((dup = strdup(str)) == NULL)
469 return NULL;
471 for (t = dup; *t; ++t) {
472 if (*t == ' ')
473 *t = 'n';
476 return dup;
479 int
480 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
482 GC *border_color, bg;
483 int *padding, *borders;
484 int ret = 0, inner_width, inner_height, x;
486 switch (t) {
487 case PROMPT:
488 border_color = r->p_borders_bg;
489 padding = r->p_padding;
490 borders = r->p_borders;
491 bg = r->bgs[0];
492 break;
493 case COMPL:
494 border_color = r->c_borders_bg;
495 padding = r->c_padding;
496 borders = r->c_borders;
497 bg = r->bgs[1];
498 break;
499 case COMPL_HIGH:
500 border_color = r->ch_borders_bg;
501 padding = r->ch_padding;
502 borders = r->ch_borders;
503 bg = r->bgs[2];
504 break;
507 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
509 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
510 inner_height = padding[0] + r->text_height + padding[2];
512 /* Border top */
513 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
515 /* Border right */
516 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
517 borders[1], ret);
519 /* Border bottom */
520 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
521 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
523 /* Border left */
524 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
526 /* bg */
527 x = r->x_zero + borders[3];
528 y += borders[0];
529 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
531 /* content */
532 y += padding[0] + r->text_height;
533 x += padding[3];
534 if (prefix != NULL) {
535 draw_string(prefix, strlen(prefix), x, y, r, t);
536 x += prefix_width;
538 draw_string(text, strlen(text), x, y, r, t);
540 return ret;
543 int
544 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
546 GC *border_color, bg;
547 int *padding, *borders;
548 int ret = 0, inner_width, inner_height, y, text_width;
550 switch (t) {
551 case PROMPT:
552 border_color = r->p_borders_bg;
553 padding = r->p_padding;
554 borders = r->p_borders;
555 bg = r->bgs[0];
556 break;
557 case COMPL:
558 border_color = r->c_borders_bg;
559 padding = r->c_padding;
560 borders = r->c_borders;
561 bg = r->bgs[1];
562 break;
563 case COMPL_HIGH:
564 border_color = r->ch_borders_bg;
565 padding = r->ch_padding;
566 borders = r->ch_borders;
567 bg = r->bgs[2];
568 break;
571 if (padding[0] < 0 || padding[2] < 0)
572 padding[0] = padding[2]
573 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
575 /* If they are still lesser than 0, set 'em to 0 */
576 if (padding[0] < 0 || padding[2] < 0)
577 padding[0] = padding[2] = 0;
579 /* Get the text width */
580 text_extents(text, strlen(text), r, &text_width, NULL);
581 if (prefix != NULL)
582 text_width += prefix_width;
584 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
586 inner_width = padding[3] + text_width + padding[1];
587 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
589 /* Border top */
590 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
592 /* Border right */
593 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
594 borders[1], INNER_HEIGHT(r));
596 /* Border bottom */
597 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
598 ret, borders[2]);
600 /* Border left */
601 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
603 /* bg */
604 x += borders[3];
605 y = r->y_zero + borders[0];
606 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
608 /* content */
609 y += padding[0] + r->text_height;
610 x += padding[3];
611 if (prefix != NULL) {
612 draw_string(prefix, strlen(prefix), x, y, r, t);
613 x += prefix_width;
615 draw_string(text, strlen(text), x, y, r, t);
617 return ret;
620 /* ,-----------------------------------------------------------------, */
621 /* | 20 char text | completion | completion | completion | compl | */
622 /* `-----------------------------------------------------------------' */
623 void
624 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
626 size_t i;
627 int x = r->x_zero;
629 /* Draw the prompt */
630 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
632 for (i = r->offset; i < cs->length; ++i) {
633 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
635 cs->completions[i].offset = x;
637 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
639 if (x > INNER_WIDTH(r))
640 break;
643 for (i += 1; i < cs->length; ++i)
644 cs->completions[i].offset = -1;
647 /* ,-----------------------------------------------------------------, */
648 /* | prompt | */
649 /* |-----------------------------------------------------------------| */
650 /* | completion | */
651 /* |-----------------------------------------------------------------| */
652 /* | completion | */
653 /* `-----------------------------------------------------------------' */
654 void
655 draw_vertically(struct rendering *r, char *text, struct completions *cs)
657 size_t i;
658 int y = r->y_zero;
660 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
662 for (i = r->offset; i < cs->length; ++i) {
663 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
665 cs->completions[i].offset = y;
667 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
669 if (y > INNER_HEIGHT(r))
670 break;
673 for (i += 1; i < cs->length; ++i)
674 cs->completions[i].offset = -1;
677 void
678 draw(struct rendering *r, char *text, struct completions *cs)
680 /* Draw the background */
681 XFillRectangle(
682 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
684 /* Draw the contents */
685 if (r->horizontal_layout)
686 draw_horizontally(r, text, cs);
687 else
688 draw_vertically(r, text, cs);
690 /* Draw the borders */
691 if (r->borders[0] != 0)
692 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
694 if (r->borders[1] != 0)
695 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
696 r->borders[1], r->height);
698 if (r->borders[2] != 0)
699 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
700 r->borders[2]);
702 if (r->borders[3] != 0)
703 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
705 /* render! */
706 XFlush(r->d);
709 /* Set some WM stuff */
710 void
711 set_win_atoms_hints(Display *d, Window w, int width, int height)
713 Atom type;
714 XClassHint *class_hint;
715 XSizeHints *size_hint;
717 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
718 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
719 32, PropModeReplace, (unsigned char *)&type, 1);
721 /* some window managers honor this properties */
722 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
723 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
724 PropModeReplace, (unsigned char *)&type, 1);
726 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
727 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
728 PropModeAppend, (unsigned char *)&type, 1);
730 /* Setting window hints */
731 class_hint = XAllocClassHint();
732 if (class_hint == NULL) {
733 fprintf(stderr, "Could not allocate memory for class hint\n");
734 exit(EX_UNAVAILABLE);
737 class_hint->res_name = RESNAME;
738 class_hint->res_class = RESCLASS;
739 XSetClassHint(d, w, class_hint);
740 XFree(class_hint);
742 size_hint = XAllocSizeHints();
743 if (size_hint == NULL) {
744 fprintf(stderr, "Could not allocate memory for size hint\n");
745 exit(EX_UNAVAILABLE);
748 size_hint->flags = PMinSize | PBaseSize;
749 size_hint->min_width = width;
750 size_hint->base_width = width;
751 size_hint->min_height = height;
752 size_hint->base_height = height;
754 XFlush(d);
757 /* Get the width and height of the window `w' */
758 void
759 get_wh(Display *d, Window *w, int *width, int *height)
761 XWindowAttributes win_attr;
763 XGetWindowAttributes(d, *w, &win_attr);
764 *height = win_attr.height;
765 *width = win_attr.width;
768 int
769 grabfocus(Display *d, Window w)
771 int i;
772 for (i = 0; i < 100; ++i) {
773 Window focuswin;
774 int revert_to_win;
776 XGetInputFocus(d, &focuswin, &revert_to_win);
778 if (focuswin == w)
779 return 1;
781 XSetInputFocus(d, w, RevertToParent, CurrentTime);
782 usleep(1000);
784 return 0;
787 /*
788 * I know this may seem a little hackish BUT is the only way I managed
789 * to actually grab that goddam keyboard. Only one call to
790 * XGrabKeyboard does not always end up with the keyboard grabbed!
791 */
792 int
793 take_keyboard(Display *d, Window w)
795 int i;
796 for (i = 0; i < 100; i++) {
797 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
798 == GrabSuccess)
799 return 1;
800 usleep(1000);
802 fprintf(stderr, "Cannot grab keyboard\n");
803 return 0;
806 unsigned long
807 parse_color(const char *str, const char *def)
809 size_t len;
810 rgba_t tmp;
811 char *ep;
813 if (str == NULL)
814 goto invc;
816 len = strlen(str);
818 /* +1 for the # ath the start */
819 if (*str != '#' || len > 9 || len < 4)
820 goto invc;
821 ++str; /* skip the # */
823 errno = 0;
824 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
826 if (errno)
827 goto invc;
829 switch (len - 1) {
830 case 3:
831 /* expand #rgb -> #rrggbb */
832 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
833 | (tmp.v & 0x00f) * 0x0011;
834 case 6:
835 /* assume 0xff opacity */
836 tmp.rgba.a = 0xff;
837 break;
838 } /* colors in #aarrggbb need no adjustments */
840 /* premultiply the alpha */
841 if (tmp.rgba.a) {
842 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
843 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
844 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
845 return tmp.v;
848 return 0U;
850 invc:
851 fprintf(stderr, "Invalid color: \"%s\".\n", str);
852 if (def != NULL)
853 return parse_color(def, NULL);
854 else
855 return 0U;
858 /*
859 * Given a string try to parse it as a number or return `def'.
860 */
861 int
862 parse_integer(const char *str, int def)
864 const char *errstr;
865 int i;
867 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
868 if (errstr != NULL) {
869 warnx("'%s' is %s; using %d as default", str, errstr, def);
870 return def;
873 return i;
876 /* Like parse_integer but recognize the percentages (i.e. strings ending with
877 * `%') */
878 int
879 parse_int_with_percentage(const char *str, int default_value, int max)
881 int len = strlen(str);
883 if (len > 0 && str[len - 1] == '%') {
884 int val;
885 char *cpy;
887 if ((cpy = strdup(str)) == NULL)
888 err(1, "strdup");
890 cpy[len - 1] = '\0';
891 val = parse_integer(cpy, default_value);
892 free(cpy);
893 return val * max / 100;
896 return parse_integer(str, default_value);
899 void
900 get_mouse_coords(Display *d, int *x, int *y)
902 Window w, root;
903 int i;
904 unsigned int u;
906 *x = *y = 0;
907 root = DefaultRootWindow(d);
909 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
910 for (i = 0; i < ScreenCount(d); ++i) {
911 if (root == RootWindow(d, i))
912 break;
917 /*
918 * Like parse_int_with_percentage but understands some special values:
919 * - middle that is (max-self)/2
920 * - center = middle
921 * - start that is 0
922 * - end that is (max-self)
923 * - mx x coordinate of the mouse
924 * - my y coordinate of the mouse
925 */
926 int
927 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
929 if (!strcmp(str, "start"))
930 return 0;
931 if (!strcmp(str, "middle") || !strcmp(str, "center"))
932 return (max - self) / 2;
933 if (!strcmp(str, "end"))
934 return max - self;
935 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
936 int x, y;
938 get_mouse_coords(d, &x, &y);
939 if (!strcmp(str, "mx"))
940 return x - 1;
941 else
942 return y - 1;
944 return parse_int_with_percentage(str, default_value, max);
947 /* Parse a string like a CSS value. */
948 /* TODO: harden a bit this function */
949 char **
950 parse_csslike(const char *str)
952 int i, j;
953 char *s, *token, **ret;
954 short any_null;
956 s = strdup(str);
957 if (s == NULL)
958 return NULL;
960 ret = malloc(4 * sizeof(char *));
961 if (ret == NULL) {
962 free(s);
963 return NULL;
966 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
967 ret[i] = strdup(token);
969 if (i == 1)
970 for (j = 1; j < 4; j++)
971 ret[j] = strdup(ret[0]);
973 if (i == 2) {
974 ret[2] = strdup(ret[0]);
975 ret[3] = strdup(ret[1]);
978 if (i == 3)
979 ret[3] = strdup(ret[1]);
981 /* before we didn't check for the return type of strdup, here we will
982 */
984 any_null = 0;
985 for (i = 0; i < 4; ++i)
986 any_null = ret[i] == NULL || any_null;
988 if (any_null)
989 for (i = 0; i < 4; ++i)
990 if (ret[i] != NULL)
991 free(ret[i]);
993 if (i == 0 || any_null) {
994 free(s);
995 free(ret);
996 return NULL;
999 return ret;
1003 * Given an event, try to understand what the users wants. If the
1004 * return value is ADD_CHAR then `input' is a pointer to a string that
1005 * will need to be free'ed later.
1007 enum action
1008 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1010 char str[SYM_BUF_SIZE] = { 0 };
1011 Status s;
1013 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1014 return DEL_CHAR;
1016 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1017 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1019 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1020 return CONFIRM;
1022 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1023 return EXIT;
1025 /* Try to read what key was pressed */
1026 s = 0;
1027 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1028 if (s == XBufferOverflow) {
1029 fprintf(stderr,
1030 "Buffer overflow when trying to create keyboard "
1031 "symbol map.\n");
1032 return EXIT;
1035 if (ev->state & ControlMask) {
1036 if (!strcmp(str, "")) /* C-u */
1037 return DEL_LINE;
1038 if (!strcmp(str, "")) /* C-w */
1039 return DEL_WORD;
1040 if (!strcmp(str, "")) /* C-h */
1041 return DEL_CHAR;
1042 if (!strcmp(str, "\r")) /* C-m */
1043 return CONFIRM_CONTINUE;
1044 if (!strcmp(str, "")) /* C-p */
1045 return PREV_COMPL;
1046 if (!strcmp(str, "")) /* C-n */
1047 return NEXT_COMPL;
1048 if (!strcmp(str, "")) /* C-c */
1049 return EXIT;
1050 if (!strcmp(str, "\t")) /* C-i */
1051 return TOGGLE_FIRST_SELECTED;
1054 *input = strdup(str);
1055 if (*input == NULL) {
1056 fprintf(stderr, "Error while allocating memory for key.\n");
1057 return EXIT;
1060 return ADD_CHAR;
1063 void
1064 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1066 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1067 /* if there is something selected expand it and return */
1068 int index = cs->selected == -1 ? 0 : cs->selected;
1069 struct completion *c = cs->completions;
1070 char *t;
1072 while (1) {
1073 if (index == 0)
1074 break;
1075 c++;
1076 index--;
1079 t = c->rcompletion;
1080 free(*text);
1081 *text = strdup(t);
1083 if (*text == NULL) {
1084 fprintf(stderr, "Memory allocation error\n");
1085 *status = ERR;
1088 *textlen = strlen(*text);
1089 return;
1092 if (!r->free_text) /* cannot accept arbitrary text */
1093 *status = LOOPING;
1096 /* cs: completion list
1097 * offset: the offset of the click
1098 * first: the first (rendered) item
1099 * def: the default action
1101 enum action
1102 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1104 ssize_t selected = first;
1105 int set = 0;
1107 if (cs->length == 0)
1108 return NO_OP;
1110 if (offset < cs->completions[selected].offset)
1111 return EXIT;
1113 /* skip the first entry */
1114 for (selected += 1; selected < cs->length; ++selected) {
1115 if (cs->completions[selected].offset == -1)
1116 break;
1118 if (offset < cs->completions[selected].offset) {
1119 cs->selected = selected - 1;
1120 set = 1;
1121 break;
1125 if (!set)
1126 cs->selected = selected - 1;
1128 return def;
1131 enum action
1132 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1134 size_t off;
1136 if (r->horizontal_layout)
1137 off = e->x;
1138 else
1139 off = e->y;
1141 switch (e->button) {
1142 case Button1:
1143 return select_clicked(cs, off, r->offset, CONFIRM);
1145 case Button3:
1146 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1148 case Button4:
1149 return SCROLL_UP;
1151 case Button5:
1152 return SCROLL_DOWN;
1155 return NO_OP;
1158 /* event loop */
1159 enum state
1160 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1161 char **vlines)
1163 enum state status = LOOPING;
1165 while (status == LOOPING) {
1166 XEvent e;
1167 XNextEvent(r->d, &e);
1169 if (XFilterEvent(&e, r->w))
1170 continue;
1172 switch (e.type) {
1173 case KeymapNotify:
1174 XRefreshKeyboardMapping(&e.xmapping);
1175 break;
1177 case FocusIn:
1178 /* Re-grab focus */
1179 if (e.xfocus.window != r->w)
1180 grabfocus(r->d, r->w);
1181 break;
1183 case VisibilityNotify:
1184 if (e.xvisibility.state != VisibilityUnobscured)
1185 XRaiseWindow(r->d, r->w);
1186 break;
1188 case MapNotify:
1189 get_wh(r->d, &r->w, &r->width, &r->height);
1190 draw(r, *text, cs);
1191 break;
1193 case KeyPress:
1194 case ButtonPress: {
1195 enum action a;
1196 char *input = NULL;
1198 if (e.type == KeyPress)
1199 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1200 else
1201 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1203 switch (a) {
1204 case NO_OP:
1205 break;
1207 case EXIT:
1208 status = ERR;
1209 break;
1211 case CONFIRM: {
1212 status = OK;
1213 confirm(&status, r, cs, text, textlen);
1214 break;
1217 case CONFIRM_CONTINUE: {
1218 status = OK_LOOP;
1219 confirm(&status, r, cs, text, textlen);
1220 break;
1223 case PREV_COMPL: {
1224 complete(cs, r->first_selected, 1, text, textlen, &status);
1225 r->offset = cs->selected;
1226 break;
1229 case NEXT_COMPL: {
1230 complete(cs, r->first_selected, 0, text, textlen, &status);
1231 r->offset = cs->selected;
1232 break;
1235 case DEL_CHAR:
1236 popc(*text);
1237 update_completions(cs, *text, lines, vlines, r->first_selected);
1238 r->offset = 0;
1239 break;
1241 case DEL_WORD: {
1242 popw(*text);
1243 update_completions(cs, *text, lines, vlines, r->first_selected);
1244 break;
1247 case DEL_LINE: {
1248 int i;
1249 for (i = 0; i < *textlen; ++i)
1250 *(*text + i) = 0;
1251 update_completions(cs, *text, lines, vlines, r->first_selected);
1252 r->offset = 0;
1253 break;
1256 case ADD_CHAR: {
1257 int str_len, i;
1259 str_len = strlen(input);
1262 * sometimes a strange key is pressed
1263 * i.e. ctrl alone), so input will be
1264 * empty. Don't need to update
1265 * completion in that case
1267 if (str_len == 0)
1268 break;
1270 for (i = 0; i < str_len; ++i) {
1271 *textlen = pushc(text, *textlen, input[i]);
1272 if (*textlen == -1) {
1273 fprintf(stderr,
1274 "Memory allocation "
1275 "error\n");
1276 status = ERR;
1277 break;
1281 if (status != ERR) {
1282 update_completions(
1283 cs, *text, lines, vlines, r->first_selected);
1284 free(input);
1287 r->offset = 0;
1288 break;
1291 case TOGGLE_FIRST_SELECTED:
1292 r->first_selected = !r->first_selected;
1293 if (r->first_selected && cs->selected < 0)
1294 cs->selected = 0;
1295 if (!r->first_selected && cs->selected == 0)
1296 cs->selected = -1;
1297 break;
1299 case SCROLL_DOWN:
1300 r->offset = MIN(r->offset + 1, cs->length - 1);
1301 break;
1303 case SCROLL_UP:
1304 r->offset = MAX((ssize_t)r->offset - 1, 0);
1305 break;
1310 draw(r, *text, cs);
1313 return status;
1316 int
1317 load_font(struct rendering *r, const char *fontname)
1319 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1320 return 0;
1323 void
1324 xim_init(struct rendering *r, XrmDatabase *xdb)
1326 XIMStyle best_match_style;
1327 XIMStyles *xis;
1328 int i;
1330 /* Open the X input method */
1331 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1332 err(1, "XOpenIM");
1334 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1335 fprintf(stderr, "Input Styles could not be retrieved\n");
1336 exit(EX_UNAVAILABLE);
1339 best_match_style = 0;
1340 for (i = 0; i < xis->count_styles; ++i) {
1341 XIMStyle ts = xis->supported_styles[i];
1342 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1343 best_match_style = ts;
1344 break;
1347 XFree(xis);
1349 if (!best_match_style)
1350 fprintf(stderr, "No matching input style could be determined\n");
1352 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1353 XNFocusWindow, r->w, NULL);
1354 if (r->xic == NULL)
1355 err(1, "XCreateIC");
1358 void
1359 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1360 int y, int ox, int oy, unsigned long background_pixel)
1362 XSetWindowAttributes attr;
1364 /* Create the window */
1365 attr.colormap = cmap;
1366 attr.override_redirect = 1;
1367 attr.border_pixel = 0;
1368 attr.background_pixel = background_pixel;
1369 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1370 | ButtonPress | VisibilityChangeMask;
1372 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1373 vinfo.depth, InputOutput, vinfo.visual,
1374 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1377 void
1378 ps1extents(struct rendering *r)
1380 char *dup;
1381 dup = strdupn(r->ps1);
1382 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1383 free(dup);
1386 void
1387 usage(char *prgname)
1389 fprintf(stderr,
1390 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1391 " [-d separator] [-e window] [-f font] [-G color] [-g "
1392 "size]\n"
1393 " [-H height] [-I color] [-i size] [-J color] [-j "
1394 "size] [-l layout]\n"
1395 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1396 "color]\n"
1397 " [-t color] [-W width] [-x coord] [-y coord]\n",
1398 prgname);
1401 int
1402 main(int argc, char **argv)
1404 struct completions *cs;
1405 struct rendering r;
1406 XVisualInfo vinfo;
1407 Colormap cmap;
1408 size_t nlines, i;
1409 Window parent_window;
1410 XrmDatabase xdb;
1411 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1412 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1413 ch_borders_bg[4]; /* N E S W */
1414 enum state status;
1415 int ch;
1416 int offset_x, offset_y, x, y;
1417 int textlen, d_width, d_height;
1418 short embed;
1419 char *sep, *parent_window_id;
1420 char **lines, **vlines;
1421 char *fontname, *text, *xrm;
1423 sep = NULL;
1424 parent_window_id = NULL;
1426 r.first_selected = 0;
1427 r.free_text = 1;
1428 r.multiple_select = 0;
1429 r.offset = 0;
1431 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1432 switch (ch) {
1433 case 'h': /* help */
1434 usage(*argv);
1435 return 0;
1436 case 'v': /* version */
1437 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1438 return 0;
1439 case 'e': /* embed */
1440 if ((parent_window_id = strdup(optarg)) == NULL)
1441 err(1, "strdup");
1442 break;
1443 case 'd':
1444 if ((sep = strdup(optarg)) == NULL)
1445 err(1, "strdup");
1446 break;
1447 case 'A':
1448 r.free_text = 0;
1449 break;
1450 case 'm':
1451 r.multiple_select = 1;
1452 break;
1453 default:
1454 break;
1458 lines = readlines(&nlines);
1460 vlines = NULL;
1461 if (sep != NULL) {
1462 int l;
1463 l = strlen(sep);
1464 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1465 err(1, "calloc");
1467 for (i = 0; i < nlines; i++) {
1468 char *t;
1469 t = strstr(lines[i], sep);
1470 if (t == NULL)
1471 vlines[i] = lines[i];
1472 else
1473 vlines[i] = t + l;
1477 setlocale(LC_ALL, getenv("LANG"));
1479 status = LOOPING;
1481 /* where the monitor start (used only with xinerama) */
1482 offset_x = offset_y = 0;
1484 /* default width and height */
1485 r.width = 400;
1486 r.height = 20;
1488 /* default position on the screen */
1489 x = y = 0;
1491 for (i = 0; i < 4; ++i) {
1492 /* default paddings */
1493 r.p_padding[i] = 10;
1494 r.c_padding[i] = 10;
1495 r.ch_padding[i] = 10;
1497 /* default borders */
1498 r.borders[i] = 0;
1499 r.p_borders[i] = 0;
1500 r.c_borders[i] = 0;
1501 r.ch_borders[i] = 0;
1504 /* the prompt. We duplicate the string so later is easy to
1505 * free (in the case it's been overwritten by the user) */
1506 if ((r.ps1 = strdup("$ ")) == NULL)
1507 err(1, "strdup");
1509 /* same for the font name */
1510 if ((fontname = strdup(DEFFONT)) == NULL)
1511 err(1, "strdup");
1513 textlen = 10;
1514 if ((text = malloc(textlen * sizeof(char))) == NULL)
1515 err(1, "malloc");
1517 /* struct completions *cs = filter(text, lines); */
1518 if ((cs = compls_new(nlines)) == NULL)
1519 err(1, "compls_new");
1521 /* start talking to xorg */
1522 r.d = XOpenDisplay(NULL);
1523 if (r.d == NULL) {
1524 fprintf(stderr, "Could not open display!\n");
1525 return EX_UNAVAILABLE;
1528 embed = 1;
1529 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1530 parent_window = DefaultRootWindow(r.d);
1531 embed = 0;
1534 /* get display size */
1535 get_wh(r.d, &parent_window, &d_width, &d_height);
1537 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1538 XineramaScreenInfo *info;
1539 Window rr;
1540 Window root;
1541 int number_of_screens, monitors, i;
1542 int root_x, root_y, win_x, win_y;
1543 unsigned int mask;
1544 short res;
1546 number_of_screens = XScreenCount(r.d);
1547 for (i = 0; i < number_of_screens; ++i) {
1548 root = XRootWindow(r.d, i);
1549 res = XQueryPointer(
1550 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1551 if (res)
1552 break;
1555 if (!res) {
1556 fprintf(stderr, "No mouse found.\n");
1557 root_x = 0;
1558 root_y = 0;
1561 /* Now find in which monitor the mice is */
1562 info = XineramaQueryScreens(r.d, &monitors);
1563 if (info) {
1564 for (i = 0; i < monitors; ++i) {
1565 if (info[i].x_org <= root_x
1566 && root_x <= (info[i].x_org + info[i].width)
1567 && info[i].y_org <= root_y
1568 && root_y <= (info[i].y_org + info[i].height)) {
1569 offset_x = info[i].x_org;
1570 offset_y = info[i].y_org;
1571 d_width = info[i].width;
1572 d_height = info[i].height;
1573 break;
1577 XFree(info);
1580 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1581 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1583 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1584 fgs[2] = parse_color("#000", NULL);
1586 bgs[0] = bgs[1] = parse_color("#000", NULL);
1587 bgs[2] = parse_color("#fff", NULL);
1589 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1591 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1592 = parse_color("#000", NULL);
1593 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1594 = parse_color("#000", NULL);
1595 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1596 = parse_color("#000", NULL);
1598 r.horizontal_layout = 1;
1600 /* Read the resources */
1601 XrmInitialize();
1602 xrm = XResourceManagerString(r.d);
1603 xdb = NULL;
1604 if (xrm != NULL) {
1605 XrmValue value;
1606 char *datatype[20];
1608 xdb = XrmGetStringDatabase(xrm);
1610 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1611 free(fontname);
1612 if ((fontname = strdup(value.addr)) == NULL)
1613 err(1, "strdup");
1614 } else {
1615 fprintf(stderr, "no font defined, using %s\n", fontname);
1618 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1619 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1620 else
1621 fprintf(stderr, "no layout defined, using horizontal\n");
1623 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1624 free(r.ps1);
1625 r.ps1 = normalize_str(value.addr);
1626 } else {
1627 fprintf(stderr,
1628 "no prompt defined, using \"%s\" as "
1629 "default\n",
1630 r.ps1);
1633 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1634 char **sizes;
1635 sizes = parse_csslike(value.addr);
1636 if (sizes != NULL)
1637 for (i = 0; i < 4; ++i)
1638 r.p_borders[i] = parse_integer(sizes[i], 0);
1639 else
1640 fprintf(stderr,
1641 "error while parsing "
1642 "MyMenu.prompt.border.size");
1645 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1646 char **colors;
1647 colors = parse_csslike(value.addr);
1648 if (colors != NULL)
1649 for (i = 0; i < 4; ++i)
1650 p_borders_bg[i] = parse_color(colors[i], "#000");
1651 else
1652 fprintf(stderr,
1653 "error while parsing "
1654 "MyMenu.prompt.border.color");
1657 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1658 char **colors;
1659 colors = parse_csslike(value.addr);
1660 if (colors != NULL)
1661 for (i = 0; i < 4; ++i)
1662 r.p_padding[i] = parse_integer(colors[i], 0);
1663 else
1664 fprintf(stderr,
1665 "error while parsing "
1666 "MyMenu.prompt.padding");
1669 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1670 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1671 else
1672 fprintf(stderr, "no width defined, using %d\n", r.width);
1674 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1675 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1676 else
1677 fprintf(stderr, "no height defined, using %d\n", r.height);
1679 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1680 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1682 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1683 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1685 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1686 char **borders;
1687 borders = parse_csslike(value.addr);
1688 if (borders != NULL)
1689 for (i = 0; i < 4; ++i)
1690 r.borders[i] = parse_int_with_percentage(
1691 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1692 else
1693 fprintf(stderr,
1694 "error while parsing "
1695 "MyMenu.border.size\n");
1698 /* Prompt */
1699 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1700 fgs[0] = parse_color(value.addr, "#fff");
1702 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1703 bgs[0] = parse_color(value.addr, "#000");
1705 /* Completions */
1706 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1707 fgs[1] = parse_color(value.addr, "#fff");
1709 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1710 bgs[1] = parse_color(value.addr, "#000");
1712 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1713 char **paddings;
1714 paddings = parse_csslike(value.addr);
1715 if (paddings != NULL)
1716 for (i = 0; i < 4; ++i)
1717 r.c_padding[i] = parse_integer(paddings[i], 0);
1718 else
1719 fprintf(stderr,
1720 "Error while parsing "
1721 "MyMenu.completion.padding");
1724 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1725 char **sizes;
1726 sizes = parse_csslike(value.addr);
1727 if (sizes != NULL)
1728 for (i = 0; i < 4; ++i)
1729 r.c_borders[i] = parse_integer(sizes[i], 0);
1730 else
1731 fprintf(stderr,
1732 "Error while parsing "
1733 "MyMenu.completion.border.size");
1736 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1737 char **sizes;
1738 sizes = parse_csslike(value.addr);
1739 if (sizes != NULL)
1740 for (i = 0; i < 4; ++i)
1741 c_borders_bg[i] = parse_color(sizes[i], "#000");
1742 else
1743 fprintf(stderr,
1744 "Error while parsing "
1745 "MyMenu.completion.border.color");
1748 /* Completion Highlighted */
1749 if (XrmGetResource(
1750 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1751 fgs[2] = parse_color(value.addr, "#000");
1753 if (XrmGetResource(
1754 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1755 bgs[2] = parse_color(value.addr, "#fff");
1757 if (XrmGetResource(
1758 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1759 char **paddings;
1760 paddings = parse_csslike(value.addr);
1761 if (paddings != NULL)
1762 for (i = 0; i < 4; ++i)
1763 r.ch_padding[i] = parse_integer(paddings[i], 0);
1764 else
1765 fprintf(stderr,
1766 "Error while parsing "
1767 "MyMenu.completion_highlighted."
1768 "padding");
1771 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1772 &value)) {
1773 char **sizes;
1774 sizes = parse_csslike(value.addr);
1775 if (sizes != NULL)
1776 for (i = 0; i < 4; ++i)
1777 r.ch_borders[i] = parse_integer(sizes[i], 0);
1778 else
1779 fprintf(stderr,
1780 "Error while parsing "
1781 "MyMenu.completion_highlighted."
1782 "border.size");
1785 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1786 &value)) {
1787 char **colors;
1788 colors = parse_csslike(value.addr);
1789 if (colors != NULL)
1790 for (i = 0; i < 4; ++i)
1791 ch_borders_bg[i] = parse_color(colors[i], "#000");
1792 else
1793 fprintf(stderr,
1794 "Error while parsing "
1795 "MyMenu.completion_highlighted."
1796 "border.color");
1799 /* Border */
1800 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1801 char **colors;
1802 colors = parse_csslike(value.addr);
1803 if (colors != NULL)
1804 for (i = 0; i < 4; ++i)
1805 borders_bg[i] = parse_color(colors[i], "#000");
1806 else
1807 fprintf(stderr,
1808 "error while parsing "
1809 "MyMenu.border.color\n");
1813 /* Second round of args parsing */
1814 optind = 0; /* reset the option index */
1815 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1816 switch (ch) {
1817 case 'a':
1818 r.first_selected = 1;
1819 break;
1820 case 'A':
1821 /* free_text -- already catched */
1822 case 'd':
1823 /* separator -- this case was already catched */
1824 case 'e':
1825 /* embedding mymenu this case was already catched. */
1826 case 'm':
1827 /* multiple selection this case was already catched.
1829 break;
1830 case 'p': {
1831 char *newprompt;
1832 newprompt = strdup(optarg);
1833 if (newprompt != NULL) {
1834 free(r.ps1);
1835 r.ps1 = newprompt;
1837 break;
1839 case 'x':
1840 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1841 break;
1842 case 'y':
1843 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1844 break;
1845 case 'P': {
1846 char **paddings;
1847 if ((paddings = parse_csslike(optarg)) != NULL)
1848 for (i = 0; i < 4; ++i)
1849 r.p_padding[i] = parse_integer(paddings[i], 0);
1850 break;
1852 case 'G': {
1853 char **colors;
1854 if ((colors = parse_csslike(optarg)) != NULL)
1855 for (i = 0; i < 4; ++i)
1856 p_borders_bg[i] = parse_color(colors[i], "#000");
1857 break;
1859 case 'g': {
1860 char **sizes;
1861 if ((sizes = parse_csslike(optarg)) != NULL)
1862 for (i = 0; i < 4; ++i)
1863 r.p_borders[i] = parse_integer(sizes[i], 0);
1864 break;
1866 case 'I': {
1867 char **colors;
1868 if ((colors = parse_csslike(optarg)) != NULL)
1869 for (i = 0; i < 4; ++i)
1870 c_borders_bg[i] = parse_color(colors[i], "#000");
1871 break;
1873 case 'i': {
1874 char **sizes;
1875 if ((sizes = parse_csslike(optarg)) != NULL)
1876 for (i = 0; i < 4; ++i)
1877 r.c_borders[i] = parse_integer(sizes[i], 0);
1878 break;
1880 case 'J': {
1881 char **colors;
1882 if ((colors = parse_csslike(optarg)) != NULL)
1883 for (i = 0; i < 4; ++i)
1884 ch_borders_bg[i] = parse_color(colors[i], "#000");
1885 break;
1887 case 'j': {
1888 char **sizes;
1889 if ((sizes = parse_csslike(optarg)) != NULL)
1890 for (i = 0; i < 4; ++i)
1891 r.ch_borders[i] = parse_integer(sizes[i], 0);
1892 break;
1894 case 'l':
1895 r.horizontal_layout = !strcmp(optarg, "horizontal");
1896 break;
1897 case 'f': {
1898 char *newfont;
1899 if ((newfont = strdup(optarg)) != NULL) {
1900 free(fontname);
1901 fontname = newfont;
1903 break;
1905 case 'W':
1906 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1907 break;
1908 case 'H':
1909 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1910 break;
1911 case 'b': {
1912 char **borders;
1913 if ((borders = parse_csslike(optarg)) != NULL) {
1914 for (i = 0; i < 4; ++i)
1915 r.borders[i] = parse_integer(borders[i], 0);
1916 } else
1917 fprintf(stderr, "Error parsing b option\n");
1918 break;
1920 case 'B': {
1921 char **colors;
1922 if ((colors = parse_csslike(optarg)) != NULL) {
1923 for (i = 0; i < 4; ++i)
1924 borders_bg[i] = parse_color(colors[i], "#000");
1925 } else
1926 fprintf(stderr, "error while parsing B option\n");
1927 break;
1929 case 't':
1930 fgs[0] = parse_color(optarg, NULL);
1931 break;
1932 case 'T':
1933 bgs[0] = parse_color(optarg, NULL);
1934 break;
1935 case 'c':
1936 fgs[1] = parse_color(optarg, NULL);
1937 break;
1938 case 'C':
1939 bgs[1] = parse_color(optarg, NULL);
1940 break;
1941 case 's':
1942 fgs[2] = parse_color(optarg, NULL);
1943 break;
1944 case 'S':
1945 bgs[2] = parse_color(optarg, NULL);
1946 break;
1947 default:
1948 fprintf(stderr, "Unrecognized option %c\n", ch);
1949 status = ERR;
1950 break;
1954 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1955 fprintf(stderr, "height, width, x or y are lesser than 0.");
1956 status = ERR;
1959 /* since only now we know if the first should be selected,
1960 * update the completion here */
1961 update_completions(cs, text, lines, vlines, r.first_selected);
1963 /* update the prompt lenght, only now we surely know the length of it
1965 r.ps1len = strlen(r.ps1);
1967 /* Create the window */
1968 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1969 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1970 XMapRaised(r.d, r.w);
1972 /* If embed, listen for other events as well */
1973 if (embed) {
1974 Window *children, parent, root;
1975 unsigned int children_no;
1977 XSelectInput(r.d, parent_window, FocusChangeMask);
1978 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1979 && children) {
1980 for (i = 0; i < children_no && children[i] != r.w; ++i)
1981 XSelectInput(r.d, children[i], FocusChangeMask);
1982 XFree(children);
1984 grabfocus(r.d, r.w);
1987 take_keyboard(r.d, r.w);
1989 r.x_zero = r.borders[3];
1990 r.y_zero = r.borders[0];
1993 XGCValues values;
1995 for (i = 0; i < 3; ++i) {
1996 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1997 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2000 for (i = 0; i < 4; ++i) {
2001 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2002 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2008 /* Load the colors in our GCs */
2009 for (i = 0; i < 3; ++i) {
2010 XSetForeground(r.d, r.fgs[i], fgs[i]);
2011 XSetForeground(r.d, r.bgs[i], bgs[i]);
2014 for (i = 0; i < 4; ++i) {
2015 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2016 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2017 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2018 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2021 if (load_font(&r, fontname) == -1)
2022 status = ERR;
2024 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2026 for (i = 0; i < 3; ++i) {
2027 rgba_t c;
2028 XRenderColor xrcolor;
2030 c = *(rgba_t *)&fgs[i];
2031 xrcolor.red = EXPANDBITS(c.rgba.r);
2032 xrcolor.green = EXPANDBITS(c.rgba.g);
2033 xrcolor.blue = EXPANDBITS(c.rgba.b);
2034 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2035 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2038 /* compute prompt dimensions */
2039 ps1extents(&r);
2041 xim_init(&r, &xdb);
2043 #ifdef __OpenBSD__
2044 if (pledge("stdio", "") == -1)
2045 err(1, "pledge");
2046 #endif
2048 /* Cache text height */
2049 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2051 /* Draw the window for the first time */
2052 draw(&r, text, cs);
2054 /* Main loop */
2055 while (status == LOOPING || status == OK_LOOP) {
2056 status = loop(&r, &text, &textlen, cs, lines, vlines);
2058 if (status != ERR)
2059 printf("%s\n", text);
2061 if (!r.multiple_select && status == OK_LOOP)
2062 status = OK;
2065 XUngrabKeyboard(r.d, CurrentTime);
2067 for (i = 0; i < 3; ++i)
2068 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2070 for (i = 0; i < 3; ++i) {
2071 XFreeGC(r.d, r.fgs[i]);
2072 XFreeGC(r.d, r.bgs[i]);
2075 for (i = 0; i < 4; ++i) {
2076 XFreeGC(r.d, r.borders_bg[i]);
2077 XFreeGC(r.d, r.p_borders_bg[i]);
2078 XFreeGC(r.d, r.c_borders_bg[i]);
2079 XFreeGC(r.d, r.ch_borders_bg[i]);
2082 XDestroyIC(r.xic);
2083 XCloseIM(r.xim);
2085 for (i = 0; i < 3; ++i)
2086 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2087 XftFontClose(r.d, r.font);
2088 XftDrawDestroy(r.xftdraw);
2090 free(r.ps1);
2091 free(fontname);
2092 free(text);
2094 free(lines);
2095 free(vlines);
2096 compls_delete(cs);
2098 XFreeColormap(r.d, cmap);
2100 XDestroyWindow(r.d, r.w);
2101 XCloseDisplay(r.d);
2103 return status != OK;