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;
120 /*
121 * The X (or Y, depending on the layour) at which the item is
122 * rendered
123 */
124 int offset;
125 };
127 /* Wrap the linked list of completions */
128 struct completions {
129 struct completion *completions;
130 ssize_t selected;
131 size_t length;
132 };
134 /* idea stolen from lemonbar; ty lemonboy */
135 typedef union {
136 struct {
137 uint8_t b;
138 uint8_t g;
139 uint8_t r;
140 uint8_t a;
141 } rgba;
142 uint32_t v;
143 } rgba_t;
145 extern char *optarg;
146 extern int optind;
148 /* Return a newly allocated (and empty) completion list */
149 struct completions *
150 compls_new(size_t length)
152 struct completions *cs = malloc(sizeof(struct completions));
154 if (cs == NULL)
155 return cs;
157 cs->completions = calloc(length, sizeof(struct completion));
158 if (cs->completions == NULL) {
159 free(cs);
160 return NULL;
163 cs->selected = -1;
164 cs->length = length;
165 return cs;
168 /* Delete the wrapper and the whole list */
169 void
170 compls_delete(struct completions *cs)
172 if (cs == NULL)
173 return;
175 free(cs->completions);
176 free(cs);
179 /*
180 * Create a completion list from a text and the list of possible
181 * completions (null terminated). Expects a non-null `cs'. `lines' and
182 * `vlines' should have the same length OR `vlines' is NULL.
183 */
184 void
185 filter(struct completions *cs, char *text, char **lines, char **vlines)
187 size_t index = 0;
188 size_t matching = 0;
189 char *l;
191 if (vlines == NULL)
192 vlines = lines;
194 while (1) {
195 if (lines[index] == NULL)
196 break;
198 l = vlines[index] != NULL ? vlines[index] : lines[index];
200 if (strcasestr(l, text) != NULL) {
201 struct completion *c = &cs->completions[matching];
202 c->completion = l;
203 c->rcompletion = lines[index];
204 matching++;
207 index++;
209 cs->length = matching;
210 cs->selected = -1;
213 /* Update the given completion */
214 void
215 update_completions(struct completions *cs, char *text, char **lines,
216 char **vlines, short first_selected)
218 filter(cs, text, lines, vlines);
219 if (first_selected && cs->length > 0)
220 cs->selected = 0;
223 /*
224 * Select the next or previous selection and update some state. `text'
225 * will be updated with the text of the completion and `textlen' with
226 * the new length. If the memory cannot be allocated `status' will be
227 * set to `ERR'.
228 */
229 void
230 complete(struct completions *cs, short first_selected, short p,
231 char **text, int *textlen, enum state *status)
233 struct completion *n;
234 int index;
236 if (cs == NULL || cs->length == 0)
237 return;
239 /*
240 * If the first is always selected and the first entry is
241 * different from the text, expand the text and return
242 */
243 if (first_selected &&
244 cs->selected == 0 &&
245 strcmp(cs->completions->completion, *text) != 0 &&
246 !p) {
247 free(*text);
248 *text = strdup(cs->completions->completion);
249 if (text == NULL) {
250 *status = ERR;
251 return;
253 *textlen = strlen(*text);
254 return;
257 index = cs->selected;
259 if (index == -1 && p)
260 index = 0;
261 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
262 % cs->length;
264 n = &cs->completions[cs->selected];
266 free(*text);
267 *text = strdup(n->completion);
268 if (text == NULL) {
269 fprintf(stderr, "Memory allocation error!\n");
270 *status = ERR;
271 return;
273 *textlen = strlen(*text);
276 /* Push the character c at the end of the string pointed by p */
277 int
278 pushc(char **p, int maxlen, char c)
280 int len;
282 len = strnlen(*p, maxlen);
283 if (!(len < maxlen - 2)) {
284 char *newptr;
286 maxlen += maxlen >> 1;
287 newptr = realloc(*p, maxlen);
288 if (newptr == NULL) /* bad */
289 return -1;
290 *p = newptr;
293 (*p)[len] = c;
294 (*p)[len + 1] = '\0';
295 return maxlen;
298 /*
299 * Remove the last rune from the *UTF-8* string! This is different
300 * from just setting the last byte to 0 (in some cases ofc). Return a
301 * pointer (e) to the last nonzero char. If e < p then p is empty!
302 */
303 char *
304 popc(char *p)
306 int len = strlen(p);
307 char *e;
309 if (len == 0)
310 return p;
312 e = p + len - 1;
314 do {
315 char c = *e;
317 *e = '\0';
318 e -= 1;
320 /*
321 * If c is a starting byte (11......) or is under
322 * U+007F we're done.
323 */
324 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
325 break;
326 } while (e >= p);
328 return e;
331 /* Remove the last word plus trailing white spaces from the given string */
332 void
333 popw(char *w)
335 int len;
336 short in_word = 1;
338 if ((len = strlen(w)) == 0)
339 return;
341 while (1) {
342 char *e = popc(w);
344 if (e < w)
345 return;
347 if (in_word && isspace(*e))
348 in_word = 0;
350 if (!in_word && !isspace(*e))
351 return;
355 /*
356 * If the string is surrounded by quates (`"') remove them and replace
357 * every `\"' in the string with a single double-quote.
358 */
359 char *
360 normalize_str(const char *str)
362 int len, p;
363 char *s;
365 if ((len = strlen(str)) == 0)
366 return NULL;
368 if ((s = calloc(len, sizeof(char))) == NULL)
369 err(1, "calloc");
370 p = 0;
372 while (*str) {
373 char c = *str;
375 if (*str == '\\') {
376 if (*(str + 1)) {
377 s[p] = *(str + 1);
378 p++;
379 str += 2; /* skip this and the next char */
380 continue;
381 } else
382 break;
384 if (c == '"') {
385 str++; /* skip only this char */
386 continue;
388 s[p] = c;
389 p++;
390 str++;
393 return s;
396 char **
397 readlines(size_t *lineslen)
399 size_t len = 0, cap = 0;
400 size_t linesize = 0;
401 ssize_t linelen;
402 char *line = NULL, **lines = NULL;
404 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
405 if (linelen != 0 && line[linelen-1] == '\n')
406 line[linelen-1] = '\0';
408 if (len == cap) {
409 size_t newcap;
410 void *t;
412 newcap = MAX(cap * 1.5, 32);
413 t = recallocarray(lines, cap, newcap, sizeof(char *));
414 if (t == NULL)
415 err(1, "recallocarray");
416 cap = newcap;
417 lines = t;
420 if ((lines[len++] = strdup(line)) == NULL)
421 err(1, "strdup");
424 if (ferror(stdin))
425 err(1, "getline");
426 free(line);
428 *lineslen = len;
429 return lines;
432 /*
433 * Compute the dimensions of the string str once rendered.
434 * It'll return the width and set ret_width and ret_height if not NULL
435 */
436 int
437 text_extents(char *str, int len, struct rendering *r, int *ret_width,
438 int *ret_height)
440 int height, width;
441 XGlyphInfo gi;
442 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
443 height = r->font->ascent - r->font->descent;
444 width = gi.width - gi.x;
446 if (ret_width != NULL)
447 *ret_width = width;
448 if (ret_height != NULL)
449 *ret_height = height;
450 return width;
453 void
454 draw_string(char *str, int len, int x, int y, struct rendering *r,
455 enum obj_type tt)
457 XftColor xftcolor;
458 if (tt == PROMPT)
459 xftcolor = r->xft_colors[0];
460 if (tt == COMPL)
461 xftcolor = r->xft_colors[1];
462 if (tt == COMPL_HIGH)
463 xftcolor = r->xft_colors[2];
465 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
468 /* Duplicate the string and substitute every space with a 'n` */
469 char *
470 strdupn(char *str)
472 char *t, *dup;
474 if (str == NULL || *str == '\0')
475 return NULL;
477 if ((dup = strdup(str)) == NULL)
478 return NULL;
480 for (t = dup; *t; ++t) {
481 if (*t == ' ')
482 *t = 'n';
485 return dup;
488 int
489 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
490 enum obj_type t, char *text)
492 GC *border_color, bg;
493 int *padding, *borders;
494 int ret = 0, inner_width, inner_height, x;
496 switch (t) {
497 case PROMPT:
498 border_color = r->p_borders_bg;
499 padding = r->p_padding;
500 borders = r->p_borders;
501 bg = r->bgs[0];
502 break;
503 case COMPL:
504 border_color = r->c_borders_bg;
505 padding = r->c_padding;
506 borders = r->c_borders;
507 bg = r->bgs[1];
508 break;
509 case COMPL_HIGH:
510 border_color = r->ch_borders_bg;
511 padding = r->ch_padding;
512 borders = r->ch_borders;
513 bg = r->bgs[2];
514 break;
517 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
519 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
520 inner_height = padding[0] + r->text_height + padding[2];
522 /* Border top */
523 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
524 borders[0]);
526 /* Border right */
527 XFillRectangle(r->d, r->w, border_color[1],
528 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
530 /* Border bottom */
531 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
532 y + borders[0] + padding[0] + r->text_height + padding[2],
533 r->width, borders[2]);
535 /* Border left */
536 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
537 ret);
539 /* bg */
540 x = r->x_zero + borders[3];
541 y += borders[0];
542 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
544 /* content */
545 y += padding[0] + r->text_height;
546 x += padding[3];
547 if (prefix != NULL) {
548 draw_string(prefix, strlen(prefix), x, y, r, t);
549 x += prefix_width;
551 draw_string(text, strlen(text), x, y, r, t);
553 return ret;
556 int
557 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
558 enum obj_type t, char *text)
560 GC *border_color, bg;
561 int *padding, *borders;
562 int ret = 0, inner_width, inner_height, y, text_width;
564 switch (t) {
565 case PROMPT:
566 border_color = r->p_borders_bg;
567 padding = r->p_padding;
568 borders = r->p_borders;
569 bg = r->bgs[0];
570 break;
571 case COMPL:
572 border_color = r->c_borders_bg;
573 padding = r->c_padding;
574 borders = r->c_borders;
575 bg = r->bgs[1];
576 break;
577 case COMPL_HIGH:
578 border_color = r->ch_borders_bg;
579 padding = r->ch_padding;
580 borders = r->ch_borders;
581 bg = r->bgs[2];
582 break;
585 if (padding[0] < 0 || padding[2] < 0) {
586 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
587 - r->text_height;
588 padding[0] /= 2;
590 padding[2] = padding[0];
593 /* If they are still lesser than 0, set 'em to 0 */
594 if (padding[0] < 0 || padding[2] < 0)
595 padding[0] = padding[2] = 0;
597 /* Get the text width */
598 text_extents(text, strlen(text), r, &text_width, NULL);
599 if (prefix != NULL)
600 text_width += prefix_width;
602 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
604 inner_width = padding[3] + text_width + padding[1];
605 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
607 /* Border top */
608 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
609 borders[0]);
611 /* Border right */
612 XFillRectangle(r->d, r->w, border_color[1],
613 x + borders[3] + inner_width, r->y_zero, borders[1],
614 INNER_HEIGHT(r));
616 /* Border bottom */
617 XFillRectangle(r->d, r->w, border_color[2], x,
618 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
619 borders[2]);
621 /* Border left */
622 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
623 INNER_HEIGHT(r));
625 /* bg */
626 x += borders[3];
627 y = r->y_zero + borders[0];
628 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
630 /* content */
631 y += padding[0] + r->text_height;
632 x += padding[3];
633 if (prefix != NULL) {
634 draw_string(prefix, strlen(prefix), x, y, r, t);
635 x += prefix_width;
637 draw_string(text, strlen(text), x, y, r, t);
639 return ret;
642 /*
643 * ,-----------------------------------------------------------------,
644 * | 20 char text | completion | completion | completion | compl |
645 * `-----------------------------------------------------------------'
646 */
647 void
648 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
650 size_t i;
651 int x = r->x_zero;
653 /* Draw the prompt */
654 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
656 for (i = r->offset; i < cs->length; ++i) {
657 enum obj_type t;
659 if (cs->selected == (ssize_t)i)
660 t = COMPL_HIGH;
661 else
662 t = COMPL;
664 cs->completions[i].offset = x;
666 x += draw_h_box(r, x, NULL, 0, t,
667 cs->completions[i].completion);
669 if (x > INNER_WIDTH(r))
670 break;
673 for (i += 1; i < cs->length; ++i)
674 cs->completions[i].offset = -1;
677 /*
678 * ,-----------------------------------------------------------------,
679 * | prompt |
680 * |-----------------------------------------------------------------|
681 * | completion |
682 * |-----------------------------------------------------------------|
683 * | completion |
684 * `-----------------------------------------------------------------'
685 */
686 void
687 draw_vertically(struct rendering *r, char *text, struct completions *cs)
689 size_t i;
690 int y = r->y_zero;
692 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
694 for (i = r->offset; i < cs->length; ++i) {
695 enum obj_type t;
697 if (cs->selected == (ssize_t)i)
698 t = COMPL_HIGH;
699 else
700 t = COMPL;
702 cs->completions[i].offset = y;
704 y += draw_v_box(r, y, NULL, 0, t,
705 cs->completions[i].completion);
707 if (y > INNER_HEIGHT(r))
708 break;
711 for (i += 1; i < cs->length; ++i)
712 cs->completions[i].offset = -1;
715 void
716 draw(struct rendering *r, char *text, struct completions *cs)
718 /* Draw the background */
719 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
720 INNER_WIDTH(r), INNER_HEIGHT(r));
722 /* Draw the contents */
723 if (r->horizontal_layout)
724 draw_horizontally(r, text, cs);
725 else
726 draw_vertically(r, text, cs);
728 /* Draw the borders */
729 if (r->borders[0] != 0)
730 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
731 r->borders[0]);
733 if (r->borders[1] != 0)
734 XFillRectangle(r->d, r->w, r->borders_bg[1],
735 r->width - r->borders[1], 0, r->borders[1],
736 r->height);
738 if (r->borders[2] != 0)
739 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
740 r->height - r->borders[2], r->width, r->borders[2]);
742 if (r->borders[3] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
744 r->borders[3], r->height);
746 /* render! */
747 XFlush(r->d);
750 /* Set some WM stuff */
751 void
752 set_win_atoms_hints(Display *d, Window w, int width, int height)
754 Atom type;
755 XClassHint *class_hint;
756 XSizeHints *size_hint;
758 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
759 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
760 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
761 (unsigned char *)&type, 1);
763 /* some window managers honor this properties */
764 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
765 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
766 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
767 (unsigned char *)&type, 1);
769 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
770 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
771 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
772 (unsigned char *)&type, 1);
774 /* Setting window hints */
775 class_hint = XAllocClassHint();
776 if (class_hint == NULL) {
777 fprintf(stderr, "Could not allocate memory for class hint\n");
778 exit(EX_UNAVAILABLE);
781 class_hint->res_name = RESNAME;
782 class_hint->res_class = RESCLASS;
783 XSetClassHint(d, w, class_hint);
784 XFree(class_hint);
786 size_hint = XAllocSizeHints();
787 if (size_hint == NULL) {
788 fprintf(stderr, "Could not allocate memory for size hint\n");
789 exit(EX_UNAVAILABLE);
792 size_hint->flags = PMinSize | PBaseSize;
793 size_hint->min_width = width;
794 size_hint->base_width = width;
795 size_hint->min_height = height;
796 size_hint->base_height = height;
798 XFlush(d);
801 /* Get the width and height of the window `w' */
802 void
803 get_wh(Display *d, Window *w, int *width, int *height)
805 XWindowAttributes win_attr;
807 XGetWindowAttributes(d, *w, &win_attr);
808 *height = win_attr.height;
809 *width = win_attr.width;
812 int
813 grabfocus(Display *d, Window w)
815 int i;
816 for (i = 0; i < 100; ++i) {
817 Window focuswin;
818 int revert_to_win;
820 XGetInputFocus(d, &focuswin, &revert_to_win);
822 if (focuswin == w)
823 return 1;
825 XSetInputFocus(d, w, RevertToParent, CurrentTime);
826 usleep(1000);
828 return 0;
831 /*
832 * I know this may seem a little hackish BUT is the only way I managed
833 * to actually grab that goddam keyboard. Only one call to
834 * XGrabKeyboard does not always end up with the keyboard grabbed!
835 */
836 int
837 take_keyboard(Display *d, Window w)
839 int i;
840 for (i = 0; i < 100; i++) {
841 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
842 CurrentTime) == GrabSuccess)
843 return 1;
844 usleep(1000);
846 fprintf(stderr, "Cannot grab keyboard\n");
847 return 0;
850 unsigned long
851 parse_color(const char *str, const char *def)
853 size_t len;
854 rgba_t tmp;
855 char *ep;
857 if (str == NULL)
858 goto invc;
860 len = strlen(str);
862 /* +1 for the # ath the start */
863 if (*str != '#' || len > 9 || len < 4)
864 goto invc;
865 ++str; /* skip the # */
867 errno = 0;
868 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
870 if (errno)
871 goto invc;
873 switch (len - 1) {
874 case 3:
875 /* expand #rgb -> #rrggbb */
876 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
877 | (tmp.v & 0x00f) * 0x0011;
878 case 6:
879 /* assume 0xff opacity */
880 tmp.rgba.a = 0xff;
881 break;
882 } /* colors in #aarrggbb need no adjustments */
884 /* premultiply the alpha */
885 if (tmp.rgba.a) {
886 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
887 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
888 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
889 return tmp.v;
892 return 0U;
894 invc:
895 fprintf(stderr, "Invalid color: \"%s\".\n", str);
896 if (def != NULL)
897 return parse_color(def, NULL);
898 else
899 return 0U;
902 /*
903 * Given a string try to parse it as a number or return `def'.
904 */
905 int
906 parse_integer(const char *str, int def)
908 const char *errstr;
909 int i;
911 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
912 if (errstr != NULL) {
913 warnx("'%s' is %s; using %d as default", str, errstr, def);
914 return def;
917 return i;
920 /*
921 * Like parse_integer but recognize the percentages (i.e. strings
922 * ending with `%')
923 */
924 int
925 parse_int_with_percentage(const char *str, int default_value, int max)
927 int len = strlen(str);
929 if (len > 0 && str[len - 1] == '%') {
930 int val;
931 char *cpy;
933 if ((cpy = strdup(str)) == NULL)
934 err(1, "strdup");
936 cpy[len - 1] = '\0';
937 val = parse_integer(cpy, default_value);
938 free(cpy);
939 return val * max / 100;
942 return parse_integer(str, default_value);
945 void
946 get_mouse_coords(Display *d, int *x, int *y)
948 Window w, root;
949 int i;
950 unsigned int u;
952 *x = *y = 0;
953 root = DefaultRootWindow(d);
955 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
956 for (i = 0; i < ScreenCount(d); ++i) {
957 if (root == RootWindow(d, i))
958 break;
963 /*
964 * Like parse_int_with_percentage but understands some special values:
965 * - middle that is (max-self)/2
966 * - center = middle
967 * - start that is 0
968 * - end that is (max-self)
969 * - mx x coordinate of the mouse
970 * - my y coordinate of the mouse
971 */
972 int
973 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
974 int self)
976 if (!strcmp(str, "start"))
977 return 0;
978 if (!strcmp(str, "middle") || !strcmp(str, "center"))
979 return (max - self) / 2;
980 if (!strcmp(str, "end"))
981 return max - self;
982 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
983 int x, y;
985 get_mouse_coords(d, &x, &y);
986 if (!strcmp(str, "mx"))
987 return x - 1;
988 else
989 return y - 1;
991 return parse_int_with_percentage(str, default_value, max);
994 /* Parse a string like a CSS value. */
995 /* TODO: harden a bit this function */
996 char **
997 parse_csslike(const char *str)
999 int i, j;
1000 char *s, *token, **ret;
1001 short any_null;
1003 s = strdup(str);
1004 if (s == NULL)
1005 return NULL;
1007 ret = malloc(4 * sizeof(char *));
1008 if (ret == NULL) {
1009 free(s);
1010 return NULL;
1013 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1014 ret[i] = strdup(token);
1016 if (i == 1)
1017 for (j = 1; j < 4; j++)
1018 ret[j] = strdup(ret[0]);
1020 if (i == 2) {
1021 ret[2] = strdup(ret[0]);
1022 ret[3] = strdup(ret[1]);
1025 if (i == 3)
1026 ret[3] = strdup(ret[1]);
1029 * before we didn't check for the return type of strdup, here
1030 * we will
1033 any_null = 0;
1034 for (i = 0; i < 4; ++i)
1035 any_null = ret[i] == NULL || any_null;
1037 if (any_null)
1038 for (i = 0; i < 4; ++i)
1039 if (ret[i] != NULL)
1040 free(ret[i]);
1042 if (i == 0 || any_null) {
1043 free(s);
1044 free(ret);
1045 return NULL;
1048 return ret;
1052 * Given an event, try to understand what the users wants. If the
1053 * return value is ADD_CHAR then `input' is a pointer to a string that
1054 * will need to be free'ed later.
1056 enum action
1057 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1059 char str[SYM_BUF_SIZE] = { 0 };
1060 Status s;
1062 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1063 return DEL_CHAR;
1065 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1066 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1068 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1069 return CONFIRM;
1071 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1072 return EXIT;
1074 /* Try to read what key was pressed */
1075 s = 0;
1076 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1077 if (s == XBufferOverflow) {
1078 fprintf(stderr,
1079 "Buffer overflow when trying to create keyboard "
1080 "symbol map.\n");
1081 return EXIT;
1084 if (ev->state & ControlMask) {
1085 if (!strcmp(str, "")) /* C-u */
1086 return DEL_LINE;
1087 if (!strcmp(str, "")) /* C-w */
1088 return DEL_WORD;
1089 if (!strcmp(str, "")) /* C-h */
1090 return DEL_CHAR;
1091 if (!strcmp(str, "\r")) /* C-m */
1092 return CONFIRM_CONTINUE;
1093 if (!strcmp(str, "")) /* C-p */
1094 return PREV_COMPL;
1095 if (!strcmp(str, "")) /* C-n */
1096 return NEXT_COMPL;
1097 if (!strcmp(str, "")) /* C-c */
1098 return EXIT;
1099 if (!strcmp(str, "\t")) /* C-i */
1100 return TOGGLE_FIRST_SELECTED;
1103 *input = strdup(str);
1104 if (*input == NULL) {
1105 fprintf(stderr, "Error while allocating memory for key.\n");
1106 return EXIT;
1109 return ADD_CHAR;
1112 void
1113 confirm(enum state *status, struct rendering *r, struct completions *cs,
1114 char **text, int *textlen)
1116 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1117 /* if there is something selected expand it and return */
1118 int index = cs->selected == -1 ? 0 : cs->selected;
1119 struct completion *c = cs->completions;
1120 char *t;
1122 while (1) {
1123 if (index == 0)
1124 break;
1125 c++;
1126 index--;
1129 t = c->rcompletion;
1130 free(*text);
1131 *text = strdup(t);
1133 if (*text == NULL) {
1134 fprintf(stderr, "Memory allocation error\n");
1135 *status = ERR;
1138 *textlen = strlen(*text);
1139 return;
1142 if (!r->free_text) /* cannot accept arbitrary text */
1143 *status = LOOPING;
1147 * cs: completion list
1148 * offset: the offset of the click
1149 * first: the first (rendered) item
1150 * def: the default action
1152 enum action
1153 select_clicked(struct completions *cs, size_t offset, size_t first,
1154 enum action def)
1156 ssize_t selected = first;
1157 int set = 0;
1159 if (cs->length == 0)
1160 return NO_OP;
1162 if (offset < cs->completions[selected].offset)
1163 return EXIT;
1165 /* skip the first entry */
1166 for (selected += 1; selected < cs->length; ++selected) {
1167 if (cs->completions[selected].offset == -1)
1168 break;
1170 if (offset < cs->completions[selected].offset) {
1171 cs->selected = selected - 1;
1172 set = 1;
1173 break;
1177 if (!set)
1178 cs->selected = selected - 1;
1180 return def;
1183 enum action
1184 handle_mouse(struct rendering *r, struct completions *cs,
1185 XButtonPressedEvent *e)
1187 size_t off;
1189 if (r->horizontal_layout)
1190 off = e->x;
1191 else
1192 off = e->y;
1194 switch (e->button) {
1195 case Button1:
1196 return select_clicked(cs, off, r->offset, CONFIRM);
1198 case Button3:
1199 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1201 case Button4:
1202 return SCROLL_UP;
1204 case Button5:
1205 return SCROLL_DOWN;
1208 return NO_OP;
1211 /* event loop */
1212 enum state
1213 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1214 char **lines, char **vlines)
1216 enum state status = LOOPING;
1218 while (status == LOOPING) {
1219 XEvent e;
1220 XNextEvent(r->d, &e);
1222 if (XFilterEvent(&e, r->w))
1223 continue;
1225 switch (e.type) {
1226 case KeymapNotify:
1227 XRefreshKeyboardMapping(&e.xmapping);
1228 break;
1230 case FocusIn:
1231 /* Re-grab focus */
1232 if (e.xfocus.window != r->w)
1233 grabfocus(r->d, r->w);
1234 break;
1236 case VisibilityNotify:
1237 if (e.xvisibility.state != VisibilityUnobscured)
1238 XRaiseWindow(r->d, r->w);
1239 break;
1241 case MapNotify:
1242 get_wh(r->d, &r->w, &r->width, &r->height);
1243 draw(r, *text, cs);
1244 break;
1246 case KeyPress:
1247 case ButtonPress: {
1248 enum action a;
1249 char *input = NULL;
1251 if (e.type == KeyPress)
1252 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1253 r->xic, &input);
1254 else
1255 a = handle_mouse(r, cs,
1256 (XButtonPressedEvent *)&e);
1258 switch (a) {
1259 case NO_OP:
1260 break;
1262 case EXIT:
1263 status = ERR;
1264 break;
1266 case CONFIRM: {
1267 status = OK;
1268 confirm(&status, r, cs, text, textlen);
1269 break;
1272 case CONFIRM_CONTINUE: {
1273 status = OK_LOOP;
1274 confirm(&status, r, cs, text, textlen);
1275 break;
1278 case PREV_COMPL: {
1279 complete(cs, r->first_selected, 1, text,
1280 textlen, &status);
1281 r->offset = cs->selected;
1282 break;
1285 case NEXT_COMPL: {
1286 complete(cs, r->first_selected, 0, text,
1287 textlen, &status);
1288 r->offset = cs->selected;
1289 break;
1292 case DEL_CHAR:
1293 popc(*text);
1294 update_completions(cs, *text, lines, vlines,
1295 r->first_selected);
1296 r->offset = 0;
1297 break;
1299 case DEL_WORD: {
1300 popw(*text);
1301 update_completions(cs, *text, lines, vlines,
1302 r->first_selected);
1303 break;
1306 case DEL_LINE: {
1307 int i;
1308 for (i = 0; i < *textlen; ++i)
1309 *(*text + i) = 0;
1310 update_completions(cs, *text, lines, vlines,
1311 r->first_selected);
1312 r->offset = 0;
1313 break;
1316 case ADD_CHAR: {
1317 int str_len, i;
1319 str_len = strlen(input);
1322 * sometimes a strange key is pressed
1323 * i.e. ctrl alone), so input will be
1324 * empty. Don't need to update
1325 * completion in that case
1327 if (str_len == 0)
1328 break;
1330 for (i = 0; i < str_len; ++i) {
1331 *textlen = pushc(text, *textlen,
1332 input[i]);
1333 if (*textlen == -1) {
1334 fprintf(stderr,
1335 "Memory allocation "
1336 "error\n");
1337 status = ERR;
1338 break;
1342 if (status != ERR) {
1343 update_completions(cs, *text, lines,
1344 vlines, r->first_selected);
1345 free(input);
1348 r->offset = 0;
1349 break;
1352 case TOGGLE_FIRST_SELECTED:
1353 r->first_selected = !r->first_selected;
1354 if (r->first_selected && cs->selected < 0)
1355 cs->selected = 0;
1356 if (!r->first_selected && cs->selected == 0)
1357 cs->selected = -1;
1358 break;
1360 case SCROLL_DOWN:
1361 r->offset = MIN(r->offset + 1, cs->length - 1);
1362 break;
1364 case SCROLL_UP:
1365 r->offset = MAX((ssize_t)r->offset - 1, 0);
1366 break;
1371 draw(r, *text, cs);
1374 return status;
1377 int
1378 load_font(struct rendering *r, const char *fontname)
1380 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1381 return 0;
1384 void
1385 xim_init(struct rendering *r, XrmDatabase *xdb)
1387 XIMStyle best_match_style;
1388 XIMStyles *xis;
1389 int i;
1391 /* Open the X input method */
1392 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1393 err(1, "XOpenIM");
1395 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1396 fprintf(stderr, "Input Styles could not be retrieved\n");
1397 exit(EX_UNAVAILABLE);
1400 best_match_style = 0;
1401 for (i = 0; i < xis->count_styles; ++i) {
1402 XIMStyle ts = xis->supported_styles[i];
1403 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1404 best_match_style = ts;
1405 break;
1408 XFree(xis);
1410 if (!best_match_style)
1411 fprintf(stderr,
1412 "No matching input style could be determined\n");
1414 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1415 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1416 if (r->xic == NULL)
1417 err(1, "XCreateIC");
1420 void
1421 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1422 XVisualInfo vinfo, int x, int y, int ox, int oy,
1423 unsigned long background_pixel)
1425 XSetWindowAttributes attr;
1426 unsigned long vmask;
1428 /* Create the window */
1429 attr.colormap = cmap;
1430 attr.override_redirect = 1;
1431 attr.border_pixel = 0;
1432 attr.background_pixel = background_pixel;
1433 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1434 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1436 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1437 CWOverrideRedirect;
1439 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1440 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1443 void
1444 ps1extents(struct rendering *r)
1446 char *dup;
1447 dup = strdupn(r->ps1);
1448 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1449 free(dup);
1452 void
1453 usage(char *prgname)
1455 fprintf(stderr,
1456 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1457 " [-d separator] [-e window] [-f font] [-G color] [-g "
1458 "size]\n"
1459 " [-H height] [-I color] [-i size] [-J color] [-j "
1460 "size] [-l layout]\n"
1461 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1462 "color]\n"
1463 " [-t color] [-W width] [-x coord] [-y coord]\n",
1464 prgname);
1467 int
1468 main(int argc, char **argv)
1470 struct completions *cs;
1471 struct rendering r;
1472 XVisualInfo vinfo;
1473 Colormap cmap;
1474 size_t nlines, i;
1475 Window parent_window;
1476 XrmDatabase xdb;
1477 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1478 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1479 ch_borders_bg[4]; /* N E S W */
1480 enum state status;
1481 int ch;
1482 int offset_x, offset_y, x, y;
1483 int textlen, d_width, d_height;
1484 short embed;
1485 char *sep, *parent_window_id;
1486 char **lines, **vlines;
1487 char *fontname, *text, *xrm;
1489 sep = NULL;
1490 parent_window_id = NULL;
1492 r.first_selected = 0;
1493 r.free_text = 1;
1494 r.multiple_select = 0;
1495 r.offset = 0;
1497 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1498 switch (ch) {
1499 case 'h': /* help */
1500 usage(*argv);
1501 return 0;
1502 case 'v': /* version */
1503 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1504 return 0;
1505 case 'e': /* embed */
1506 if ((parent_window_id = strdup(optarg)) == NULL)
1507 err(1, "strdup");
1508 break;
1509 case 'd':
1510 if ((sep = strdup(optarg)) == NULL)
1511 err(1, "strdup");
1512 break;
1513 case 'A':
1514 r.free_text = 0;
1515 break;
1516 case 'm':
1517 r.multiple_select = 1;
1518 break;
1519 default:
1520 break;
1524 lines = readlines(&nlines);
1526 vlines = NULL;
1527 if (sep != NULL) {
1528 int l;
1529 l = strlen(sep);
1530 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1531 err(1, "calloc");
1533 for (i = 0; i < nlines; i++) {
1534 char *t;
1535 t = strstr(lines[i], sep);
1536 if (t == NULL)
1537 vlines[i] = lines[i];
1538 else
1539 vlines[i] = t + l;
1543 setlocale(LC_ALL, getenv("LANG"));
1545 status = LOOPING;
1547 /* where the monitor start (used only with xinerama) */
1548 offset_x = offset_y = 0;
1550 /* default width and height */
1551 r.width = 400;
1552 r.height = 20;
1554 /* default position on the screen */
1555 x = y = 0;
1557 for (i = 0; i < 4; ++i) {
1558 /* default paddings */
1559 r.p_padding[i] = 10;
1560 r.c_padding[i] = 10;
1561 r.ch_padding[i] = 10;
1563 /* default borders */
1564 r.borders[i] = 0;
1565 r.p_borders[i] = 0;
1566 r.c_borders[i] = 0;
1567 r.ch_borders[i] = 0;
1571 * The prompt. We duplicate the string so later is easy to
1572 * free (in the case it's been overwritten by the user)
1574 if ((r.ps1 = strdup("$ ")) == NULL)
1575 err(1, "strdup");
1577 /* same for the font name */
1578 if ((fontname = strdup(DEFFONT)) == NULL)
1579 err(1, "strdup");
1581 textlen = 10;
1582 if ((text = malloc(textlen * sizeof(char))) == NULL)
1583 err(1, "malloc");
1585 /* struct completions *cs = filter(text, lines); */
1586 if ((cs = compls_new(nlines)) == NULL)
1587 err(1, "compls_new");
1589 /* start talking to xorg */
1590 r.d = XOpenDisplay(NULL);
1591 if (r.d == NULL) {
1592 fprintf(stderr, "Could not open display!\n");
1593 return EX_UNAVAILABLE;
1596 embed = 1;
1597 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1598 parent_window = DefaultRootWindow(r.d);
1599 embed = 0;
1602 /* get display size */
1603 get_wh(r.d, &parent_window, &d_width, &d_height);
1605 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1606 XineramaScreenInfo *info;
1607 Window rr;
1608 Window root;
1609 int number_of_screens, monitors, i;
1610 int root_x, root_y, win_x, win_y;
1611 unsigned int mask;
1612 short res;
1614 number_of_screens = XScreenCount(r.d);
1615 for (i = 0; i < number_of_screens; ++i) {
1616 root = XRootWindow(r.d, i);
1617 res = XQueryPointer(
1618 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1619 if (res)
1620 break;
1623 if (!res) {
1624 fprintf(stderr, "No mouse found.\n");
1625 root_x = 0;
1626 root_y = 0;
1629 /* Now find in which monitor the mice is */
1630 info = XineramaQueryScreens(r.d, &monitors);
1631 if (info) {
1632 for (i = 0; i < monitors; ++i) {
1633 if (info[i].x_org <= root_x
1634 && root_x <= (info[i].x_org + info[i].width)
1635 && info[i].y_org <= root_y
1636 && root_y <= (info[i].y_org + info[i].height)) {
1637 offset_x = info[i].x_org;
1638 offset_y = info[i].y_org;
1639 d_width = info[i].width;
1640 d_height = info[i].height;
1641 break;
1645 XFree(info);
1648 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1649 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1650 AllocNone);
1652 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1653 fgs[2] = parse_color("#000", NULL);
1655 bgs[0] = bgs[1] = parse_color("#000", NULL);
1656 bgs[2] = parse_color("#fff", NULL);
1658 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1659 parse_color("#000", NULL);
1661 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1662 = parse_color("#000", NULL);
1663 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1664 = parse_color("#000", NULL);
1665 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1666 = parse_color("#000", NULL);
1668 r.horizontal_layout = 1;
1670 /* Read the resources */
1671 XrmInitialize();
1672 xrm = XResourceManagerString(r.d);
1673 xdb = NULL;
1674 if (xrm != NULL) {
1675 XrmValue value;
1676 char *datatype[20];
1678 xdb = XrmGetStringDatabase(xrm);
1680 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1681 free(fontname);
1682 if ((fontname = strdup(value.addr)) == NULL)
1683 err(1, "strdup");
1684 } else {
1685 fprintf(stderr, "no font defined, using %s\n", fontname);
1688 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1689 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1690 else
1691 fprintf(stderr, "no layout defined, using horizontal\n");
1693 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1694 free(r.ps1);
1695 r.ps1 = normalize_str(value.addr);
1696 } else {
1697 fprintf(stderr,
1698 "no prompt defined, using \"%s\" as "
1699 "default\n",
1700 r.ps1);
1703 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1704 char **sizes;
1705 sizes = parse_csslike(value.addr);
1706 if (sizes != NULL)
1707 for (i = 0; i < 4; ++i)
1708 r.p_borders[i] = parse_integer(sizes[i], 0);
1709 else
1710 fprintf(stderr,
1711 "error while parsing "
1712 "MyMenu.prompt.border.size");
1715 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1716 char **colors;
1717 colors = parse_csslike(value.addr);
1718 if (colors != NULL)
1719 for (i = 0; i < 4; ++i)
1720 p_borders_bg[i] = parse_color(colors[i], "#000");
1721 else
1722 fprintf(stderr,
1723 "error while parsing "
1724 "MyMenu.prompt.border.color");
1727 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1728 char **colors;
1729 colors = parse_csslike(value.addr);
1730 if (colors != NULL)
1731 for (i = 0; i < 4; ++i)
1732 r.p_padding[i] = parse_integer(colors[i], 0);
1733 else
1734 fprintf(stderr,
1735 "error while parsing "
1736 "MyMenu.prompt.padding");
1739 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1740 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1741 else
1742 fprintf(stderr, "no width defined, using %d\n", r.width);
1744 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1745 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1746 else
1747 fprintf(stderr, "no height defined, using %d\n", r.height);
1749 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1750 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1752 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1753 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1755 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1756 char **borders;
1757 borders = parse_csslike(value.addr);
1758 if (borders != NULL)
1759 for (i = 0; i < 4; ++i)
1760 r.borders[i] = parse_int_with_percentage(
1761 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1762 else
1763 fprintf(stderr,
1764 "error while parsing "
1765 "MyMenu.border.size\n");
1768 /* Prompt */
1769 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1770 fgs[0] = parse_color(value.addr, "#fff");
1772 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1773 bgs[0] = parse_color(value.addr, "#000");
1775 /* Completions */
1776 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1777 fgs[1] = parse_color(value.addr, "#fff");
1779 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1780 bgs[1] = parse_color(value.addr, "#000");
1782 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1783 char **paddings;
1784 paddings = parse_csslike(value.addr);
1785 if (paddings != NULL)
1786 for (i = 0; i < 4; ++i)
1787 r.c_padding[i] = parse_integer(paddings[i], 0);
1788 else
1789 fprintf(stderr,
1790 "Error while parsing "
1791 "MyMenu.completion.padding");
1794 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1795 char **sizes;
1796 sizes = parse_csslike(value.addr);
1797 if (sizes != NULL)
1798 for (i = 0; i < 4; ++i)
1799 r.c_borders[i] = parse_integer(sizes[i], 0);
1800 else
1801 fprintf(stderr,
1802 "Error while parsing "
1803 "MyMenu.completion.border.size");
1806 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1807 char **sizes;
1808 sizes = parse_csslike(value.addr);
1809 if (sizes != NULL)
1810 for (i = 0; i < 4; ++i)
1811 c_borders_bg[i] = parse_color(sizes[i], "#000");
1812 else
1813 fprintf(stderr,
1814 "Error while parsing "
1815 "MyMenu.completion.border.color");
1818 /* Completion Highlighted */
1819 if (XrmGetResource(
1820 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1821 fgs[2] = parse_color(value.addr, "#000");
1823 if (XrmGetResource(
1824 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1825 bgs[2] = parse_color(value.addr, "#fff");
1827 if (XrmGetResource(
1828 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1829 char **paddings;
1830 paddings = parse_csslike(value.addr);
1831 if (paddings != NULL)
1832 for (i = 0; i < 4; ++i)
1833 r.ch_padding[i] = parse_integer(paddings[i], 0);
1834 else
1835 fprintf(stderr,
1836 "Error while parsing "
1837 "MyMenu.completion_highlighted."
1838 "padding");
1841 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1842 &value)) {
1843 char **sizes;
1844 sizes = parse_csslike(value.addr);
1845 if (sizes != NULL)
1846 for (i = 0; i < 4; ++i)
1847 r.ch_borders[i] = parse_integer(sizes[i], 0);
1848 else
1849 fprintf(stderr,
1850 "Error while parsing "
1851 "MyMenu.completion_highlighted."
1852 "border.size");
1855 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1856 &value)) {
1857 char **colors;
1858 colors = parse_csslike(value.addr);
1859 if (colors != NULL)
1860 for (i = 0; i < 4; ++i)
1861 ch_borders_bg[i] = parse_color(colors[i], "#000");
1862 else
1863 fprintf(stderr,
1864 "Error while parsing "
1865 "MyMenu.completion_highlighted."
1866 "border.color");
1869 /* Border */
1870 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1871 char **colors;
1872 colors = parse_csslike(value.addr);
1873 if (colors != NULL)
1874 for (i = 0; i < 4; ++i)
1875 borders_bg[i] = parse_color(colors[i], "#000");
1876 else
1877 fprintf(stderr,
1878 "error while parsing "
1879 "MyMenu.border.color\n");
1883 /* Second round of args parsing */
1884 optind = 0; /* reset the option index */
1885 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1886 switch (ch) {
1887 case 'a':
1888 r.first_selected = 1;
1889 break;
1890 case 'A':
1891 /* free_text -- already catched */
1892 case 'd':
1893 /* separator -- this case was already catched */
1894 case 'e':
1895 /* embedding mymenu this case was already catched. */
1896 case 'm':
1897 /* multiple selection this case was already catched.
1899 break;
1900 case 'p': {
1901 char *newprompt;
1902 newprompt = strdup(optarg);
1903 if (newprompt != NULL) {
1904 free(r.ps1);
1905 r.ps1 = newprompt;
1907 break;
1909 case 'x':
1910 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1911 break;
1912 case 'y':
1913 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1914 break;
1915 case 'P': {
1916 char **paddings;
1917 if ((paddings = parse_csslike(optarg)) != NULL)
1918 for (i = 0; i < 4; ++i)
1919 r.p_padding[i] = parse_integer(paddings[i], 0);
1920 break;
1922 case 'G': {
1923 char **colors;
1924 if ((colors = parse_csslike(optarg)) != NULL)
1925 for (i = 0; i < 4; ++i)
1926 p_borders_bg[i] = parse_color(colors[i], "#000");
1927 break;
1929 case 'g': {
1930 char **sizes;
1931 if ((sizes = parse_csslike(optarg)) != NULL)
1932 for (i = 0; i < 4; ++i)
1933 r.p_borders[i] = parse_integer(sizes[i], 0);
1934 break;
1936 case 'I': {
1937 char **colors;
1938 if ((colors = parse_csslike(optarg)) != NULL)
1939 for (i = 0; i < 4; ++i)
1940 c_borders_bg[i] = parse_color(colors[i], "#000");
1941 break;
1943 case 'i': {
1944 char **sizes;
1945 if ((sizes = parse_csslike(optarg)) != NULL)
1946 for (i = 0; i < 4; ++i)
1947 r.c_borders[i] = parse_integer(sizes[i], 0);
1948 break;
1950 case 'J': {
1951 char **colors;
1952 if ((colors = parse_csslike(optarg)) != NULL)
1953 for (i = 0; i < 4; ++i)
1954 ch_borders_bg[i] = parse_color(colors[i], "#000");
1955 break;
1957 case 'j': {
1958 char **sizes;
1959 if ((sizes = parse_csslike(optarg)) != NULL)
1960 for (i = 0; i < 4; ++i)
1961 r.ch_borders[i] = parse_integer(sizes[i], 0);
1962 break;
1964 case 'l':
1965 r.horizontal_layout = !strcmp(optarg, "horizontal");
1966 break;
1967 case 'f': {
1968 char *newfont;
1969 if ((newfont = strdup(optarg)) != NULL) {
1970 free(fontname);
1971 fontname = newfont;
1973 break;
1975 case 'W':
1976 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1977 break;
1978 case 'H':
1979 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1980 break;
1981 case 'b': {
1982 char **borders;
1983 if ((borders = parse_csslike(optarg)) != NULL) {
1984 for (i = 0; i < 4; ++i)
1985 r.borders[i] = parse_integer(borders[i], 0);
1986 } else
1987 fprintf(stderr, "Error parsing b option\n");
1988 break;
1990 case 'B': {
1991 char **colors;
1992 if ((colors = parse_csslike(optarg)) != NULL) {
1993 for (i = 0; i < 4; ++i)
1994 borders_bg[i] = parse_color(colors[i], "#000");
1995 } else
1996 fprintf(stderr, "error while parsing B option\n");
1997 break;
1999 case 't':
2000 fgs[0] = parse_color(optarg, NULL);
2001 break;
2002 case 'T':
2003 bgs[0] = parse_color(optarg, NULL);
2004 break;
2005 case 'c':
2006 fgs[1] = parse_color(optarg, NULL);
2007 break;
2008 case 'C':
2009 bgs[1] = parse_color(optarg, NULL);
2010 break;
2011 case 's':
2012 fgs[2] = parse_color(optarg, NULL);
2013 break;
2014 case 'S':
2015 bgs[2] = parse_color(optarg, NULL);
2016 break;
2017 default:
2018 fprintf(stderr, "Unrecognized option %c\n", ch);
2019 status = ERR;
2020 break;
2024 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2025 fprintf(stderr, "height, width, x or y are lesser than 0.");
2026 status = ERR;
2029 /* since only now we know if the first should be selected,
2030 * update the completion here */
2031 update_completions(cs, text, lines, vlines, r.first_selected);
2033 /* update the prompt lenght, only now we surely know the length of it
2035 r.ps1len = strlen(r.ps1);
2037 /* Create the window */
2038 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2039 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2040 XMapRaised(r.d, r.w);
2042 /* If embed, listen for other events as well */
2043 if (embed) {
2044 Window *children, parent, root;
2045 unsigned int children_no;
2047 XSelectInput(r.d, parent_window, FocusChangeMask);
2048 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2049 && children) {
2050 for (i = 0; i < children_no && children[i] != r.w; ++i)
2051 XSelectInput(r.d, children[i], FocusChangeMask);
2052 XFree(children);
2054 grabfocus(r.d, r.w);
2057 take_keyboard(r.d, r.w);
2059 r.x_zero = r.borders[3];
2060 r.y_zero = r.borders[0];
2063 XGCValues values;
2065 for (i = 0; i < 3; ++i) {
2066 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2067 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2070 for (i = 0; i < 4; ++i) {
2071 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2072 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2073 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2074 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2078 /* Load the colors in our GCs */
2079 for (i = 0; i < 3; ++i) {
2080 XSetForeground(r.d, r.fgs[i], fgs[i]);
2081 XSetForeground(r.d, r.bgs[i], bgs[i]);
2084 for (i = 0; i < 4; ++i) {
2085 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2086 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2087 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2088 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2091 if (load_font(&r, fontname) == -1)
2092 status = ERR;
2094 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2096 for (i = 0; i < 3; ++i) {
2097 rgba_t c;
2098 XRenderColor xrcolor;
2100 c = *(rgba_t *)&fgs[i];
2101 xrcolor.red = EXPANDBITS(c.rgba.r);
2102 xrcolor.green = EXPANDBITS(c.rgba.g);
2103 xrcolor.blue = EXPANDBITS(c.rgba.b);
2104 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2105 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2108 /* compute prompt dimensions */
2109 ps1extents(&r);
2111 xim_init(&r, &xdb);
2113 #ifdef __OpenBSD__
2114 if (pledge("stdio", "") == -1)
2115 err(1, "pledge");
2116 #endif
2118 /* Cache text height */
2119 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2121 /* Draw the window for the first time */
2122 draw(&r, text, cs);
2124 /* Main loop */
2125 while (status == LOOPING || status == OK_LOOP) {
2126 status = loop(&r, &text, &textlen, cs, lines, vlines);
2128 if (status != ERR)
2129 printf("%s\n", text);
2131 if (!r.multiple_select && status == OK_LOOP)
2132 status = OK;
2135 XUngrabKeyboard(r.d, CurrentTime);
2137 for (i = 0; i < 3; ++i)
2138 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2140 for (i = 0; i < 3; ++i) {
2141 XFreeGC(r.d, r.fgs[i]);
2142 XFreeGC(r.d, r.bgs[i]);
2145 for (i = 0; i < 4; ++i) {
2146 XFreeGC(r.d, r.borders_bg[i]);
2147 XFreeGC(r.d, r.p_borders_bg[i]);
2148 XFreeGC(r.d, r.c_borders_bg[i]);
2149 XFreeGC(r.d, r.ch_borders_bg[i]);
2152 XDestroyIC(r.xic);
2153 XCloseIM(r.xim);
2155 for (i = 0; i < 3; ++i)
2156 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2157 XftFontClose(r.d, r.font);
2158 XftDrawDestroy(r.xftdraw);
2160 free(r.ps1);
2161 free(fontname);
2162 free(text);
2164 free(lines);
2165 free(vlines);
2166 compls_delete(cs);
2168 XFreeColormap(r.d, cmap);
2170 XDestroyWindow(r.d, r.w);
2171 XCloseDisplay(r.d);
2173 return status != OK;