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 *dup;
466 len = strlen(str);
468 if (str == NULL || len == 0)
469 return NULL;
471 if ((dup = strdup(str)) == NULL)
472 return NULL;
474 for (i = 0; i < len; ++i)
475 if (dup[i] == ' ')
476 dup[i] = 'n';
478 return dup;
481 int
482 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
484 GC *border_color, bg;
485 int *padding, *borders;
486 int ret = 0, inner_width, inner_height, x;
488 switch (t) {
489 case PROMPT:
490 border_color = r->p_borders_bg;
491 padding = r->p_padding;
492 borders = r->p_borders;
493 bg = r->bgs[0];
494 break;
495 case COMPL:
496 border_color = r->c_borders_bg;
497 padding = r->c_padding;
498 borders = r->c_borders;
499 bg = r->bgs[1];
500 break;
501 case COMPL_HIGH:
502 border_color = r->ch_borders_bg;
503 padding = r->ch_padding;
504 borders = r->ch_borders;
505 bg = r->bgs[2];
506 break;
509 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
511 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
512 inner_height = padding[0] + r->text_height + padding[2];
514 /* Border top */
515 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
517 /* Border right */
518 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + INNER_WIDTH(r) - borders[1], y,
519 borders[1], ret);
521 /* Border bottom */
522 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
523 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
525 /* Border left */
526 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
528 /* bg */
529 x = r->x_zero + borders[3];
530 y += borders[0];
531 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
533 /* content */
534 y += padding[0] + r->text_height;
535 x += padding[3];
536 if (prefix != NULL) {
537 draw_string(prefix, strlen(prefix), x, y, r, t);
538 x += prefix_width;
540 draw_string(text, strlen(text), x, y, r, t);
542 return ret;
545 int
546 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
548 GC *border_color, bg;
549 int *padding, *borders;
550 int ret = 0, inner_width, inner_height, y, text_width;
552 switch (t) {
553 case PROMPT:
554 border_color = r->p_borders_bg;
555 padding = r->p_padding;
556 borders = r->p_borders;
557 bg = r->bgs[0];
558 break;
559 case COMPL:
560 border_color = r->c_borders_bg;
561 padding = r->c_padding;
562 borders = r->c_borders;
563 bg = r->bgs[1];
564 break;
565 case COMPL_HIGH:
566 border_color = r->ch_borders_bg;
567 padding = r->ch_padding;
568 borders = r->ch_borders;
569 bg = r->bgs[2];
570 break;
573 if (padding[0] < 0 || padding[2] < 0)
574 padding[0] = padding[2]
575 = (INNER_HEIGHT(r) - borders[0] - borders[2] - r->text_height) / 2;
577 /* If they are still lesser than 0, set 'em to 0 */
578 if (padding[0] < 0 || padding[2] < 0)
579 padding[0] = padding[2] = 0;
581 /* Get the text width */
582 text_extents(text, strlen(text), r, &text_width, NULL);
583 if (prefix != NULL)
584 text_width += prefix_width;
586 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
588 inner_width = padding[3] + text_width + padding[1];
589 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
591 /* Border top */
592 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
594 /* Border right */
595 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
596 borders[1], INNER_HEIGHT(r));
598 /* Border bottom */
599 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + INNER_HEIGHT(r) - borders[2],
600 ret, borders[2]);
602 /* Border left */
603 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], INNER_HEIGHT(r));
605 /* bg */
606 x += borders[3];
607 y = r->y_zero + borders[0];
608 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
610 /* content */
611 y += padding[0] + r->text_height;
612 x += padding[3];
613 if (prefix != NULL) {
614 draw_string(prefix, strlen(prefix), x, y, r, t);
615 x += prefix_width;
617 draw_string(text, strlen(text), x, y, r, t);
619 return ret;
622 /* ,-----------------------------------------------------------------, */
623 /* | 20 char text | completion | completion | completion | compl | */
624 /* `-----------------------------------------------------------------' */
625 void
626 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
628 size_t i;
629 int x = r->x_zero;
631 /* Draw the prompt */
632 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
634 for (i = r->offset; i < cs->length; ++i) {
635 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
637 cs->completions[i].offset = x;
639 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
641 if (x > INNER_WIDTH(r))
642 break;
645 for (i += 1; i < cs->length; ++i)
646 cs->completions[i].offset = -1;
649 /* ,-----------------------------------------------------------------, */
650 /* | prompt | */
651 /* |-----------------------------------------------------------------| */
652 /* | completion | */
653 /* |-----------------------------------------------------------------| */
654 /* | completion | */
655 /* `-----------------------------------------------------------------' */
656 void
657 draw_vertically(struct rendering *r, char *text, struct completions *cs)
659 size_t i;
660 int y = r->y_zero;
662 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
664 for (i = r->offset; i < cs->length; ++i) {
665 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
667 cs->completions[i].offset = y;
669 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
671 if (y > INNER_HEIGHT(r))
672 break;
675 for (i += 1; i < cs->length; ++i)
676 cs->completions[i].offset = -1;
679 void
680 draw(struct rendering *r, char *text, struct completions *cs)
682 /* Draw the background */
683 XFillRectangle(
684 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, INNER_WIDTH(r), INNER_HEIGHT(r));
686 /* Draw the contents */
687 if (r->horizontal_layout)
688 draw_horizontally(r, text, cs);
689 else
690 draw_vertically(r, text, cs);
692 /* Draw the borders */
693 if (r->borders[0] != 0)
694 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
696 if (r->borders[1] != 0)
697 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
698 r->borders[1], r->height);
700 if (r->borders[2] != 0)
701 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
702 r->borders[2]);
704 if (r->borders[3] != 0)
705 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
707 /* render! */
708 XFlush(r->d);
711 /* Set some WM stuff */
712 void
713 set_win_atoms_hints(Display *d, Window w, int width, int height)
715 Atom type;
716 XClassHint *class_hint;
717 XSizeHints *size_hint;
719 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
720 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
721 32, PropModeReplace, (unsigned char *)&type, 1);
723 /* some window managers honor this properties */
724 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
725 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
726 PropModeReplace, (unsigned char *)&type, 1);
728 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
729 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
730 PropModeAppend, (unsigned char *)&type, 1);
732 /* Setting window hints */
733 class_hint = XAllocClassHint();
734 if (class_hint == NULL) {
735 fprintf(stderr, "Could not allocate memory for class hint\n");
736 exit(EX_UNAVAILABLE);
739 class_hint->res_name = RESNAME;
740 class_hint->res_class = RESCLASS;
741 XSetClassHint(d, w, class_hint);
742 XFree(class_hint);
744 size_hint = XAllocSizeHints();
745 if (size_hint == NULL) {
746 fprintf(stderr, "Could not allocate memory for size hint\n");
747 exit(EX_UNAVAILABLE);
750 size_hint->flags = PMinSize | PBaseSize;
751 size_hint->min_width = width;
752 size_hint->base_width = width;
753 size_hint->min_height = height;
754 size_hint->base_height = height;
756 XFlush(d);
759 /* Get the width and height of the window `w' */
760 void
761 get_wh(Display *d, Window *w, int *width, int *height)
763 XWindowAttributes win_attr;
765 XGetWindowAttributes(d, *w, &win_attr);
766 *height = win_attr.height;
767 *width = win_attr.width;
770 int
771 grabfocus(Display *d, Window w)
773 int i;
774 for (i = 0; i < 100; ++i) {
775 Window focuswin;
776 int revert_to_win;
778 XGetInputFocus(d, &focuswin, &revert_to_win);
780 if (focuswin == w)
781 return 1;
783 XSetInputFocus(d, w, RevertToParent, CurrentTime);
784 usleep(1000);
786 return 0;
789 /*
790 * I know this may seem a little hackish BUT is the only way I managed
791 * to actually grab that goddam keyboard. Only one call to
792 * XGrabKeyboard does not always end up with the keyboard grabbed!
793 */
794 int
795 take_keyboard(Display *d, Window w)
797 int i;
798 for (i = 0; i < 100; i++) {
799 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
800 == GrabSuccess)
801 return 1;
802 usleep(1000);
804 fprintf(stderr, "Cannot grab keyboard\n");
805 return 0;
808 unsigned long
809 parse_color(const char *str, const char *def)
811 size_t len;
812 rgba_t tmp;
813 char *ep;
815 if (str == NULL)
816 goto invc;
818 len = strlen(str);
820 /* +1 for the # ath the start */
821 if (*str != '#' || len > 9 || len < 4)
822 goto invc;
823 ++str; /* skip the # */
825 errno = 0;
826 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
828 if (errno)
829 goto invc;
831 switch (len - 1) {
832 case 3:
833 /* expand #rgb -> #rrggbb */
834 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
835 | (tmp.v & 0x00f) * 0x0011;
836 case 6:
837 /* assume 0xff opacity */
838 tmp.rgba.a = 0xff;
839 break;
840 } /* colors in #aarrggbb need no adjustments */
842 /* premultiply the alpha */
843 if (tmp.rgba.a) {
844 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
845 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
846 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
847 return tmp.v;
850 return 0U;
852 invc:
853 fprintf(stderr, "Invalid color: \"%s\".\n", str);
854 if (def != NULL)
855 return parse_color(def, NULL);
856 else
857 return 0U;
860 /*
861 * Given a string try to parse it as a number or return `def'.
862 */
863 int
864 parse_integer(const char *str, int def)
866 const char *errstr;
867 int i;
869 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
870 if (errstr != NULL) {
871 warnx("'%s' is %s; using %d as default", str, errstr, def);
872 return def;
875 return i;
878 /* Like parse_integer but recognize the percentages (i.e. strings ending with
879 * `%') */
880 int
881 parse_int_with_percentage(const char *str, int default_value, int max)
883 int len = strlen(str);
885 if (len > 0 && str[len - 1] == '%') {
886 int val;
887 char *cpy;
889 if ((cpy = strdup(str)) == NULL)
890 err(1, "strdup");
892 cpy[len - 1] = '\0';
893 val = parse_integer(cpy, default_value);
894 free(cpy);
895 return val * max / 100;
898 return parse_integer(str, default_value);
901 void
902 get_mouse_coords(Display *d, int *x, int *y)
904 Window w, root;
905 int i;
906 unsigned int u;
908 *x = *y = 0;
909 root = DefaultRootWindow(d);
911 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
912 for (i = 0; i < ScreenCount(d); ++i) {
913 if (root == RootWindow(d, i))
914 break;
919 /*
920 * Like parse_int_with_percentage but understands some special values:
921 * - middle that is (max-self)/2
922 * - center = middle
923 * - start that is 0
924 * - end that is (max-self)
925 * - mx x coordinate of the mouse
926 * - my y coordinate of the mouse
927 */
928 int
929 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
931 if (!strcmp(str, "start"))
932 return 0;
933 if (!strcmp(str, "middle") || !strcmp(str, "center"))
934 return (max - self) / 2;
935 if (!strcmp(str, "end"))
936 return max - self;
937 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
938 int x, y;
940 get_mouse_coords(d, &x, &y);
941 if (!strcmp(str, "mx"))
942 return x - 1;
943 else
944 return y - 1;
946 return parse_int_with_percentage(str, default_value, max);
949 /* Parse a string like a CSS value. */
950 /* TODO: harden a bit this function */
951 char **
952 parse_csslike(const char *str)
954 int i, j;
955 char *s, *token, **ret;
956 short any_null;
958 s = strdup(str);
959 if (s == NULL)
960 return NULL;
962 ret = malloc(4 * sizeof(char *));
963 if (ret == NULL) {
964 free(s);
965 return NULL;
968 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
969 ret[i] = strdup(token);
971 if (i == 1)
972 for (j = 1; j < 4; j++)
973 ret[j] = strdup(ret[0]);
975 if (i == 2) {
976 ret[2] = strdup(ret[0]);
977 ret[3] = strdup(ret[1]);
980 if (i == 3)
981 ret[3] = strdup(ret[1]);
983 /* before we didn't check for the return type of strdup, here we will
984 */
986 any_null = 0;
987 for (i = 0; i < 4; ++i)
988 any_null = ret[i] == NULL || any_null;
990 if (any_null)
991 for (i = 0; i < 4; ++i)
992 if (ret[i] != NULL)
993 free(ret[i]);
995 if (i == 0 || any_null) {
996 free(s);
997 free(ret);
998 return NULL;
1001 return ret;
1005 * Given an event, try to understand what the users wants. If the
1006 * return value is ADD_CHAR then `input' is a pointer to a string that
1007 * will need to be free'ed later.
1009 enum action
1010 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1012 char str[SYM_BUF_SIZE] = { 0 };
1013 Status s;
1015 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1016 return DEL_CHAR;
1018 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1019 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1021 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1022 return CONFIRM;
1024 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1025 return EXIT;
1027 /* Try to read what key was pressed */
1028 s = 0;
1029 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1030 if (s == XBufferOverflow) {
1031 fprintf(stderr,
1032 "Buffer overflow when trying to create keyboard "
1033 "symbol map.\n");
1034 return EXIT;
1037 if (ev->state & ControlMask) {
1038 if (!strcmp(str, "")) /* C-u */
1039 return DEL_LINE;
1040 if (!strcmp(str, "")) /* C-w */
1041 return DEL_WORD;
1042 if (!strcmp(str, "")) /* C-h */
1043 return DEL_CHAR;
1044 if (!strcmp(str, "\r")) /* C-m */
1045 return CONFIRM_CONTINUE;
1046 if (!strcmp(str, "")) /* C-p */
1047 return PREV_COMPL;
1048 if (!strcmp(str, "")) /* C-n */
1049 return NEXT_COMPL;
1050 if (!strcmp(str, "")) /* C-c */
1051 return EXIT;
1052 if (!strcmp(str, "\t")) /* C-i */
1053 return TOGGLE_FIRST_SELECTED;
1056 *input = strdup(str);
1057 if (*input == NULL) {
1058 fprintf(stderr, "Error while allocating memory for key.\n");
1059 return EXIT;
1062 return ADD_CHAR;
1065 void
1066 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1068 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1069 /* if there is something selected expand it and return */
1070 int index = cs->selected == -1 ? 0 : cs->selected;
1071 struct completion *c = cs->completions;
1072 char *t;
1074 while (1) {
1075 if (index == 0)
1076 break;
1077 c++;
1078 index--;
1081 t = c->rcompletion;
1082 free(*text);
1083 *text = strdup(t);
1085 if (*text == NULL) {
1086 fprintf(stderr, "Memory allocation error\n");
1087 *status = ERR;
1090 *textlen = strlen(*text);
1091 return;
1094 if (!r->free_text) /* cannot accept arbitrary text */
1095 *status = LOOPING;
1098 /* cs: completion list
1099 * offset: the offset of the click
1100 * first: the first (rendered) item
1101 * def: the default action
1103 enum action
1104 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1106 ssize_t selected = first;
1107 int set = 0;
1109 if (cs->length == 0)
1110 return NO_OP;
1112 if (offset < cs->completions[selected].offset)
1113 return EXIT;
1115 /* skip the first entry */
1116 for (selected += 1; selected < cs->length; ++selected) {
1117 if (cs->completions[selected].offset == -1)
1118 break;
1120 if (offset < cs->completions[selected].offset) {
1121 cs->selected = selected - 1;
1122 set = 1;
1123 break;
1127 if (!set)
1128 cs->selected = selected - 1;
1130 return def;
1133 enum action
1134 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1136 size_t off;
1138 if (r->horizontal_layout)
1139 off = e->x;
1140 else
1141 off = e->y;
1143 switch (e->button) {
1144 case Button1:
1145 return select_clicked(cs, off, r->offset, CONFIRM);
1147 case Button3:
1148 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1150 case Button4:
1151 return SCROLL_UP;
1153 case Button5:
1154 return SCROLL_DOWN;
1157 return NO_OP;
1160 /* event loop */
1161 enum state
1162 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1163 char **vlines)
1165 enum state status = LOOPING;
1167 while (status == LOOPING) {
1168 XEvent e;
1169 XNextEvent(r->d, &e);
1171 if (XFilterEvent(&e, r->w))
1172 continue;
1174 switch (e.type) {
1175 case KeymapNotify:
1176 XRefreshKeyboardMapping(&e.xmapping);
1177 break;
1179 case FocusIn:
1180 /* Re-grab focus */
1181 if (e.xfocus.window != r->w)
1182 grabfocus(r->d, r->w);
1183 break;
1185 case VisibilityNotify:
1186 if (e.xvisibility.state != VisibilityUnobscured)
1187 XRaiseWindow(r->d, r->w);
1188 break;
1190 case MapNotify:
1191 get_wh(r->d, &r->w, &r->width, &r->height);
1192 draw(r, *text, cs);
1193 break;
1195 case KeyPress:
1196 case ButtonPress: {
1197 enum action a;
1198 char *input = NULL;
1200 if (e.type == KeyPress)
1201 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1202 else
1203 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1205 switch (a) {
1206 case NO_OP:
1207 break;
1209 case EXIT:
1210 status = ERR;
1211 break;
1213 case CONFIRM: {
1214 status = OK;
1215 confirm(&status, r, cs, text, textlen);
1216 break;
1219 case CONFIRM_CONTINUE: {
1220 status = OK_LOOP;
1221 confirm(&status, r, cs, text, textlen);
1222 break;
1225 case PREV_COMPL: {
1226 complete(cs, r->first_selected, 1, text, textlen, &status);
1227 r->offset = cs->selected;
1228 break;
1231 case NEXT_COMPL: {
1232 complete(cs, r->first_selected, 0, text, textlen, &status);
1233 r->offset = cs->selected;
1234 break;
1237 case DEL_CHAR:
1238 popc(*text);
1239 update_completions(cs, *text, lines, vlines, r->first_selected);
1240 r->offset = 0;
1241 break;
1243 case DEL_WORD: {
1244 popw(*text);
1245 update_completions(cs, *text, lines, vlines, r->first_selected);
1246 break;
1249 case DEL_LINE: {
1250 int i;
1251 for (i = 0; i < *textlen; ++i)
1252 *(*text + i) = 0;
1253 update_completions(cs, *text, lines, vlines, r->first_selected);
1254 r->offset = 0;
1255 break;
1258 case ADD_CHAR: {
1259 int str_len, i;
1261 str_len = strlen(input);
1264 * sometimes a strange key is pressed
1265 * i.e. ctrl alone), so input will be
1266 * empty. Don't need to update
1267 * completion in that case
1269 if (str_len == 0)
1270 break;
1272 for (i = 0; i < str_len; ++i) {
1273 *textlen = pushc(text, *textlen, input[i]);
1274 if (*textlen == -1) {
1275 fprintf(stderr,
1276 "Memory allocation "
1277 "error\n");
1278 status = ERR;
1279 break;
1283 if (status != ERR) {
1284 update_completions(
1285 cs, *text, lines, vlines, r->first_selected);
1286 free(input);
1289 r->offset = 0;
1290 break;
1293 case TOGGLE_FIRST_SELECTED:
1294 r->first_selected = !r->first_selected;
1295 if (r->first_selected && cs->selected < 0)
1296 cs->selected = 0;
1297 if (!r->first_selected && cs->selected == 0)
1298 cs->selected = -1;
1299 break;
1301 case SCROLL_DOWN:
1302 r->offset = MIN(r->offset + 1, cs->length - 1);
1303 break;
1305 case SCROLL_UP:
1306 r->offset = MAX((ssize_t)r->offset - 1, 0);
1307 break;
1312 draw(r, *text, cs);
1315 return status;
1318 int
1319 load_font(struct rendering *r, const char *fontname)
1321 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1322 return 0;
1325 void
1326 xim_init(struct rendering *r, XrmDatabase *xdb)
1328 XIMStyle best_match_style;
1329 XIMStyles *xis;
1330 int i;
1332 /* Open the X input method */
1333 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1334 err(1, "XOpenIM");
1336 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1337 fprintf(stderr, "Input Styles could not be retrieved\n");
1338 exit(EX_UNAVAILABLE);
1341 best_match_style = 0;
1342 for (i = 0; i < xis->count_styles; ++i) {
1343 XIMStyle ts = xis->supported_styles[i];
1344 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1345 best_match_style = ts;
1346 break;
1349 XFree(xis);
1351 if (!best_match_style)
1352 fprintf(stderr, "No matching input style could be determined\n");
1354 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1355 XNFocusWindow, r->w, NULL);
1356 if (r->xic == NULL)
1357 err(1, "XCreateIC");
1360 void
1361 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1362 int y, int ox, int oy, unsigned long background_pixel)
1364 XSetWindowAttributes attr;
1366 /* Create the window */
1367 attr.colormap = cmap;
1368 attr.override_redirect = 1;
1369 attr.border_pixel = 0;
1370 attr.background_pixel = background_pixel;
1371 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1372 | ButtonPress | VisibilityChangeMask;
1374 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1375 vinfo.depth, InputOutput, vinfo.visual,
1376 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1379 void
1380 ps1extents(struct rendering *r)
1382 char *dup;
1383 dup = strdupn(r->ps1);
1384 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1385 free(dup);
1388 void
1389 usage(char *prgname)
1391 fprintf(stderr,
1392 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1393 " [-d separator] [-e window] [-f font] [-G color] [-g "
1394 "size]\n"
1395 " [-H height] [-I color] [-i size] [-J color] [-j "
1396 "size] [-l layout]\n"
1397 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1398 "color]\n"
1399 " [-t color] [-W width] [-x coord] [-y coord]\n",
1400 prgname);
1403 int
1404 main(int argc, char **argv)
1406 struct completions *cs;
1407 struct rendering r;
1408 XVisualInfo vinfo;
1409 Colormap cmap;
1410 size_t nlines, i;
1411 Window parent_window;
1412 XrmDatabase xdb;
1413 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1414 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1415 ch_borders_bg[4]; /* N E S W */
1416 enum state status;
1417 int ch;
1418 int offset_x, offset_y, x, y;
1419 int textlen, d_width, d_height;
1420 short embed;
1421 char *sep, *parent_window_id;
1422 char **lines, **vlines;
1423 char *fontname, *text, *xrm;
1425 sep = NULL;
1426 parent_window_id = NULL;
1428 r.first_selected = 0;
1429 r.free_text = 1;
1430 r.multiple_select = 0;
1431 r.offset = 0;
1433 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1434 switch (ch) {
1435 case 'h': /* help */
1436 usage(*argv);
1437 return 0;
1438 case 'v': /* version */
1439 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1440 return 0;
1441 case 'e': /* embed */
1442 if ((parent_window_id = strdup(optarg)) == NULL)
1443 err(1, "strdup");
1444 break;
1445 case 'd':
1446 if ((sep = strdup(optarg)) == NULL)
1447 err(1, "strdup");
1448 break;
1449 case 'A':
1450 r.free_text = 0;
1451 break;
1452 case 'm':
1453 r.multiple_select = 1;
1454 break;
1455 default:
1456 break;
1460 lines = readlines(&nlines);
1462 vlines = NULL;
1463 if (sep != NULL) {
1464 int l;
1465 l = strlen(sep);
1466 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1467 err(1, "calloc");
1469 for (i = 0; i < nlines; i++) {
1470 char *t;
1471 t = strstr(lines[i], sep);
1472 if (t == NULL)
1473 vlines[i] = lines[i];
1474 else
1475 vlines[i] = t + l;
1479 setlocale(LC_ALL, getenv("LANG"));
1481 status = LOOPING;
1483 /* where the monitor start (used only with xinerama) */
1484 offset_x = offset_y = 0;
1486 /* default width and height */
1487 r.width = 400;
1488 r.height = 20;
1490 /* default position on the screen */
1491 x = y = 0;
1493 for (i = 0; i < 4; ++i) {
1494 /* default paddings */
1495 r.p_padding[i] = 10;
1496 r.c_padding[i] = 10;
1497 r.ch_padding[i] = 10;
1499 /* default borders */
1500 r.borders[i] = 0;
1501 r.p_borders[i] = 0;
1502 r.c_borders[i] = 0;
1503 r.ch_borders[i] = 0;
1506 /* the prompt. We duplicate the string so later is easy to
1507 * free (in the case it's been overwritten by the user) */
1508 if ((r.ps1 = strdup("$ ")) == NULL)
1509 err(1, "strdup");
1511 /* same for the font name */
1512 if ((fontname = strdup(DEFFONT)) == NULL)
1513 err(1, "strdup");
1515 textlen = 10;
1516 if ((text = malloc(textlen * sizeof(char))) == NULL)
1517 err(1, "malloc");
1519 /* struct completions *cs = filter(text, lines); */
1520 if ((cs = compls_new(nlines)) == NULL)
1521 err(1, "compls_new");
1523 /* start talking to xorg */
1524 r.d = XOpenDisplay(NULL);
1525 if (r.d == NULL) {
1526 fprintf(stderr, "Could not open display!\n");
1527 return EX_UNAVAILABLE;
1530 embed = 1;
1531 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1532 parent_window = DefaultRootWindow(r.d);
1533 embed = 0;
1536 /* get display size */
1537 get_wh(r.d, &parent_window, &d_width, &d_height);
1539 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1540 XineramaScreenInfo *info;
1541 Window rr;
1542 Window root;
1543 int number_of_screens, monitors, i;
1544 int root_x, root_y, win_x, win_y;
1545 unsigned int mask;
1546 short res;
1548 number_of_screens = XScreenCount(r.d);
1549 for (i = 0; i < number_of_screens; ++i) {
1550 root = XRootWindow(r.d, i);
1551 res = XQueryPointer(
1552 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1553 if (res)
1554 break;
1557 if (!res) {
1558 fprintf(stderr, "No mouse found.\n");
1559 root_x = 0;
1560 root_y = 0;
1563 /* Now find in which monitor the mice is */
1564 info = XineramaQueryScreens(r.d, &monitors);
1565 if (info) {
1566 for (i = 0; i < monitors; ++i) {
1567 if (info[i].x_org <= root_x
1568 && root_x <= (info[i].x_org + info[i].width)
1569 && info[i].y_org <= root_y
1570 && root_y <= (info[i].y_org + info[i].height)) {
1571 offset_x = info[i].x_org;
1572 offset_y = info[i].y_org;
1573 d_width = info[i].width;
1574 d_height = info[i].height;
1575 break;
1579 XFree(info);
1582 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1583 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1585 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1586 fgs[2] = parse_color("#000", NULL);
1588 bgs[0] = bgs[1] = parse_color("#000", NULL);
1589 bgs[2] = parse_color("#fff", NULL);
1591 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1593 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1594 = parse_color("#000", NULL);
1595 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1596 = parse_color("#000", NULL);
1597 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1598 = parse_color("#000", NULL);
1600 r.horizontal_layout = 1;
1602 /* Read the resources */
1603 XrmInitialize();
1604 xrm = XResourceManagerString(r.d);
1605 xdb = NULL;
1606 if (xrm != NULL) {
1607 XrmValue value;
1608 char *datatype[20];
1610 xdb = XrmGetStringDatabase(xrm);
1612 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1613 free(fontname);
1614 if ((fontname = strdup(value.addr)) == NULL)
1615 err(1, "strdup");
1616 } else {
1617 fprintf(stderr, "no font defined, using %s\n", fontname);
1620 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1621 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1622 else
1623 fprintf(stderr, "no layout defined, using horizontal\n");
1625 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1626 free(r.ps1);
1627 r.ps1 = normalize_str(value.addr);
1628 } else {
1629 fprintf(stderr,
1630 "no prompt defined, using \"%s\" as "
1631 "default\n",
1632 r.ps1);
1635 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1636 char **sizes;
1637 sizes = parse_csslike(value.addr);
1638 if (sizes != NULL)
1639 for (i = 0; i < 4; ++i)
1640 r.p_borders[i] = parse_integer(sizes[i], 0);
1641 else
1642 fprintf(stderr,
1643 "error while parsing "
1644 "MyMenu.prompt.border.size");
1647 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1648 char **colors;
1649 colors = parse_csslike(value.addr);
1650 if (colors != NULL)
1651 for (i = 0; i < 4; ++i)
1652 p_borders_bg[i] = parse_color(colors[i], "#000");
1653 else
1654 fprintf(stderr,
1655 "error while parsing "
1656 "MyMenu.prompt.border.color");
1659 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1660 char **colors;
1661 colors = parse_csslike(value.addr);
1662 if (colors != NULL)
1663 for (i = 0; i < 4; ++i)
1664 r.p_padding[i] = parse_integer(colors[i], 0);
1665 else
1666 fprintf(stderr,
1667 "error while parsing "
1668 "MyMenu.prompt.padding");
1671 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1672 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1673 else
1674 fprintf(stderr, "no width defined, using %d\n", r.width);
1676 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1677 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1678 else
1679 fprintf(stderr, "no height defined, using %d\n", r.height);
1681 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1682 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1684 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1685 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1687 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1688 char **borders;
1689 borders = parse_csslike(value.addr);
1690 if (borders != NULL)
1691 for (i = 0; i < 4; ++i)
1692 r.borders[i] = parse_int_with_percentage(
1693 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1694 else
1695 fprintf(stderr,
1696 "error while parsing "
1697 "MyMenu.border.size\n");
1700 /* Prompt */
1701 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1702 fgs[0] = parse_color(value.addr, "#fff");
1704 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1705 bgs[0] = parse_color(value.addr, "#000");
1707 /* Completions */
1708 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1709 fgs[1] = parse_color(value.addr, "#fff");
1711 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1712 bgs[1] = parse_color(value.addr, "#000");
1714 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1715 char **paddings;
1716 paddings = parse_csslike(value.addr);
1717 if (paddings != NULL)
1718 for (i = 0; i < 4; ++i)
1719 r.c_padding[i] = parse_integer(paddings[i], 0);
1720 else
1721 fprintf(stderr,
1722 "Error while parsing "
1723 "MyMenu.completion.padding");
1726 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1727 char **sizes;
1728 sizes = parse_csslike(value.addr);
1729 if (sizes != NULL)
1730 for (i = 0; i < 4; ++i)
1731 r.c_borders[i] = parse_integer(sizes[i], 0);
1732 else
1733 fprintf(stderr,
1734 "Error while parsing "
1735 "MyMenu.completion.border.size");
1738 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1739 char **sizes;
1740 sizes = parse_csslike(value.addr);
1741 if (sizes != NULL)
1742 for (i = 0; i < 4; ++i)
1743 c_borders_bg[i] = parse_color(sizes[i], "#000");
1744 else
1745 fprintf(stderr,
1746 "Error while parsing "
1747 "MyMenu.completion.border.color");
1750 /* Completion Highlighted */
1751 if (XrmGetResource(
1752 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1753 fgs[2] = parse_color(value.addr, "#000");
1755 if (XrmGetResource(
1756 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1757 bgs[2] = parse_color(value.addr, "#fff");
1759 if (XrmGetResource(
1760 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1761 char **paddings;
1762 paddings = parse_csslike(value.addr);
1763 if (paddings != NULL)
1764 for (i = 0; i < 4; ++i)
1765 r.ch_padding[i] = parse_integer(paddings[i], 0);
1766 else
1767 fprintf(stderr,
1768 "Error while parsing "
1769 "MyMenu.completion_highlighted."
1770 "padding");
1773 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1774 &value)) {
1775 char **sizes;
1776 sizes = parse_csslike(value.addr);
1777 if (sizes != NULL)
1778 for (i = 0; i < 4; ++i)
1779 r.ch_borders[i] = parse_integer(sizes[i], 0);
1780 else
1781 fprintf(stderr,
1782 "Error while parsing "
1783 "MyMenu.completion_highlighted."
1784 "border.size");
1787 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1788 &value)) {
1789 char **colors;
1790 colors = parse_csslike(value.addr);
1791 if (colors != NULL)
1792 for (i = 0; i < 4; ++i)
1793 ch_borders_bg[i] = parse_color(colors[i], "#000");
1794 else
1795 fprintf(stderr,
1796 "Error while parsing "
1797 "MyMenu.completion_highlighted."
1798 "border.color");
1801 /* Border */
1802 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1803 char **colors;
1804 colors = parse_csslike(value.addr);
1805 if (colors != NULL)
1806 for (i = 0; i < 4; ++i)
1807 borders_bg[i] = parse_color(colors[i], "#000");
1808 else
1809 fprintf(stderr,
1810 "error while parsing "
1811 "MyMenu.border.color\n");
1815 /* Second round of args parsing */
1816 optind = 0; /* reset the option index */
1817 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1818 switch (ch) {
1819 case 'a':
1820 r.first_selected = 1;
1821 break;
1822 case 'A':
1823 /* free_text -- already catched */
1824 case 'd':
1825 /* separator -- this case was already catched */
1826 case 'e':
1827 /* embedding mymenu this case was already catched. */
1828 case 'm':
1829 /* multiple selection this case was already catched.
1831 break;
1832 case 'p': {
1833 char *newprompt;
1834 newprompt = strdup(optarg);
1835 if (newprompt != NULL) {
1836 free(r.ps1);
1837 r.ps1 = newprompt;
1839 break;
1841 case 'x':
1842 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1843 break;
1844 case 'y':
1845 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1846 break;
1847 case 'P': {
1848 char **paddings;
1849 if ((paddings = parse_csslike(optarg)) != NULL)
1850 for (i = 0; i < 4; ++i)
1851 r.p_padding[i] = parse_integer(paddings[i], 0);
1852 break;
1854 case 'G': {
1855 char **colors;
1856 if ((colors = parse_csslike(optarg)) != NULL)
1857 for (i = 0; i < 4; ++i)
1858 p_borders_bg[i] = parse_color(colors[i], "#000");
1859 break;
1861 case 'g': {
1862 char **sizes;
1863 if ((sizes = parse_csslike(optarg)) != NULL)
1864 for (i = 0; i < 4; ++i)
1865 r.p_borders[i] = parse_integer(sizes[i], 0);
1866 break;
1868 case 'I': {
1869 char **colors;
1870 if ((colors = parse_csslike(optarg)) != NULL)
1871 for (i = 0; i < 4; ++i)
1872 c_borders_bg[i] = parse_color(colors[i], "#000");
1873 break;
1875 case 'i': {
1876 char **sizes;
1877 if ((sizes = parse_csslike(optarg)) != NULL)
1878 for (i = 0; i < 4; ++i)
1879 r.c_borders[i] = parse_integer(sizes[i], 0);
1880 break;
1882 case 'J': {
1883 char **colors;
1884 if ((colors = parse_csslike(optarg)) != NULL)
1885 for (i = 0; i < 4; ++i)
1886 ch_borders_bg[i] = parse_color(colors[i], "#000");
1887 break;
1889 case 'j': {
1890 char **sizes;
1891 if ((sizes = parse_csslike(optarg)) != NULL)
1892 for (i = 0; i < 4; ++i)
1893 r.ch_borders[i] = parse_integer(sizes[i], 0);
1894 break;
1896 case 'l':
1897 r.horizontal_layout = !strcmp(optarg, "horizontal");
1898 break;
1899 case 'f': {
1900 char *newfont;
1901 if ((newfont = strdup(optarg)) != NULL) {
1902 free(fontname);
1903 fontname = newfont;
1905 break;
1907 case 'W':
1908 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1909 break;
1910 case 'H':
1911 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1912 break;
1913 case 'b': {
1914 char **borders;
1915 if ((borders = parse_csslike(optarg)) != NULL) {
1916 for (i = 0; i < 4; ++i)
1917 r.borders[i] = parse_integer(borders[i], 0);
1918 } else
1919 fprintf(stderr, "Error parsing b option\n");
1920 break;
1922 case 'B': {
1923 char **colors;
1924 if ((colors = parse_csslike(optarg)) != NULL) {
1925 for (i = 0; i < 4; ++i)
1926 borders_bg[i] = parse_color(colors[i], "#000");
1927 } else
1928 fprintf(stderr, "error while parsing B option\n");
1929 break;
1931 case 't':
1932 fgs[0] = parse_color(optarg, NULL);
1933 break;
1934 case 'T':
1935 bgs[0] = parse_color(optarg, NULL);
1936 break;
1937 case 'c':
1938 fgs[1] = parse_color(optarg, NULL);
1939 break;
1940 case 'C':
1941 bgs[1] = parse_color(optarg, NULL);
1942 break;
1943 case 's':
1944 fgs[2] = parse_color(optarg, NULL);
1945 break;
1946 case 'S':
1947 bgs[2] = parse_color(optarg, NULL);
1948 break;
1949 default:
1950 fprintf(stderr, "Unrecognized option %c\n", ch);
1951 status = ERR;
1952 break;
1956 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1957 fprintf(stderr, "height, width, x or y are lesser than 0.");
1958 status = ERR;
1961 /* since only now we know if the first should be selected,
1962 * update the completion here */
1963 update_completions(cs, text, lines, vlines, r.first_selected);
1965 /* update the prompt lenght, only now we surely know the length of it
1967 r.ps1len = strlen(r.ps1);
1969 /* Create the window */
1970 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1971 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1972 XMapRaised(r.d, r.w);
1974 /* If embed, listen for other events as well */
1975 if (embed) {
1976 Window *children, parent, root;
1977 unsigned int children_no;
1979 XSelectInput(r.d, parent_window, FocusChangeMask);
1980 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1981 && children) {
1982 for (i = 0; i < children_no && children[i] != r.w; ++i)
1983 XSelectInput(r.d, children[i], FocusChangeMask);
1984 XFree(children);
1986 grabfocus(r.d, r.w);
1989 take_keyboard(r.d, r.w);
1991 r.x_zero = r.borders[3];
1992 r.y_zero = r.borders[0];
1995 XGCValues values;
1997 for (i = 0; i < 3; ++i) {
1998 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
1999 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2002 for (i = 0; i < 4; ++i) {
2003 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2004 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2005 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2006 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2010 /* Load the colors in our GCs */
2011 for (i = 0; i < 3; ++i) {
2012 XSetForeground(r.d, r.fgs[i], fgs[i]);
2013 XSetForeground(r.d, r.bgs[i], bgs[i]);
2016 for (i = 0; i < 4; ++i) {
2017 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2018 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2019 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2020 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2023 if (load_font(&r, fontname) == -1)
2024 status = ERR;
2026 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2028 for (i = 0; i < 3; ++i) {
2029 rgba_t c;
2030 XRenderColor xrcolor;
2032 c = *(rgba_t *)&fgs[i];
2033 xrcolor.red = EXPANDBITS(c.rgba.r);
2034 xrcolor.green = EXPANDBITS(c.rgba.g);
2035 xrcolor.blue = EXPANDBITS(c.rgba.b);
2036 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2037 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2040 /* compute prompt dimensions */
2041 ps1extents(&r);
2043 xim_init(&r, &xdb);
2045 #ifdef __OpenBSD__
2046 if (pledge("stdio", "") == -1)
2047 err(1, "pledge");
2048 #endif
2050 /* Cache text height */
2051 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2053 /* Draw the window for the first time */
2054 draw(&r, text, cs);
2056 /* Main loop */
2057 while (status == LOOPING || status == OK_LOOP) {
2058 status = loop(&r, &text, &textlen, cs, lines, vlines);
2060 if (status != ERR)
2061 printf("%s\n", text);
2063 if (!r.multiple_select && status == OK_LOOP)
2064 status = OK;
2067 XUngrabKeyboard(r.d, CurrentTime);
2069 for (i = 0; i < 3; ++i)
2070 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2072 for (i = 0; i < 3; ++i) {
2073 XFreeGC(r.d, r.fgs[i]);
2074 XFreeGC(r.d, r.bgs[i]);
2077 for (i = 0; i < 4; ++i) {
2078 XFreeGC(r.d, r.borders_bg[i]);
2079 XFreeGC(r.d, r.p_borders_bg[i]);
2080 XFreeGC(r.d, r.c_borders_bg[i]);
2081 XFreeGC(r.d, r.ch_borders_bg[i]);
2084 XDestroyIC(r.xic);
2085 XCloseIM(r.xim);
2087 for (i = 0; i < 3; ++i)
2088 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2089 XftFontClose(r.d, r.font);
2090 XftDrawDestroy(r.xftdraw);
2092 free(r.ps1);
2093 free(fontname);
2094 free(text);
2096 free(lines);
2097 free(vlines);
2098 compls_delete(cs);
2100 XFreeColormap(r.d, cmap);
2102 XDestroyWindow(r.d, r.w);
2103 XCloseDisplay(r.d);
2105 return status != OK;