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 /* The number of char to read */
58 #define STDIN_CHUNKS 128
60 /* The number of lines to allocate in advance */
61 #define LINES_CHUNK 64
63 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
64 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
66 /* The states of the event loop */
67 enum state { LOOPING, OK_LOOP, OK, ERR };
69 /*
70 * For the drawing-related function. The text to be rendere could be
71 * the prompt, a completion or a highlighted completion
72 */
73 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
75 /* These are the possible action to be performed after user input. */
76 enum action {
77 NO_OP,
78 EXIT,
79 CONFIRM,
80 CONFIRM_CONTINUE,
81 NEXT_COMPL,
82 PREV_COMPL,
83 DEL_CHAR,
84 DEL_WORD,
85 DEL_LINE,
86 ADD_CHAR,
87 TOGGLE_FIRST_SELECTED,
88 SCROLL_DOWN,
89 SCROLL_UP,
90 };
92 /* A big set of values that needs to be carried around for drawing. A
93 * big struct to rule them all */
94 struct rendering {
95 Display *d; /* Connection to xorg */
96 Window w;
97 XIM xim;
98 int width;
99 int height;
100 int p_padding[4];
101 int c_padding[4];
102 int ch_padding[4];
103 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
104 the borders) */
105 int y_zero; /* like x_zero but for the y axis */
107 int offset; /* scroll offset */
109 short free_text;
110 short first_selected;
111 short multiple_select;
113 /* four border width */
114 int borders[4];
115 int p_borders[4];
116 int c_borders[4];
117 int ch_borders[4];
119 short horizontal_layout;
121 /* prompt */
122 char *ps1;
123 int ps1len;
124 int ps1w; /* ps1 width */
125 int ps1h; /* ps1 height */
127 int text_height; /* cache for the vertical layout */
129 XIC xic;
131 /* colors */
132 GC fgs[4];
133 GC bgs[4];
134 GC borders_bg[4];
135 GC p_borders_bg[4];
136 GC c_borders_bg[4];
137 GC ch_borders_bg[4];
138 #ifdef USE_XFT
139 XftFont *font;
140 XftDraw *xftdraw;
141 XftColor xft_colors[3];
142 #else
143 XFontSet font;
144 #endif
145 };
147 struct completion {
148 char *completion;
149 char *rcompletion;
150 int offset; /* the x (or y, depending on the layout) coordinate at
151 which the item is rendered */
152 };
154 /* Wrap the linked list of completions */
155 struct completions {
156 struct completion *completions;
157 ssize_t selected;
158 size_t length;
159 };
161 /* idea stolen from lemonbar. ty lemonboy */
162 typedef union {
163 struct {
164 uint8_t b;
165 uint8_t g;
166 uint8_t r;
167 uint8_t a;
168 } rgba;
169 uint32_t v;
170 } rgba_t;
172 extern char *optarg;
173 extern int optind;
175 /* Return a newly allocated (and empty) completion list */
176 struct completions *
177 compls_new(size_t length)
179 struct completions *cs = malloc(sizeof(struct completions));
181 if (cs == NULL)
182 return cs;
184 cs->completions = calloc(length, sizeof(struct completion));
185 if (cs->completions == NULL) {
186 free(cs);
187 return NULL;
190 cs->selected = -1;
191 cs->length = length;
192 return cs;
195 /* Delete the wrapper and the whole list */
196 void
197 compls_delete(struct completions *cs)
199 if (cs == NULL)
200 return;
202 free(cs->completions);
203 free(cs);
206 /*
207 * Create a completion list from a text and the list of possible
208 * completions (null terminated). Expects a non-null `cs'. `lines' and
209 * `vlines' should have the same length OR `vlines' is NULL.
210 */
211 void
212 filter(struct completions *cs, char *text, char **lines, char **vlines)
214 size_t index = 0;
215 size_t matching = 0;
216 char *l;
218 if (vlines == NULL)
219 vlines = lines;
221 while (1) {
222 if (lines[index] == NULL)
223 break;
225 l = vlines[index] != NULL ? vlines[index] : lines[index];
227 if (strcasestr(l, text) != NULL) {
228 struct completion *c = &cs->completions[matching];
229 c->completion = l;
230 c->rcompletion = lines[index];
231 matching++;
234 index++;
236 cs->length = matching;
237 cs->selected = -1;
240 /* Update the given completion */
241 void
242 update_completions(struct completions *cs, char *text, char **lines,
243 char **vlines, short first_selected)
245 filter(cs, text, lines, vlines);
246 if (first_selected && cs->length > 0)
247 cs->selected = 0;
250 /*
251 * Select the next or previous selection and update some state. `text'
252 * will be updated with the text of the completion and `textlen' with
253 * the new length. If the memory cannot be allocated `status' will be
254 * set to `ERR'.
255 */
256 void
257 complete(struct completions *cs, short first_selected, short p, char **text,
258 int *textlen, enum state *status)
260 struct completion *n;
261 int index;
263 if (cs == NULL || cs->length == 0)
264 return;
266 /*
267 * If the first is always selected and the first entry is
268 * different from the text, expand the text and return
269 */
270 if (first_selected && cs->selected == 0
271 && strcmp(cs->completions->completion, *text) != 0 && !p) {
272 free(*text);
273 *text = strdup(cs->completions->completion);
274 if (text == NULL) {
275 *status = ERR;
276 return;
278 *textlen = strlen(*text);
279 return;
282 index = cs->selected;
284 if (index == -1 && p)
285 index = 0;
286 index = cs->selected
287 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
289 n = &cs->completions[cs->selected];
291 free(*text);
292 *text = strdup(n->completion);
293 if (text == NULL) {
294 fprintf(stderr, "Memory allocation error!\n");
295 *status = ERR;
296 return;
298 *textlen = strlen(*text);
301 /* Push the character c at the end of the string pointed by p */
302 int
303 pushc(char **p, int maxlen, char c)
305 int len;
307 len = strnlen(*p, maxlen);
308 if (!(len < maxlen - 2)) {
309 char *newptr;
311 maxlen += maxlen >> 1;
312 newptr = realloc(*p, maxlen);
313 if (newptr == NULL) /* bad */
314 return -1;
315 *p = newptr;
318 (*p)[len] = c;
319 (*p)[len + 1] = '\0';
320 return maxlen;
323 /*
324 * Remove the last rune from the *UTF-8* string! This is different
325 * from just setting the last byte to 0 (in some cases ofc). Return a
326 * pointer (e) to the last nonzero char. If e < p then p is empty!
327 */
328 char *
329 popc(char *p)
331 int len = strlen(p);
332 char *e;
334 if (len == 0)
335 return p;
337 e = p + len - 1;
339 do {
340 char c = *e;
342 *e = '\0';
343 e -= 1;
345 /*
346 * If c is a starting byte (11......) or is under
347 * U+007F we're done.
348 */
349 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
350 break;
351 } while (e >= p);
353 return e;
356 /* Remove the last word plus trailing white spaces from the given string */
357 void
358 popw(char *w)
360 int len;
361 short in_word = 1;
363 if ((len = strlen(w)) == 0)
364 return;
366 while (1) {
367 char *e = popc(w);
369 if (e < w)
370 return;
372 if (in_word && isspace(*e))
373 in_word = 0;
375 if (!in_word && !isspace(*e))
376 return;
380 /*
381 * If the string is surrounded by quates (`"') remove them and replace
382 * every `\"' in the string with a single double-quote.
383 */
384 char *
385 normalize_str(const char *str)
387 int len, p;
388 char *s;
390 if ((len = strlen(str)) == 0)
391 return NULL;
393 if ((s = calloc(len, sizeof(char))) == NULL)
394 err(1, "calloc");
395 p = 0;
397 while (*str) {
398 char c = *str;
400 if (*str == '\\') {
401 if (*(str + 1)) {
402 s[p] = *(str + 1);
403 p++;
404 str += 2; /* skip this and the next char */
405 continue;
406 } else
407 break;
409 if (c == '"') {
410 str++; /* skip only this char */
411 continue;
413 s[p] = c;
414 p++;
415 str++;
418 return s;
421 size_t
422 read_stdin(char **buf)
424 size_t offset = 0;
425 size_t len = STDIN_CHUNKS;
427 *buf = malloc(len * sizeof(char));
428 if (*buf == NULL)
429 goto err;
431 while (1) {
432 ssize_t r;
433 size_t i;
435 r = read(0, *buf + offset, STDIN_CHUNKS);
437 if (r < 1)
438 return len;
440 offset += r;
442 len += STDIN_CHUNKS;
443 *buf = realloc(*buf, len);
444 if (*buf == NULL)
445 goto err;
447 for (i = offset; i < len; ++i)
448 (*buf)[i] = '\0';
451 err:
452 fprintf(stderr, "Error in allocating memory for stdin.\n");
453 exit(EX_UNAVAILABLE);
456 size_t
457 readlines(char ***lns, char **buf)
459 size_t i, len, ll, lines;
460 short in_line = 0;
462 lines = 0;
464 *buf = NULL;
465 len = read_stdin(buf);
467 ll = LINES_CHUNK;
468 *lns = malloc(ll * sizeof(char *));
470 if (*lns == NULL)
471 goto err;
473 for (i = 0; i < len; i++) {
474 char c = (*buf)[i];
476 if (c == '\0')
477 break;
479 if (c == '\n')
480 (*buf)[i] = '\0';
482 if (in_line && c == '\n')
483 in_line = 0;
485 if (!in_line && c != '\n') {
486 in_line = 1;
487 (*lns)[lines] = (*buf) + i;
488 lines++;
490 if (lines == ll) { /* resize */
491 ll += LINES_CHUNK;
492 *lns = realloc(*lns, ll * sizeof(char *));
493 if (*lns == NULL)
494 goto err;
499 (*lns)[lines] = NULL;
501 return lines;
503 err:
504 fprintf(stderr, "Error in memory allocation.\n");
505 exit(EX_UNAVAILABLE);
508 /*
509 * Compute the dimensions of the string str once rendered.
510 * It'll return the width and set ret_width and ret_height if not NULL
511 */
512 int
513 text_extents(char *str, int len, struct rendering *r, int *ret_width,
514 int *ret_height)
516 int height, width;
517 #ifdef USE_XFT
518 XGlyphInfo gi;
519 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
520 height = r->font->ascent - r->font->descent;
521 width = gi.width - gi.x;
522 #else
523 XRectangle rect;
524 XmbTextExtents(r->font, str, len, NULL, &rect);
525 height = rect.height;
526 width = rect.width;
527 #endif
528 if (ret_width != NULL)
529 *ret_width = width;
530 if (ret_height != NULL)
531 *ret_height = height;
532 return width;
535 void
536 draw_string(char *str, int len, int x, int y, struct rendering *r,
537 enum obj_type tt)
539 #ifdef USE_XFT
540 XftColor xftcolor;
541 if (tt == PROMPT)
542 xftcolor = r->xft_colors[0];
543 if (tt == COMPL)
544 xftcolor = r->xft_colors[1];
545 if (tt == COMPL_HIGH)
546 xftcolor = r->xft_colors[2];
548 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
549 #else
550 GC gc;
551 if (tt == PROMPT)
552 gc = r->fgs[0];
553 if (tt == COMPL)
554 gc = r->fgs[1];
555 if (tt == COMPL_HIGH)
556 gc = r->fgs[2];
557 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
558 #endif
561 /* Duplicate the string and substitute every space with a 'n` */
562 char *
563 strdupn(char *str)
565 int len, i;
566 char *dup;
568 len = strlen(str);
570 if (str == NULL || len == 0)
571 return NULL;
573 if ((dup = strdup(str)) == NULL)
574 return NULL;
576 for (i = 0; i < len; ++i)
577 if (dup[i] == ' ')
578 dup[i] = 'n';
580 return dup;
583 int
584 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
585 enum obj_type t, char *text)
587 GC *border_color, bg;
588 int *padding, *borders;
589 int ret = 0, inner_width, inner_height, x;
591 switch (t) {
592 case PROMPT:
593 border_color = r->p_borders_bg;
594 padding = r->p_padding;
595 borders = r->p_borders;
596 bg = r->bgs[0];
597 break;
598 case COMPL:
599 border_color = r->c_borders_bg;
600 padding = r->c_padding;
601 borders = r->c_borders;
602 bg = r->bgs[1];
603 break;
604 case COMPL_HIGH:
605 border_color = r->ch_borders_bg;
606 padding = r->ch_padding;
607 borders = r->ch_borders;
608 bg = r->bgs[2];
609 break;
612 ret = borders[0] + padding[0] + r->text_height + padding[2]
613 + borders[2];
615 inner_width = inner_width(r) - borders[1] - borders[3];
616 inner_height = padding[0] + r->text_height + padding[2];
618 /* Border top */
619 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
620 borders[0]);
622 /* Border right */
623 XFillRectangle(r->d, r->w, border_color[1],
624 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
626 /* Border bottom */
627 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
628 y + borders[0] + padding[0] + r->text_height + padding[2],
629 r->width, borders[2]);
631 /* Border left */
632 XFillRectangle(
633 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
635 /* bg */
636 x = r->x_zero + borders[3];
637 y += borders[0];
638 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
640 /* content */
641 y += padding[0] + r->text_height;
642 x += padding[3];
643 if (prefix != NULL) {
644 draw_string(prefix, strlen(prefix), x, y, r, t);
645 x += prefix_width;
647 draw_string(text, strlen(text), x, y, r, t);
649 return ret;
652 int
653 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
654 enum obj_type t, char *text)
656 GC *border_color, bg;
657 int *padding, *borders;
658 int ret = 0, inner_width, inner_height, y, text_width;
660 switch (t) {
661 case PROMPT:
662 border_color = r->p_borders_bg;
663 padding = r->p_padding;
664 borders = r->p_borders;
665 bg = r->bgs[0];
666 break;
667 case COMPL:
668 border_color = r->c_borders_bg;
669 padding = r->c_padding;
670 borders = r->c_borders;
671 bg = r->bgs[1];
672 break;
673 case COMPL_HIGH:
674 border_color = r->ch_borders_bg;
675 padding = r->ch_padding;
676 borders = r->ch_borders;
677 bg = r->bgs[2];
678 break;
681 if (padding[0] < 0 || padding[2] < 0)
682 padding[0] = padding[2]
683 = (inner_height(r) - borders[0] - borders[2]
684 - r->text_height)
685 / 2;
687 /* If they are still lesser than 0, set 'em to 0 */
688 if (padding[0] < 0 || padding[2] < 0)
689 padding[0] = padding[2] = 0;
691 /* Get the text width */
692 text_extents(text, strlen(text), r, &text_width, NULL);
693 if (prefix != NULL)
694 text_width += prefix_width;
696 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
698 inner_width = padding[3] + text_width + padding[1];
699 inner_height = inner_height(r) - borders[0] - borders[2];
701 /* Border top */
702 XFillRectangle(
703 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
705 /* Border right */
706 XFillRectangle(r->d, r->w, border_color[1],
707 x + borders[3] + inner_width, r->y_zero, borders[1],
708 inner_height(r));
710 /* Border bottom */
711 XFillRectangle(r->d, r->w, border_color[2], x,
712 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
714 /* Border left */
715 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
716 inner_height(r));
718 /* bg */
719 x += borders[3];
720 y = r->y_zero + borders[0];
721 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
723 /* content */
724 y += padding[0] + r->text_height;
725 x += padding[3];
726 if (prefix != NULL) {
727 draw_string(prefix, strlen(prefix), x, y, r, t);
728 x += prefix_width;
730 draw_string(text, strlen(text), x, y, r, t);
732 return ret;
735 /* ,-----------------------------------------------------------------, */
736 /* | 20 char text | completion | completion | completion | compl | */
737 /* `-----------------------------------------------------------------' */
738 void
739 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
741 size_t i;
742 int x = r->x_zero;
744 /* Draw the prompt */
745 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
747 for (i = r->offset; i < cs->length; ++i) {
748 enum obj_type t
749 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
751 cs->completions[i].offset = x;
753 x += draw_h_box(
754 r, x, NULL, 0, t, cs->completions[i].completion);
756 if (x > inner_width(r))
757 break;
760 for (i += 1; i < cs->length; ++i)
761 cs->completions[i].offset = -1;
764 /* ,-----------------------------------------------------------------, */
765 /* | prompt | */
766 /* |-----------------------------------------------------------------| */
767 /* | completion | */
768 /* |-----------------------------------------------------------------| */
769 /* | completion | */
770 /* `-----------------------------------------------------------------' */
771 void
772 draw_vertically(struct rendering *r, char *text, struct completions *cs)
774 size_t i;
775 int y = r->y_zero;
777 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
779 for (i = r->offset; i < cs->length; ++i) {
780 enum obj_type t
781 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
783 cs->completions[i].offset = y;
785 y += draw_v_box(
786 r, y, NULL, 0, t, cs->completions[i].completion);
788 if (y > inner_height(r))
789 break;
792 for (i += 1; i < cs->length; ++i)
793 cs->completions[i].offset = -1;
796 void
797 draw(struct rendering *r, char *text, struct completions *cs)
799 /* Draw the background */
800 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
801 inner_width(r), inner_height(r));
803 /* Draw the contents */
804 if (r->horizontal_layout)
805 draw_horizontally(r, text, cs);
806 else
807 draw_vertically(r, text, cs);
809 /* Draw the borders */
810 if (r->borders[0] != 0)
811 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
812 r->borders[0]);
814 if (r->borders[1] != 0)
815 XFillRectangle(r->d, r->w, r->borders_bg[1],
816 r->width - r->borders[1], 0, r->borders[1],
817 r->height);
819 if (r->borders[2] != 0)
820 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
821 r->height - r->borders[2], r->width, r->borders[2]);
823 if (r->borders[3] != 0)
824 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
825 r->borders[3], r->height);
827 /* render! */
828 XFlush(r->d);
831 /* Set some WM stuff */
832 void
833 set_win_atoms_hints(Display *d, Window w, int width, int height)
835 Atom type;
836 XClassHint *class_hint;
837 XSizeHints *size_hint;
839 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
840 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
841 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
842 (unsigned char *)&type, 1);
844 /* some window managers honor this properties */
845 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
846 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
847 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
848 (unsigned char *)&type, 1);
850 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
851 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
852 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
853 (unsigned char *)&type, 1);
855 /* Setting window hints */
856 class_hint = XAllocClassHint();
857 if (class_hint == NULL) {
858 fprintf(stderr, "Could not allocate memory for class hint\n");
859 exit(EX_UNAVAILABLE);
862 class_hint->res_name = resname;
863 class_hint->res_class = resclass;
864 XSetClassHint(d, w, class_hint);
865 XFree(class_hint);
867 size_hint = XAllocSizeHints();
868 if (size_hint == NULL) {
869 fprintf(stderr, "Could not allocate memory for size hint\n");
870 exit(EX_UNAVAILABLE);
873 size_hint->flags = PMinSize | PBaseSize;
874 size_hint->min_width = width;
875 size_hint->base_width = width;
876 size_hint->min_height = height;
877 size_hint->base_height = height;
879 XFlush(d);
882 /* Get the width and height of the window `w' */
883 void
884 get_wh(Display *d, Window *w, int *width, int *height)
886 XWindowAttributes win_attr;
888 XGetWindowAttributes(d, *w, &win_attr);
889 *height = win_attr.height;
890 *width = win_attr.width;
893 int
894 grabfocus(Display *d, Window w)
896 int i;
897 for (i = 0; i < 100; ++i) {
898 Window focuswin;
899 int revert_to_win;
901 XGetInputFocus(d, &focuswin, &revert_to_win);
903 if (focuswin == w)
904 return 1;
906 XSetInputFocus(d, w, RevertToParent, CurrentTime);
907 usleep(1000);
909 return 0;
912 /*
913 * I know this may seem a little hackish BUT is the only way I managed
914 * to actually grab that goddam keyboard. Only one call to
915 * XGrabKeyboard does not always end up with the keyboard grabbed!
916 */
917 int
918 take_keyboard(Display *d, Window w)
920 int i;
921 for (i = 0; i < 100; i++) {
922 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
923 CurrentTime)
924 == GrabSuccess)
925 return 1;
926 usleep(1000);
928 fprintf(stderr, "Cannot grab keyboard\n");
929 return 0;
932 unsigned long
933 parse_color(const char *str, const char *def)
935 size_t len;
936 rgba_t tmp;
937 char *ep;
939 if (str == NULL)
940 goto invc;
942 len = strlen(str);
944 /* +1 for the # ath the start */
945 if (*str != '#' || len > 9 || len < 4)
946 goto invc;
947 ++str; /* skip the # */
949 errno = 0;
950 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
952 if (errno)
953 goto invc;
955 switch (len - 1) {
956 case 3:
957 /* expand #rgb -> #rrggbb */
958 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
959 | (tmp.v & 0x00f) * 0x0011;
960 case 6:
961 /* assume 0xff opacity */
962 tmp.rgba.a = 0xff;
963 break;
964 } /* colors in #aarrggbb need no adjustments */
966 /* premultiply the alpha */
967 if (tmp.rgba.a) {
968 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
969 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
970 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
971 return tmp.v;
974 return 0U;
976 invc:
977 fprintf(stderr, "Invalid color: \"%s\".\n", str);
978 if (def != NULL)
979 return parse_color(def, NULL);
980 else
981 return 0U;
984 /*
985 * Given a string try to parse it as a number or return `default_value'.
986 */
987 int
988 parse_integer(const char *str, int default_value)
990 long lval;
991 char *ep;
993 errno = 0;
994 lval = strtol(str, &ep, 10);
996 if (str[0] == '\0' || *ep != '\0') { /* NaN */
997 fprintf(stderr,
998 "'%s' is not a valid number! Using %d as default.\n",
999 str, default_value);
1000 return default_value;
1003 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
1004 || (lval > INT_MAX || lval < INT_MIN)) {
1005 fprintf(stderr, "%s out of range! Using %d as default.\n",
1006 str, default_value);
1007 return default_value;
1010 return lval;
1013 /* Like parse_integer but recognize the percentages (i.e. strings ending with
1014 * `%') */
1015 int
1016 parse_int_with_percentage(const char *str, int default_value, int max)
1018 int len = strlen(str);
1020 if (len > 0 && str[len - 1] == '%') {
1021 int val;
1022 char *cpy;
1024 if ((cpy = strdup(str)) == NULL)
1025 err(1, "strdup");
1027 cpy[len - 1] = '\0';
1028 val = parse_integer(cpy, default_value);
1029 free(cpy);
1030 return val * max / 100;
1033 return parse_integer(str, default_value);
1036 void
1037 get_mouse_coords(Display *d, int *x, int *y)
1039 Window w, root;
1040 int i;
1041 unsigned int u;
1043 *x = *y = 0;
1044 root = DefaultRootWindow(d);
1046 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1047 for (i = 0; i < ScreenCount(d); ++i) {
1048 if (root == RootWindow(d, i))
1049 break;
1055 * Like parse_int_with_percentage but understands some special values:
1056 * - middle that is (max-self)/2
1057 * - center = middle
1058 * - start that is 0
1059 * - end that is (max-self)
1060 * - mx x coordinate of the mouse
1061 * - my y coordinate of the mouse
1063 int
1064 parse_int_with_pos(
1065 Display *d, const char *str, int default_value, int max, int self)
1067 if (!strcmp(str, "start"))
1068 return 0;
1069 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1070 return (max - self) / 2;
1071 if (!strcmp(str, "end"))
1072 return max - self;
1073 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1074 int x, y;
1076 get_mouse_coords(d, &x, &y);
1077 if (!strcmp(str, "mx"))
1078 return x;
1079 else
1080 return y;
1082 return parse_int_with_percentage(str, default_value, max);
1085 /* Parse a string like a CSS value. */
1086 /* TODO: harden a bit this function */
1087 char **
1088 parse_csslike(const char *str)
1090 int i, j;
1091 char *s, *token, **ret;
1092 short any_null;
1094 s = strdup(str);
1095 if (s == NULL)
1096 return NULL;
1098 ret = malloc(4 * sizeof(char *));
1099 if (ret == NULL) {
1100 free(s);
1101 return NULL;
1104 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1105 ret[i] = strdup(token);
1107 if (i == 1)
1108 for (j = 1; j < 4; j++)
1109 ret[j] = strdup(ret[0]);
1111 if (i == 2) {
1112 ret[2] = strdup(ret[0]);
1113 ret[3] = strdup(ret[1]);
1116 if (i == 3)
1117 ret[3] = strdup(ret[1]);
1119 /* before we didn't check for the return type of strdup, here we will
1122 any_null = 0;
1123 for (i = 0; i < 4; ++i)
1124 any_null = ret[i] == NULL || any_null;
1126 if (any_null)
1127 for (i = 0; i < 4; ++i)
1128 if (ret[i] != NULL)
1129 free(ret[i]);
1131 if (i == 0 || any_null) {
1132 free(s);
1133 free(ret);
1134 return NULL;
1137 return ret;
1141 * Given an event, try to understand what the users wants. If the
1142 * return value is ADD_CHAR then `input' is a pointer to a string that
1143 * will need to be free'ed later.
1145 enum action
1146 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1148 char str[SYM_BUF_SIZE] = { 0 };
1149 Status s;
1151 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1152 return DEL_CHAR;
1154 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1155 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1157 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1158 return CONFIRM;
1160 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1161 return EXIT;
1163 /* Try to read what key was pressed */
1164 s = 0;
1165 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1166 if (s == XBufferOverflow) {
1167 fprintf(stderr,
1168 "Buffer overflow when trying to create keyboard "
1169 "symbol map.\n");
1170 return EXIT;
1173 if (ev->state & ControlMask) {
1174 if (!strcmp(str, "")) /* C-u */
1175 return DEL_LINE;
1176 if (!strcmp(str, "")) /* C-w */
1177 return DEL_WORD;
1178 if (!strcmp(str, "")) /* C-h */
1179 return DEL_CHAR;
1180 if (!strcmp(str, "\r")) /* C-m */
1181 return CONFIRM_CONTINUE;
1182 if (!strcmp(str, "")) /* C-p */
1183 return PREV_COMPL;
1184 if (!strcmp(str, "")) /* C-n */
1185 return NEXT_COMPL;
1186 if (!strcmp(str, "")) /* C-c */
1187 return EXIT;
1188 if (!strcmp(str, "\t")) /* C-i */
1189 return TOGGLE_FIRST_SELECTED;
1192 *input = strdup(str);
1193 if (*input == NULL) {
1194 fprintf(stderr, "Error while allocating memory for key.\n");
1195 return EXIT;
1198 return ADD_CHAR;
1201 void
1202 confirm(enum state *status, struct rendering *r, struct completions *cs,
1203 char **text, int *textlen)
1205 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1206 /* if there is something selected expand it and return */
1207 int index = cs->selected == -1 ? 0 : cs->selected;
1208 struct completion *c = cs->completions;
1209 char *t;
1211 while (1) {
1212 if (index == 0)
1213 break;
1214 c++;
1215 index--;
1218 t = c->rcompletion;
1219 free(*text);
1220 *text = strdup(t);
1222 if (*text == NULL) {
1223 fprintf(stderr, "Memory allocation error\n");
1224 *status = ERR;
1227 *textlen = strlen(*text);
1228 return;
1231 if (!r->free_text) /* cannot accept arbitrary text */
1232 *status = LOOPING;
1235 /* cs: completion list
1236 * offset: the offset of the click
1237 * first: the first (rendered) item
1238 * def: the default action
1240 enum action
1241 select_clicked(
1242 struct completions *cs, size_t offset, size_t first, enum action def)
1244 ssize_t selected = first;
1245 int set = 0;
1247 if (cs->length == 0)
1248 return NO_OP;
1250 if (offset < cs->completions[selected].offset)
1251 return NO_OP;
1253 /* skip the first entry */
1254 for (selected += 1; selected < cs->length; ++selected) {
1255 if (cs->completions[selected].offset == -1)
1256 break;
1258 if (offset < cs->completions[selected].offset) {
1259 cs->selected = selected - 1;
1260 set = 1;
1261 break;
1265 if (!set)
1266 cs->selected = selected - 1;
1268 return def;
1271 enum action
1272 handle_mouse(
1273 struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1275 size_t off;
1277 if (r->horizontal_layout)
1278 off = e->x;
1279 else
1280 off = e->y;
1282 switch (e->button) {
1283 case Button1:
1284 return select_clicked(cs, off, r->offset, CONFIRM);
1286 case Button3:
1287 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1289 case Button4:
1290 return SCROLL_UP;
1292 case Button5:
1293 return SCROLL_DOWN;
1296 return NO_OP;
1299 /* event loop */
1300 enum state
1301 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1302 char **lines, char **vlines)
1304 enum state status = LOOPING;
1306 while (status == LOOPING) {
1307 XEvent e;
1308 XNextEvent(r->d, &e);
1310 if (XFilterEvent(&e, r->w))
1311 continue;
1313 switch (e.type) {
1314 case KeymapNotify:
1315 XRefreshKeyboardMapping(&e.xmapping);
1316 break;
1318 case FocusIn:
1319 /* Re-grab focus */
1320 if (e.xfocus.window != r->w)
1321 grabfocus(r->d, r->w);
1322 break;
1324 case VisibilityNotify:
1325 if (e.xvisibility.state != VisibilityUnobscured)
1326 XRaiseWindow(r->d, r->w);
1327 break;
1329 case MapNotify:
1330 get_wh(r->d, &r->w, &r->width, &r->height);
1331 draw(r, *text, cs);
1332 break;
1334 case KeyPress:
1335 case ButtonPress: {
1336 enum action a;
1337 char *input = NULL;
1339 if (e.type == KeyPress)
1340 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1341 r->xic, &input);
1342 else
1343 a = handle_mouse(
1344 r, cs, (XButtonPressedEvent *)&e);
1346 switch (a) {
1347 case NO_OP:
1348 break;
1350 case EXIT:
1351 status = ERR;
1352 break;
1354 case CONFIRM: {
1355 status = OK;
1356 confirm(&status, r, cs, text, textlen);
1357 break;
1360 case CONFIRM_CONTINUE: {
1361 status = OK_LOOP;
1362 confirm(&status, r, cs, text, textlen);
1363 break;
1366 case PREV_COMPL: {
1367 complete(cs, r->first_selected, 1, text,
1368 textlen, &status);
1369 r->offset = cs->selected;
1370 break;
1373 case NEXT_COMPL: {
1374 complete(cs, r->first_selected, 0, text,
1375 textlen, &status);
1376 r->offset = cs->selected;
1377 break;
1380 case DEL_CHAR:
1381 popc(*text);
1382 update_completions(cs, *text, lines, vlines,
1383 r->first_selected);
1384 r->offset = 0;
1385 break;
1387 case DEL_WORD: {
1388 popw(*text);
1389 update_completions(cs, *text, lines, vlines,
1390 r->first_selected);
1391 break;
1394 case DEL_LINE: {
1395 int i;
1396 for (i = 0; i < *textlen; ++i)
1397 *(*text + i) = 0;
1398 update_completions(cs, *text, lines, vlines,
1399 r->first_selected);
1400 r->offset = 0;
1401 break;
1404 case ADD_CHAR: {
1405 int str_len, i;
1407 str_len = strlen(input);
1410 * sometimes a strange key is pressed
1411 * i.e. ctrl alone), so input will be
1412 * empty. Don't need to update
1413 * completion in that case
1415 if (str_len == 0)
1416 break;
1418 for (i = 0; i < str_len; ++i) {
1419 *textlen = pushc(
1420 text, *textlen, input[i]);
1421 if (*textlen == -1) {
1422 fprintf(stderr,
1423 "Memory allocation "
1424 "error\n");
1425 status = ERR;
1426 break;
1430 if (status != ERR) {
1431 update_completions(cs, *text, lines,
1432 vlines, r->first_selected);
1433 free(input);
1436 r->offset = 0;
1437 break;
1440 case TOGGLE_FIRST_SELECTED:
1441 r->first_selected = !r->first_selected;
1442 if (r->first_selected && cs->selected < 0)
1443 cs->selected = 0;
1444 if (!r->first_selected && cs->selected == 0)
1445 cs->selected = -1;
1446 break;
1448 case SCROLL_DOWN:
1449 r->offset
1450 = MIN(r->offset + 1, cs->length - 1);
1451 break;
1453 case SCROLL_UP:
1454 r->offset = MAX((ssize_t)r->offset - 1, 0);
1455 break;
1460 draw(r, *text, cs);
1463 return status;
1466 int
1467 load_font(struct rendering *r, const char *fontname)
1469 #ifdef USE_XFT
1470 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1471 return 0;
1472 #else
1473 char **missing_charset_list;
1474 int missing_charset_count;
1476 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1477 &missing_charset_count, NULL);
1478 if (r->font != NULL)
1479 return 0;
1481 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1483 if (!strcmp(fontname, default_fontname))
1484 return -1;
1486 return load_font(r, default_fontname);
1487 #endif
1490 void
1491 xim_init(struct rendering *r, XrmDatabase *xdb)
1493 XIMStyle best_match_style;
1494 XIMStyles *xis;
1495 int i;
1497 /* Open the X input method */
1498 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1499 err(1, "XOpenIM");
1501 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1502 fprintf(stderr, "Input Styles could not be retrieved\n");
1503 exit(EX_UNAVAILABLE);
1506 best_match_style = 0;
1507 for (i = 0; i < xis->count_styles; ++i) {
1508 XIMStyle ts = xis->supported_styles[i];
1509 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1510 best_match_style = ts;
1511 break;
1514 XFree(xis);
1516 if (!best_match_style)
1517 fprintf(stderr,
1518 "No matching input style could be determined\n");
1520 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1521 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1522 if (r->xic == NULL)
1523 err(1, "XCreateIC");
1526 void
1527 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1528 XVisualInfo vinfo, int x, int y, int ox, int oy,
1529 unsigned long background_pixel)
1531 XSetWindowAttributes attr;
1533 /* Create the window */
1534 attr.colormap = cmap;
1535 attr.override_redirect = 1;
1536 attr.border_pixel = 0;
1537 attr.background_pixel = background_pixel;
1538 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1539 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1541 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1542 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1543 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1544 | CWOverrideRedirect,
1545 &attr);
1548 void
1549 ps1extents(struct rendering *r)
1551 char *dup;
1552 dup = strdupn(r->ps1);
1553 text_extents(
1554 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1555 free(dup);
1558 void
1559 usage(char *prgname)
1561 fprintf(stderr,
1562 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1563 " [-d separator] [-e window] [-f font] [-G color] [-g "
1564 "size]\n"
1565 " [-H height] [-I color] [-i size] [-J color] [-j "
1566 "size] [-l layout]\n"
1567 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1568 "color]\n"
1569 " [-t color] [-W width] [-x coord] [-y coord]\n",
1570 prgname);
1573 int
1574 main(int argc, char **argv)
1576 struct completions *cs;
1577 struct rendering r;
1578 XVisualInfo vinfo;
1579 Colormap cmap;
1580 size_t nlines, i;
1581 Window parent_window;
1582 XrmDatabase xdb;
1583 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1584 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1585 ch_borders_bg[4]; /* N E S W */
1586 enum state status;
1587 int ch;
1588 int offset_x, offset_y, x, y;
1589 int textlen, d_width, d_height;
1590 short embed;
1591 char *sep, *parent_window_id;
1592 char **lines, *buf, **vlines;
1593 char *fontname, *text, *xrm;
1595 #ifdef __OpenBSD__
1596 /* stdio & rpath: to read/write stdio/stdout/stderr */
1597 /* unix: to connect to XOrg */
1598 pledge("stdio rpath unix", "");
1599 #endif
1601 sep = NULL;
1602 parent_window_id = NULL;
1604 r.first_selected = 0;
1605 r.free_text = 1;
1606 r.multiple_select = 0;
1607 r.offset = 0;
1609 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1610 switch (ch) {
1611 case 'h': /* help */
1612 usage(*argv);
1613 return 0;
1614 case 'v': /* version */
1615 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1616 return 0;
1617 case 'e': /* embed */
1618 if ((parent_window_id = strdup(optarg)) == NULL)
1619 err(1, "strdup");
1620 break;
1621 case 'd':
1622 if ((sep = strdup(optarg)) == NULL)
1623 err(1, "strdup");
1624 break;
1625 case 'A':
1626 r.free_text = 0;
1627 break;
1628 case 'm':
1629 r.multiple_select = 1;
1630 break;
1631 default:
1632 break;
1636 /* Read the completions */
1637 lines = NULL;
1638 buf = NULL;
1639 nlines = readlines(&lines, &buf);
1641 vlines = NULL;
1642 if (sep != NULL) {
1643 int l;
1644 l = strlen(sep);
1645 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1646 err(1, "calloc");
1648 for (i = 0; i < nlines; i++) {
1649 char *t;
1650 t = strstr(lines[i], sep);
1651 if (t == NULL)
1652 vlines[i] = lines[i];
1653 else
1654 vlines[i] = t + l;
1658 setlocale(LC_ALL, getenv("LANG"));
1660 status = LOOPING;
1662 /* where the monitor start (used only with xinerama) */
1663 offset_x = offset_y = 0;
1665 /* default width and height */
1666 r.width = 400;
1667 r.height = 20;
1669 /* default position on the screen */
1670 x = y = 0;
1672 for (i = 0; i < 4; ++i) {
1673 /* default paddings */
1674 r.p_padding[i] = 10;
1675 r.c_padding[i] = 10;
1676 r.ch_padding[i] = 10;
1678 /* default borders */
1679 r.borders[i] = 0;
1680 r.p_borders[i] = 0;
1681 r.c_borders[i] = 0;
1682 r.ch_borders[i] = 0;
1685 /* the prompt. We duplicate the string so later is easy to
1686 * free (in the case it's been overwritten by the user) */
1687 if ((r.ps1 = strdup("$ ")) == NULL)
1688 err(1, "strdup");
1690 /* same for the font name */
1691 if ((fontname = strdup(default_fontname)) == NULL)
1692 err(1, "strdup");
1694 textlen = 10;
1695 if ((text = malloc(textlen * sizeof(char))) == NULL)
1696 err(1, "malloc");
1698 /* struct completions *cs = filter(text, lines); */
1699 if ((cs = compls_new(nlines)) == NULL)
1700 err(1, "compls_new");
1702 /* start talking to xorg */
1703 r.d = XOpenDisplay(NULL);
1704 if (r.d == NULL) {
1705 fprintf(stderr, "Could not open display!\n");
1706 return EX_UNAVAILABLE;
1709 embed = 1;
1710 if (!(parent_window_id
1711 && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1712 parent_window = DefaultRootWindow(r.d);
1713 embed = 0;
1716 /* get display size */
1717 get_wh(r.d, &parent_window, &d_width, &d_height);
1719 #ifdef USE_XINERAMA
1720 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1721 XineramaScreenInfo *info;
1722 Window rr;
1723 Window root;
1724 int number_of_screens, monitors, i;
1725 int root_x, root_y, win_x, win_y;
1726 unsigned int mask;
1727 short res;
1729 number_of_screens = XScreenCount(r.d);
1730 for (i = 0; i < number_of_screens; ++i) {
1731 root = XRootWindow(r.d, i);
1732 res = XQueryPointer(r.d, root, &rr, &rr, &root_x,
1733 &root_y, &win_x, &win_y, &mask);
1734 if (res)
1735 break;
1738 if (!res) {
1739 fprintf(stderr, "No mouse found.\n");
1740 root_x = 0;
1741 root_y = 0;
1744 /* Now find in which monitor the mice is */
1745 info = XineramaQueryScreens(r.d, &monitors);
1746 if (info) {
1747 for (i = 0; i < monitors; ++i) {
1748 if (info[i].x_org <= root_x
1749 && root_x <= (info[i].x_org
1750 + info[i].width)
1751 && info[i].y_org <= root_y
1752 && root_y <= (info[i].y_org
1753 + info[i].height)) {
1754 offset_x = info[i].x_org;
1755 offset_y = info[i].y_org;
1756 d_width = info[i].width;
1757 d_height = info[i].height;
1758 break;
1762 XFree(info);
1764 #endif
1766 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1767 cmap = XCreateColormap(
1768 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1770 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1771 fgs[2] = parse_color("#000", NULL);
1773 bgs[0] = bgs[1] = parse_color("#000", NULL);
1774 bgs[2] = parse_color("#fff", NULL);
1776 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1777 = parse_color("#000", NULL);
1779 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1780 = parse_color("#000", NULL);
1781 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1782 = parse_color("#000", NULL);
1783 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1784 = ch_borders_bg[3] = parse_color("#000", NULL);
1786 r.horizontal_layout = 1;
1788 /* Read the resources */
1789 XrmInitialize();
1790 xrm = XResourceManagerString(r.d);
1791 xdb = NULL;
1792 if (xrm != NULL) {
1793 XrmValue value;
1794 char *datatype[20];
1796 xdb = XrmGetStringDatabase(xrm);
1798 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1799 == 1) {
1800 free(fontname);
1801 if ((fontname = strdup(value.addr)) == NULL)
1802 err(1, "strdup");
1803 } else {
1804 fprintf(stderr, "no font defined, using %s\n",
1805 fontname);
1808 if (XrmGetResource(
1809 xdb, "MyMenu.layout", "*", datatype, &value)
1810 == 1)
1811 r.horizontal_layout
1812 = !strcmp(value.addr, "horizontal");
1813 else
1814 fprintf(stderr,
1815 "no layout defined, using horizontal\n");
1817 if (XrmGetResource(
1818 xdb, "MyMenu.prompt", "*", datatype, &value)
1819 == 1) {
1820 free(r.ps1);
1821 r.ps1 = normalize_str(value.addr);
1822 } else {
1823 fprintf(stderr,
1824 "no prompt defined, using \"%s\" as "
1825 "default\n",
1826 r.ps1);
1829 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1830 datatype, &value)
1831 == 1) {
1832 char **sizes;
1833 sizes = parse_csslike(value.addr);
1834 if (sizes != NULL)
1835 for (i = 0; i < 4; ++i)
1836 r.p_borders[i]
1837 = parse_integer(sizes[i], 0);
1838 else
1839 fprintf(stderr,
1840 "error while parsing "
1841 "MyMenu.prompt.border.size");
1844 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1845 datatype, &value)
1846 == 1) {
1847 char **colors;
1848 colors = parse_csslike(value.addr);
1849 if (colors != NULL)
1850 for (i = 0; i < 4; ++i)
1851 p_borders_bg[i] = parse_color(
1852 colors[i], "#000");
1853 else
1854 fprintf(stderr,
1855 "error while parsing "
1856 "MyMenu.prompt.border.color");
1859 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1860 datatype, &value)
1861 == 1) {
1862 char **colors;
1863 colors = parse_csslike(value.addr);
1864 if (colors != NULL)
1865 for (i = 0; i < 4; ++i)
1866 r.p_padding[i]
1867 = parse_integer(colors[i], 0);
1868 else
1869 fprintf(stderr,
1870 "error while parsing "
1871 "MyMenu.prompt.padding");
1874 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1875 == 1)
1876 r.width = parse_int_with_percentage(
1877 value.addr, r.width, d_width);
1878 else
1879 fprintf(stderr, "no width defined, using %d\n",
1880 r.width);
1882 if (XrmGetResource(
1883 xdb, "MyMenu.height", "*", datatype, &value)
1884 == 1)
1885 r.height = parse_int_with_percentage(
1886 value.addr, r.height, d_height);
1887 else
1888 fprintf(stderr, "no height defined, using %d\n",
1889 r.height);
1891 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1892 == 1)
1893 x = parse_int_with_pos(
1894 r.d, value.addr, x, d_width, r.width);
1896 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1897 == 1)
1898 y = parse_int_with_pos(
1899 r.d, value.addr, y, d_height, r.height);
1901 if (XrmGetResource(
1902 xdb, "MyMenu.border.size", "*", datatype, &value)
1903 == 1) {
1904 char **borders;
1905 borders = parse_csslike(value.addr);
1906 if (borders != NULL)
1907 for (i = 0; i < 4; ++i)
1908 r.borders[i]
1909 = parse_int_with_percentage(
1910 borders[i], 0,
1911 (i % 2) == 0
1912 ? d_height
1913 : d_width);
1914 else
1915 fprintf(stderr,
1916 "error while parsing "
1917 "MyMenu.border.size\n");
1920 /* Prompt */
1921 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1922 datatype, &value)
1923 == 1)
1924 fgs[0] = parse_color(value.addr, "#fff");
1926 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1927 datatype, &value)
1928 == 1)
1929 bgs[0] = parse_color(value.addr, "#000");
1931 /* Completions */
1932 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1933 datatype, &value)
1934 == 1)
1935 fgs[1] = parse_color(value.addr, "#fff");
1937 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1938 datatype, &value)
1939 == 1)
1940 bgs[1] = parse_color(value.addr, "#000");
1942 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1943 datatype, &value)
1944 == 1) {
1945 char **paddings;
1946 paddings = parse_csslike(value.addr);
1947 if (paddings != NULL)
1948 for (i = 0; i < 4; ++i)
1949 r.c_padding[i] = parse_integer(
1950 paddings[i], 0);
1951 else
1952 fprintf(stderr,
1953 "Error while parsing "
1954 "MyMenu.completion.padding");
1957 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1958 datatype, &value)
1959 == 1) {
1960 char **sizes;
1961 sizes = parse_csslike(value.addr);
1962 if (sizes != NULL)
1963 for (i = 0; i < 4; ++i)
1964 r.c_borders[i]
1965 = parse_integer(sizes[i], 0);
1966 else
1967 fprintf(stderr,
1968 "Error while parsing "
1969 "MyMenu.completion.border.size");
1972 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1973 datatype, &value)
1974 == 1) {
1975 char **sizes;
1976 sizes = parse_csslike(value.addr);
1977 if (sizes != NULL)
1978 for (i = 0; i < 4; ++i)
1979 c_borders_bg[i] = parse_color(
1980 sizes[i], "#000");
1981 else
1982 fprintf(stderr,
1983 "Error while parsing "
1984 "MyMenu.completion.border.color");
1987 /* Completion Highlighted */
1988 if (XrmGetResource(xdb,
1989 "MyMenu.completion_highlighted.foreground", "*",
1990 datatype, &value)
1991 == 1)
1992 fgs[2] = parse_color(value.addr, "#000");
1994 if (XrmGetResource(xdb,
1995 "MyMenu.completion_highlighted.background", "*",
1996 datatype, &value)
1997 == 1)
1998 bgs[2] = parse_color(value.addr, "#fff");
2000 if (XrmGetResource(xdb,
2001 "MyMenu.completion_highlighted.padding", "*",
2002 datatype, &value)
2003 == 1) {
2004 char **paddings;
2005 paddings = parse_csslike(value.addr);
2006 if (paddings != NULL)
2007 for (i = 0; i < 4; ++i)
2008 r.ch_padding[i] = parse_integer(
2009 paddings[i], 0);
2010 else
2011 fprintf(stderr,
2012 "Error while parsing "
2013 "MyMenu.completion_highlighted."
2014 "padding");
2017 if (XrmGetResource(xdb,
2018 "MyMenu.completion_highlighted.border.size", "*",
2019 datatype, &value)
2020 == 1) {
2021 char **sizes;
2022 sizes = parse_csslike(value.addr);
2023 if (sizes != NULL)
2024 for (i = 0; i < 4; ++i)
2025 r.ch_borders[i]
2026 = parse_integer(sizes[i], 0);
2027 else
2028 fprintf(stderr,
2029 "Error while parsing "
2030 "MyMenu.completion_highlighted."
2031 "border.size");
2034 if (XrmGetResource(xdb,
2035 "MyMenu.completion_highlighted.border.color", "*",
2036 datatype, &value)
2037 == 1) {
2038 char **colors;
2039 colors = parse_csslike(value.addr);
2040 if (colors != NULL)
2041 for (i = 0; i < 4; ++i)
2042 ch_borders_bg[i] = parse_color(
2043 colors[i], "#000");
2044 else
2045 fprintf(stderr,
2046 "Error while parsing "
2047 "MyMenu.completion_highlighted."
2048 "border.color");
2051 /* Border */
2052 if (XrmGetResource(
2053 xdb, "MyMenu.border.color", "*", datatype, &value)
2054 == 1) {
2055 char **colors;
2056 colors = parse_csslike(value.addr);
2057 if (colors != NULL)
2058 for (i = 0; i < 4; ++i)
2059 borders_bg[i] = parse_color(
2060 colors[i], "#000");
2061 else
2062 fprintf(stderr,
2063 "error while parsing "
2064 "MyMenu.border.color\n");
2068 /* Second round of args parsing */
2069 optind = 0; /* reset the option index */
2070 while ((ch = getopt(argc, argv, ARGS)) != -1) {
2071 switch (ch) {
2072 case 'a':
2073 r.first_selected = 1;
2074 break;
2075 case 'A':
2076 /* free_text -- already catched */
2077 case 'd':
2078 /* separator -- this case was already catched */
2079 case 'e':
2080 /* embedding mymenu this case was already catched. */
2081 case 'm':
2082 /* multiple selection this case was already catched.
2084 break;
2085 case 'p': {
2086 char *newprompt;
2087 newprompt = strdup(optarg);
2088 if (newprompt != NULL) {
2089 free(r.ps1);
2090 r.ps1 = newprompt;
2092 break;
2094 case 'x':
2095 x = parse_int_with_pos(
2096 r.d, optarg, x, d_width, r.width);
2097 break;
2098 case 'y':
2099 y = parse_int_with_pos(
2100 r.d, optarg, y, d_height, r.height);
2101 break;
2102 case 'P': {
2103 char **paddings;
2104 if ((paddings = parse_csslike(optarg)) != NULL)
2105 for (i = 0; i < 4; ++i)
2106 r.p_padding[i] = parse_integer(
2107 paddings[i], 0);
2108 break;
2110 case 'G': {
2111 char **colors;
2112 if ((colors = parse_csslike(optarg)) != NULL)
2113 for (i = 0; i < 4; ++i)
2114 p_borders_bg[i] = parse_color(
2115 colors[i], "#000");
2116 break;
2118 case 'g': {
2119 char **sizes;
2120 if ((sizes = parse_csslike(optarg)) != NULL)
2121 for (i = 0; i < 4; ++i)
2122 r.p_borders[i]
2123 = parse_integer(sizes[i], 0);
2124 break;
2126 case 'I': {
2127 char **colors;
2128 if ((colors = parse_csslike(optarg)) != NULL)
2129 for (i = 0; i < 4; ++i)
2130 c_borders_bg[i] = parse_color(
2131 colors[i], "#000");
2132 break;
2134 case 'i': {
2135 char **sizes;
2136 if ((sizes = parse_csslike(optarg)) != NULL)
2137 for (i = 0; i < 4; ++i)
2138 r.c_borders[i]
2139 = parse_integer(sizes[i], 0);
2140 break;
2142 case 'J': {
2143 char **colors;
2144 if ((colors = parse_csslike(optarg)) != NULL)
2145 for (i = 0; i < 4; ++i)
2146 ch_borders_bg[i] = parse_color(
2147 colors[i], "#000");
2148 break;
2150 case 'j': {
2151 char **sizes;
2152 if ((sizes = parse_csslike(optarg)) != NULL)
2153 for (i = 0; i < 4; ++i)
2154 r.ch_borders[i]
2155 = parse_integer(sizes[i], 0);
2156 break;
2158 case 'l':
2159 r.horizontal_layout = !strcmp(optarg, "horizontal");
2160 break;
2161 case 'f': {
2162 char *newfont;
2163 if ((newfont = strdup(optarg)) != NULL) {
2164 free(fontname);
2165 fontname = newfont;
2167 break;
2169 case 'W':
2170 r.width = parse_int_with_percentage(
2171 optarg, r.width, d_width);
2172 break;
2173 case 'H':
2174 r.height = parse_int_with_percentage(
2175 optarg, r.height, d_height);
2176 break;
2177 case 'b': {
2178 char **borders;
2179 if ((borders = parse_csslike(optarg)) != NULL) {
2180 for (i = 0; i < 4; ++i)
2181 r.borders[i] = parse_integer(
2182 borders[i], 0);
2183 } else
2184 fprintf(stderr, "Error parsing b option\n");
2185 break;
2187 case 'B': {
2188 char **colors;
2189 if ((colors = parse_csslike(optarg)) != NULL) {
2190 for (i = 0; i < 4; ++i)
2191 borders_bg[i] = parse_color(
2192 colors[i], "#000");
2193 } else
2194 fprintf(stderr,
2195 "error while parsing B option\n");
2196 break;
2198 case 't':
2199 fgs[0] = parse_color(optarg, NULL);
2200 break;
2201 case 'T':
2202 bgs[0] = parse_color(optarg, NULL);
2203 break;
2204 case 'c':
2205 fgs[1] = parse_color(optarg, NULL);
2206 break;
2207 case 'C':
2208 bgs[1] = parse_color(optarg, NULL);
2209 break;
2210 case 's':
2211 fgs[2] = parse_color(optarg, NULL);
2212 break;
2213 case 'S':
2214 fgs[2] = parse_color(optarg, NULL);
2215 break;
2216 default:
2217 fprintf(stderr, "Unrecognized option %c\n", ch);
2218 status = ERR;
2219 break;
2223 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2224 fprintf(stderr, "height, width, x or y are lesser than 0.");
2225 status = ERR;
2228 /* since only now we know if the first should be selected,
2229 * update the completion here */
2230 update_completions(cs, text, lines, vlines, r.first_selected);
2232 /* update the prompt lenght, only now we surely know the length of it
2234 r.ps1len = strlen(r.ps1);
2236 /* Create the window */
2237 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2238 offset_y, bgs[1]);
2239 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2240 XMapRaised(r.d, r.w);
2242 /* If embed, listen for other events as well */
2243 if (embed) {
2244 Window *children, parent, root;
2245 unsigned int children_no;
2247 XSelectInput(r.d, parent_window, FocusChangeMask);
2248 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2249 &children_no)
2250 && children) {
2251 for (i = 0; i < children_no && children[i] != r.w;
2252 ++i)
2253 XSelectInput(
2254 r.d, children[i], FocusChangeMask);
2255 XFree(children);
2257 grabfocus(r.d, r.w);
2260 take_keyboard(r.d, r.w);
2262 r.x_zero = r.borders[3];
2263 r.y_zero = r.borders[0];
2266 XGCValues values;
2268 for (i = 0; i < 3; ++i) {
2269 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2270 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2273 for (i = 0; i < 4; ++i) {
2274 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2275 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2276 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2277 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2281 /* Load the colors in our GCs */
2282 for (i = 0; i < 3; ++i) {
2283 XSetForeground(r.d, r.fgs[i], fgs[i]);
2284 XSetForeground(r.d, r.bgs[i], bgs[i]);
2287 for (i = 0; i < 4; ++i) {
2288 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2289 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2290 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2291 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2294 if (load_font(&r, fontname) == -1)
2295 status = ERR;
2297 #ifdef USE_XFT
2298 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2300 for (i = 0; i < 3; ++i) {
2301 rgba_t c;
2302 XRenderColor xrcolor;
2304 c = *(rgba_t *)&fgs[i];
2305 xrcolor.red = EXPANDBITS(c.rgba.r);
2306 xrcolor.green = EXPANDBITS(c.rgba.g);
2307 xrcolor.blue = EXPANDBITS(c.rgba.b);
2308 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2309 XftColorAllocValue(
2310 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2312 #endif
2314 /* compute prompt dimensions */
2315 ps1extents(&r);
2317 xim_init(&r, &xdb);
2319 #ifdef __OpenBSD__
2320 /* Now we need only the ability to write */
2321 pledge("stdio", "");
2322 #endif
2324 /* Cache text height */
2325 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2327 /* Draw the window for the first time */
2328 draw(&r, text, cs);
2330 /* Main loop */
2331 while (status == LOOPING || status == OK_LOOP) {
2332 status = loop(&r, &text, &textlen, cs, lines, vlines);
2334 if (status != ERR)
2335 printf("%s\n", text);
2337 if (!r.multiple_select && status == OK_LOOP)
2338 status = OK;
2341 XUngrabKeyboard(r.d, CurrentTime);
2343 #ifdef USE_XFT
2344 for (i = 0; i < 3; ++i)
2345 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2346 #endif
2348 for (i = 0; i < 3; ++i) {
2349 XFreeGC(r.d, r.fgs[i]);
2350 XFreeGC(r.d, r.bgs[i]);
2353 for (i = 0; i < 4; ++i) {
2354 XFreeGC(r.d, r.borders_bg[i]);
2355 XFreeGC(r.d, r.p_borders_bg[i]);
2356 XFreeGC(r.d, r.c_borders_bg[i]);
2357 XFreeGC(r.d, r.ch_borders_bg[i]);
2360 XDestroyIC(r.xic);
2361 XCloseIM(r.xim);
2363 #ifdef USE_XFT
2364 for (i = 0; i < 3; ++i)
2365 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2366 XftFontClose(r.d, r.font);
2367 XftDrawDestroy(r.xftdraw);
2368 #else
2369 XFreeFontSet(r.d, r.font);
2370 #endif
2372 free(r.ps1);
2373 free(fontname);
2374 free(text);
2376 free(buf);
2377 free(lines);
2378 free(vlines);
2379 compls_delete(cs);
2381 XFreeColormap(r.d, cmap);
2383 XDestroyWindow(r.d, r.w);
2384 XCloseDisplay(r.d);
2386 return status != OK;