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 EXIT,
78 CONFIRM,
79 CONFIRM_CONTINUE,
80 NEXT_COMPL,
81 PREV_COMPL,
82 DEL_CHAR,
83 DEL_WORD,
84 DEL_LINE,
85 ADD_CHAR,
86 TOGGLE_FIRST_SELECTED
87 };
89 /* A big set of values that needs to be carried around for drawing. A
90 big struct to rule them all */
91 struct rendering {
92 Display *d; /* Connection to xorg */
93 Window w;
94 XIM xim;
95 int width;
96 int height;
97 int p_padding[4];
98 int c_padding[4];
99 int ch_padding[4];
100 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
101 the borders) */
102 int y_zero; /* like x_zero but for the y axis */
104 size_t offset; /* scroll offset */
106 short free_text;
107 short first_selected;
108 short multiple_select;
110 /* four border width */
111 int borders[4];
112 int p_borders[4];
113 int c_borders[4];
114 int ch_borders[4];
116 short horizontal_layout;
118 /* prompt */
119 char *ps1;
120 int ps1len;
121 int ps1w; /* ps1 width */
122 int ps1h; /* ps1 height */
124 int text_height; /* cache for the vertical layout */
126 XIC xic;
128 /* colors */
129 GC fgs[4];
130 GC bgs[4];
131 GC borders_bg[4];
132 GC p_borders_bg[4];
133 GC c_borders_bg[4];
134 GC ch_borders_bg[4];
135 #ifdef USE_XFT
136 XftFont *font;
137 XftDraw *xftdraw;
138 XftColor xft_colors[3];
139 #else
140 XFontSet font;
141 #endif
142 };
144 struct completion {
145 char *completion;
146 char *rcompletion;
147 };
149 /* Wrap the linked list of completions */
150 struct completions {
151 struct completion *completions;
152 ssize_t selected;
153 size_t length;
154 };
156 /* idea stolen from lemonbar. ty lemonboy */
157 typedef union {
158 struct {
159 uint8_t b;
160 uint8_t g;
161 uint8_t r;
162 uint8_t a;
163 } rgba;
164 uint32_t v;
165 } rgba_t;
167 extern char *optarg;
168 extern int optind;
170 /* Return a newly allocated (and empty) completion list */
171 struct completions *
172 compls_new(size_t length)
174 struct completions *cs = malloc(sizeof(struct completions));
176 if (cs == NULL)
177 return cs;
179 cs->completions = calloc(length, sizeof(struct completion));
180 if (cs->completions == NULL) {
181 free(cs);
182 return NULL;
185 cs->selected = -1;
186 cs->length = length;
187 return cs;
190 /* Delete the wrapper and the whole list */
191 void
192 compls_delete(struct completions *cs)
194 if (cs == NULL)
195 return;
197 free(cs->completions);
198 free(cs);
201 /*
202 * Create a completion list from a text and the list of possible
203 * completions (null terminated). Expects a non-null `cs'. `lines' and
204 * `vlines' should have the same length OR `vlines' is NULL.
205 */
206 void
207 filter(struct completions *cs, char *text, char **lines, char **vlines)
209 size_t index = 0;
210 size_t matching = 0;
211 char *l;
213 if (vlines == NULL)
214 vlines = lines;
216 while (1) {
217 if (lines[index] == NULL)
218 break;
220 l = vlines[index] != NULL ? vlines[index] : lines[index];
222 if (strcasestr(l, text) != NULL) {
223 struct completion *c = &cs->completions[matching];
224 c->completion = l;
225 c->rcompletion = lines[index];
226 matching++;
229 index++;
231 cs->length = matching;
232 cs->selected = -1;
235 /* Update the given completion */
236 void
237 update_completions(struct completions *cs, char *text, char **lines,
238 char **vlines, short first_selected)
240 filter(cs, text, lines, vlines);
241 if (first_selected && cs->length > 0)
242 cs->selected = 0;
245 /*
246 * Select the next or previous selection and update some state. `text'
247 * will be updated with the text of the completion and `textlen' with
248 * the new length. If the memory cannot be allocated `status' will be
249 * set to `ERR'.
250 */
251 void
252 complete(struct completions *cs, short first_selected, short p, char **text,
253 int *textlen, enum state *status)
255 struct completion *n;
256 int index;
258 if (cs == NULL || cs->length == 0)
259 return;
261 /*
262 * If the first is always selected and the first entry is
263 * different from the text, expand the text and return
264 */
265 if (first_selected && cs->selected == 0
266 && strcmp(cs->completions->completion, *text) != 0 && !p) {
267 free(*text);
268 *text = strdup(cs->completions->completion);
269 if (text == NULL) {
270 *status = ERR;
271 return;
273 *textlen = strlen(*text);
274 return;
277 index = cs->selected;
279 if (index == -1 && p)
280 index = 0;
281 index = cs->selected
282 = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
284 n = &cs->completions[cs->selected];
286 free(*text);
287 *text = strdup(n->completion);
288 if (text == NULL) {
289 fprintf(stderr, "Memory allocation error!\n");
290 *status = ERR;
291 return;
293 *textlen = strlen(*text);
296 /* Push the character c at the end of the string pointed by p */
297 int
298 pushc(char **p, int maxlen, char c)
300 int len;
302 len = strnlen(*p, maxlen);
303 if (!(len < maxlen - 2)) {
304 char *newptr;
306 maxlen += maxlen >> 1;
307 newptr = realloc(*p, maxlen);
308 if (newptr == NULL) /* bad */
309 return -1;
310 *p = newptr;
313 (*p)[len] = c;
314 (*p)[len + 1] = '\0';
315 return maxlen;
318 /*
319 * Remove the last rune from the *UTF-8* string! This is different
320 * from just setting the last byte to 0 (in some cases ofc). Return a
321 * pointer (e) to the last nonzero char. If e < p then p is empty!
322 */
323 char *
324 popc(char *p)
326 int len = strlen(p);
327 char *e;
329 if (len == 0)
330 return p;
332 e = p + len - 1;
334 do {
335 char c = *e;
337 *e = '\0';
338 e -= 1;
340 /*
341 * If c is a starting byte (11......) or is under
342 * U+007F we're done.
343 */
344 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
345 break;
346 } while (e >= p);
348 return e;
351 /* Remove the last word plus trailing white spaces from the given string */
352 void
353 popw(char *w)
355 int len;
356 short in_word = 1;
358 if ((len = strlen(w)) == 0)
359 return;
361 while (1) {
362 char *e = popc(w);
364 if (e < w)
365 return;
367 if (in_word && isspace(*e))
368 in_word = 0;
370 if (!in_word && !isspace(*e))
371 return;
375 /*
376 * If the string is surrounded by quates (`"') remove them and replace
377 * every `\"' in the string with a single double-quote.
378 */
379 char *
380 normalize_str(const char *str)
382 int len, p;
383 char *s;
385 if ((len = strlen(str)) == 0)
386 return NULL;
388 if ((s = calloc(len, sizeof(char))) == NULL)
389 err(1, "calloc");
390 p = 0;
392 while (*str) {
393 char c = *str;
395 if (*str == '\\') {
396 if (*(str + 1)) {
397 s[p] = *(str + 1);
398 p++;
399 str += 2; /* skip this and the next char */
400 continue;
401 } else
402 break;
404 if (c == '"') {
405 str++; /* skip only this char */
406 continue;
408 s[p] = c;
409 p++;
410 str++;
413 return s;
416 size_t
417 read_stdin(char **buf)
419 size_t offset = 0;
420 size_t len = STDIN_CHUNKS;
422 *buf = malloc(len * sizeof(char));
423 if (*buf == NULL)
424 goto err;
426 while (1) {
427 ssize_t r;
428 size_t i;
430 r = read(0, *buf + offset, STDIN_CHUNKS);
432 if (r < 1)
433 return len;
435 offset += r;
437 len += STDIN_CHUNKS;
438 *buf = realloc(*buf, len);
439 if (*buf == NULL)
440 goto err;
442 for (i = offset; i < len; ++i)
443 (*buf)[i] = '\0';
446 err:
447 fprintf(stderr, "Error in allocating memory for stdin.\n");
448 exit(EX_UNAVAILABLE);
451 size_t
452 readlines(char ***lns, char **buf)
454 size_t i, len, ll, lines;
455 short in_line = 0;
457 lines = 0;
459 *buf = NULL;
460 len = read_stdin(buf);
462 ll = LINES_CHUNK;
463 *lns = malloc(ll * sizeof(char *));
465 if (*lns == NULL)
466 goto err;
468 for (i = 0; i < len; i++) {
469 char c = (*buf)[i];
471 if (c == '\0')
472 break;
474 if (c == '\n')
475 (*buf)[i] = '\0';
477 if (in_line && c == '\n')
478 in_line = 0;
480 if (!in_line && c != '\n') {
481 in_line = 1;
482 (*lns)[lines] = (*buf) + i;
483 lines++;
485 if (lines == ll) { /* resize */
486 ll += LINES_CHUNK;
487 *lns = realloc(*lns, ll * sizeof(char *));
488 if (*lns == NULL)
489 goto err;
494 (*lns)[lines] = NULL;
496 return lines;
498 err:
499 fprintf(stderr, "Error in memory allocation.\n");
500 exit(EX_UNAVAILABLE);
503 /*
504 * Compute the dimensions of the string str once rendered.
505 * It'll return the width and set ret_width and ret_height if not NULL
506 */
507 int
508 text_extents(char *str, int len, struct rendering *r, int *ret_width,
509 int *ret_height)
511 int height, width;
512 #ifdef USE_XFT
513 XGlyphInfo gi;
514 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
515 height = r->font->ascent - r->font->descent;
516 width = gi.width - gi.x;
517 #else
518 XRectangle rect;
519 XmbTextExtents(r->font, str, len, NULL, &rect);
520 height = rect.height;
521 width = rect.width;
522 #endif
523 if (ret_width != NULL)
524 *ret_width = width;
525 if (ret_height != NULL)
526 *ret_height = height;
527 return width;
530 void
531 draw_string(char *str, int len, int x, int y, struct rendering *r,
532 enum obj_type tt)
534 #ifdef USE_XFT
535 XftColor xftcolor;
536 if (tt == PROMPT)
537 xftcolor = r->xft_colors[0];
538 if (tt == COMPL)
539 xftcolor = r->xft_colors[1];
540 if (tt == COMPL_HIGH)
541 xftcolor = r->xft_colors[2];
543 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
544 #else
545 GC gc;
546 if (tt == PROMPT)
547 gc = r->fgs[0];
548 if (tt == COMPL)
549 gc = r->fgs[1];
550 if (tt == COMPL_HIGH)
551 gc = r->fgs[2];
552 Xutf8DrawString(r->d, r->w, r->font, gc, x, y, str, len);
553 #endif
556 /* Duplicate the string and substitute every space with a 'n` */
557 char *
558 strdupn(char *str)
560 int len, i;
561 char *dup;
563 len = strlen(str);
565 if (str == NULL || len == 0)
566 return NULL;
568 if ((dup = strdup(str)) == NULL)
569 return NULL;
571 for (i = 0; i < len; ++i)
572 if (dup[i] == ' ')
573 dup[i] = 'n';
575 return dup;
578 int
579 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
580 enum obj_type t, char *text)
582 GC *border_color, bg;
583 int *padding, *borders;
584 int ret = 0, inner_width, inner_height, x;
586 switch (t) {
587 case PROMPT:
588 border_color = r->p_borders_bg;
589 padding = r->p_padding;
590 borders = r->p_borders;
591 bg = r->bgs[0];
592 break;
593 case COMPL:
594 border_color = r->c_borders_bg;
595 padding = r->c_padding;
596 borders = r->c_borders;
597 bg = r->bgs[1];
598 break;
599 case COMPL_HIGH:
600 border_color = r->ch_borders_bg;
601 padding = r->ch_padding;
602 borders = r->ch_borders;
603 bg = r->bgs[2];
604 break;
607 ret = borders[0] + padding[0] + r->text_height + padding[2]
608 + borders[2];
610 inner_width = inner_width(r) - borders[1] - borders[3];
611 inner_height = padding[0] + r->text_height + padding[2];
613 /* Border top */
614 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
615 borders[0]);
617 /* Border right */
618 XFillRectangle(r->d, r->w, border_color[1],
619 r->x_zero + inner_width(r) - borders[1], y, borders[1], ret);
621 /* Border bottom */
622 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
623 y + borders[0] + padding[0] + r->text_height + padding[2],
624 r->width, borders[2]);
626 /* Border left */
627 XFillRectangle(
628 r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
630 /* bg */
631 x = r->x_zero + borders[3];
632 y += borders[0];
633 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
635 /* content */
636 y += padding[0] + r->text_height;
637 x += padding[3];
638 if (prefix != NULL) {
639 draw_string(prefix, strlen(prefix), x, y, r, t);
640 x += prefix_width;
642 draw_string(text, strlen(text), x, y, r, t);
644 return ret;
647 int
648 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
649 enum obj_type t, char *text)
651 GC *border_color, bg;
652 int *padding, *borders;
653 int ret = 0, inner_width, inner_height, y, text_width;
655 switch (t) {
656 case PROMPT:
657 border_color = r->p_borders_bg;
658 padding = r->p_padding;
659 borders = r->p_borders;
660 bg = r->bgs[0];
661 break;
662 case COMPL:
663 border_color = r->c_borders_bg;
664 padding = r->c_padding;
665 borders = r->c_borders;
666 bg = r->bgs[1];
667 break;
668 case COMPL_HIGH:
669 border_color = r->ch_borders_bg;
670 padding = r->ch_padding;
671 borders = r->ch_borders;
672 bg = r->bgs[2];
673 break;
676 if (padding[0] < 0 || padding[2] < 0)
677 padding[0] = padding[2]
678 = (inner_height(r) - borders[0] - borders[2]
679 - r->text_height)
680 / 2;
682 /* If they are still lesser than 0, set 'em to 0 */
683 if (padding[0] < 0 || padding[2] < 0)
684 padding[0] = padding[2] = 0;
686 /* Get the text width */
687 text_extents(text, strlen(text), r, &text_width, NULL);
688 if (prefix != NULL)
689 text_width += prefix_width;
691 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
693 inner_width = padding[3] + text_width + padding[1];
694 inner_height = inner_height(r) - borders[0] - borders[2];
696 /* Border top */
697 XFillRectangle(
698 r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
700 /* Border right */
701 XFillRectangle(r->d, r->w, border_color[1],
702 x + borders[3] + inner_width, r->y_zero, borders[1],
703 inner_height(r));
705 /* Border bottom */
706 XFillRectangle(r->d, r->w, border_color[2], x,
707 r->y_zero + inner_height(r) - borders[2], ret, borders[2]);
709 /* Border left */
710 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
711 inner_height(r));
713 /* bg */
714 x += borders[3];
715 y = r->y_zero + borders[0];
716 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
718 /* content */
719 y += padding[0] + r->text_height;
720 x += padding[3];
721 if (prefix != NULL) {
722 draw_string(prefix, strlen(prefix), x, y, r, t);
723 x += prefix_width;
725 draw_string(text, strlen(text), x, y, r, t);
727 return ret;
730 /* ,-----------------------------------------------------------------, */
731 /* | 20 char text | completion | completion | completion | compl | */
732 /* `-----------------------------------------------------------------' */
733 void
734 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
736 size_t i;
737 int x = r->x_zero;
739 /* Draw the prompt */
740 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
742 for (i = r->offset; i < cs->length; ++i) {
743 enum obj_type t
744 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
746 x += draw_h_box(
747 r, x, NULL, 0, t, cs->completions[i].completion);
749 if (x > inner_width(r))
750 break;
754 /* ,-----------------------------------------------------------------, */
755 /* | prompt | */
756 /* |-----------------------------------------------------------------| */
757 /* | completion | */
758 /* |-----------------------------------------------------------------| */
759 /* | completion | */
760 /* `-----------------------------------------------------------------' */
761 void
762 draw_vertically(struct rendering *r, char *text, struct completions *cs)
764 size_t i;
765 int y = r->y_zero;
767 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
769 for (i = r->offset; i < cs->length; ++i) {
770 enum obj_type t
771 = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
773 y += draw_v_box(
774 r, y, NULL, 0, t, cs->completions[i].completion);
776 if (y > inner_height(r))
777 break;
781 void
782 draw(struct rendering *r, char *text, struct completions *cs)
784 /* Draw the background */
785 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
786 inner_width(r), inner_height(r));
788 /* Draw the contents */
789 if (r->horizontal_layout)
790 draw_horizontally(r, text, cs);
791 else
792 draw_vertically(r, text, cs);
794 /* Draw the borders */
795 if (r->borders[0] != 0)
796 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
797 r->borders[0]);
799 if (r->borders[1] != 0)
800 XFillRectangle(r->d, r->w, r->borders_bg[1],
801 r->width - r->borders[1], 0, r->borders[1],
802 r->height);
804 if (r->borders[2] != 0)
805 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
806 r->height - r->borders[2], r->width, r->borders[2]);
808 if (r->borders[3] != 0)
809 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
810 r->borders[3], r->height);
812 /* render! */
813 XFlush(r->d);
816 /* Set some WM stuff */
817 void
818 set_win_atoms_hints(Display *d, Window w, int width, int height)
820 Atom type;
821 XClassHint *class_hint;
822 XSizeHints *size_hint;
824 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
825 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
826 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
827 (unsigned char *)&type, 1);
829 /* some window managers honor this properties */
830 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
831 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
832 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
833 (unsigned char *)&type, 1);
835 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
836 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
837 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
838 (unsigned char *)&type, 1);
840 /* Setting window hints */
841 class_hint = XAllocClassHint();
842 if (class_hint == NULL) {
843 fprintf(stderr, "Could not allocate memory for class hint\n");
844 exit(EX_UNAVAILABLE);
847 class_hint->res_name = resname;
848 class_hint->res_class = resclass;
849 XSetClassHint(d, w, class_hint);
850 XFree(class_hint);
852 size_hint = XAllocSizeHints();
853 if (size_hint == NULL) {
854 fprintf(stderr, "Could not allocate memory for size hint\n");
855 exit(EX_UNAVAILABLE);
858 size_hint->flags = PMinSize | PBaseSize;
859 size_hint->min_width = width;
860 size_hint->base_width = width;
861 size_hint->min_height = height;
862 size_hint->base_height = height;
864 XFlush(d);
867 /* Get the width and height of the window `w' */
868 void
869 get_wh(Display *d, Window *w, int *width, int *height)
871 XWindowAttributes win_attr;
873 XGetWindowAttributes(d, *w, &win_attr);
874 *height = win_attr.height;
875 *width = win_attr.width;
878 int
879 grabfocus(Display *d, Window w)
881 int i;
882 for (i = 0; i < 100; ++i) {
883 Window focuswin;
884 int revert_to_win;
886 XGetInputFocus(d, &focuswin, &revert_to_win);
888 if (focuswin == w)
889 return 1;
891 XSetInputFocus(d, w, RevertToParent, CurrentTime);
892 usleep(1000);
894 return 0;
897 /*
898 * I know this may seem a little hackish BUT is the only way I managed
899 * to actually grab that goddam keyboard. Only one call to
900 * XGrabKeyboard does not always end up with the keyboard grabbed!
901 */
902 int
903 take_keyboard(Display *d, Window w)
905 int i;
906 for (i = 0; i < 100; i++) {
907 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
908 CurrentTime)
909 == GrabSuccess)
910 return 1;
911 usleep(1000);
913 fprintf(stderr, "Cannot grab keyboard\n");
914 return 0;
917 unsigned long
918 parse_color(const char *str, const char *def)
920 size_t len;
921 rgba_t tmp;
922 char *ep;
924 if (str == NULL)
925 goto invc;
927 len = strlen(str);
929 /* +1 for the # ath the start */
930 if (*str != '#' || len > 9 || len < 4)
931 goto invc;
932 ++str; /* skip the # */
934 errno = 0;
935 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
937 if (errno)
938 goto invc;
940 switch (len - 1) {
941 case 3:
942 /* expand #rgb -> #rrggbb */
943 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
944 | (tmp.v & 0x00f) * 0x0011;
945 case 6:
946 /* assume 0xff opacity */
947 tmp.rgba.a = 0xff;
948 break;
949 } /* colors in #aarrggbb need no adjustments */
951 /* premultiply the alpha */
952 if (tmp.rgba.a) {
953 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
954 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
955 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
956 return tmp.v;
959 return 0U;
961 invc:
962 fprintf(stderr, "Invalid color: \"%s\".\n", str);
963 if (def != NULL)
964 return parse_color(def, NULL);
965 else
966 return 0U;
969 /*
970 * Given a string try to parse it as a number or return `default_value'.
971 */
972 int
973 parse_integer(const char *str, int default_value)
975 long lval;
976 char *ep;
978 errno = 0;
979 lval = strtol(str, &ep, 10);
981 if (str[0] == '\0' || *ep != '\0') { /* NaN */
982 fprintf(stderr,
983 "'%s' is not a valid number! Using %d as default.\n",
984 str, default_value);
985 return default_value;
988 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
989 || (lval > INT_MAX || lval < INT_MIN)) {
990 fprintf(stderr, "%s out of range! Using %d as default.\n",
991 str, default_value);
992 return default_value;
995 return lval;
998 /* Like parse_integer but recognize the percentages (i.e. strings ending with
999 * `%') */
1000 int
1001 parse_int_with_percentage(const char *str, int default_value, int max)
1003 int len = strlen(str);
1005 if (len > 0 && str[len - 1] == '%') {
1006 int val;
1007 char *cpy;
1009 if ((cpy = strdup(str)) == NULL)
1010 err(1, "strdup");
1012 cpy[len - 1] = '\0';
1013 val = parse_integer(cpy, default_value);
1014 free(cpy);
1015 return val * max / 100;
1018 return parse_integer(str, default_value);
1022 * Like parse_int_with_percentage but understands some special values:
1023 * - middle that is (max-self)/2
1024 * - start that is 0
1025 * - end that is (max-self)
1027 int
1028 parse_int_with_pos(const char *str, int default_value, int max, int self)
1030 if (!strcmp(str, "start"))
1031 return 0;
1032 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1033 return (max - self) / 2;
1034 if (!strcmp(str, "end"))
1035 return max - self;
1036 return parse_int_with_percentage(str, default_value, max);
1039 /* Parse a string like a CSS value. */
1040 /* TODO: harden a bit this function */
1041 char **
1042 parse_csslike(const char *str)
1044 int i, j;
1045 char *s, *token, **ret;
1046 short any_null;
1048 s = strdup(str);
1049 if (s == NULL)
1050 return NULL;
1052 ret = malloc(4 * sizeof(char *));
1053 if (ret == NULL) {
1054 free(s);
1055 return NULL;
1058 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1059 ret[i] = strdup(token);
1061 if (i == 1)
1062 for (j = 1; j < 4; j++)
1063 ret[j] = strdup(ret[0]);
1065 if (i == 2) {
1066 ret[2] = strdup(ret[0]);
1067 ret[3] = strdup(ret[1]);
1070 if (i == 3)
1071 ret[3] = strdup(ret[1]);
1073 /* before we didn't check for the return type of strdup, here we will
1076 any_null = 0;
1077 for (i = 0; i < 4; ++i)
1078 any_null = ret[i] == NULL || any_null;
1080 if (any_null)
1081 for (i = 0; i < 4; ++i)
1082 if (ret[i] != NULL)
1083 free(ret[i]);
1085 if (i == 0 || any_null) {
1086 free(s);
1087 free(ret);
1088 return NULL;
1091 return ret;
1095 * Given an event, try to understand what the users wants. If the
1096 * return value is ADD_CHAR then `input' is a pointer to a string that
1097 * will need to be free'ed later.
1099 enum action
1100 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1102 char str[SYM_BUF_SIZE] = { 0 };
1103 Status s;
1105 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1106 return DEL_CHAR;
1108 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1109 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1111 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1112 return CONFIRM;
1114 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1115 return EXIT;
1117 /* Try to read what key was pressed */
1118 s = 0;
1119 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1120 if (s == XBufferOverflow) {
1121 fprintf(stderr,
1122 "Buffer overflow when trying to create keyboard "
1123 "symbol map.\n");
1124 return EXIT;
1127 if (ev->state & ControlMask) {
1128 if (!strcmp(str, "")) /* C-u */
1129 return DEL_LINE;
1130 if (!strcmp(str, "")) /* C-w */
1131 return DEL_WORD;
1132 if (!strcmp(str, "")) /* C-h */
1133 return DEL_CHAR;
1134 if (!strcmp(str, "\r")) /* C-m */
1135 return CONFIRM_CONTINUE;
1136 if (!strcmp(str, "")) /* C-p */
1137 return PREV_COMPL;
1138 if (!strcmp(str, "")) /* C-n */
1139 return NEXT_COMPL;
1140 if (!strcmp(str, "")) /* C-c */
1141 return EXIT;
1142 if (!strcmp(str, "\t")) /* C-i */
1143 return TOGGLE_FIRST_SELECTED;
1146 *input = strdup(str);
1147 if (*input == NULL) {
1148 fprintf(stderr, "Error while allocating memory for key.\n");
1149 return EXIT;
1152 return ADD_CHAR;
1155 void
1156 confirm(enum state *status, struct rendering *r, struct completions *cs,
1157 char **text, int *textlen)
1159 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1160 /* if there is something selected expand it and return */
1161 int index = cs->selected == -1 ? 0 : cs->selected;
1162 struct completion *c = cs->completions;
1163 char *t;
1165 while (1) {
1166 if (index == 0)
1167 break;
1168 c++;
1169 index--;
1172 t = c->rcompletion;
1173 free(*text);
1174 *text = strdup(t);
1176 if (*text == NULL) {
1177 fprintf(stderr, "Memory allocation error\n");
1178 *status = ERR;
1181 *textlen = strlen(*text);
1182 return;
1185 if (!r->free_text) /* cannot accept arbitrary text */
1186 *status = LOOPING;
1189 /* event loop */
1190 enum state
1191 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1192 char **lines, char **vlines)
1194 enum state status = LOOPING;
1196 while (status == LOOPING) {
1197 XEvent e;
1198 XNextEvent(r->d, &e);
1200 if (XFilterEvent(&e, r->w))
1201 continue;
1203 switch (e.type) {
1204 case KeymapNotify:
1205 XRefreshKeyboardMapping(&e.xmapping);
1206 break;
1208 case FocusIn:
1209 /* Re-grab focus */
1210 if (e.xfocus.window != r->w)
1211 grabfocus(r->d, r->w);
1212 break;
1214 case VisibilityNotify:
1215 if (e.xvisibility.state != VisibilityUnobscured)
1216 XRaiseWindow(r->d, r->w);
1217 break;
1219 case MapNotify:
1220 get_wh(r->d, &r->w, &r->width, &r->height);
1221 draw(r, *text, cs);
1222 break;
1224 case KeyPress: {
1225 XKeyPressedEvent *ev = (XKeyPressedEvent *)&e;
1226 char *input;
1228 switch (parse_event(r->d, ev, r->xic, &input)) {
1229 case EXIT:
1230 status = ERR;
1231 break;
1233 case CONFIRM: {
1234 status = OK;
1235 confirm(&status, r, cs, text, textlen);
1236 break;
1239 case CONFIRM_CONTINUE: {
1240 status = OK_LOOP;
1241 confirm(&status, r, cs, text, textlen);
1242 break;
1245 case PREV_COMPL: {
1246 complete(cs, r->first_selected, 1, text,
1247 textlen, &status);
1248 r->offset = cs->selected;
1249 break;
1252 case NEXT_COMPL: {
1253 complete(cs, r->first_selected, 0, text,
1254 textlen, &status);
1255 r->offset = cs->selected;
1256 break;
1259 case DEL_CHAR:
1260 popc(*text);
1261 update_completions(cs, *text, lines, vlines,
1262 r->first_selected);
1263 r->offset = 0;
1264 break;
1266 case DEL_WORD: {
1267 popw(*text);
1268 update_completions(cs, *text, lines, vlines,
1269 r->first_selected);
1270 break;
1273 case DEL_LINE: {
1274 int i;
1275 for (i = 0; i < *textlen; ++i)
1276 *(*text + i) = 0;
1277 update_completions(cs, *text, lines, vlines,
1278 r->first_selected);
1279 r->offset = 0;
1280 break;
1283 case ADD_CHAR: {
1284 int str_len, i;
1286 str_len = strlen(input);
1289 * sometimes a strange key is pressed
1290 * i.e. ctrl alone), so input will be
1291 * empty. Don't need to update
1292 * completion in that case
1294 if (str_len == 0)
1295 break;
1297 for (i = 0; i < str_len; ++i) {
1298 *textlen = pushc(
1299 text, *textlen, input[i]);
1300 if (*textlen == -1) {
1301 fprintf(stderr,
1302 "Memory allocation "
1303 "error\n");
1304 status = ERR;
1305 break;
1309 if (status != ERR) {
1310 update_completions(cs, *text, lines,
1311 vlines, r->first_selected);
1312 free(input);
1315 r->offset = 0;
1316 break;
1319 case TOGGLE_FIRST_SELECTED:
1320 r->first_selected = !r->first_selected;
1321 if (r->first_selected && cs->selected < 0)
1322 cs->selected = 0;
1323 if (!r->first_selected && cs->selected == 0)
1324 cs->selected = -1;
1325 break;
1329 case ButtonPress: {
1330 XButtonPressedEvent *ev = (XButtonPressedEvent *)&e;
1331 /* if (ev->button == Button1) { /\* click *\/ */
1332 /* int x = ev->x - r.border_w; */
1333 /* int y = ev->y - r.border_n; */
1334 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1335 /* } */
1337 if (ev->button == Button4) /* scroll up */
1338 r->offset = MAX((ssize_t)r->offset - 1, 0);
1340 if (ev->button == Button5) /* scroll down */
1341 r->offset
1342 = MIN(r->offset + 1, cs->length - 1);
1344 break;
1348 draw(r, *text, cs);
1351 return status;
1354 int
1355 load_font(struct rendering *r, const char *fontname)
1357 #ifdef USE_XFT
1358 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1359 return 0;
1360 #else
1361 char **missing_charset_list;
1362 int missing_charset_count;
1364 r->font = XCreateFontSet(r->d, fontname, &missing_charset_list,
1365 &missing_charset_count, NULL);
1366 if (r->font != NULL)
1367 return 0;
1369 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1371 if (!strcmp(fontname, default_fontname))
1372 return -1;
1374 return load_font(r, default_fontname);
1375 #endif
1378 void
1379 xim_init(struct rendering *r, XrmDatabase *xdb)
1381 XIMStyle best_match_style;
1382 XIMStyles *xis;
1383 int i;
1385 /* Open the X input method */
1386 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1387 err(1, "XOpenIM");
1389 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1390 fprintf(stderr, "Input Styles could not be retrieved\n");
1391 exit(EX_UNAVAILABLE);
1394 best_match_style = 0;
1395 for (i = 0; i < xis->count_styles; ++i) {
1396 XIMStyle ts = xis->supported_styles[i];
1397 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1398 best_match_style = ts;
1399 break;
1402 XFree(xis);
1404 if (!best_match_style)
1405 fprintf(stderr,
1406 "No matching input style could be determined\n");
1408 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1409 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1410 if (r->xic == NULL)
1411 err(1, "XCreateIC");
1414 void
1415 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1416 XVisualInfo vinfo, int x, int y, int ox, int oy,
1417 unsigned long background_pixel)
1419 XSetWindowAttributes attr;
1421 /* Create the window */
1422 attr.colormap = cmap;
1423 attr.override_redirect = 1;
1424 attr.border_pixel = 0;
1425 attr.background_pixel = background_pixel;
1426 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1427 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1429 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width,
1430 r->height, 0, vinfo.depth, InputOutput, vinfo.visual,
1431 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask
1432 | CWOverrideRedirect,
1433 &attr);
1436 void
1437 ps1extents(struct rendering *r)
1439 char *dup;
1440 dup = strdupn(r->ps1);
1441 text_extents(
1442 dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1443 free(dup);
1446 void
1447 usage(char *prgname)
1449 fprintf(stderr,
1450 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1451 " [-d separator] [-e window] [-f font] [-G color] [-g "
1452 "size]\n"
1453 " [-H height] [-I color] [-i size] [-J color] [-j "
1454 "size] [-l layout]\n"
1455 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1456 "color]\n"
1457 " [-t color] [-W width] [-x coord] [-y coord]\n",
1458 prgname);
1461 int
1462 main(int argc, char **argv)
1464 struct completions *cs;
1465 struct rendering r;
1466 XVisualInfo vinfo;
1467 Colormap cmap;
1468 size_t nlines, i;
1469 Window parent_window;
1470 XrmDatabase xdb;
1471 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1472 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1473 ch_borders_bg[4]; /* N E S W */
1474 enum state status;
1475 int ch;
1476 int offset_x, offset_y, x, y;
1477 int textlen, d_width, d_height;
1478 short embed;
1479 char *sep, *parent_window_id;
1480 char **lines, *buf, **vlines;
1481 char *fontname, *text, *xrm;
1483 #ifdef __OpenBSD__
1484 /* stdio & rpath: to read/write stdio/stdout/stderr */
1485 /* unix: to connect to XOrg */
1486 pledge("stdio rpath unix", "");
1487 #endif
1489 sep = NULL;
1490 parent_window_id = NULL;
1492 r.first_selected = 0;
1493 r.free_text = 1;
1494 r.multiple_select = 0;
1495 r.offset = 0;
1497 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1498 switch (ch) {
1499 case 'h': /* help */
1500 usage(*argv);
1501 return 0;
1502 case 'v': /* version */
1503 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1504 return 0;
1505 case 'e': /* embed */
1506 if ((parent_window_id = strdup(optarg)) == NULL)
1507 err(1, "strdup");
1508 break;
1509 case 'd':
1510 if ((sep = strdup(optarg)) == NULL)
1511 err(1, "strdup");
1512 break;
1513 case 'A':
1514 r.free_text = 0;
1515 break;
1516 case 'm':
1517 r.multiple_select = 1;
1518 break;
1519 default:
1520 break;
1524 /* Read the completions */
1525 lines = NULL;
1526 buf = NULL;
1527 nlines = readlines(&lines, &buf);
1529 vlines = NULL;
1530 if (sep != NULL) {
1531 int l;
1532 l = strlen(sep);
1533 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1534 err(1, "calloc");
1536 for (i = 0; i < nlines; i++) {
1537 char *t;
1538 t = strstr(lines[i], sep);
1539 if (t == NULL)
1540 vlines[i] = lines[i];
1541 else
1542 vlines[i] = t + l;
1546 setlocale(LC_ALL, getenv("LANG"));
1548 status = LOOPING;
1550 /* where the monitor start (used only with xinerama) */
1551 offset_x = offset_y = 0;
1553 /* default width and height */
1554 r.width = 400;
1555 r.height = 20;
1557 /* default position on the screen */
1558 x = y = 0;
1560 for (i = 0; i < 4; ++i) {
1561 /* default paddings */
1562 r.p_padding[i] = 10;
1563 r.c_padding[i] = 10;
1564 r.ch_padding[i] = 10;
1566 /* default borders */
1567 r.borders[i] = 0;
1568 r.p_borders[i] = 0;
1569 r.c_borders[i] = 0;
1570 r.ch_borders[i] = 0;
1573 /* the prompt. We duplicate the string so later is easy to
1574 * free (in the case it's been overwritten by the user) */
1575 if ((r.ps1 = strdup("$ ")) == NULL)
1576 err(1, "strdup");
1578 /* same for the font name */
1579 if ((fontname = strdup(default_fontname)) == NULL)
1580 err(1, "strdup");
1582 textlen = 10;
1583 if ((text = malloc(textlen * sizeof(char))) == NULL)
1584 err(1, "malloc");
1586 /* struct completions *cs = filter(text, lines); */
1587 if ((cs = compls_new(nlines)) == NULL)
1588 err(1, "compls_new");
1590 /* start talking to xorg */
1591 r.d = XOpenDisplay(NULL);
1592 if (r.d == NULL) {
1593 fprintf(stderr, "Could not open display!\n");
1594 return EX_UNAVAILABLE;
1597 embed = 1;
1598 if (!(parent_window_id
1599 && (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(r.d, root, &rr, &rr, &root_x,
1621 &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
1638 + info[i].width)
1639 && info[i].y_org <= root_y
1640 && root_y <= (info[i].y_org
1641 + info[i].height)) {
1642 offset_x = info[i].x_org;
1643 offset_y = info[i].y_org;
1644 d_width = info[i].width;
1645 d_height = info[i].height;
1646 break;
1650 XFree(info);
1652 #endif
1654 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1655 cmap = XCreateColormap(
1656 r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1658 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1659 fgs[2] = parse_color("#000", NULL);
1661 bgs[0] = bgs[1] = parse_color("#000", NULL);
1662 bgs[2] = parse_color("#fff", NULL);
1664 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3]
1665 = parse_color("#000", NULL);
1667 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1668 = parse_color("#000", NULL);
1669 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1670 = parse_color("#000", NULL);
1671 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2]
1672 = ch_borders_bg[3] = parse_color("#000", NULL);
1674 r.horizontal_layout = 1;
1676 /* Read the resources */
1677 XrmInitialize();
1678 xrm = XResourceManagerString(r.d);
1679 xdb = NULL;
1680 if (xrm != NULL) {
1681 XrmValue value;
1682 char *datatype[20];
1684 xdb = XrmGetStringDatabase(xrm);
1686 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)
1687 == 1) {
1688 free(fontname);
1689 if ((fontname = strdup(value.addr)) == NULL)
1690 err(1, "strdup");
1691 } else {
1692 fprintf(stderr, "no font defined, using %s\n",
1693 fontname);
1696 if (XrmGetResource(
1697 xdb, "MyMenu.layout", "*", datatype, &value)
1698 == 1)
1699 r.horizontal_layout
1700 = !strcmp(value.addr, "horizontal");
1701 else
1702 fprintf(stderr,
1703 "no layout defined, using horizontal\n");
1705 if (XrmGetResource(
1706 xdb, "MyMenu.prompt", "*", datatype, &value)
1707 == 1) {
1708 free(r.ps1);
1709 r.ps1 = normalize_str(value.addr);
1710 } else {
1711 fprintf(stderr,
1712 "no prompt defined, using \"%s\" as "
1713 "default\n",
1714 r.ps1);
1717 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*",
1718 datatype, &value)
1719 == 1) {
1720 char **sizes;
1721 sizes = parse_csslike(value.addr);
1722 if (sizes != NULL)
1723 for (i = 0; i < 4; ++i)
1724 r.p_borders[i]
1725 = parse_integer(sizes[i], 0);
1726 else
1727 fprintf(stderr,
1728 "error while parsing "
1729 "MyMenu.prompt.border.size");
1732 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*",
1733 datatype, &value)
1734 == 1) {
1735 char **colors;
1736 colors = parse_csslike(value.addr);
1737 if (colors != NULL)
1738 for (i = 0; i < 4; ++i)
1739 p_borders_bg[i] = parse_color(
1740 colors[i], "#000");
1741 else
1742 fprintf(stderr,
1743 "error while parsing "
1744 "MyMenu.prompt.border.color");
1747 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*",
1748 datatype, &value)
1749 == 1) {
1750 char **colors;
1751 colors = parse_csslike(value.addr);
1752 if (colors != NULL)
1753 for (i = 0; i < 4; ++i)
1754 r.p_padding[i]
1755 = parse_integer(colors[i], 0);
1756 else
1757 fprintf(stderr,
1758 "error while parsing "
1759 "MyMenu.prompt.padding");
1762 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value)
1763 == 1)
1764 r.width = parse_int_with_percentage(
1765 value.addr, r.width, d_width);
1766 else
1767 fprintf(stderr, "no width defined, using %d\n",
1768 r.width);
1770 if (XrmGetResource(
1771 xdb, "MyMenu.height", "*", datatype, &value)
1772 == 1)
1773 r.height = parse_int_with_percentage(
1774 value.addr, r.height, d_height);
1775 else
1776 fprintf(stderr, "no height defined, using %d\n",
1777 r.height);
1779 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value)
1780 == 1)
1781 x = parse_int_with_pos(
1782 value.addr, x, d_width, r.width);
1784 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value)
1785 == 1)
1786 y = parse_int_with_pos(
1787 value.addr, y, d_height, r.height);
1789 if (XrmGetResource(
1790 xdb, "MyMenu.border.size", "*", datatype, &value)
1791 == 1) {
1792 char **borders;
1793 borders = parse_csslike(value.addr);
1794 if (borders != NULL)
1795 for (i = 0; i < 4; ++i)
1796 r.borders[i]
1797 = parse_int_with_percentage(
1798 borders[i], 0,
1799 (i % 2) == 0
1800 ? d_height
1801 : d_width);
1802 else
1803 fprintf(stderr,
1804 "error while parsing "
1805 "MyMenu.border.size\n");
1808 /* Prompt */
1809 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*",
1810 datatype, &value)
1811 == 1)
1812 fgs[0] = parse_color(value.addr, "#fff");
1814 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*",
1815 datatype, &value)
1816 == 1)
1817 bgs[0] = parse_color(value.addr, "#000");
1819 /* Completions */
1820 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*",
1821 datatype, &value)
1822 == 1)
1823 fgs[1] = parse_color(value.addr, "#fff");
1825 if (XrmGetResource(xdb, "MyMenu.completion.background", "*",
1826 datatype, &value)
1827 == 1)
1828 bgs[1] = parse_color(value.addr, "#000");
1830 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*",
1831 datatype, &value)
1832 == 1) {
1833 char **paddings;
1834 paddings = parse_csslike(value.addr);
1835 if (paddings != NULL)
1836 for (i = 0; i < 4; ++i)
1837 r.c_padding[i] = parse_integer(
1838 paddings[i], 0);
1839 else
1840 fprintf(stderr,
1841 "Error while parsing "
1842 "MyMenu.completion.padding");
1845 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*",
1846 datatype, &value)
1847 == 1) {
1848 char **sizes;
1849 sizes = parse_csslike(value.addr);
1850 if (sizes != NULL)
1851 for (i = 0; i < 4; ++i)
1852 r.c_borders[i]
1853 = parse_integer(sizes[i], 0);
1854 else
1855 fprintf(stderr,
1856 "Error while parsing "
1857 "MyMenu.completion.border.size");
1860 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*",
1861 datatype, &value)
1862 == 1) {
1863 char **sizes;
1864 sizes = parse_csslike(value.addr);
1865 if (sizes != NULL)
1866 for (i = 0; i < 4; ++i)
1867 c_borders_bg[i] = parse_color(
1868 sizes[i], "#000");
1869 else
1870 fprintf(stderr,
1871 "Error while parsing "
1872 "MyMenu.completion.border.color");
1875 /* Completion Highlighted */
1876 if (XrmGetResource(xdb,
1877 "MyMenu.completion_highlighted.foreground", "*",
1878 datatype, &value)
1879 == 1)
1880 fgs[2] = parse_color(value.addr, "#000");
1882 if (XrmGetResource(xdb,
1883 "MyMenu.completion_highlighted.background", "*",
1884 datatype, &value)
1885 == 1)
1886 bgs[2] = parse_color(value.addr, "#fff");
1888 if (XrmGetResource(xdb,
1889 "MyMenu.completion_highlighted.padding", "*",
1890 datatype, &value)
1891 == 1) {
1892 char **paddings;
1893 paddings = parse_csslike(value.addr);
1894 if (paddings != NULL)
1895 for (i = 0; i < 4; ++i)
1896 r.ch_padding[i] = parse_integer(
1897 paddings[i], 0);
1898 else
1899 fprintf(stderr,
1900 "Error while parsing "
1901 "MyMenu.completion_highlighted."
1902 "padding");
1905 if (XrmGetResource(xdb,
1906 "MyMenu.completion_highlighted.border.size", "*",
1907 datatype, &value)
1908 == 1) {
1909 char **sizes;
1910 sizes = parse_csslike(value.addr);
1911 if (sizes != NULL)
1912 for (i = 0; i < 4; ++i)
1913 r.ch_borders[i]
1914 = parse_integer(sizes[i], 0);
1915 else
1916 fprintf(stderr,
1917 "Error while parsing "
1918 "MyMenu.completion_highlighted."
1919 "border.size");
1922 if (XrmGetResource(xdb,
1923 "MyMenu.completion_highlighted.border.color", "*",
1924 datatype, &value)
1925 == 1) {
1926 char **colors;
1927 colors = parse_csslike(value.addr);
1928 if (colors != NULL)
1929 for (i = 0; i < 4; ++i)
1930 ch_borders_bg[i] = parse_color(
1931 colors[i], "#000");
1932 else
1933 fprintf(stderr,
1934 "Error while parsing "
1935 "MyMenu.completion_highlighted."
1936 "border.color");
1939 /* Border */
1940 if (XrmGetResource(
1941 xdb, "MyMenu.border.color", "*", datatype, &value)
1942 == 1) {
1943 char **colors;
1944 colors = parse_csslike(value.addr);
1945 if (colors != NULL)
1946 for (i = 0; i < 4; ++i)
1947 borders_bg[i] = parse_color(
1948 colors[i], "#000");
1949 else
1950 fprintf(stderr,
1951 "error while parsing "
1952 "MyMenu.border.color\n");
1956 /* Second round of args parsing */
1957 optind = 0; /* reset the option index */
1958 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1959 switch (ch) {
1960 case 'a':
1961 r.first_selected = 1;
1962 break;
1963 case 'A':
1964 /* free_text -- already catched */
1965 case 'd':
1966 /* separator -- this case was already catched */
1967 case 'e':
1968 /* embedding mymenu this case was already catched. */
1969 case 'm':
1970 /* multiple selection this case was already catched.
1972 break;
1973 case 'p': {
1974 char *newprompt;
1975 newprompt = strdup(optarg);
1976 if (newprompt != NULL) {
1977 free(r.ps1);
1978 r.ps1 = newprompt;
1980 break;
1982 case 'x':
1983 x = parse_int_with_pos(optarg, x, d_width, r.width);
1984 break;
1985 case 'y':
1986 y = parse_int_with_pos(optarg, y, d_height, r.height);
1987 break;
1988 case 'P': {
1989 char **paddings;
1990 if ((paddings = parse_csslike(optarg)) != NULL)
1991 for (i = 0; i < 4; ++i)
1992 r.p_padding[i] = parse_integer(
1993 paddings[i], 0);
1994 break;
1996 case 'G': {
1997 char **colors;
1998 if ((colors = parse_csslike(optarg)) != NULL)
1999 for (i = 0; i < 4; ++i)
2000 p_borders_bg[i] = parse_color(
2001 colors[i], "#000");
2002 break;
2004 case 'g': {
2005 char **sizes;
2006 if ((sizes = parse_csslike(optarg)) != NULL)
2007 for (i = 0; i < 4; ++i)
2008 r.p_borders[i]
2009 = parse_integer(sizes[i], 0);
2010 break;
2012 case 'I': {
2013 char **colors;
2014 if ((colors = parse_csslike(optarg)) != NULL)
2015 for (i = 0; i < 4; ++i)
2016 c_borders_bg[i] = parse_color(
2017 colors[i], "#000");
2018 break;
2020 case 'i': {
2021 char **sizes;
2022 if ((sizes = parse_csslike(optarg)) != NULL)
2023 for (i = 0; i < 4; ++i)
2024 r.c_borders[i]
2025 = parse_integer(sizes[i], 0);
2026 break;
2028 case 'J': {
2029 char **colors;
2030 if ((colors = parse_csslike(optarg)) != NULL)
2031 for (i = 0; i < 4; ++i)
2032 ch_borders_bg[i] = parse_color(
2033 colors[i], "#000");
2034 break;
2036 case 'j': {
2037 char **sizes;
2038 if ((sizes = parse_csslike(optarg)) != NULL)
2039 for (i = 0; i < 4; ++i)
2040 r.ch_borders[i]
2041 = parse_integer(sizes[i], 0);
2042 break;
2044 case 'l':
2045 r.horizontal_layout = !strcmp(optarg, "horizontal");
2046 break;
2047 case 'f': {
2048 char *newfont;
2049 if ((newfont = strdup(optarg)) != NULL) {
2050 free(fontname);
2051 fontname = newfont;
2053 break;
2055 case 'W':
2056 r.width = parse_int_with_percentage(
2057 optarg, r.width, d_width);
2058 break;
2059 case 'H':
2060 r.height = parse_int_with_percentage(
2061 optarg, r.height, d_height);
2062 break;
2063 case 'b': {
2064 char **borders;
2065 if ((borders = parse_csslike(optarg)) != NULL) {
2066 for (i = 0; i < 4; ++i)
2067 r.borders[i] = parse_integer(
2068 borders[i], 0);
2069 } else
2070 fprintf(stderr, "Error parsing b option\n");
2071 break;
2073 case 'B': {
2074 char **colors;
2075 if ((colors = parse_csslike(optarg)) != NULL) {
2076 for (i = 0; i < 4; ++i)
2077 borders_bg[i] = parse_color(
2078 colors[i], "#000");
2079 } else
2080 fprintf(stderr,
2081 "error while parsing B option\n");
2082 break;
2084 case 't':
2085 fgs[0] = parse_color(optarg, NULL);
2086 break;
2087 case 'T':
2088 bgs[0] = parse_color(optarg, NULL);
2089 break;
2090 case 'c':
2091 fgs[1] = parse_color(optarg, NULL);
2092 break;
2093 case 'C':
2094 bgs[1] = parse_color(optarg, NULL);
2095 break;
2096 case 's':
2097 fgs[2] = parse_color(optarg, NULL);
2098 break;
2099 case 'S':
2100 fgs[2] = parse_color(optarg, NULL);
2101 break;
2102 default:
2103 fprintf(stderr, "Unrecognized option %c\n", ch);
2104 status = ERR;
2105 break;
2109 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2110 fprintf(stderr, "height, width, x or y are lesser than 0.");
2111 status = ERR;
2114 /* since only now we know if the first should be selected,
2115 * update the completion here */
2116 update_completions(cs, text, lines, vlines, r.first_selected);
2118 /* update the prompt lenght, only now we surely know the length of it
2120 r.ps1len = strlen(r.ps1);
2122 /* Create the window */
2123 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x,
2124 offset_y, bgs[1]);
2125 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2126 XMapRaised(r.d, r.w);
2128 /* If embed, listen for other events as well */
2129 if (embed) {
2130 Window *children, parent, root;
2131 unsigned int children_no;
2133 XSelectInput(r.d, parent_window, FocusChangeMask);
2134 if (XQueryTree(r.d, parent_window, &root, &parent, &children,
2135 &children_no)
2136 && children) {
2137 for (i = 0; i < children_no && children[i] != r.w;
2138 ++i)
2139 XSelectInput(
2140 r.d, children[i], FocusChangeMask);
2141 XFree(children);
2143 grabfocus(r.d, r.w);
2146 take_keyboard(r.d, r.w);
2148 r.x_zero = r.borders[3];
2149 r.y_zero = r.borders[0];
2152 XGCValues values;
2154 for (i = 0; i < 3; ++i) {
2155 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2156 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2159 for (i = 0; i < 4; ++i) {
2160 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2161 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2162 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2163 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2167 /* Load the colors in our GCs */
2168 for (i = 0; i < 3; ++i) {
2169 XSetForeground(r.d, r.fgs[i], fgs[i]);
2170 XSetForeground(r.d, r.bgs[i], bgs[i]);
2173 for (i = 0; i < 4; ++i) {
2174 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2175 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2176 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2177 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2180 if (load_font(&r, fontname) == -1)
2181 status = ERR;
2183 #ifdef USE_XFT
2184 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2186 for (i = 0; i < 3; ++i) {
2187 rgba_t c;
2188 XRenderColor xrcolor;
2190 c = *(rgba_t *)&fgs[i];
2191 xrcolor.red = EXPANDBITS(c.rgba.r);
2192 xrcolor.green = EXPANDBITS(c.rgba.g);
2193 xrcolor.blue = EXPANDBITS(c.rgba.b);
2194 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2195 XftColorAllocValue(
2196 r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2198 #endif
2200 /* compute prompt dimensions */
2201 ps1extents(&r);
2203 xim_init(&r, &xdb);
2205 #ifdef __OpenBSD__
2206 /* Now we need only the ability to write */
2207 pledge("stdio", "");
2208 #endif
2210 /* Cache text height */
2211 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2213 /* Draw the window for the first time */
2214 draw(&r, text, cs);
2216 /* Main loop */
2217 while (status == LOOPING || status == OK_LOOP) {
2218 status = loop(&r, &text, &textlen, cs, lines, vlines);
2220 if (status != ERR)
2221 printf("%s\n", text);
2223 if (!r.multiple_select && status == OK_LOOP)
2224 status = OK;
2227 XUngrabKeyboard(r.d, CurrentTime);
2229 #ifdef USE_XFT
2230 for (i = 0; i < 3; ++i)
2231 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2232 #endif
2234 for (i = 0; i < 3; ++i) {
2235 XFreeGC(r.d, r.fgs[i]);
2236 XFreeGC(r.d, r.bgs[i]);
2239 for (i = 0; i < 4; ++i) {
2240 XFreeGC(r.d, r.borders_bg[i]);
2241 XFreeGC(r.d, r.p_borders_bg[i]);
2242 XFreeGC(r.d, r.c_borders_bg[i]);
2243 XFreeGC(r.d, r.ch_borders_bg[i]);
2246 XDestroyIC(r.xic);
2247 XCloseIM(r.xim);
2249 #ifdef USE_XFT
2250 for (i = 0; i < 3; ++i)
2251 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2252 XftFontClose(r.d, r.font);
2253 XftDrawDestroy(r.xftdraw);
2254 #else
2255 XFreeFontSet(r.d, r.font);
2256 #endif
2258 free(r.ps1);
2259 free(fontname);
2260 free(text);
2262 free(buf);
2263 free(lines);
2264 free(vlines);
2265 compls_delete(cs);
2267 XFreeColormap(r.d, cmap);
2269 XDestroyWindow(r.d, r.w);
2270 XCloseDisplay(r.d);
2272 return status != OK;