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 /* find the current xinerama monitor if possible */
813 void
814 findmonitor(Display *d, int *x, int *y, int *width, int *height)
816 XineramaScreenInfo *info;
817 Window rr;
818 Window root;
819 int screens, monitors, i;
820 int rootx, rooty, winx, winy;
821 unsigned int mask;
822 short res;
824 if (!XineramaIsActive(d))
825 return;
827 screens = XScreenCount(d);
828 for (i = 0; i < screens; ++i) {
829 root = XRootWindow(d, i);
830 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
831 &winy, &mask);
832 if (res)
833 break;
836 if (!res)
837 return;
839 /* Now find in which monitor the mice is */
840 info = XineramaQueryScreens(d, &monitors);
841 if (info == NULL)
842 return;
844 for (i = 0; i < monitors; ++i) {
845 if (info[i].x_org <= rootx &&
846 rootx <= (info[i].x_org + info[i].width) &&
847 info[i].y_org <= rooty &&
848 rooty <= (info[i].y_org + info[i].height)) {
849 *x = info[i].x_org;
850 *y = info[i].y_org;
851 *width = info[i].width;
852 *height = info[i].height;
853 break;
857 XFree(info);
860 int
861 grabfocus(Display *d, Window w)
863 int i;
864 for (i = 0; i < 100; ++i) {
865 Window focuswin;
866 int revert_to_win;
868 XGetInputFocus(d, &focuswin, &revert_to_win);
870 if (focuswin == w)
871 return 1;
873 XSetInputFocus(d, w, RevertToParent, CurrentTime);
874 usleep(1000);
876 return 0;
879 /*
880 * I know this may seem a little hackish BUT is the only way I managed
881 * to actually grab that goddam keyboard. Only one call to
882 * XGrabKeyboard does not always end up with the keyboard grabbed!
883 */
884 int
885 take_keyboard(Display *d, Window w)
887 int i;
888 for (i = 0; i < 100; i++) {
889 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
890 CurrentTime) == GrabSuccess)
891 return 1;
892 usleep(1000);
894 fprintf(stderr, "Cannot grab keyboard\n");
895 return 0;
898 unsigned long
899 parse_color(const char *str, const char *def)
901 size_t len;
902 rgba_t tmp;
903 char *ep;
905 if (str == NULL)
906 goto invc;
908 len = strlen(str);
910 /* +1 for the # ath the start */
911 if (*str != '#' || len > 9 || len < 4)
912 goto invc;
913 ++str; /* skip the # */
915 errno = 0;
916 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
918 if (errno)
919 goto invc;
921 switch (len - 1) {
922 case 3:
923 /* expand #rgb -> #rrggbb */
924 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
925 | (tmp.v & 0x00f) * 0x0011;
926 case 6:
927 /* assume 0xff opacity */
928 tmp.rgba.a = 0xff;
929 break;
930 } /* colors in #aarrggbb need no adjustments */
932 /* premultiply the alpha */
933 if (tmp.rgba.a) {
934 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
935 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
936 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
937 return tmp.v;
940 return 0U;
942 invc:
943 fprintf(stderr, "Invalid color: \"%s\".\n", str);
944 if (def != NULL)
945 return parse_color(def, NULL);
946 else
947 return 0U;
950 /*
951 * Given a string try to parse it as a number or return `def'.
952 */
953 int
954 parse_integer(const char *str, int def)
956 const char *errstr;
957 int i;
959 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
960 if (errstr != NULL) {
961 warnx("'%s' is %s; using %d as default", str, errstr, def);
962 return def;
965 return i;
968 /*
969 * Like parse_integer but recognize the percentages (i.e. strings
970 * ending with `%')
971 */
972 int
973 parse_int_with_percentage(const char *str, int default_value, int max)
975 int len = strlen(str);
977 if (len > 0 && str[len - 1] == '%') {
978 int val;
979 char *cpy;
981 if ((cpy = strdup(str)) == NULL)
982 err(1, "strdup");
984 cpy[len - 1] = '\0';
985 val = parse_integer(cpy, default_value);
986 free(cpy);
987 return val * max / 100;
990 return parse_integer(str, default_value);
993 void
994 get_mouse_coords(Display *d, int *x, int *y)
996 Window w, root;
997 int i;
998 unsigned int u;
1000 *x = *y = 0;
1001 root = DefaultRootWindow(d);
1003 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1004 for (i = 0; i < ScreenCount(d); ++i) {
1005 if (root == RootWindow(d, i))
1006 break;
1012 * Like parse_int_with_percentage but understands some special values:
1013 * - middle that is (max-self)/2
1014 * - center = middle
1015 * - start that is 0
1016 * - end that is (max-self)
1017 * - mx x coordinate of the mouse
1018 * - my y coordinate of the mouse
1020 int
1021 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1022 int self)
1024 if (!strcmp(str, "start"))
1025 return 0;
1026 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1027 return (max - self) / 2;
1028 if (!strcmp(str, "end"))
1029 return max - self;
1030 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1031 int x, y;
1033 get_mouse_coords(d, &x, &y);
1034 if (!strcmp(str, "mx"))
1035 return x - 1;
1036 else
1037 return y - 1;
1039 return parse_int_with_percentage(str, default_value, max);
1042 /* Parse a string like a CSS value. */
1043 /* TODO: harden a bit this function */
1044 char **
1045 parse_csslike(const char *str)
1047 int i, j;
1048 char *s, *token, **ret;
1049 short any_null;
1051 s = strdup(str);
1052 if (s == NULL)
1053 return NULL;
1055 ret = malloc(4 * sizeof(char *));
1056 if (ret == NULL) {
1057 free(s);
1058 return NULL;
1061 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1062 ret[i] = strdup(token);
1064 if (i == 1)
1065 for (j = 1; j < 4; j++)
1066 ret[j] = strdup(ret[0]);
1068 if (i == 2) {
1069 ret[2] = strdup(ret[0]);
1070 ret[3] = strdup(ret[1]);
1073 if (i == 3)
1074 ret[3] = strdup(ret[1]);
1077 * before we didn't check for the return type of strdup, here
1078 * we will
1081 any_null = 0;
1082 for (i = 0; i < 4; ++i)
1083 any_null = ret[i] == NULL || any_null;
1085 if (any_null)
1086 for (i = 0; i < 4; ++i)
1087 if (ret[i] != NULL)
1088 free(ret[i]);
1090 if (i == 0 || any_null) {
1091 free(s);
1092 free(ret);
1093 return NULL;
1096 return ret;
1100 * Given an event, try to understand what the users wants. If the
1101 * return value is ADD_CHAR then `input' is a pointer to a string that
1102 * will need to be free'ed later.
1104 enum action
1105 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1107 char str[SYM_BUF_SIZE] = { 0 };
1108 Status s;
1110 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1111 return DEL_CHAR;
1113 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1114 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1116 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1117 return CONFIRM;
1119 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1120 return EXIT;
1122 /* Try to read what key was pressed */
1123 s = 0;
1124 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1125 if (s == XBufferOverflow) {
1126 fprintf(stderr,
1127 "Buffer overflow when trying to create keyboard "
1128 "symbol map.\n");
1129 return EXIT;
1132 if (ev->state & ControlMask) {
1133 if (!strcmp(str, "")) /* C-u */
1134 return DEL_LINE;
1135 if (!strcmp(str, "")) /* C-w */
1136 return DEL_WORD;
1137 if (!strcmp(str, "")) /* C-h */
1138 return DEL_CHAR;
1139 if (!strcmp(str, "\r")) /* C-m */
1140 return CONFIRM_CONTINUE;
1141 if (!strcmp(str, "")) /* C-p */
1142 return PREV_COMPL;
1143 if (!strcmp(str, "")) /* C-n */
1144 return NEXT_COMPL;
1145 if (!strcmp(str, "")) /* C-c */
1146 return EXIT;
1147 if (!strcmp(str, "\t")) /* C-i */
1148 return TOGGLE_FIRST_SELECTED;
1151 *input = strdup(str);
1152 if (*input == NULL) {
1153 fprintf(stderr, "Error while allocating memory for key.\n");
1154 return EXIT;
1157 return ADD_CHAR;
1160 void
1161 confirm(enum state *status, struct rendering *r, struct completions *cs,
1162 char **text, int *textlen)
1164 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1165 /* if there is something selected expand it and return */
1166 int index = cs->selected == -1 ? 0 : cs->selected;
1167 struct completion *c = cs->completions;
1168 char *t;
1170 while (1) {
1171 if (index == 0)
1172 break;
1173 c++;
1174 index--;
1177 t = c->rcompletion;
1178 free(*text);
1179 *text = strdup(t);
1181 if (*text == NULL) {
1182 fprintf(stderr, "Memory allocation error\n");
1183 *status = ERR;
1186 *textlen = strlen(*text);
1187 return;
1190 if (!r->free_text) /* cannot accept arbitrary text */
1191 *status = LOOPING;
1195 * cs: completion list
1196 * offset: the offset of the click
1197 * first: the first (rendered) item
1198 * def: the default action
1200 enum action
1201 select_clicked(struct completions *cs, size_t offset, size_t first,
1202 enum action def)
1204 ssize_t selected = first;
1205 int set = 0;
1207 if (cs->length == 0)
1208 return NO_OP;
1210 if (offset < cs->completions[selected].offset)
1211 return EXIT;
1213 /* skip the first entry */
1214 for (selected += 1; selected < cs->length; ++selected) {
1215 if (cs->completions[selected].offset == -1)
1216 break;
1218 if (offset < cs->completions[selected].offset) {
1219 cs->selected = selected - 1;
1220 set = 1;
1221 break;
1225 if (!set)
1226 cs->selected = selected - 1;
1228 return def;
1231 enum action
1232 handle_mouse(struct rendering *r, struct completions *cs,
1233 XButtonPressedEvent *e)
1235 size_t off;
1237 if (r->horizontal_layout)
1238 off = e->x;
1239 else
1240 off = e->y;
1242 switch (e->button) {
1243 case Button1:
1244 return select_clicked(cs, off, r->offset, CONFIRM);
1246 case Button3:
1247 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1249 case Button4:
1250 return SCROLL_UP;
1252 case Button5:
1253 return SCROLL_DOWN;
1256 return NO_OP;
1259 /* event loop */
1260 enum state
1261 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1262 char **lines, char **vlines)
1264 enum state status = LOOPING;
1266 while (status == LOOPING) {
1267 XEvent e;
1268 XNextEvent(r->d, &e);
1270 if (XFilterEvent(&e, r->w))
1271 continue;
1273 switch (e.type) {
1274 case KeymapNotify:
1275 XRefreshKeyboardMapping(&e.xmapping);
1276 break;
1278 case FocusIn:
1279 /* Re-grab focus */
1280 if (e.xfocus.window != r->w)
1281 grabfocus(r->d, r->w);
1282 break;
1284 case VisibilityNotify:
1285 if (e.xvisibility.state != VisibilityUnobscured)
1286 XRaiseWindow(r->d, r->w);
1287 break;
1289 case MapNotify:
1290 get_wh(r->d, &r->w, &r->width, &r->height);
1291 draw(r, *text, cs);
1292 break;
1294 case KeyPress:
1295 case ButtonPress: {
1296 enum action a;
1297 char *input = NULL;
1299 if (e.type == KeyPress)
1300 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1301 r->xic, &input);
1302 else
1303 a = handle_mouse(r, cs,
1304 (XButtonPressedEvent *)&e);
1306 switch (a) {
1307 case NO_OP:
1308 break;
1310 case EXIT:
1311 status = ERR;
1312 break;
1314 case CONFIRM: {
1315 status = OK;
1316 confirm(&status, r, cs, text, textlen);
1317 break;
1320 case CONFIRM_CONTINUE: {
1321 status = OK_LOOP;
1322 confirm(&status, r, cs, text, textlen);
1323 break;
1326 case PREV_COMPL: {
1327 complete(cs, r->first_selected, 1, text,
1328 textlen, &status);
1329 r->offset = cs->selected;
1330 break;
1333 case NEXT_COMPL: {
1334 complete(cs, r->first_selected, 0, text,
1335 textlen, &status);
1336 r->offset = cs->selected;
1337 break;
1340 case DEL_CHAR:
1341 popc(*text);
1342 update_completions(cs, *text, lines, vlines,
1343 r->first_selected);
1344 r->offset = 0;
1345 break;
1347 case DEL_WORD: {
1348 popw(*text);
1349 update_completions(cs, *text, lines, vlines,
1350 r->first_selected);
1351 break;
1354 case DEL_LINE: {
1355 int i;
1356 for (i = 0; i < *textlen; ++i)
1357 *(*text + i) = 0;
1358 update_completions(cs, *text, lines, vlines,
1359 r->first_selected);
1360 r->offset = 0;
1361 break;
1364 case ADD_CHAR: {
1365 int str_len, i;
1367 str_len = strlen(input);
1370 * sometimes a strange key is pressed
1371 * i.e. ctrl alone), so input will be
1372 * empty. Don't need to update
1373 * completion in that case
1375 if (str_len == 0)
1376 break;
1378 for (i = 0; i < str_len; ++i) {
1379 *textlen = pushc(text, *textlen,
1380 input[i]);
1381 if (*textlen == -1) {
1382 fprintf(stderr,
1383 "Memory allocation "
1384 "error\n");
1385 status = ERR;
1386 break;
1390 if (status != ERR) {
1391 update_completions(cs, *text, lines,
1392 vlines, r->first_selected);
1393 free(input);
1396 r->offset = 0;
1397 break;
1400 case TOGGLE_FIRST_SELECTED:
1401 r->first_selected = !r->first_selected;
1402 if (r->first_selected && cs->selected < 0)
1403 cs->selected = 0;
1404 if (!r->first_selected && cs->selected == 0)
1405 cs->selected = -1;
1406 break;
1408 case SCROLL_DOWN:
1409 r->offset = MIN(r->offset + 1, cs->length - 1);
1410 break;
1412 case SCROLL_UP:
1413 r->offset = MAX((ssize_t)r->offset - 1, 0);
1414 break;
1419 draw(r, *text, cs);
1422 return status;
1425 int
1426 load_font(struct rendering *r, const char *fontname)
1428 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1429 return 0;
1432 void
1433 xim_init(struct rendering *r, XrmDatabase *xdb)
1435 XIMStyle best_match_style;
1436 XIMStyles *xis;
1437 int i;
1439 /* Open the X input method */
1440 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1441 err(1, "XOpenIM");
1443 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1444 fprintf(stderr, "Input Styles could not be retrieved\n");
1445 exit(EX_UNAVAILABLE);
1448 best_match_style = 0;
1449 for (i = 0; i < xis->count_styles; ++i) {
1450 XIMStyle ts = xis->supported_styles[i];
1451 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1452 best_match_style = ts;
1453 break;
1456 XFree(xis);
1458 if (!best_match_style)
1459 fprintf(stderr,
1460 "No matching input style could be determined\n");
1462 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1463 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1464 if (r->xic == NULL)
1465 err(1, "XCreateIC");
1468 void
1469 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1470 XVisualInfo vinfo, int x, int y, int ox, int oy,
1471 unsigned long background_pixel)
1473 XSetWindowAttributes attr;
1474 unsigned long vmask;
1476 /* Create the window */
1477 attr.colormap = cmap;
1478 attr.override_redirect = 1;
1479 attr.border_pixel = 0;
1480 attr.background_pixel = background_pixel;
1481 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1482 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1484 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1485 CWOverrideRedirect;
1487 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1488 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1491 void
1492 ps1extents(struct rendering *r)
1494 char *dup;
1495 dup = strdupn(r->ps1);
1496 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1497 free(dup);
1500 void
1501 usage(char *prgname)
1503 fprintf(stderr,
1504 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1505 " [-d separator] [-e window] [-f font] [-G color] [-g "
1506 "size]\n"
1507 " [-H height] [-I color] [-i size] [-J color] [-j "
1508 "size] [-l layout]\n"
1509 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1510 "color]\n"
1511 " [-t color] [-W width] [-x coord] [-y coord]\n",
1512 prgname);
1515 int
1516 main(int argc, char **argv)
1518 struct completions *cs;
1519 struct rendering r;
1520 XVisualInfo vinfo;
1521 Colormap cmap;
1522 size_t nlines, i;
1523 Window parent_window;
1524 XrmDatabase xdb;
1525 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1526 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1527 ch_borders_bg[4]; /* N E S W */
1528 enum state status;
1529 int ch;
1530 int offset_x, offset_y, x, y;
1531 int textlen, d_width, d_height;
1532 short embed;
1533 char *sep, *parent_window_id;
1534 char **lines, **vlines;
1535 char *fontname, *text, *xrm;
1537 sep = NULL;
1538 parent_window_id = NULL;
1540 r.first_selected = 0;
1541 r.free_text = 1;
1542 r.multiple_select = 0;
1543 r.offset = 0;
1545 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1546 switch (ch) {
1547 case 'h': /* help */
1548 usage(*argv);
1549 return 0;
1550 case 'v': /* version */
1551 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1552 return 0;
1553 case 'e': /* embed */
1554 if ((parent_window_id = strdup(optarg)) == NULL)
1555 err(1, "strdup");
1556 break;
1557 case 'd':
1558 if ((sep = strdup(optarg)) == NULL)
1559 err(1, "strdup");
1560 break;
1561 case 'A':
1562 r.free_text = 0;
1563 break;
1564 case 'm':
1565 r.multiple_select = 1;
1566 break;
1567 default:
1568 break;
1572 lines = readlines(&nlines);
1574 vlines = NULL;
1575 if (sep != NULL) {
1576 int l;
1577 l = strlen(sep);
1578 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1579 err(1, "calloc");
1581 for (i = 0; i < nlines; i++) {
1582 char *t;
1583 t = strstr(lines[i], sep);
1584 if (t == NULL)
1585 vlines[i] = lines[i];
1586 else
1587 vlines[i] = t + l;
1591 setlocale(LC_ALL, getenv("LANG"));
1593 status = LOOPING;
1595 /* where the monitor start (used only with xinerama) */
1596 offset_x = offset_y = 0;
1598 /* default width and height */
1599 r.width = 400;
1600 r.height = 20;
1602 /* default position on the screen */
1603 x = y = 0;
1605 for (i = 0; i < 4; ++i) {
1606 /* default paddings */
1607 r.p_padding[i] = 10;
1608 r.c_padding[i] = 10;
1609 r.ch_padding[i] = 10;
1611 /* default borders */
1612 r.borders[i] = 0;
1613 r.p_borders[i] = 0;
1614 r.c_borders[i] = 0;
1615 r.ch_borders[i] = 0;
1619 * The prompt. We duplicate the string so later is easy to
1620 * free (in the case it's been overwritten by the user)
1622 if ((r.ps1 = strdup("$ ")) == NULL)
1623 err(1, "strdup");
1625 /* same for the font name */
1626 if ((fontname = strdup(DEFFONT)) == NULL)
1627 err(1, "strdup");
1629 textlen = 10;
1630 if ((text = malloc(textlen * sizeof(char))) == NULL)
1631 err(1, "malloc");
1633 /* struct completions *cs = filter(text, lines); */
1634 if ((cs = compls_new(nlines)) == NULL)
1635 err(1, "compls_new");
1637 /* start talking to xorg */
1638 r.d = XOpenDisplay(NULL);
1639 if (r.d == NULL) {
1640 fprintf(stderr, "Could not open display!\n");
1641 return EX_UNAVAILABLE;
1644 embed = 1;
1645 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1646 parent_window = DefaultRootWindow(r.d);
1647 embed = 0;
1650 /* get display size */
1651 get_wh(r.d, &parent_window, &d_width, &d_height);
1653 if (!embed)
1654 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1656 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1657 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1658 AllocNone);
1660 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1661 fgs[2] = parse_color("#000", NULL);
1663 bgs[0] = bgs[1] = parse_color("#000", NULL);
1664 bgs[2] = parse_color("#fff", NULL);
1666 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1667 parse_color("#000", NULL);
1669 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1670 = parse_color("#000", NULL);
1671 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1672 = parse_color("#000", NULL);
1673 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1674 = parse_color("#000", NULL);
1676 r.horizontal_layout = 1;
1678 /* Read the resources */
1679 XrmInitialize();
1680 xrm = XResourceManagerString(r.d);
1681 xdb = NULL;
1682 if (xrm != NULL) {
1683 XrmValue value;
1684 char *datatype[20];
1686 xdb = XrmGetStringDatabase(xrm);
1688 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1689 free(fontname);
1690 if ((fontname = strdup(value.addr)) == NULL)
1691 err(1, "strdup");
1692 } else {
1693 fprintf(stderr, "no font defined, using %s\n", fontname);
1696 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1697 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1698 else
1699 fprintf(stderr, "no layout defined, using horizontal\n");
1701 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1702 free(r.ps1);
1703 r.ps1 = normalize_str(value.addr);
1704 } else {
1705 fprintf(stderr,
1706 "no prompt defined, using \"%s\" as "
1707 "default\n",
1708 r.ps1);
1711 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1712 char **sizes;
1713 sizes = parse_csslike(value.addr);
1714 if (sizes != NULL)
1715 for (i = 0; i < 4; ++i)
1716 r.p_borders[i] = parse_integer(sizes[i], 0);
1717 else
1718 fprintf(stderr,
1719 "error while parsing "
1720 "MyMenu.prompt.border.size");
1723 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1724 char **colors;
1725 colors = parse_csslike(value.addr);
1726 if (colors != NULL)
1727 for (i = 0; i < 4; ++i)
1728 p_borders_bg[i] = parse_color(colors[i], "#000");
1729 else
1730 fprintf(stderr,
1731 "error while parsing "
1732 "MyMenu.prompt.border.color");
1735 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1736 char **colors;
1737 colors = parse_csslike(value.addr);
1738 if (colors != NULL)
1739 for (i = 0; i < 4; ++i)
1740 r.p_padding[i] = parse_integer(colors[i], 0);
1741 else
1742 fprintf(stderr,
1743 "error while parsing "
1744 "MyMenu.prompt.padding");
1747 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1748 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1749 else
1750 fprintf(stderr, "no width defined, using %d\n", r.width);
1752 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1753 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1754 else
1755 fprintf(stderr, "no height defined, using %d\n", r.height);
1757 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1758 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1760 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1761 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1763 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1764 char **borders;
1765 borders = parse_csslike(value.addr);
1766 if (borders != NULL)
1767 for (i = 0; i < 4; ++i)
1768 r.borders[i] = parse_int_with_percentage(
1769 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1770 else
1771 fprintf(stderr,
1772 "error while parsing "
1773 "MyMenu.border.size\n");
1776 /* Prompt */
1777 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1778 fgs[0] = parse_color(value.addr, "#fff");
1780 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1781 bgs[0] = parse_color(value.addr, "#000");
1783 /* Completions */
1784 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1785 fgs[1] = parse_color(value.addr, "#fff");
1787 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1788 bgs[1] = parse_color(value.addr, "#000");
1790 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1791 char **paddings;
1792 paddings = parse_csslike(value.addr);
1793 if (paddings != NULL)
1794 for (i = 0; i < 4; ++i)
1795 r.c_padding[i] = parse_integer(paddings[i], 0);
1796 else
1797 fprintf(stderr,
1798 "Error while parsing "
1799 "MyMenu.completion.padding");
1802 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1803 char **sizes;
1804 sizes = parse_csslike(value.addr);
1805 if (sizes != NULL)
1806 for (i = 0; i < 4; ++i)
1807 r.c_borders[i] = parse_integer(sizes[i], 0);
1808 else
1809 fprintf(stderr,
1810 "Error while parsing "
1811 "MyMenu.completion.border.size");
1814 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1815 char **sizes;
1816 sizes = parse_csslike(value.addr);
1817 if (sizes != NULL)
1818 for (i = 0; i < 4; ++i)
1819 c_borders_bg[i] = parse_color(sizes[i], "#000");
1820 else
1821 fprintf(stderr,
1822 "Error while parsing "
1823 "MyMenu.completion.border.color");
1826 /* Completion Highlighted */
1827 if (XrmGetResource(
1828 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1829 fgs[2] = parse_color(value.addr, "#000");
1831 if (XrmGetResource(
1832 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1833 bgs[2] = parse_color(value.addr, "#fff");
1835 if (XrmGetResource(
1836 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1837 char **paddings;
1838 paddings = parse_csslike(value.addr);
1839 if (paddings != NULL)
1840 for (i = 0; i < 4; ++i)
1841 r.ch_padding[i] = parse_integer(paddings[i], 0);
1842 else
1843 fprintf(stderr,
1844 "Error while parsing "
1845 "MyMenu.completion_highlighted."
1846 "padding");
1849 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1850 &value)) {
1851 char **sizes;
1852 sizes = parse_csslike(value.addr);
1853 if (sizes != NULL)
1854 for (i = 0; i < 4; ++i)
1855 r.ch_borders[i] = parse_integer(sizes[i], 0);
1856 else
1857 fprintf(stderr,
1858 "Error while parsing "
1859 "MyMenu.completion_highlighted."
1860 "border.size");
1863 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1864 &value)) {
1865 char **colors;
1866 colors = parse_csslike(value.addr);
1867 if (colors != NULL)
1868 for (i = 0; i < 4; ++i)
1869 ch_borders_bg[i] = parse_color(colors[i], "#000");
1870 else
1871 fprintf(stderr,
1872 "Error while parsing "
1873 "MyMenu.completion_highlighted."
1874 "border.color");
1877 /* Border */
1878 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1879 char **colors;
1880 colors = parse_csslike(value.addr);
1881 if (colors != NULL)
1882 for (i = 0; i < 4; ++i)
1883 borders_bg[i] = parse_color(colors[i], "#000");
1884 else
1885 fprintf(stderr,
1886 "error while parsing "
1887 "MyMenu.border.color\n");
1891 /* Second round of args parsing */
1892 optind = 0; /* reset the option index */
1893 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1894 switch (ch) {
1895 case 'a':
1896 r.first_selected = 1;
1897 break;
1898 case 'A':
1899 /* free_text -- already catched */
1900 case 'd':
1901 /* separator -- this case was already catched */
1902 case 'e':
1903 /* embedding mymenu this case was already catched. */
1904 case 'm':
1905 /* multiple selection this case was already catched.
1907 break;
1908 case 'p': {
1909 char *newprompt;
1910 newprompt = strdup(optarg);
1911 if (newprompt != NULL) {
1912 free(r.ps1);
1913 r.ps1 = newprompt;
1915 break;
1917 case 'x':
1918 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1919 break;
1920 case 'y':
1921 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1922 break;
1923 case 'P': {
1924 char **paddings;
1925 if ((paddings = parse_csslike(optarg)) != NULL)
1926 for (i = 0; i < 4; ++i)
1927 r.p_padding[i] = parse_integer(paddings[i], 0);
1928 break;
1930 case 'G': {
1931 char **colors;
1932 if ((colors = parse_csslike(optarg)) != NULL)
1933 for (i = 0; i < 4; ++i)
1934 p_borders_bg[i] = parse_color(colors[i], "#000");
1935 break;
1937 case 'g': {
1938 char **sizes;
1939 if ((sizes = parse_csslike(optarg)) != NULL)
1940 for (i = 0; i < 4; ++i)
1941 r.p_borders[i] = parse_integer(sizes[i], 0);
1942 break;
1944 case 'I': {
1945 char **colors;
1946 if ((colors = parse_csslike(optarg)) != NULL)
1947 for (i = 0; i < 4; ++i)
1948 c_borders_bg[i] = parse_color(colors[i], "#000");
1949 break;
1951 case 'i': {
1952 char **sizes;
1953 if ((sizes = parse_csslike(optarg)) != NULL)
1954 for (i = 0; i < 4; ++i)
1955 r.c_borders[i] = parse_integer(sizes[i], 0);
1956 break;
1958 case 'J': {
1959 char **colors;
1960 if ((colors = parse_csslike(optarg)) != NULL)
1961 for (i = 0; i < 4; ++i)
1962 ch_borders_bg[i] = parse_color(colors[i], "#000");
1963 break;
1965 case 'j': {
1966 char **sizes;
1967 if ((sizes = parse_csslike(optarg)) != NULL)
1968 for (i = 0; i < 4; ++i)
1969 r.ch_borders[i] = parse_integer(sizes[i], 0);
1970 break;
1972 case 'l':
1973 r.horizontal_layout = !strcmp(optarg, "horizontal");
1974 break;
1975 case 'f': {
1976 char *newfont;
1977 if ((newfont = strdup(optarg)) != NULL) {
1978 free(fontname);
1979 fontname = newfont;
1981 break;
1983 case 'W':
1984 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1985 break;
1986 case 'H':
1987 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1988 break;
1989 case 'b': {
1990 char **borders;
1991 if ((borders = parse_csslike(optarg)) != NULL) {
1992 for (i = 0; i < 4; ++i)
1993 r.borders[i] = parse_integer(borders[i], 0);
1994 } else
1995 fprintf(stderr, "Error parsing b option\n");
1996 break;
1998 case 'B': {
1999 char **colors;
2000 if ((colors = parse_csslike(optarg)) != NULL) {
2001 for (i = 0; i < 4; ++i)
2002 borders_bg[i] = parse_color(colors[i], "#000");
2003 } else
2004 fprintf(stderr, "error while parsing B option\n");
2005 break;
2007 case 't':
2008 fgs[0] = parse_color(optarg, NULL);
2009 break;
2010 case 'T':
2011 bgs[0] = parse_color(optarg, NULL);
2012 break;
2013 case 'c':
2014 fgs[1] = parse_color(optarg, NULL);
2015 break;
2016 case 'C':
2017 bgs[1] = parse_color(optarg, NULL);
2018 break;
2019 case 's':
2020 fgs[2] = parse_color(optarg, NULL);
2021 break;
2022 case 'S':
2023 bgs[2] = parse_color(optarg, NULL);
2024 break;
2025 default:
2026 fprintf(stderr, "Unrecognized option %c\n", ch);
2027 status = ERR;
2028 break;
2032 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2033 fprintf(stderr, "height, width, x or y are lesser than 0.");
2034 status = ERR;
2037 /* since only now we know if the first should be selected,
2038 * update the completion here */
2039 update_completions(cs, text, lines, vlines, r.first_selected);
2041 /* update the prompt lenght, only now we surely know the length of it
2043 r.ps1len = strlen(r.ps1);
2045 /* Create the window */
2046 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2047 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2048 XMapRaised(r.d, r.w);
2050 /* If embed, listen for other events as well */
2051 if (embed) {
2052 Window *children, parent, root;
2053 unsigned int children_no;
2055 XSelectInput(r.d, parent_window, FocusChangeMask);
2056 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2057 && children) {
2058 for (i = 0; i < children_no && children[i] != r.w; ++i)
2059 XSelectInput(r.d, children[i], FocusChangeMask);
2060 XFree(children);
2062 grabfocus(r.d, r.w);
2065 take_keyboard(r.d, r.w);
2067 r.x_zero = r.borders[3];
2068 r.y_zero = r.borders[0];
2071 XGCValues values;
2073 for (i = 0; i < 3; ++i) {
2074 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2075 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2078 for (i = 0; i < 4; ++i) {
2079 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2080 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2081 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2082 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2086 /* Load the colors in our GCs */
2087 for (i = 0; i < 3; ++i) {
2088 XSetForeground(r.d, r.fgs[i], fgs[i]);
2089 XSetForeground(r.d, r.bgs[i], bgs[i]);
2092 for (i = 0; i < 4; ++i) {
2093 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2094 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2095 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2096 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2099 if (load_font(&r, fontname) == -1)
2100 status = ERR;
2102 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2104 for (i = 0; i < 3; ++i) {
2105 rgba_t c;
2106 XRenderColor xrcolor;
2108 c = *(rgba_t *)&fgs[i];
2109 xrcolor.red = EXPANDBITS(c.rgba.r);
2110 xrcolor.green = EXPANDBITS(c.rgba.g);
2111 xrcolor.blue = EXPANDBITS(c.rgba.b);
2112 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2113 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2116 /* compute prompt dimensions */
2117 ps1extents(&r);
2119 xim_init(&r, &xdb);
2121 #ifdef __OpenBSD__
2122 if (pledge("stdio", "") == -1)
2123 err(1, "pledge");
2124 #endif
2126 /* Cache text height */
2127 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2129 /* Draw the window for the first time */
2130 draw(&r, text, cs);
2132 /* Main loop */
2133 while (status == LOOPING || status == OK_LOOP) {
2134 status = loop(&r, &text, &textlen, cs, lines, vlines);
2136 if (status != ERR)
2137 printf("%s\n", text);
2139 if (!r.multiple_select && status == OK_LOOP)
2140 status = OK;
2143 XUngrabKeyboard(r.d, CurrentTime);
2145 for (i = 0; i < 3; ++i)
2146 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2148 for (i = 0; i < 3; ++i) {
2149 XFreeGC(r.d, r.fgs[i]);
2150 XFreeGC(r.d, r.bgs[i]);
2153 for (i = 0; i < 4; ++i) {
2154 XFreeGC(r.d, r.borders_bg[i]);
2155 XFreeGC(r.d, r.p_borders_bg[i]);
2156 XFreeGC(r.d, r.c_borders_bg[i]);
2157 XFreeGC(r.d, r.ch_borders_bg[i]);
2160 XDestroyIC(r.xic);
2161 XCloseIM(r.xim);
2163 for (i = 0; i < 3; ++i)
2164 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2165 XftFontClose(r.d, r.font);
2166 XftDrawDestroy(r.xftdraw);
2168 free(r.ps1);
2169 free(fontname);
2170 free(text);
2172 free(lines);
2173 free(vlines);
2174 compls_delete(cs);
2176 XFreeColormap(r.d, cmap);
2178 XDestroyWindow(r.d, r.w);
2179 XCloseDisplay(r.d);
2181 return status != OK;