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>
19 #ifdef USE_XINERAMA
20 #include <X11/extensions/Xinerama.h>
21 #endif
23 #ifdef USE_XFT
24 #include <X11/Xft/Xft.h>
25 #endif
27 #ifndef VERSION
28 #define VERSION "unknown"
29 #endif
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #define SYM_BUF_SIZE 4
36 #ifdef USE_XFT
37 #define default_fontname "monospace"
38 #else
39 #define default_fontname "fixed"
40 #endif
42 #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:"
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
49 /*
50 * If we don't have or we don't want an "ignore case" completion
51 * style, fall back to `strstr(3)`
52 */
53 #ifndef USE_STRCASESTR
54 #define strcasestr strstr
55 #endif
57 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
58 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
60 /* The states of the event loop */
61 enum state { LOOPING, OK_LOOP, OK, ERR };
63 /*
64 * For the drawing-related function. The text to be rendere could be
65 * the prompt, a completion or a highlighted completion
66 */
67 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
69 /* These are the possible action to be performed after user input. */
70 enum action {
71 NO_OP,
72 EXIT,
73 CONFIRM,
74 CONFIRM_CONTINUE,
75 NEXT_COMPL,
76 PREV_COMPL,
77 DEL_CHAR,
78 DEL_WORD,
79 DEL_LINE,
80 ADD_CHAR,
81 TOGGLE_FIRST_SELECTED,
82 SCROLL_DOWN,
83 SCROLL_UP,
84 };
86 /* A big set of values that needs to be carried around for drawing. A
87 * big struct to rule them all */
88 struct rendering {
89 Display *d; /* Connection to xorg */
90 Window w;
91 XIM xim;
92 int width;
93 int height;
94 int p_padding[4];
95 int c_padding[4];
96 int ch_padding[4];
97 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
98 the borders) */
99 int y_zero; /* like x_zero but for the y axis */
101 int offset; /* scroll offset */
103 short free_text;
104 short first_selected;
105 short multiple_select;
107 /* four border width */
108 int borders[4];
109 int p_borders[4];
110 int c_borders[4];
111 int ch_borders[4];
113 short horizontal_layout;
115 /* prompt */
116 char *ps1;
117 int ps1len;
118 int ps1w; /* ps1 width */
119 int ps1h; /* ps1 height */
121 int text_height; /* cache for the vertical layout */
123 XIC xic;
125 /* colors */
126 GC fgs[4];
127 GC bgs[4];
128 GC borders_bg[4];
129 GC p_borders_bg[4];
130 GC c_borders_bg[4];
131 GC ch_borders_bg[4];
132 #ifdef USE_XFT
133 XftFont *font;
134 XftDraw *xftdraw;
135 XftColor xft_colors[3];
136 #else
137 XFontSet font;
138 #endif
139 };
141 struct completion {
142 char *completion;
143 char *rcompletion;
144 int offset; /* the x (or y, depending on the layout) coordinate at
145 which the item is rendered */
146 };
148 /* Wrap the linked list of completions */
149 struct completions {
150 struct completion *completions;
151 ssize_t selected;
152 size_t length;
153 };
155 /* idea stolen from lemonbar. ty lemonboy */
156 typedef union {
157 struct {
158 uint8_t b;
159 uint8_t g;
160 uint8_t r;
161 uint8_t a;
162 } rgba;
163 uint32_t v;
164 } rgba_t;
166 extern char *optarg;
167 extern int optind;
169 /* Return a newly allocated (and empty) completion list */
170 struct completions *
171 compls_new(size_t length)
173 struct completions *cs = malloc(sizeof(struct completions));
175 if (cs == NULL)
176 return cs;
178 cs->completions = calloc(length, sizeof(struct completion));
179 if (cs->completions == NULL) {
180 free(cs);
181 return NULL;
184 cs->selected = -1;
185 cs->length = length;
186 return cs;
189 /* Delete the wrapper and the whole list */
190 void
191 compls_delete(struct completions *cs)
193 if (cs == NULL)
194 return;
196 free(cs->completions);
197 free(cs);
200 /*
201 * Create a completion list from a text and the list of possible
202 * completions (null terminated). Expects a non-null `cs'. `lines' and
203 * `vlines' should have the same length OR `vlines' is NULL.
204 */
205 void
206 filter(struct completions *cs, char *text, char **lines, char **vlines)
208 size_t index = 0;
209 size_t matching = 0;
210 char *l;
212 if (vlines == NULL)
213 vlines = lines;
215 while (1) {
216 if (lines[index] == NULL)
217 break;
219 l = vlines[index] != NULL ? vlines[index] : lines[index];
221 if (strcasestr(l, text) != NULL) {
222 struct completion *c = &cs->completions[matching];
223 c->completion = l;
224 c->rcompletion = lines[index];
225 matching++;
228 index++;
230 cs->length = matching;
231 cs->selected = -1;
234 /* Update the given completion */
235 void
236 update_completions(
237 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
239 filter(cs, text, lines, vlines);
240 if (first_selected && cs->length > 0)
241 cs->selected = 0;
244 /*
245 * Select the next or previous selection and update some state. `text'
246 * will be updated with the text of the completion and `textlen' with
247 * the new length. If the memory cannot be allocated `status' will be
248 * set to `ERR'.
249 */
250 void
251 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
252 enum state *status)
254 struct completion *n;
255 int index;
257 if (cs == NULL || cs->length == 0)
258 return;
260 /*
261 * If the first is always selected and the first entry is
262 * different from the text, expand the text and return
263 */
264 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
265 && !p) {
266 free(*text);
267 *text = strdup(cs->completions->completion);
268 if (text == NULL) {
269 *status = ERR;
270 return;
272 *textlen = strlen(*text);
273 return;
276 index = cs->selected;
278 if (index == -1 && p)
279 index = 0;
280 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
282 n = &cs->completions[cs->selected];
284 free(*text);
285 *text = strdup(n->completion);
286 if (text == NULL) {
287 fprintf(stderr, "Memory allocation error!\n");
288 *status = ERR;
289 return;
291 *textlen = strlen(*text);
294 /* Push the character c at the end of the string pointed by p */
295 int
296 pushc(char **p, int maxlen, char c)
298 int len;
300 len = strnlen(*p, maxlen);
301 if (!(len < maxlen - 2)) {
302 char *newptr;
304 maxlen += maxlen >> 1;
305 newptr = realloc(*p, maxlen);
306 if (newptr == NULL) /* bad */
307 return -1;
308 *p = newptr;
311 (*p)[len] = c;
312 (*p)[len + 1] = '\0';
313 return maxlen;
316 /*
317 * Remove the last rune from the *UTF-8* string! This is different
318 * from just setting the last byte to 0 (in some cases ofc). Return a
319 * pointer (e) to the last nonzero char. If e < p then p is empty!
320 */
321 char *
322 popc(char *p)
324 int len = strlen(p);
325 char *e;
327 if (len == 0)
328 return p;
330 e = p + len - 1;
332 do {
333 char c = *e;
335 *e = '\0';
336 e -= 1;
338 /*
339 * If c is a starting byte (11......) or is under
340 * U+007F we're done.
341 */
342 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
343 break;
344 } while (e >= p);
346 return e;
349 /* Remove the last word plus trailing white spaces from the given string */
350 void
351 popw(char *w)
353 int len;
354 short in_word = 1;
356 if ((len = strlen(w)) == 0)
357 return;
359 while (1) {
360 char *e = popc(w);
362 if (e < w)
363 return;
365 if (in_word && isspace(*e))
366 in_word = 0;
368 if (!in_word && !isspace(*e))
369 return;
373 /*
374 * If the string is surrounded by quates (`"') remove them and replace
375 * every `\"' in the string with a single double-quote.
376 */
377 char *
378 normalize_str(const char *str)
380 int len, p;
381 char *s;
383 if ((len = strlen(str)) == 0)
384 return NULL;
386 if ((s = calloc(len, sizeof(char))) == NULL)
387 err(1, "calloc");
388 p = 0;
390 while (*str) {
391 char c = *str;
393 if (*str == '\\') {
394 if (*(str + 1)) {
395 s[p] = *(str + 1);
396 p++;
397 str += 2; /* skip this and the next char */
398 continue;
399 } else
400 break;
402 if (c == '"') {
403 str++; /* skip only this char */
404 continue;
406 s[p] = c;
407 p++;
408 str++;
411 return s;
414 char **
415 readlines(size_t *lineslen)
417 size_t len = 0, cap = 0;
418 size_t linesize = 0;
419 ssize_t linelen;
420 char *line = NULL, **lines = NULL;
422 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
423 if (linelen != 0 && line[linelen-1] == '\n')
424 line[linelen-1] = '\0';
426 if (len == cap) {
427 size_t newcap;
428 void *t;
430 newcap = MAX(cap * 1.5, 32);
431 t = recallocarray(lines, cap, newcap, sizeof(char *));
432 if (t == NULL)
433 err(1, "recallocarray");
434 cap = newcap;
435 lines = t;
438 if ((lines[len++] = strdup(line)) == NULL)
439 err(1, "strdup");
442 if (ferror(stdin))
443 err(1, "getline");
444 free(line);
446 *lineslen = len;
447 return lines;
450 /*
451 * Compute the dimensions of the string str once rendered.
452 * It'll return the width and set ret_width and ret_height if not NULL
453 */
454 int
455 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
457 int height, width;
458 #ifdef USE_XFT
459 XGlyphInfo gi;
460 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
461 height = r->font->ascent - r->font->descent;
462 width = gi.width - gi.x;
463 #else
464 XRectangle rect;
465 XmbTextExtents(r->font, str, len, NULL, &rect);
466 height = rect.height;
467 width = rect.width;
468 #endif
469 if (ret_width != NULL)
470 *ret_width = width;
471 if (ret_height != NULL)
472 *ret_height = height;
473 return width;
476 void
477 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
479 #ifdef USE_XFT
480 XftColor xftcolor;
481 if (tt == PROMPT)
482 xftcolor = r->xft_colors[0];
483 if (tt == COMPL)
484 xftcolor = r->xft_colors[1];
485 if (tt == COMPL_HIGH)
486 xftcolor = r->xft_colors[2];
488 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
489 #else
490 GC gc;
491 if (tt == PROMPT)
492 gc = r->fgs[0];
493 if (tt == COMPL)
494 gc = r->fgs[1];
495 if (tt == COMPL_HIGH)
496 gc = r->fgs[2];
497 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
498 #endif
501 /* Duplicate the string and substitute every space with a 'n` */
502 char *
503 strdupn(char *str)
505 int len, i;
506 char *dup;
508 len = strlen(str);
510 if (str == NULL || len == 0)
511 return NULL;
513 if ((dup = strdup(str)) == NULL)
514 return NULL;
516 for (i = 0; i < len; ++i)
517 if (dup[i] == ' ')
518 dup[i] = 'n';
520 return dup;
523 int
524 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
526 GC *border_color, bg;
527 int *padding, *borders;
528 int ret = 0, inner_width, inner_height, x;
530 switch (t) {
531 case PROMPT:
532 border_color = r->p_borders_bg;
533 padding = r->p_padding;
534 borders = r->p_borders;
535 bg = r->bgs[0];
536 break;
537 case COMPL:
538 border_color = r->c_borders_bg;
539 padding = r->c_padding;
540 borders = r->c_borders;
541 bg = r->bgs[1];
542 break;
543 case COMPL_HIGH:
544 border_color = r->ch_borders_bg;
545 padding = r->ch_padding;
546 borders = r->ch_borders;
547 bg = r->bgs[2];
548 break;
551 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
553 inner_width = inner_width(r) - borders[1] - borders[3];
554 inner_height = padding[0] + r->text_height + padding[2];
556 /* Border top */
557 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
559 /* Border right */
560 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
561 borders[1], ret);
563 /* Border bottom */
564 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
565 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
567 /* Border left */
568 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
570 /* bg */
571 x = r->x_zero + borders[3];
572 y += borders[0];
573 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
575 /* content */
576 y += padding[0] + r->text_height;
577 x += padding[3];
578 if (prefix != NULL) {
579 draw_string(prefix, strlen(prefix), x, y, r, t);
580 x += prefix_width;
582 draw_string(text, strlen(text), x, y, r, t);
584 return ret;
587 int
588 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
590 GC *border_color, bg;
591 int *padding, *borders;
592 int ret = 0, inner_width, inner_height, y, text_width;
594 switch (t) {
595 case PROMPT:
596 border_color = r->p_borders_bg;
597 padding = r->p_padding;
598 borders = r->p_borders;
599 bg = r->bgs[0];
600 break;
601 case COMPL:
602 border_color = r->c_borders_bg;
603 padding = r->c_padding;
604 borders = r->c_borders;
605 bg = r->bgs[1];
606 break;
607 case COMPL_HIGH:
608 border_color = r->ch_borders_bg;
609 padding = r->ch_padding;
610 borders = r->ch_borders;
611 bg = r->bgs[2];
612 break;
615 if (padding[0] < 0 || padding[2] < 0)
616 padding[0] = padding[2]
617 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
619 /* If they are still lesser than 0, set 'em to 0 */
620 if (padding[0] < 0 || padding[2] < 0)
621 padding[0] = padding[2] = 0;
623 /* Get the text width */
624 text_extents(text, strlen(text), r, &text_width, NULL);
625 if (prefix != NULL)
626 text_width += prefix_width;
628 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
630 inner_width = padding[3] + text_width + padding[1];
631 inner_height = inner_height(r) - borders[0] - borders[2];
633 /* Border top */
634 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
636 /* Border right */
637 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
638 borders[1], inner_height(r));
640 /* Border bottom */
641 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
642 ret, borders[2]);
644 /* Border left */
645 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
647 /* bg */
648 x += borders[3];
649 y = r->y_zero + borders[0];
650 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
652 /* content */
653 y += padding[0] + r->text_height;
654 x += padding[3];
655 if (prefix != NULL) {
656 draw_string(prefix, strlen(prefix), x, y, r, t);
657 x += prefix_width;
659 draw_string(text, strlen(text), x, y, r, t);
661 return ret;
664 /* ,-----------------------------------------------------------------, */
665 /* | 20 char text | completion | completion | completion | compl | */
666 /* `-----------------------------------------------------------------' */
667 void
668 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
670 size_t i;
671 int x = r->x_zero;
673 /* Draw the prompt */
674 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
676 for (i = r->offset; i < cs->length; ++i) {
677 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
679 cs->completions[i].offset = x;
681 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
683 if (x > inner_width(r))
684 break;
687 for (i += 1; i < cs->length; ++i)
688 cs->completions[i].offset = -1;
691 /* ,-----------------------------------------------------------------, */
692 /* | prompt | */
693 /* |-----------------------------------------------------------------| */
694 /* | completion | */
695 /* |-----------------------------------------------------------------| */
696 /* | completion | */
697 /* `-----------------------------------------------------------------' */
698 void
699 draw_vertically(struct rendering *r, char *text, struct completions *cs)
701 size_t i;
702 int y = r->y_zero;
704 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
706 for (i = r->offset; i < cs->length; ++i) {
707 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
709 cs->completions[i].offset = y;
711 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
713 if (y > inner_height(r))
714 break;
717 for (i += 1; i < cs->length; ++i)
718 cs->completions[i].offset = -1;
721 void
722 draw(struct rendering *r, char *text, struct completions *cs)
724 /* Draw the background */
725 XFillRectangle(
726 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
728 /* Draw the contents */
729 if (r->horizontal_layout)
730 draw_horizontally(r, text, cs);
731 else
732 draw_vertically(r, text, cs);
734 /* Draw the borders */
735 if (r->borders[0] != 0)
736 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
738 if (r->borders[1] != 0)
739 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
740 r->borders[1], r->height);
742 if (r->borders[2] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
744 r->borders[2]);
746 if (r->borders[3] != 0)
747 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
749 /* render! */
750 XFlush(r->d);
753 /* Set some WM stuff */
754 void
755 set_win_atoms_hints(Display *d, Window w, int width, int height)
757 Atom type;
758 XClassHint *class_hint;
759 XSizeHints *size_hint;
761 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
762 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
763 32, PropModeReplace, (unsigned char *)&type, 1);
765 /* some window managers honor this properties */
766 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
767 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
768 PropModeReplace, (unsigned char *)&type, 1);
770 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
771 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
772 PropModeAppend, (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, CurrentTime)
842 == 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 `default_value'.
904 */
905 int
906 parse_integer(const char *str, int default_value)
908 long lval;
909 char *ep;
911 errno = 0;
912 lval = strtol(str, &ep, 10);
914 if (str[0] == '\0' || *ep != '\0') { /* NaN */
915 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str,
916 default_value);
917 return default_value;
920 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
921 || (lval > INT_MAX || lval < INT_MIN)) {
922 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
923 return default_value;
926 return lval;
929 /* Like parse_integer but recognize the percentages (i.e. strings ending with
930 * `%') */
931 int
932 parse_int_with_percentage(const char *str, int default_value, int max)
934 int len = strlen(str);
936 if (len > 0 && str[len - 1] == '%') {
937 int val;
938 char *cpy;
940 if ((cpy = strdup(str)) == NULL)
941 err(1, "strdup");
943 cpy[len - 1] = '\0';
944 val = parse_integer(cpy, default_value);
945 free(cpy);
946 return val * max / 100;
949 return parse_integer(str, default_value);
952 void
953 get_mouse_coords(Display *d, int *x, int *y)
955 Window w, root;
956 int i;
957 unsigned int u;
959 *x = *y = 0;
960 root = DefaultRootWindow(d);
962 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
963 for (i = 0; i < ScreenCount(d); ++i) {
964 if (root == RootWindow(d, i))
965 break;
970 /*
971 * Like parse_int_with_percentage but understands some special values:
972 * - middle that is (max-self)/2
973 * - center = middle
974 * - start that is 0
975 * - end that is (max-self)
976 * - mx x coordinate of the mouse
977 * - my y coordinate of the mouse
978 */
979 int
980 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
982 if (!strcmp(str, "start"))
983 return 0;
984 if (!strcmp(str, "middle") || !strcmp(str, "center"))
985 return (max - self) / 2;
986 if (!strcmp(str, "end"))
987 return max - self;
988 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
989 int x, y;
991 get_mouse_coords(d, &x, &y);
992 if (!strcmp(str, "mx"))
993 return x - 1;
994 else
995 return y - 1;
997 return parse_int_with_percentage(str, default_value, max);
1000 /* Parse a string like a CSS value. */
1001 /* TODO: harden a bit this function */
1002 char **
1003 parse_csslike(const char *str)
1005 int i, j;
1006 char *s, *token, **ret;
1007 short any_null;
1009 s = strdup(str);
1010 if (s == NULL)
1011 return NULL;
1013 ret = malloc(4 * sizeof(char *));
1014 if (ret == NULL) {
1015 free(s);
1016 return NULL;
1019 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1020 ret[i] = strdup(token);
1022 if (i == 1)
1023 for (j = 1; j < 4; j++)
1024 ret[j] = strdup(ret[0]);
1026 if (i == 2) {
1027 ret[2] = strdup(ret[0]);
1028 ret[3] = strdup(ret[1]);
1031 if (i == 3)
1032 ret[3] = strdup(ret[1]);
1034 /* before we didn't check for the return type of strdup, here we will
1037 any_null = 0;
1038 for (i = 0; i < 4; ++i)
1039 any_null = ret[i] == NULL || any_null;
1041 if (any_null)
1042 for (i = 0; i < 4; ++i)
1043 if (ret[i] != NULL)
1044 free(ret[i]);
1046 if (i == 0 || any_null) {
1047 free(s);
1048 free(ret);
1049 return NULL;
1052 return ret;
1056 * Given an event, try to understand what the users wants. If the
1057 * return value is ADD_CHAR then `input' is a pointer to a string that
1058 * will need to be free'ed later.
1060 enum action
1061 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1063 char str[SYM_BUF_SIZE] = { 0 };
1064 Status s;
1066 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1067 return DEL_CHAR;
1069 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1070 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1072 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1073 return CONFIRM;
1075 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1076 return EXIT;
1078 /* Try to read what key was pressed */
1079 s = 0;
1080 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1081 if (s == XBufferOverflow) {
1082 fprintf(stderr,
1083 "Buffer overflow when trying to create keyboard "
1084 "symbol map.\n");
1085 return EXIT;
1088 if (ev->state & ControlMask) {
1089 if (!strcmp(str, "")) /* C-u */
1090 return DEL_LINE;
1091 if (!strcmp(str, "")) /* C-w */
1092 return DEL_WORD;
1093 if (!strcmp(str, "")) /* C-h */
1094 return DEL_CHAR;
1095 if (!strcmp(str, "\r")) /* C-m */
1096 return CONFIRM_CONTINUE;
1097 if (!strcmp(str, "")) /* C-p */
1098 return PREV_COMPL;
1099 if (!strcmp(str, "")) /* C-n */
1100 return NEXT_COMPL;
1101 if (!strcmp(str, "")) /* C-c */
1102 return EXIT;
1103 if (!strcmp(str, "\t")) /* C-i */
1104 return TOGGLE_FIRST_SELECTED;
1107 *input = strdup(str);
1108 if (*input == NULL) {
1109 fprintf(stderr, "Error while allocating memory for key.\n");
1110 return EXIT;
1113 return ADD_CHAR;
1116 void
1117 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1119 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1120 /* if there is something selected expand it and return */
1121 int index = cs->selected == -1 ? 0 : cs->selected;
1122 struct completion *c = cs->completions;
1123 char *t;
1125 while (1) {
1126 if (index == 0)
1127 break;
1128 c++;
1129 index--;
1132 t = c->rcompletion;
1133 free(*text);
1134 *text = strdup(t);
1136 if (*text == NULL) {
1137 fprintf(stderr, "Memory allocation error\n");
1138 *status = ERR;
1141 *textlen = strlen(*text);
1142 return;
1145 if (!r->free_text) /* cannot accept arbitrary text */
1146 *status = LOOPING;
1149 /* cs: completion list
1150 * offset: the offset of the click
1151 * first: the first (rendered) item
1152 * def: the default action
1154 enum action
1155 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1157 ssize_t selected = first;
1158 int set = 0;
1160 if (cs->length == 0)
1161 return NO_OP;
1163 if (offset < cs->completions[selected].offset)
1164 return EXIT;
1166 /* skip the first entry */
1167 for (selected += 1; selected < cs->length; ++selected) {
1168 if (cs->completions[selected].offset == -1)
1169 break;
1171 if (offset < cs->completions[selected].offset) {
1172 cs->selected = selected - 1;
1173 set = 1;
1174 break;
1178 if (!set)
1179 cs->selected = selected - 1;
1181 return def;
1184 enum action
1185 handle_mouse(struct rendering *r, struct completions *cs, 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, char **lines,
1214 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, r->xic, &input);
1253 else
1254 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1256 switch (a) {
1257 case NO_OP:
1258 break;
1260 case EXIT:
1261 status = ERR;
1262 break;
1264 case CONFIRM: {
1265 status = OK;
1266 confirm(&status, r, cs, text, textlen);
1267 break;
1270 case CONFIRM_CONTINUE: {
1271 status = OK_LOOP;
1272 confirm(&status, r, cs, text, textlen);
1273 break;
1276 case PREV_COMPL: {
1277 complete(cs, r->first_selected, 1, text, textlen, &status);
1278 r->offset = cs->selected;
1279 break;
1282 case NEXT_COMPL: {
1283 complete(cs, r->first_selected, 0, text, textlen, &status);
1284 r->offset = cs->selected;
1285 break;
1288 case DEL_CHAR:
1289 popc(*text);
1290 update_completions(cs, *text, lines, vlines, r->first_selected);
1291 r->offset = 0;
1292 break;
1294 case DEL_WORD: {
1295 popw(*text);
1296 update_completions(cs, *text, lines, vlines, r->first_selected);
1297 break;
1300 case DEL_LINE: {
1301 int i;
1302 for (i = 0; i < *textlen; ++i)
1303 *(*text + i) = 0;
1304 update_completions(cs, *text, lines, vlines, r->first_selected);
1305 r->offset = 0;
1306 break;
1309 case ADD_CHAR: {
1310 int str_len, i;
1312 str_len = strlen(input);
1315 * sometimes a strange key is pressed
1316 * i.e. ctrl alone), so input will be
1317 * empty. Don't need to update
1318 * completion in that case
1320 if (str_len == 0)
1321 break;
1323 for (i = 0; i < str_len; ++i) {
1324 *textlen = pushc(text, *textlen, input[i]);
1325 if (*textlen == -1) {
1326 fprintf(stderr,
1327 "Memory allocation "
1328 "error\n");
1329 status = ERR;
1330 break;
1334 if (status != ERR) {
1335 update_completions(
1336 cs, *text, lines, vlines, r->first_selected);
1337 free(input);
1340 r->offset = 0;
1341 break;
1344 case TOGGLE_FIRST_SELECTED:
1345 r->first_selected = !r->first_selected;
1346 if (r->first_selected && cs->selected < 0)
1347 cs->selected = 0;
1348 if (!r->first_selected && cs->selected == 0)
1349 cs->selected = -1;
1350 break;
1352 case SCROLL_DOWN:
1353 r->offset = MIN(r->offset + 1, cs->length - 1);
1354 break;
1356 case SCROLL_UP:
1357 r->offset = MAX((ssize_t)r->offset - 1, 0);
1358 break;
1363 draw(r, *text, cs);
1366 return status;
1369 int
1370 load_font(struct rendering *r, const char *fontname)
1372 #ifdef USE_XFT
1373 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1374 return 0;
1375 #else
1376 char **missing_charset_list;
1377 int missing_charset_count;
1379 r->font = XCreateFontSet(
1380 r->d, fontname, &missing_charset_list, &missing_charset_count, NULL);
1381 if (r->font != NULL)
1382 return 0;
1384 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1386 if (!strcmp(fontname, default_fontname))
1387 return -1;
1389 return load_font(r, default_fontname);
1390 #endif
1393 void
1394 xim_init(struct rendering *r, XrmDatabase *xdb)
1396 XIMStyle best_match_style;
1397 XIMStyles *xis;
1398 int i;
1400 /* Open the X input method */
1401 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1402 err(1, "XOpenIM");
1404 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1405 fprintf(stderr, "Input Styles could not be retrieved\n");
1406 exit(EX_UNAVAILABLE);
1409 best_match_style = 0;
1410 for (i = 0; i < xis->count_styles; ++i) {
1411 XIMStyle ts = xis->supported_styles[i];
1412 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1413 best_match_style = ts;
1414 break;
1417 XFree(xis);
1419 if (!best_match_style)
1420 fprintf(stderr, "No matching input style could be determined\n");
1422 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1423 XNFocusWindow, r->w, NULL);
1424 if (r->xic == NULL)
1425 err(1, "XCreateIC");
1428 void
1429 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1430 int y, int ox, int oy, unsigned long background_pixel)
1432 XSetWindowAttributes attr;
1434 /* Create the window */
1435 attr.colormap = cmap;
1436 attr.override_redirect = 1;
1437 attr.border_pixel = 0;
1438 attr.background_pixel = background_pixel;
1439 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1440 | ButtonPress | VisibilityChangeMask;
1442 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1443 vinfo.depth, InputOutput, vinfo.visual,
1444 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1447 void
1448 ps1extents(struct rendering *r)
1450 char *dup;
1451 dup = strdupn(r->ps1);
1452 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1453 free(dup);
1456 void
1457 usage(char *prgname)
1459 fprintf(stderr,
1460 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1461 " [-d separator] [-e window] [-f font] [-G color] [-g "
1462 "size]\n"
1463 " [-H height] [-I color] [-i size] [-J color] [-j "
1464 "size] [-l layout]\n"
1465 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1466 "color]\n"
1467 " [-t color] [-W width] [-x coord] [-y coord]\n",
1468 prgname);
1471 int
1472 main(int argc, char **argv)
1474 struct completions *cs;
1475 struct rendering r;
1476 XVisualInfo vinfo;
1477 Colormap cmap;
1478 size_t nlines, i;
1479 Window parent_window;
1480 XrmDatabase xdb;
1481 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1482 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1483 ch_borders_bg[4]; /* N E S W */
1484 enum state status;
1485 int ch;
1486 int offset_x, offset_y, x, y;
1487 int textlen, d_width, d_height;
1488 short embed;
1489 char *sep, *parent_window_id;
1490 char **lines, **vlines;
1491 char *fontname, *text, *xrm;
1493 sep = NULL;
1494 parent_window_id = NULL;
1496 r.first_selected = 0;
1497 r.free_text = 1;
1498 r.multiple_select = 0;
1499 r.offset = 0;
1501 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1502 switch (ch) {
1503 case 'h': /* help */
1504 usage(*argv);
1505 return 0;
1506 case 'v': /* version */
1507 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1508 return 0;
1509 case 'e': /* embed */
1510 if ((parent_window_id = strdup(optarg)) == NULL)
1511 err(1, "strdup");
1512 break;
1513 case 'd':
1514 if ((sep = strdup(optarg)) == NULL)
1515 err(1, "strdup");
1516 break;
1517 case 'A':
1518 r.free_text = 0;
1519 break;
1520 case 'm':
1521 r.multiple_select = 1;
1522 break;
1523 default:
1524 break;
1528 lines = readlines(&nlines);
1530 vlines = NULL;
1531 if (sep != NULL) {
1532 int l;
1533 l = strlen(sep);
1534 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1535 err(1, "calloc");
1537 for (i = 0; i < nlines; i++) {
1538 char *t;
1539 t = strstr(lines[i], sep);
1540 if (t == NULL)
1541 vlines[i] = lines[i];
1542 else
1543 vlines[i] = t + l;
1547 setlocale(LC_ALL, getenv("LANG"));
1549 status = LOOPING;
1551 /* where the monitor start (used only with xinerama) */
1552 offset_x = offset_y = 0;
1554 /* default width and height */
1555 r.width = 400;
1556 r.height = 20;
1558 /* default position on the screen */
1559 x = y = 0;
1561 for (i = 0; i < 4; ++i) {
1562 /* default paddings */
1563 r.p_padding[i] = 10;
1564 r.c_padding[i] = 10;
1565 r.ch_padding[i] = 10;
1567 /* default borders */
1568 r.borders[i] = 0;
1569 r.p_borders[i] = 0;
1570 r.c_borders[i] = 0;
1571 r.ch_borders[i] = 0;
1574 /* the prompt. We duplicate the string so later is easy to
1575 * free (in the case it's been overwritten by the user) */
1576 if ((r.ps1 = strdup("$ ")) == NULL)
1577 err(1, "strdup");
1579 /* same for the font name */
1580 if ((fontname = strdup(default_fontname)) == NULL)
1581 err(1, "strdup");
1583 textlen = 10;
1584 if ((text = malloc(textlen * sizeof(char))) == NULL)
1585 err(1, "malloc");
1587 /* struct completions *cs = filter(text, lines); */
1588 if ((cs = compls_new(nlines)) == NULL)
1589 err(1, "compls_new");
1591 /* start talking to xorg */
1592 r.d = XOpenDisplay(NULL);
1593 if (r.d == NULL) {
1594 fprintf(stderr, "Could not open display!\n");
1595 return EX_UNAVAILABLE;
1598 embed = 1;
1599 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1600 parent_window = DefaultRootWindow(r.d);
1601 embed = 0;
1604 /* get display size */
1605 get_wh(r.d, &parent_window, &d_width, &d_height);
1607 #ifdef USE_XINERAMA
1608 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1609 XineramaScreenInfo *info;
1610 Window rr;
1611 Window root;
1612 int number_of_screens, monitors, i;
1613 int root_x, root_y, win_x, win_y;
1614 unsigned int mask;
1615 short res;
1617 number_of_screens = XScreenCount(r.d);
1618 for (i = 0; i < number_of_screens; ++i) {
1619 root = XRootWindow(r.d, i);
1620 res = XQueryPointer(
1621 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1622 if (res)
1623 break;
1626 if (!res) {
1627 fprintf(stderr, "No mouse found.\n");
1628 root_x = 0;
1629 root_y = 0;
1632 /* Now find in which monitor the mice is */
1633 info = XineramaQueryScreens(r.d, &monitors);
1634 if (info) {
1635 for (i = 0; i < monitors; ++i) {
1636 if (info[i].x_org <= root_x
1637 && root_x <= (info[i].x_org + info[i].width)
1638 && info[i].y_org <= root_y
1639 && root_y <= (info[i].y_org + info[i].height)) {
1640 offset_x = info[i].x_org;
1641 offset_y = info[i].y_org;
1642 d_width = info[i].width;
1643 d_height = info[i].height;
1644 break;
1648 XFree(info);
1650 #endif
1652 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1653 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1655 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1656 fgs[2] = parse_color("#000", NULL);
1658 bgs[0] = bgs[1] = parse_color("#000", NULL);
1659 bgs[2] = parse_color("#fff", NULL);
1661 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1663 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1664 = parse_color("#000", NULL);
1665 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1666 = parse_color("#000", NULL);
1667 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1668 = parse_color("#000", NULL);
1670 r.horizontal_layout = 1;
1672 /* Read the resources */
1673 XrmInitialize();
1674 xrm = XResourceManagerString(r.d);
1675 xdb = NULL;
1676 if (xrm != NULL) {
1677 XrmValue value;
1678 char *datatype[20];
1680 xdb = XrmGetStringDatabase(xrm);
1682 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1683 free(fontname);
1684 if ((fontname = strdup(value.addr)) == NULL)
1685 err(1, "strdup");
1686 } else {
1687 fprintf(stderr, "no font defined, using %s\n", fontname);
1690 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1691 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1692 else
1693 fprintf(stderr, "no layout defined, using horizontal\n");
1695 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1696 free(r.ps1);
1697 r.ps1 = normalize_str(value.addr);
1698 } else {
1699 fprintf(stderr,
1700 "no prompt defined, using \"%s\" as "
1701 "default\n",
1702 r.ps1);
1705 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1706 char **sizes;
1707 sizes = parse_csslike(value.addr);
1708 if (sizes != NULL)
1709 for (i = 0; i < 4; ++i)
1710 r.p_borders[i] = parse_integer(sizes[i], 0);
1711 else
1712 fprintf(stderr,
1713 "error while parsing "
1714 "MyMenu.prompt.border.size");
1717 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1718 char **colors;
1719 colors = parse_csslike(value.addr);
1720 if (colors != NULL)
1721 for (i = 0; i < 4; ++i)
1722 p_borders_bg[i] = parse_color(colors[i], "#000");
1723 else
1724 fprintf(stderr,
1725 "error while parsing "
1726 "MyMenu.prompt.border.color");
1729 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1730 char **colors;
1731 colors = parse_csslike(value.addr);
1732 if (colors != NULL)
1733 for (i = 0; i < 4; ++i)
1734 r.p_padding[i] = parse_integer(colors[i], 0);
1735 else
1736 fprintf(stderr,
1737 "error while parsing "
1738 "MyMenu.prompt.padding");
1741 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1742 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1743 else
1744 fprintf(stderr, "no width defined, using %d\n", r.width);
1746 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1747 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1748 else
1749 fprintf(stderr, "no height defined, using %d\n", r.height);
1751 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1752 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1754 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1755 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1757 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1758 char **borders;
1759 borders = parse_csslike(value.addr);
1760 if (borders != NULL)
1761 for (i = 0; i < 4; ++i)
1762 r.borders[i] = parse_int_with_percentage(
1763 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1764 else
1765 fprintf(stderr,
1766 "error while parsing "
1767 "MyMenu.border.size\n");
1770 /* Prompt */
1771 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1772 fgs[0] = parse_color(value.addr, "#fff");
1774 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1775 bgs[0] = parse_color(value.addr, "#000");
1777 /* Completions */
1778 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1779 fgs[1] = parse_color(value.addr, "#fff");
1781 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1782 bgs[1] = parse_color(value.addr, "#000");
1784 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1785 char **paddings;
1786 paddings = parse_csslike(value.addr);
1787 if (paddings != NULL)
1788 for (i = 0; i < 4; ++i)
1789 r.c_padding[i] = parse_integer(paddings[i], 0);
1790 else
1791 fprintf(stderr,
1792 "Error while parsing "
1793 "MyMenu.completion.padding");
1796 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1797 char **sizes;
1798 sizes = parse_csslike(value.addr);
1799 if (sizes != NULL)
1800 for (i = 0; i < 4; ++i)
1801 r.c_borders[i] = parse_integer(sizes[i], 0);
1802 else
1803 fprintf(stderr,
1804 "Error while parsing "
1805 "MyMenu.completion.border.size");
1808 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1809 char **sizes;
1810 sizes = parse_csslike(value.addr);
1811 if (sizes != NULL)
1812 for (i = 0; i < 4; ++i)
1813 c_borders_bg[i] = parse_color(sizes[i], "#000");
1814 else
1815 fprintf(stderr,
1816 "Error while parsing "
1817 "MyMenu.completion.border.color");
1820 /* Completion Highlighted */
1821 if (XrmGetResource(
1822 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1823 fgs[2] = parse_color(value.addr, "#000");
1825 if (XrmGetResource(
1826 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1827 bgs[2] = parse_color(value.addr, "#fff");
1829 if (XrmGetResource(
1830 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1831 char **paddings;
1832 paddings = parse_csslike(value.addr);
1833 if (paddings != NULL)
1834 for (i = 0; i < 4; ++i)
1835 r.ch_padding[i] = parse_integer(paddings[i], 0);
1836 else
1837 fprintf(stderr,
1838 "Error while parsing "
1839 "MyMenu.completion_highlighted."
1840 "padding");
1843 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1844 &value)) {
1845 char **sizes;
1846 sizes = parse_csslike(value.addr);
1847 if (sizes != NULL)
1848 for (i = 0; i < 4; ++i)
1849 r.ch_borders[i] = parse_integer(sizes[i], 0);
1850 else
1851 fprintf(stderr,
1852 "Error while parsing "
1853 "MyMenu.completion_highlighted."
1854 "border.size");
1857 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1858 &value)) {
1859 char **colors;
1860 colors = parse_csslike(value.addr);
1861 if (colors != NULL)
1862 for (i = 0; i < 4; ++i)
1863 ch_borders_bg[i] = parse_color(colors[i], "#000");
1864 else
1865 fprintf(stderr,
1866 "Error while parsing "
1867 "MyMenu.completion_highlighted."
1868 "border.color");
1871 /* Border */
1872 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1873 char **colors;
1874 colors = parse_csslike(value.addr);
1875 if (colors != NULL)
1876 for (i = 0; i < 4; ++i)
1877 borders_bg[i] = parse_color(colors[i], "#000");
1878 else
1879 fprintf(stderr,
1880 "error while parsing "
1881 "MyMenu.border.color\n");
1885 /* Second round of args parsing */
1886 optind = 0; /* reset the option index */
1887 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1888 switch (ch) {
1889 case 'a':
1890 r.first_selected = 1;
1891 break;
1892 case 'A':
1893 /* free_text -- already catched */
1894 case 'd':
1895 /* separator -- this case was already catched */
1896 case 'e':
1897 /* embedding mymenu this case was already catched. */
1898 case 'm':
1899 /* multiple selection this case was already catched.
1901 break;
1902 case 'p': {
1903 char *newprompt;
1904 newprompt = strdup(optarg);
1905 if (newprompt != NULL) {
1906 free(r.ps1);
1907 r.ps1 = newprompt;
1909 break;
1911 case 'x':
1912 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1913 break;
1914 case 'y':
1915 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1916 break;
1917 case 'P': {
1918 char **paddings;
1919 if ((paddings = parse_csslike(optarg)) != NULL)
1920 for (i = 0; i < 4; ++i)
1921 r.p_padding[i] = parse_integer(paddings[i], 0);
1922 break;
1924 case 'G': {
1925 char **colors;
1926 if ((colors = parse_csslike(optarg)) != NULL)
1927 for (i = 0; i < 4; ++i)
1928 p_borders_bg[i] = parse_color(colors[i], "#000");
1929 break;
1931 case 'g': {
1932 char **sizes;
1933 if ((sizes = parse_csslike(optarg)) != NULL)
1934 for (i = 0; i < 4; ++i)
1935 r.p_borders[i] = parse_integer(sizes[i], 0);
1936 break;
1938 case 'I': {
1939 char **colors;
1940 if ((colors = parse_csslike(optarg)) != NULL)
1941 for (i = 0; i < 4; ++i)
1942 c_borders_bg[i] = parse_color(colors[i], "#000");
1943 break;
1945 case 'i': {
1946 char **sizes;
1947 if ((sizes = parse_csslike(optarg)) != NULL)
1948 for (i = 0; i < 4; ++i)
1949 r.c_borders[i] = parse_integer(sizes[i], 0);
1950 break;
1952 case 'J': {
1953 char **colors;
1954 if ((colors = parse_csslike(optarg)) != NULL)
1955 for (i = 0; i < 4; ++i)
1956 ch_borders_bg[i] = parse_color(colors[i], "#000");
1957 break;
1959 case 'j': {
1960 char **sizes;
1961 if ((sizes = parse_csslike(optarg)) != NULL)
1962 for (i = 0; i < 4; ++i)
1963 r.ch_borders[i] = parse_integer(sizes[i], 0);
1964 break;
1966 case 'l':
1967 r.horizontal_layout = !strcmp(optarg, "horizontal");
1968 break;
1969 case 'f': {
1970 char *newfont;
1971 if ((newfont = strdup(optarg)) != NULL) {
1972 free(fontname);
1973 fontname = newfont;
1975 break;
1977 case 'W':
1978 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1979 break;
1980 case 'H':
1981 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1982 break;
1983 case 'b': {
1984 char **borders;
1985 if ((borders = parse_csslike(optarg)) != NULL) {
1986 for (i = 0; i < 4; ++i)
1987 r.borders[i] = parse_integer(borders[i], 0);
1988 } else
1989 fprintf(stderr, "Error parsing b option\n");
1990 break;
1992 case 'B': {
1993 char **colors;
1994 if ((colors = parse_csslike(optarg)) != NULL) {
1995 for (i = 0; i < 4; ++i)
1996 borders_bg[i] = parse_color(colors[i], "#000");
1997 } else
1998 fprintf(stderr, "error while parsing B option\n");
1999 break;
2001 case 't':
2002 fgs[0] = parse_color(optarg, NULL);
2003 break;
2004 case 'T':
2005 bgs[0] = parse_color(optarg, NULL);
2006 break;
2007 case 'c':
2008 fgs[1] = parse_color(optarg, NULL);
2009 break;
2010 case 'C':
2011 bgs[1] = parse_color(optarg, NULL);
2012 break;
2013 case 's':
2014 fgs[2] = parse_color(optarg, NULL);
2015 break;
2016 case 'S':
2017 bgs[2] = parse_color(optarg, NULL);
2018 break;
2019 default:
2020 fprintf(stderr, "Unrecognized option %c\n", ch);
2021 status = ERR;
2022 break;
2026 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2027 fprintf(stderr, "height, width, x or y are lesser than 0.");
2028 status = ERR;
2031 /* since only now we know if the first should be selected,
2032 * update the completion here */
2033 update_completions(cs, text, lines, vlines, r.first_selected);
2035 /* update the prompt lenght, only now we surely know the length of it
2037 r.ps1len = strlen(r.ps1);
2039 /* Create the window */
2040 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2041 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2042 XMapRaised(r.d, r.w);
2044 /* If embed, listen for other events as well */
2045 if (embed) {
2046 Window *children, parent, root;
2047 unsigned int children_no;
2049 XSelectInput(r.d, parent_window, FocusChangeMask);
2050 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2051 && children) {
2052 for (i = 0; i < children_no && children[i] != r.w; ++i)
2053 XSelectInput(r.d, children[i], FocusChangeMask);
2054 XFree(children);
2056 grabfocus(r.d, r.w);
2059 take_keyboard(r.d, r.w);
2061 r.x_zero = r.borders[3];
2062 r.y_zero = r.borders[0];
2065 XGCValues values;
2067 for (i = 0; i < 3; ++i) {
2068 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2069 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2072 for (i = 0; i < 4; ++i) {
2073 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2074 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2075 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2076 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2080 /* Load the colors in our GCs */
2081 for (i = 0; i < 3; ++i) {
2082 XSetForeground(r.d, r.fgs[i], fgs[i]);
2083 XSetForeground(r.d, r.bgs[i], bgs[i]);
2086 for (i = 0; i < 4; ++i) {
2087 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2088 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2089 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2090 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2093 if (load_font(&r, fontname) == -1)
2094 status = ERR;
2096 #ifdef USE_XFT
2097 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2099 for (i = 0; i < 3; ++i) {
2100 rgba_t c;
2101 XRenderColor xrcolor;
2103 c = *(rgba_t *)&fgs[i];
2104 xrcolor.red = EXPANDBITS(c.rgba.r);
2105 xrcolor.green = EXPANDBITS(c.rgba.g);
2106 xrcolor.blue = EXPANDBITS(c.rgba.b);
2107 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2108 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2110 #endif
2112 /* compute prompt dimensions */
2113 ps1extents(&r);
2115 xim_init(&r, &xdb);
2117 #ifdef __OpenBSD__
2118 if (pledge("stdio", "") == -1)
2119 err(1, "pledge");
2120 #endif
2122 /* Cache text height */
2123 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2125 /* Draw the window for the first time */
2126 draw(&r, text, cs);
2128 /* Main loop */
2129 while (status == LOOPING || status == OK_LOOP) {
2130 status = loop(&r, &text, &textlen, cs, lines, vlines);
2132 if (status != ERR)
2133 printf("%s\n", text);
2135 if (!r.multiple_select && status == OK_LOOP)
2136 status = OK;
2139 XUngrabKeyboard(r.d, CurrentTime);
2141 #ifdef USE_XFT
2142 for (i = 0; i < 3; ++i)
2143 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2144 #endif
2146 for (i = 0; i < 3; ++i) {
2147 XFreeGC(r.d, r.fgs[i]);
2148 XFreeGC(r.d, r.bgs[i]);
2151 for (i = 0; i < 4; ++i) {
2152 XFreeGC(r.d, r.borders_bg[i]);
2153 XFreeGC(r.d, r.p_borders_bg[i]);
2154 XFreeGC(r.d, r.c_borders_bg[i]);
2155 XFreeGC(r.d, r.ch_borders_bg[i]);
2158 XDestroyIC(r.xic);
2159 XCloseIM(r.xim);
2161 #ifdef USE_XFT
2162 for (i = 0; i < 3; ++i)
2163 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2164 XftFontClose(r.d, r.font);
2165 XftDrawDestroy(r.xftdraw);
2166 #else
2167 XFreeFontSet(r.d, r.font);
2168 #endif
2170 free(r.ps1);
2171 free(fontname);
2172 free(text);
2174 free(lines);
2175 free(vlines);
2176 compls_delete(cs);
2178 XFreeColormap(r.d, cmap);
2180 XDestroyWindow(r.d, r.w);
2181 XCloseDisplay(r.d);
2183 return status != OK;