Blob


1 #include <ctype.h> /* isalnum */
2 #include <err.h>
3 #include <errno.h>
4 #include <limits.h>
5 #include <locale.h> /* setlocale */
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h> /* strdup, strlen */
10 #include <sysexits.h>
11 #include <unistd.h>
13 #include <X11/Xcms.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xresource.h>
16 #include <X11/Xutil.h>
17 #include <X11/keysym.h>
18 #include <X11/Xft/Xft.h>
20 #include <X11/extensions/Xinerama.h>
22 #ifndef VERSION
23 #define VERSION "unknown"
24 #endif
26 #define resname "MyMenu"
27 #define resclass "mymenu"
29 #define SYM_BUF_SIZE 4
31 #define default_fontname "monospace"
33 #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:"
35 #define MIN(a, b) ((a) < (b) ? (a) : (b))
36 #define MAX(a, b) ((a) > (b) ? (a) : (b))
38 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
40 #define inner_height(r) (r->height - r->borders[0] - r->borders[2])
41 #define inner_width(r) (r->width - r->borders[1] - r->borders[3])
43 /* The states of the event loop */
44 enum state { LOOPING, OK_LOOP, OK, ERR };
46 /*
47 * For the drawing-related function. The text to be rendere could be
48 * the prompt, a completion or a highlighted completion
49 */
50 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
52 /* These are the possible action to be performed after user input. */
53 enum action {
54 NO_OP,
55 EXIT,
56 CONFIRM,
57 CONFIRM_CONTINUE,
58 NEXT_COMPL,
59 PREV_COMPL,
60 DEL_CHAR,
61 DEL_WORD,
62 DEL_LINE,
63 ADD_CHAR,
64 TOGGLE_FIRST_SELECTED,
65 SCROLL_DOWN,
66 SCROLL_UP,
67 };
69 /* A big set of values that needs to be carried around for drawing. A
70 * big struct to rule them all */
71 struct rendering {
72 Display *d; /* Connection to xorg */
73 Window w;
74 XIM xim;
75 int width;
76 int height;
77 int p_padding[4];
78 int c_padding[4];
79 int ch_padding[4];
80 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
81 the borders) */
82 int y_zero; /* like x_zero but for the y axis */
84 int offset; /* scroll offset */
86 short free_text;
87 short first_selected;
88 short multiple_select;
90 /* four border width */
91 int borders[4];
92 int p_borders[4];
93 int c_borders[4];
94 int ch_borders[4];
96 short horizontal_layout;
98 /* prompt */
99 char *ps1;
100 int ps1len;
101 int ps1w; /* ps1 width */
102 int ps1h; /* ps1 height */
104 int text_height; /* cache for the vertical layout */
106 XIC xic;
108 /* colors */
109 GC fgs[4];
110 GC bgs[4];
111 GC borders_bg[4];
112 GC p_borders_bg[4];
113 GC c_borders_bg[4];
114 GC ch_borders_bg[4];
115 XftFont *font;
116 XftDraw *xftdraw;
117 XftColor xft_colors[3];
118 };
120 struct completion {
121 char *completion;
122 char *rcompletion;
123 int offset; /* the x (or y, depending on the layout) coordinate at
124 which the item is rendered */
125 };
127 /* Wrap the linked list of completions */
128 struct completions {
129 struct completion *completions;
130 ssize_t selected;
131 size_t length;
132 };
134 /* idea stolen from lemonbar. ty lemonboy */
135 typedef union {
136 struct {
137 uint8_t b;
138 uint8_t g;
139 uint8_t r;
140 uint8_t a;
141 } rgba;
142 uint32_t v;
143 } rgba_t;
145 extern char *optarg;
146 extern int optind;
148 /* Return a newly allocated (and empty) completion list */
149 struct completions *
150 compls_new(size_t length)
152 struct completions *cs = malloc(sizeof(struct completions));
154 if (cs == NULL)
155 return cs;
157 cs->completions = calloc(length, sizeof(struct completion));
158 if (cs->completions == NULL) {
159 free(cs);
160 return NULL;
163 cs->selected = -1;
164 cs->length = length;
165 return cs;
168 /* Delete the wrapper and the whole list */
169 void
170 compls_delete(struct completions *cs)
172 if (cs == NULL)
173 return;
175 free(cs->completions);
176 free(cs);
179 /*
180 * Create a completion list from a text and the list of possible
181 * completions (null terminated). Expects a non-null `cs'. `lines' and
182 * `vlines' should have the same length OR `vlines' is NULL.
183 */
184 void
185 filter(struct completions *cs, char *text, char **lines, char **vlines)
187 size_t index = 0;
188 size_t matching = 0;
189 char *l;
191 if (vlines == NULL)
192 vlines = lines;
194 while (1) {
195 if (lines[index] == NULL)
196 break;
198 l = vlines[index] != NULL ? vlines[index] : lines[index];
200 if (strcasestr(l, text) != NULL) {
201 struct completion *c = &cs->completions[matching];
202 c->completion = l;
203 c->rcompletion = lines[index];
204 matching++;
207 index++;
209 cs->length = matching;
210 cs->selected = -1;
213 /* Update the given completion */
214 void
215 update_completions(
216 struct completions *cs, char *text, char **lines, char **vlines, short first_selected)
218 filter(cs, text, lines, vlines);
219 if (first_selected && cs->length > 0)
220 cs->selected = 0;
223 /*
224 * Select the next or previous selection and update some state. `text'
225 * will be updated with the text of the completion and `textlen' with
226 * the new length. If the memory cannot be allocated `status' will be
227 * set to `ERR'.
228 */
229 void
230 complete(struct completions *cs, short first_selected, short p, char **text, int *textlen,
231 enum state *status)
233 struct completion *n;
234 int index;
236 if (cs == NULL || cs->length == 0)
237 return;
239 /*
240 * If the first is always selected and the first entry is
241 * different from the text, expand the text and return
242 */
243 if (first_selected && cs->selected == 0 && strcmp(cs->completions->completion, *text) != 0
244 && !p) {
245 free(*text);
246 *text = strdup(cs->completions->completion);
247 if (text == NULL) {
248 *status = ERR;
249 return;
251 *textlen = strlen(*text);
252 return;
255 index = cs->selected;
257 if (index == -1 && p)
258 index = 0;
259 index = cs->selected = (cs->length + (p ? index - 1 : index + 1)) % cs->length;
261 n = &cs->completions[cs->selected];
263 free(*text);
264 *text = strdup(n->completion);
265 if (text == NULL) {
266 fprintf(stderr, "Memory allocation error!\n");
267 *status = ERR;
268 return;
270 *textlen = strlen(*text);
273 /* Push the character c at the end of the string pointed by p */
274 int
275 pushc(char **p, int maxlen, char c)
277 int len;
279 len = strnlen(*p, maxlen);
280 if (!(len < maxlen - 2)) {
281 char *newptr;
283 maxlen += maxlen >> 1;
284 newptr = realloc(*p, maxlen);
285 if (newptr == NULL) /* bad */
286 return -1;
287 *p = newptr;
290 (*p)[len] = c;
291 (*p)[len + 1] = '\0';
292 return maxlen;
295 /*
296 * Remove the last rune from the *UTF-8* string! This is different
297 * from just setting the last byte to 0 (in some cases ofc). Return a
298 * pointer (e) to the last nonzero char. If e < p then p is empty!
299 */
300 char *
301 popc(char *p)
303 int len = strlen(p);
304 char *e;
306 if (len == 0)
307 return p;
309 e = p + len - 1;
311 do {
312 char c = *e;
314 *e = '\0';
315 e -= 1;
317 /*
318 * If c is a starting byte (11......) or is under
319 * U+007F we're done.
320 */
321 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
322 break;
323 } while (e >= p);
325 return e;
328 /* Remove the last word plus trailing white spaces from the given string */
329 void
330 popw(char *w)
332 int len;
333 short in_word = 1;
335 if ((len = strlen(w)) == 0)
336 return;
338 while (1) {
339 char *e = popc(w);
341 if (e < w)
342 return;
344 if (in_word && isspace(*e))
345 in_word = 0;
347 if (!in_word && !isspace(*e))
348 return;
352 /*
353 * If the string is surrounded by quates (`"') remove them and replace
354 * every `\"' in the string with a single double-quote.
355 */
356 char *
357 normalize_str(const char *str)
359 int len, p;
360 char *s;
362 if ((len = strlen(str)) == 0)
363 return NULL;
365 if ((s = calloc(len, sizeof(char))) == NULL)
366 err(1, "calloc");
367 p = 0;
369 while (*str) {
370 char c = *str;
372 if (*str == '\\') {
373 if (*(str + 1)) {
374 s[p] = *(str + 1);
375 p++;
376 str += 2; /* skip this and the next char */
377 continue;
378 } else
379 break;
381 if (c == '"') {
382 str++; /* skip only this char */
383 continue;
385 s[p] = c;
386 p++;
387 str++;
390 return s;
393 char **
394 readlines(size_t *lineslen)
396 size_t len = 0, cap = 0;
397 size_t linesize = 0;
398 ssize_t linelen;
399 char *line = NULL, **lines = NULL;
401 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
402 if (linelen != 0 && line[linelen-1] == '\n')
403 line[linelen-1] = '\0';
405 if (len == cap) {
406 size_t newcap;
407 void *t;
409 newcap = MAX(cap * 1.5, 32);
410 t = recallocarray(lines, cap, newcap, sizeof(char *));
411 if (t == NULL)
412 err(1, "recallocarray");
413 cap = newcap;
414 lines = t;
417 if ((lines[len++] = strdup(line)) == NULL)
418 err(1, "strdup");
421 if (ferror(stdin))
422 err(1, "getline");
423 free(line);
425 *lineslen = len;
426 return lines;
429 /*
430 * Compute the dimensions of the string str once rendered.
431 * It'll return the width and set ret_width and ret_height if not NULL
432 */
433 int
434 text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height)
436 int height, width;
437 XGlyphInfo gi;
438 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
439 height = r->font->ascent - r->font->descent;
440 width = gi.width - gi.x;
442 if (ret_width != NULL)
443 *ret_width = width;
444 if (ret_height != NULL)
445 *ret_height = height;
446 return width;
449 void
450 draw_string(char *str, int len, int x, int y, struct rendering *r, enum obj_type tt)
452 XftColor xftcolor;
453 if (tt == PROMPT)
454 xftcolor = r->xft_colors[0];
455 if (tt == COMPL)
456 xftcolor = r->xft_colors[1];
457 if (tt == COMPL_HIGH)
458 xftcolor = r->xft_colors[2];
460 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
463 /* Duplicate the string and substitute every space with a 'n` */
464 char *
465 strdupn(char *str)
467 int len, i;
468 char *dup;
470 len = strlen(str);
472 if (str == NULL || len == 0)
473 return NULL;
475 if ((dup = strdup(str)) == NULL)
476 return NULL;
478 for (i = 0; i < len; ++i)
479 if (dup[i] == ' ')
480 dup[i] = 'n';
482 return dup;
485 int
486 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width, enum obj_type t, char *text)
488 GC *border_color, bg;
489 int *padding, *borders;
490 int ret = 0, inner_width, inner_height, x;
492 switch (t) {
493 case PROMPT:
494 border_color = r->p_borders_bg;
495 padding = r->p_padding;
496 borders = r->p_borders;
497 bg = r->bgs[0];
498 break;
499 case COMPL:
500 border_color = r->c_borders_bg;
501 padding = r->c_padding;
502 borders = r->c_borders;
503 bg = r->bgs[1];
504 break;
505 case COMPL_HIGH:
506 border_color = r->ch_borders_bg;
507 padding = r->ch_padding;
508 borders = r->ch_borders;
509 bg = r->bgs[2];
510 break;
513 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
515 inner_width = inner_width(r) - borders[1] - borders[3];
516 inner_height = padding[0] + r->text_height + padding[2];
518 /* Border top */
519 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width, borders[0]);
521 /* Border right */
522 XFillRectangle(r->d, r->w, border_color[1], r->x_zero + inner_width(r) - borders[1], y,
523 borders[1], ret);
525 /* Border bottom */
526 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
527 y + borders[0] + padding[0] + r->text_height + padding[2], r->width, borders[2]);
529 /* Border left */
530 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3], ret);
532 /* bg */
533 x = r->x_zero + borders[3];
534 y += borders[0];
535 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
537 /* content */
538 y += padding[0] + r->text_height;
539 x += padding[3];
540 if (prefix != NULL) {
541 draw_string(prefix, strlen(prefix), x, y, r, t);
542 x += prefix_width;
544 draw_string(text, strlen(text), x, y, r, t);
546 return ret;
549 int
550 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width, enum obj_type t, char *text)
552 GC *border_color, bg;
553 int *padding, *borders;
554 int ret = 0, inner_width, inner_height, y, text_width;
556 switch (t) {
557 case PROMPT:
558 border_color = r->p_borders_bg;
559 padding = r->p_padding;
560 borders = r->p_borders;
561 bg = r->bgs[0];
562 break;
563 case COMPL:
564 border_color = r->c_borders_bg;
565 padding = r->c_padding;
566 borders = r->c_borders;
567 bg = r->bgs[1];
568 break;
569 case COMPL_HIGH:
570 border_color = r->ch_borders_bg;
571 padding = r->ch_padding;
572 borders = r->ch_borders;
573 bg = r->bgs[2];
574 break;
577 if (padding[0] < 0 || padding[2] < 0)
578 padding[0] = padding[2]
579 = (inner_height(r) - borders[0] - borders[2] - r->text_height) / 2;
581 /* If they are still lesser than 0, set 'em to 0 */
582 if (padding[0] < 0 || padding[2] < 0)
583 padding[0] = padding[2] = 0;
585 /* Get the text width */
586 text_extents(text, strlen(text), r, &text_width, NULL);
587 if (prefix != NULL)
588 text_width += prefix_width;
590 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
592 inner_width = padding[3] + text_width + padding[1];
593 inner_height = inner_height(r) - borders[0] - borders[2];
595 /* Border top */
596 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret, borders[0]);
598 /* Border right */
599 XFillRectangle(r->d, r->w, border_color[1], x + borders[3] + inner_width, r->y_zero,
600 borders[1], inner_height(r));
602 /* Border bottom */
603 XFillRectangle(r->d, r->w, border_color[2], x, r->y_zero + inner_height(r) - borders[2],
604 ret, borders[2]);
606 /* Border left */
607 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3], inner_height(r));
609 /* bg */
610 x += borders[3];
611 y = r->y_zero + borders[0];
612 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
614 /* content */
615 y += padding[0] + r->text_height;
616 x += padding[3];
617 if (prefix != NULL) {
618 draw_string(prefix, strlen(prefix), x, y, r, t);
619 x += prefix_width;
621 draw_string(text, strlen(text), x, y, r, t);
623 return ret;
626 /* ,-----------------------------------------------------------------, */
627 /* | 20 char text | completion | completion | completion | compl | */
628 /* `-----------------------------------------------------------------' */
629 void
630 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
632 size_t i;
633 int x = r->x_zero;
635 /* Draw the prompt */
636 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
638 for (i = r->offset; i < cs->length; ++i) {
639 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
641 cs->completions[i].offset = x;
643 x += draw_h_box(r, x, NULL, 0, t, cs->completions[i].completion);
645 if (x > inner_width(r))
646 break;
649 for (i += 1; i < cs->length; ++i)
650 cs->completions[i].offset = -1;
653 /* ,-----------------------------------------------------------------, */
654 /* | prompt | */
655 /* |-----------------------------------------------------------------| */
656 /* | completion | */
657 /* |-----------------------------------------------------------------| */
658 /* | completion | */
659 /* `-----------------------------------------------------------------' */
660 void
661 draw_vertically(struct rendering *r, char *text, struct completions *cs)
663 size_t i;
664 int y = r->y_zero;
666 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
668 for (i = r->offset; i < cs->length; ++i) {
669 enum obj_type t = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
671 cs->completions[i].offset = y;
673 y += draw_v_box(r, y, NULL, 0, t, cs->completions[i].completion);
675 if (y > inner_height(r))
676 break;
679 for (i += 1; i < cs->length; ++i)
680 cs->completions[i].offset = -1;
683 void
684 draw(struct rendering *r, char *text, struct completions *cs)
686 /* Draw the background */
687 XFillRectangle(
688 r->d, r->w, r->bgs[1], r->x_zero, r->y_zero, inner_width(r), inner_height(r));
690 /* Draw the contents */
691 if (r->horizontal_layout)
692 draw_horizontally(r, text, cs);
693 else
694 draw_vertically(r, text, cs);
696 /* Draw the borders */
697 if (r->borders[0] != 0)
698 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width, r->borders[0]);
700 if (r->borders[1] != 0)
701 XFillRectangle(r->d, r->w, r->borders_bg[1], r->width - r->borders[1], 0,
702 r->borders[1], r->height);
704 if (r->borders[2] != 0)
705 XFillRectangle(r->d, r->w, r->borders_bg[2], 0, r->height - r->borders[2], r->width,
706 r->borders[2]);
708 if (r->borders[3] != 0)
709 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0, r->borders[3], r->height);
711 /* render! */
712 XFlush(r->d);
715 /* Set some WM stuff */
716 void
717 set_win_atoms_hints(Display *d, Window w, int width, int height)
719 Atom type;
720 XClassHint *class_hint;
721 XSizeHints *size_hint;
723 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
724 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0), XInternAtom(d, "ATOM", 0),
725 32, PropModeReplace, (unsigned char *)&type, 1);
727 /* some window managers honor this properties */
728 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
729 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
730 PropModeReplace, (unsigned char *)&type, 1);
732 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
733 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0), XInternAtom(d, "ATOM", 0), 32,
734 PropModeAppend, (unsigned char *)&type, 1);
736 /* Setting window hints */
737 class_hint = XAllocClassHint();
738 if (class_hint == NULL) {
739 fprintf(stderr, "Could not allocate memory for class hint\n");
740 exit(EX_UNAVAILABLE);
743 class_hint->res_name = resname;
744 class_hint->res_class = resclass;
745 XSetClassHint(d, w, class_hint);
746 XFree(class_hint);
748 size_hint = XAllocSizeHints();
749 if (size_hint == NULL) {
750 fprintf(stderr, "Could not allocate memory for size hint\n");
751 exit(EX_UNAVAILABLE);
754 size_hint->flags = PMinSize | PBaseSize;
755 size_hint->min_width = width;
756 size_hint->base_width = width;
757 size_hint->min_height = height;
758 size_hint->base_height = height;
760 XFlush(d);
763 /* Get the width and height of the window `w' */
764 void
765 get_wh(Display *d, Window *w, int *width, int *height)
767 XWindowAttributes win_attr;
769 XGetWindowAttributes(d, *w, &win_attr);
770 *height = win_attr.height;
771 *width = win_attr.width;
774 int
775 grabfocus(Display *d, Window w)
777 int i;
778 for (i = 0; i < 100; ++i) {
779 Window focuswin;
780 int revert_to_win;
782 XGetInputFocus(d, &focuswin, &revert_to_win);
784 if (focuswin == w)
785 return 1;
787 XSetInputFocus(d, w, RevertToParent, CurrentTime);
788 usleep(1000);
790 return 0;
793 /*
794 * I know this may seem a little hackish BUT is the only way I managed
795 * to actually grab that goddam keyboard. Only one call to
796 * XGrabKeyboard does not always end up with the keyboard grabbed!
797 */
798 int
799 take_keyboard(Display *d, Window w)
801 int i;
802 for (i = 0; i < 100; i++) {
803 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync, CurrentTime)
804 == GrabSuccess)
805 return 1;
806 usleep(1000);
808 fprintf(stderr, "Cannot grab keyboard\n");
809 return 0;
812 unsigned long
813 parse_color(const char *str, const char *def)
815 size_t len;
816 rgba_t tmp;
817 char *ep;
819 if (str == NULL)
820 goto invc;
822 len = strlen(str);
824 /* +1 for the # ath the start */
825 if (*str != '#' || len > 9 || len < 4)
826 goto invc;
827 ++str; /* skip the # */
829 errno = 0;
830 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
832 if (errno)
833 goto invc;
835 switch (len - 1) {
836 case 3:
837 /* expand #rgb -> #rrggbb */
838 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
839 | (tmp.v & 0x00f) * 0x0011;
840 case 6:
841 /* assume 0xff opacity */
842 tmp.rgba.a = 0xff;
843 break;
844 } /* colors in #aarrggbb need no adjustments */
846 /* premultiply the alpha */
847 if (tmp.rgba.a) {
848 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
849 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
850 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
851 return tmp.v;
854 return 0U;
856 invc:
857 fprintf(stderr, "Invalid color: \"%s\".\n", str);
858 if (def != NULL)
859 return parse_color(def, NULL);
860 else
861 return 0U;
864 /*
865 * Given a string try to parse it as a number or return `def'.
866 */
867 int
868 parse_integer(const char *str, int def)
870 const char *errstr;
871 int i;
873 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
874 if (errstr != NULL) {
875 warnx("'%s' is %s; using %d as default", str, errstr, def);
876 return def;
879 return i;
882 /* Like parse_integer but recognize the percentages (i.e. strings ending with
883 * `%') */
884 int
885 parse_int_with_percentage(const char *str, int default_value, int max)
887 int len = strlen(str);
889 if (len > 0 && str[len - 1] == '%') {
890 int val;
891 char *cpy;
893 if ((cpy = strdup(str)) == NULL)
894 err(1, "strdup");
896 cpy[len - 1] = '\0';
897 val = parse_integer(cpy, default_value);
898 free(cpy);
899 return val * max / 100;
902 return parse_integer(str, default_value);
905 void
906 get_mouse_coords(Display *d, int *x, int *y)
908 Window w, root;
909 int i;
910 unsigned int u;
912 *x = *y = 0;
913 root = DefaultRootWindow(d);
915 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
916 for (i = 0; i < ScreenCount(d); ++i) {
917 if (root == RootWindow(d, i))
918 break;
923 /*
924 * Like parse_int_with_percentage but understands some special values:
925 * - middle that is (max-self)/2
926 * - center = middle
927 * - start that is 0
928 * - end that is (max-self)
929 * - mx x coordinate of the mouse
930 * - my y coordinate of the mouse
931 */
932 int
933 parse_int_with_pos(Display *d, const char *str, int default_value, int max, int self)
935 if (!strcmp(str, "start"))
936 return 0;
937 if (!strcmp(str, "middle") || !strcmp(str, "center"))
938 return (max - self) / 2;
939 if (!strcmp(str, "end"))
940 return max - self;
941 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
942 int x, y;
944 get_mouse_coords(d, &x, &y);
945 if (!strcmp(str, "mx"))
946 return x - 1;
947 else
948 return y - 1;
950 return parse_int_with_percentage(str, default_value, max);
953 /* Parse a string like a CSS value. */
954 /* TODO: harden a bit this function */
955 char **
956 parse_csslike(const char *str)
958 int i, j;
959 char *s, *token, **ret;
960 short any_null;
962 s = strdup(str);
963 if (s == NULL)
964 return NULL;
966 ret = malloc(4 * sizeof(char *));
967 if (ret == NULL) {
968 free(s);
969 return NULL;
972 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
973 ret[i] = strdup(token);
975 if (i == 1)
976 for (j = 1; j < 4; j++)
977 ret[j] = strdup(ret[0]);
979 if (i == 2) {
980 ret[2] = strdup(ret[0]);
981 ret[3] = strdup(ret[1]);
984 if (i == 3)
985 ret[3] = strdup(ret[1]);
987 /* before we didn't check for the return type of strdup, here we will
988 */
990 any_null = 0;
991 for (i = 0; i < 4; ++i)
992 any_null = ret[i] == NULL || any_null;
994 if (any_null)
995 for (i = 0; i < 4; ++i)
996 if (ret[i] != NULL)
997 free(ret[i]);
999 if (i == 0 || any_null) {
1000 free(s);
1001 free(ret);
1002 return NULL;
1005 return ret;
1009 * Given an event, try to understand what the users wants. If the
1010 * return value is ADD_CHAR then `input' is a pointer to a string that
1011 * will need to be free'ed later.
1013 enum action
1014 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1016 char str[SYM_BUF_SIZE] = { 0 };
1017 Status s;
1019 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1020 return DEL_CHAR;
1022 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1023 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1025 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1026 return CONFIRM;
1028 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1029 return EXIT;
1031 /* Try to read what key was pressed */
1032 s = 0;
1033 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1034 if (s == XBufferOverflow) {
1035 fprintf(stderr,
1036 "Buffer overflow when trying to create keyboard "
1037 "symbol map.\n");
1038 return EXIT;
1041 if (ev->state & ControlMask) {
1042 if (!strcmp(str, "")) /* C-u */
1043 return DEL_LINE;
1044 if (!strcmp(str, "")) /* C-w */
1045 return DEL_WORD;
1046 if (!strcmp(str, "")) /* C-h */
1047 return DEL_CHAR;
1048 if (!strcmp(str, "\r")) /* C-m */
1049 return CONFIRM_CONTINUE;
1050 if (!strcmp(str, "")) /* C-p */
1051 return PREV_COMPL;
1052 if (!strcmp(str, "")) /* C-n */
1053 return NEXT_COMPL;
1054 if (!strcmp(str, "")) /* C-c */
1055 return EXIT;
1056 if (!strcmp(str, "\t")) /* C-i */
1057 return TOGGLE_FIRST_SELECTED;
1060 *input = strdup(str);
1061 if (*input == NULL) {
1062 fprintf(stderr, "Error while allocating memory for key.\n");
1063 return EXIT;
1066 return ADD_CHAR;
1069 void
1070 confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen)
1072 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1073 /* if there is something selected expand it and return */
1074 int index = cs->selected == -1 ? 0 : cs->selected;
1075 struct completion *c = cs->completions;
1076 char *t;
1078 while (1) {
1079 if (index == 0)
1080 break;
1081 c++;
1082 index--;
1085 t = c->rcompletion;
1086 free(*text);
1087 *text = strdup(t);
1089 if (*text == NULL) {
1090 fprintf(stderr, "Memory allocation error\n");
1091 *status = ERR;
1094 *textlen = strlen(*text);
1095 return;
1098 if (!r->free_text) /* cannot accept arbitrary text */
1099 *status = LOOPING;
1102 /* cs: completion list
1103 * offset: the offset of the click
1104 * first: the first (rendered) item
1105 * def: the default action
1107 enum action
1108 select_clicked(struct completions *cs, size_t offset, size_t first, enum action def)
1110 ssize_t selected = first;
1111 int set = 0;
1113 if (cs->length == 0)
1114 return NO_OP;
1116 if (offset < cs->completions[selected].offset)
1117 return EXIT;
1119 /* skip the first entry */
1120 for (selected += 1; selected < cs->length; ++selected) {
1121 if (cs->completions[selected].offset == -1)
1122 break;
1124 if (offset < cs->completions[selected].offset) {
1125 cs->selected = selected - 1;
1126 set = 1;
1127 break;
1131 if (!set)
1132 cs->selected = selected - 1;
1134 return def;
1137 enum action
1138 handle_mouse(struct rendering *r, struct completions *cs, XButtonPressedEvent *e)
1140 size_t off;
1142 if (r->horizontal_layout)
1143 off = e->x;
1144 else
1145 off = e->y;
1147 switch (e->button) {
1148 case Button1:
1149 return select_clicked(cs, off, r->offset, CONFIRM);
1151 case Button3:
1152 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1154 case Button4:
1155 return SCROLL_UP;
1157 case Button5:
1158 return SCROLL_DOWN;
1161 return NO_OP;
1164 /* event loop */
1165 enum state
1166 loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines,
1167 char **vlines)
1169 enum state status = LOOPING;
1171 while (status == LOOPING) {
1172 XEvent e;
1173 XNextEvent(r->d, &e);
1175 if (XFilterEvent(&e, r->w))
1176 continue;
1178 switch (e.type) {
1179 case KeymapNotify:
1180 XRefreshKeyboardMapping(&e.xmapping);
1181 break;
1183 case FocusIn:
1184 /* Re-grab focus */
1185 if (e.xfocus.window != r->w)
1186 grabfocus(r->d, r->w);
1187 break;
1189 case VisibilityNotify:
1190 if (e.xvisibility.state != VisibilityUnobscured)
1191 XRaiseWindow(r->d, r->w);
1192 break;
1194 case MapNotify:
1195 get_wh(r->d, &r->w, &r->width, &r->height);
1196 draw(r, *text, cs);
1197 break;
1199 case KeyPress:
1200 case ButtonPress: {
1201 enum action a;
1202 char *input = NULL;
1204 if (e.type == KeyPress)
1205 a = parse_event(r->d, (XKeyPressedEvent *)&e, r->xic, &input);
1206 else
1207 a = handle_mouse(r, cs, (XButtonPressedEvent *)&e);
1209 switch (a) {
1210 case NO_OP:
1211 break;
1213 case EXIT:
1214 status = ERR;
1215 break;
1217 case CONFIRM: {
1218 status = OK;
1219 confirm(&status, r, cs, text, textlen);
1220 break;
1223 case CONFIRM_CONTINUE: {
1224 status = OK_LOOP;
1225 confirm(&status, r, cs, text, textlen);
1226 break;
1229 case PREV_COMPL: {
1230 complete(cs, r->first_selected, 1, text, textlen, &status);
1231 r->offset = cs->selected;
1232 break;
1235 case NEXT_COMPL: {
1236 complete(cs, r->first_selected, 0, text, textlen, &status);
1237 r->offset = cs->selected;
1238 break;
1241 case DEL_CHAR:
1242 popc(*text);
1243 update_completions(cs, *text, lines, vlines, r->first_selected);
1244 r->offset = 0;
1245 break;
1247 case DEL_WORD: {
1248 popw(*text);
1249 update_completions(cs, *text, lines, vlines, r->first_selected);
1250 break;
1253 case DEL_LINE: {
1254 int i;
1255 for (i = 0; i < *textlen; ++i)
1256 *(*text + i) = 0;
1257 update_completions(cs, *text, lines, vlines, r->first_selected);
1258 r->offset = 0;
1259 break;
1262 case ADD_CHAR: {
1263 int str_len, i;
1265 str_len = strlen(input);
1268 * sometimes a strange key is pressed
1269 * i.e. ctrl alone), so input will be
1270 * empty. Don't need to update
1271 * completion in that case
1273 if (str_len == 0)
1274 break;
1276 for (i = 0; i < str_len; ++i) {
1277 *textlen = pushc(text, *textlen, input[i]);
1278 if (*textlen == -1) {
1279 fprintf(stderr,
1280 "Memory allocation "
1281 "error\n");
1282 status = ERR;
1283 break;
1287 if (status != ERR) {
1288 update_completions(
1289 cs, *text, lines, vlines, r->first_selected);
1290 free(input);
1293 r->offset = 0;
1294 break;
1297 case TOGGLE_FIRST_SELECTED:
1298 r->first_selected = !r->first_selected;
1299 if (r->first_selected && cs->selected < 0)
1300 cs->selected = 0;
1301 if (!r->first_selected && cs->selected == 0)
1302 cs->selected = -1;
1303 break;
1305 case SCROLL_DOWN:
1306 r->offset = MIN(r->offset + 1, cs->length - 1);
1307 break;
1309 case SCROLL_UP:
1310 r->offset = MAX((ssize_t)r->offset - 1, 0);
1311 break;
1316 draw(r, *text, cs);
1319 return status;
1322 int
1323 load_font(struct rendering *r, const char *fontname)
1325 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1326 return 0;
1329 void
1330 xim_init(struct rendering *r, XrmDatabase *xdb)
1332 XIMStyle best_match_style;
1333 XIMStyles *xis;
1334 int i;
1336 /* Open the X input method */
1337 if ((r->xim = XOpenIM(r->d, *xdb, resname, resclass)) == NULL)
1338 err(1, "XOpenIM");
1340 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1341 fprintf(stderr, "Input Styles could not be retrieved\n");
1342 exit(EX_UNAVAILABLE);
1345 best_match_style = 0;
1346 for (i = 0; i < xis->count_styles; ++i) {
1347 XIMStyle ts = xis->supported_styles[i];
1348 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1349 best_match_style = ts;
1350 break;
1353 XFree(xis);
1355 if (!best_match_style)
1356 fprintf(stderr, "No matching input style could be determined\n");
1358 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style, XNClientWindow, r->w,
1359 XNFocusWindow, r->w, NULL);
1360 if (r->xic == NULL)
1361 err(1, "XCreateIC");
1364 void
1365 create_window(struct rendering *r, Window parent_window, Colormap cmap, XVisualInfo vinfo, int x,
1366 int y, int ox, int oy, unsigned long background_pixel)
1368 XSetWindowAttributes attr;
1370 /* Create the window */
1371 attr.colormap = cmap;
1372 attr.override_redirect = 1;
1373 attr.border_pixel = 0;
1374 attr.background_pixel = background_pixel;
1375 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeymapStateMask
1376 | ButtonPress | VisibilityChangeMask;
1378 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1379 vinfo.depth, InputOutput, vinfo.visual,
1380 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);
1383 void
1384 ps1extents(struct rendering *r)
1386 char *dup;
1387 dup = strdupn(r->ps1);
1388 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1389 free(dup);
1392 void
1393 usage(char *prgname)
1395 fprintf(stderr,
1396 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1397 " [-d separator] [-e window] [-f font] [-G color] [-g "
1398 "size]\n"
1399 " [-H height] [-I color] [-i size] [-J color] [-j "
1400 "size] [-l layout]\n"
1401 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1402 "color]\n"
1403 " [-t color] [-W width] [-x coord] [-y coord]\n",
1404 prgname);
1407 int
1408 main(int argc, char **argv)
1410 struct completions *cs;
1411 struct rendering r;
1412 XVisualInfo vinfo;
1413 Colormap cmap;
1414 size_t nlines, i;
1415 Window parent_window;
1416 XrmDatabase xdb;
1417 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1418 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1419 ch_borders_bg[4]; /* N E S W */
1420 enum state status;
1421 int ch;
1422 int offset_x, offset_y, x, y;
1423 int textlen, d_width, d_height;
1424 short embed;
1425 char *sep, *parent_window_id;
1426 char **lines, **vlines;
1427 char *fontname, *text, *xrm;
1429 sep = NULL;
1430 parent_window_id = NULL;
1432 r.first_selected = 0;
1433 r.free_text = 1;
1434 r.multiple_select = 0;
1435 r.offset = 0;
1437 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1438 switch (ch) {
1439 case 'h': /* help */
1440 usage(*argv);
1441 return 0;
1442 case 'v': /* version */
1443 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1444 return 0;
1445 case 'e': /* embed */
1446 if ((parent_window_id = strdup(optarg)) == NULL)
1447 err(1, "strdup");
1448 break;
1449 case 'd':
1450 if ((sep = strdup(optarg)) == NULL)
1451 err(1, "strdup");
1452 break;
1453 case 'A':
1454 r.free_text = 0;
1455 break;
1456 case 'm':
1457 r.multiple_select = 1;
1458 break;
1459 default:
1460 break;
1464 lines = readlines(&nlines);
1466 vlines = NULL;
1467 if (sep != NULL) {
1468 int l;
1469 l = strlen(sep);
1470 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1471 err(1, "calloc");
1473 for (i = 0; i < nlines; i++) {
1474 char *t;
1475 t = strstr(lines[i], sep);
1476 if (t == NULL)
1477 vlines[i] = lines[i];
1478 else
1479 vlines[i] = t + l;
1483 setlocale(LC_ALL, getenv("LANG"));
1485 status = LOOPING;
1487 /* where the monitor start (used only with xinerama) */
1488 offset_x = offset_y = 0;
1490 /* default width and height */
1491 r.width = 400;
1492 r.height = 20;
1494 /* default position on the screen */
1495 x = y = 0;
1497 for (i = 0; i < 4; ++i) {
1498 /* default paddings */
1499 r.p_padding[i] = 10;
1500 r.c_padding[i] = 10;
1501 r.ch_padding[i] = 10;
1503 /* default borders */
1504 r.borders[i] = 0;
1505 r.p_borders[i] = 0;
1506 r.c_borders[i] = 0;
1507 r.ch_borders[i] = 0;
1510 /* the prompt. We duplicate the string so later is easy to
1511 * free (in the case it's been overwritten by the user) */
1512 if ((r.ps1 = strdup("$ ")) == NULL)
1513 err(1, "strdup");
1515 /* same for the font name */
1516 if ((fontname = strdup(default_fontname)) == NULL)
1517 err(1, "strdup");
1519 textlen = 10;
1520 if ((text = malloc(textlen * sizeof(char))) == NULL)
1521 err(1, "malloc");
1523 /* struct completions *cs = filter(text, lines); */
1524 if ((cs = compls_new(nlines)) == NULL)
1525 err(1, "compls_new");
1527 /* start talking to xorg */
1528 r.d = XOpenDisplay(NULL);
1529 if (r.d == NULL) {
1530 fprintf(stderr, "Could not open display!\n");
1531 return EX_UNAVAILABLE;
1534 embed = 1;
1535 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1536 parent_window = DefaultRootWindow(r.d);
1537 embed = 0;
1540 /* get display size */
1541 get_wh(r.d, &parent_window, &d_width, &d_height);
1543 if (!embed && XineramaIsActive(r.d)) { /* find the mice */
1544 XineramaScreenInfo *info;
1545 Window rr;
1546 Window root;
1547 int number_of_screens, monitors, i;
1548 int root_x, root_y, win_x, win_y;
1549 unsigned int mask;
1550 short res;
1552 number_of_screens = XScreenCount(r.d);
1553 for (i = 0; i < number_of_screens; ++i) {
1554 root = XRootWindow(r.d, i);
1555 res = XQueryPointer(
1556 r.d, root, &rr, &rr, &root_x, &root_y, &win_x, &win_y, &mask);
1557 if (res)
1558 break;
1561 if (!res) {
1562 fprintf(stderr, "No mouse found.\n");
1563 root_x = 0;
1564 root_y = 0;
1567 /* Now find in which monitor the mice is */
1568 info = XineramaQueryScreens(r.d, &monitors);
1569 if (info) {
1570 for (i = 0; i < monitors; ++i) {
1571 if (info[i].x_org <= root_x
1572 && root_x <= (info[i].x_org + info[i].width)
1573 && info[i].y_org <= root_y
1574 && root_y <= (info[i].y_org + info[i].height)) {
1575 offset_x = info[i].x_org;
1576 offset_y = info[i].y_org;
1577 d_width = info[i].width;
1578 d_height = info[i].height;
1579 break;
1583 XFree(info);
1586 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1587 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual, AllocNone);
1589 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1590 fgs[2] = parse_color("#000", NULL);
1592 bgs[0] = bgs[1] = parse_color("#000", NULL);
1593 bgs[2] = parse_color("#fff", NULL);
1595 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] = parse_color("#000", NULL);
1597 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1598 = parse_color("#000", NULL);
1599 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1600 = parse_color("#000", NULL);
1601 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1602 = parse_color("#000", NULL);
1604 r.horizontal_layout = 1;
1606 /* Read the resources */
1607 XrmInitialize();
1608 xrm = XResourceManagerString(r.d);
1609 xdb = NULL;
1610 if (xrm != NULL) {
1611 XrmValue value;
1612 char *datatype[20];
1614 xdb = XrmGetStringDatabase(xrm);
1616 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1617 free(fontname);
1618 if ((fontname = strdup(value.addr)) == NULL)
1619 err(1, "strdup");
1620 } else {
1621 fprintf(stderr, "no font defined, using %s\n", fontname);
1624 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1625 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1626 else
1627 fprintf(stderr, "no layout defined, using horizontal\n");
1629 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1630 free(r.ps1);
1631 r.ps1 = normalize_str(value.addr);
1632 } else {
1633 fprintf(stderr,
1634 "no prompt defined, using \"%s\" as "
1635 "default\n",
1636 r.ps1);
1639 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1640 char **sizes;
1641 sizes = parse_csslike(value.addr);
1642 if (sizes != NULL)
1643 for (i = 0; i < 4; ++i)
1644 r.p_borders[i] = parse_integer(sizes[i], 0);
1645 else
1646 fprintf(stderr,
1647 "error while parsing "
1648 "MyMenu.prompt.border.size");
1651 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1652 char **colors;
1653 colors = parse_csslike(value.addr);
1654 if (colors != NULL)
1655 for (i = 0; i < 4; ++i)
1656 p_borders_bg[i] = parse_color(colors[i], "#000");
1657 else
1658 fprintf(stderr,
1659 "error while parsing "
1660 "MyMenu.prompt.border.color");
1663 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1664 char **colors;
1665 colors = parse_csslike(value.addr);
1666 if (colors != NULL)
1667 for (i = 0; i < 4; ++i)
1668 r.p_padding[i] = parse_integer(colors[i], 0);
1669 else
1670 fprintf(stderr,
1671 "error while parsing "
1672 "MyMenu.prompt.padding");
1675 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1676 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1677 else
1678 fprintf(stderr, "no width defined, using %d\n", r.width);
1680 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1681 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1682 else
1683 fprintf(stderr, "no height defined, using %d\n", r.height);
1685 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1686 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1688 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1689 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1691 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1692 char **borders;
1693 borders = parse_csslike(value.addr);
1694 if (borders != NULL)
1695 for (i = 0; i < 4; ++i)
1696 r.borders[i] = parse_int_with_percentage(
1697 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1698 else
1699 fprintf(stderr,
1700 "error while parsing "
1701 "MyMenu.border.size\n");
1704 /* Prompt */
1705 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1706 fgs[0] = parse_color(value.addr, "#fff");
1708 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1709 bgs[0] = parse_color(value.addr, "#000");
1711 /* Completions */
1712 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1713 fgs[1] = parse_color(value.addr, "#fff");
1715 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1716 bgs[1] = parse_color(value.addr, "#000");
1718 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1719 char **paddings;
1720 paddings = parse_csslike(value.addr);
1721 if (paddings != NULL)
1722 for (i = 0; i < 4; ++i)
1723 r.c_padding[i] = parse_integer(paddings[i], 0);
1724 else
1725 fprintf(stderr,
1726 "Error while parsing "
1727 "MyMenu.completion.padding");
1730 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1731 char **sizes;
1732 sizes = parse_csslike(value.addr);
1733 if (sizes != NULL)
1734 for (i = 0; i < 4; ++i)
1735 r.c_borders[i] = parse_integer(sizes[i], 0);
1736 else
1737 fprintf(stderr,
1738 "Error while parsing "
1739 "MyMenu.completion.border.size");
1742 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1743 char **sizes;
1744 sizes = parse_csslike(value.addr);
1745 if (sizes != NULL)
1746 for (i = 0; i < 4; ++i)
1747 c_borders_bg[i] = parse_color(sizes[i], "#000");
1748 else
1749 fprintf(stderr,
1750 "Error while parsing "
1751 "MyMenu.completion.border.color");
1754 /* Completion Highlighted */
1755 if (XrmGetResource(
1756 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1757 fgs[2] = parse_color(value.addr, "#000");
1759 if (XrmGetResource(
1760 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1761 bgs[2] = parse_color(value.addr, "#fff");
1763 if (XrmGetResource(
1764 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1765 char **paddings;
1766 paddings = parse_csslike(value.addr);
1767 if (paddings != NULL)
1768 for (i = 0; i < 4; ++i)
1769 r.ch_padding[i] = parse_integer(paddings[i], 0);
1770 else
1771 fprintf(stderr,
1772 "Error while parsing "
1773 "MyMenu.completion_highlighted."
1774 "padding");
1777 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1778 &value)) {
1779 char **sizes;
1780 sizes = parse_csslike(value.addr);
1781 if (sizes != NULL)
1782 for (i = 0; i < 4; ++i)
1783 r.ch_borders[i] = parse_integer(sizes[i], 0);
1784 else
1785 fprintf(stderr,
1786 "Error while parsing "
1787 "MyMenu.completion_highlighted."
1788 "border.size");
1791 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1792 &value)) {
1793 char **colors;
1794 colors = parse_csslike(value.addr);
1795 if (colors != NULL)
1796 for (i = 0; i < 4; ++i)
1797 ch_borders_bg[i] = parse_color(colors[i], "#000");
1798 else
1799 fprintf(stderr,
1800 "Error while parsing "
1801 "MyMenu.completion_highlighted."
1802 "border.color");
1805 /* Border */
1806 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1807 char **colors;
1808 colors = parse_csslike(value.addr);
1809 if (colors != NULL)
1810 for (i = 0; i < 4; ++i)
1811 borders_bg[i] = parse_color(colors[i], "#000");
1812 else
1813 fprintf(stderr,
1814 "error while parsing "
1815 "MyMenu.border.color\n");
1819 /* Second round of args parsing */
1820 optind = 0; /* reset the option index */
1821 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1822 switch (ch) {
1823 case 'a':
1824 r.first_selected = 1;
1825 break;
1826 case 'A':
1827 /* free_text -- already catched */
1828 case 'd':
1829 /* separator -- this case was already catched */
1830 case 'e':
1831 /* embedding mymenu this case was already catched. */
1832 case 'm':
1833 /* multiple selection this case was already catched.
1835 break;
1836 case 'p': {
1837 char *newprompt;
1838 newprompt = strdup(optarg);
1839 if (newprompt != NULL) {
1840 free(r.ps1);
1841 r.ps1 = newprompt;
1843 break;
1845 case 'x':
1846 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1847 break;
1848 case 'y':
1849 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1850 break;
1851 case 'P': {
1852 char **paddings;
1853 if ((paddings = parse_csslike(optarg)) != NULL)
1854 for (i = 0; i < 4; ++i)
1855 r.p_padding[i] = parse_integer(paddings[i], 0);
1856 break;
1858 case 'G': {
1859 char **colors;
1860 if ((colors = parse_csslike(optarg)) != NULL)
1861 for (i = 0; i < 4; ++i)
1862 p_borders_bg[i] = parse_color(colors[i], "#000");
1863 break;
1865 case 'g': {
1866 char **sizes;
1867 if ((sizes = parse_csslike(optarg)) != NULL)
1868 for (i = 0; i < 4; ++i)
1869 r.p_borders[i] = parse_integer(sizes[i], 0);
1870 break;
1872 case 'I': {
1873 char **colors;
1874 if ((colors = parse_csslike(optarg)) != NULL)
1875 for (i = 0; i < 4; ++i)
1876 c_borders_bg[i] = parse_color(colors[i], "#000");
1877 break;
1879 case 'i': {
1880 char **sizes;
1881 if ((sizes = parse_csslike(optarg)) != NULL)
1882 for (i = 0; i < 4; ++i)
1883 r.c_borders[i] = parse_integer(sizes[i], 0);
1884 break;
1886 case 'J': {
1887 char **colors;
1888 if ((colors = parse_csslike(optarg)) != NULL)
1889 for (i = 0; i < 4; ++i)
1890 ch_borders_bg[i] = parse_color(colors[i], "#000");
1891 break;
1893 case 'j': {
1894 char **sizes;
1895 if ((sizes = parse_csslike(optarg)) != NULL)
1896 for (i = 0; i < 4; ++i)
1897 r.ch_borders[i] = parse_integer(sizes[i], 0);
1898 break;
1900 case 'l':
1901 r.horizontal_layout = !strcmp(optarg, "horizontal");
1902 break;
1903 case 'f': {
1904 char *newfont;
1905 if ((newfont = strdup(optarg)) != NULL) {
1906 free(fontname);
1907 fontname = newfont;
1909 break;
1911 case 'W':
1912 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1913 break;
1914 case 'H':
1915 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1916 break;
1917 case 'b': {
1918 char **borders;
1919 if ((borders = parse_csslike(optarg)) != NULL) {
1920 for (i = 0; i < 4; ++i)
1921 r.borders[i] = parse_integer(borders[i], 0);
1922 } else
1923 fprintf(stderr, "Error parsing b option\n");
1924 break;
1926 case 'B': {
1927 char **colors;
1928 if ((colors = parse_csslike(optarg)) != NULL) {
1929 for (i = 0; i < 4; ++i)
1930 borders_bg[i] = parse_color(colors[i], "#000");
1931 } else
1932 fprintf(stderr, "error while parsing B option\n");
1933 break;
1935 case 't':
1936 fgs[0] = parse_color(optarg, NULL);
1937 break;
1938 case 'T':
1939 bgs[0] = parse_color(optarg, NULL);
1940 break;
1941 case 'c':
1942 fgs[1] = parse_color(optarg, NULL);
1943 break;
1944 case 'C':
1945 bgs[1] = parse_color(optarg, NULL);
1946 break;
1947 case 's':
1948 fgs[2] = parse_color(optarg, NULL);
1949 break;
1950 case 'S':
1951 bgs[2] = parse_color(optarg, NULL);
1952 break;
1953 default:
1954 fprintf(stderr, "Unrecognized option %c\n", ch);
1955 status = ERR;
1956 break;
1960 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1961 fprintf(stderr, "height, width, x or y are lesser than 0.");
1962 status = ERR;
1965 /* since only now we know if the first should be selected,
1966 * update the completion here */
1967 update_completions(cs, text, lines, vlines, r.first_selected);
1969 /* update the prompt lenght, only now we surely know the length of it
1971 r.ps1len = strlen(r.ps1);
1973 /* Create the window */
1974 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1975 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1976 XMapRaised(r.d, r.w);
1978 /* If embed, listen for other events as well */
1979 if (embed) {
1980 Window *children, parent, root;
1981 unsigned int children_no;
1983 XSelectInput(r.d, parent_window, FocusChangeMask);
1984 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
1985 && children) {
1986 for (i = 0; i < children_no && children[i] != r.w; ++i)
1987 XSelectInput(r.d, children[i], FocusChangeMask);
1988 XFree(children);
1990 grabfocus(r.d, r.w);
1993 take_keyboard(r.d, r.w);
1995 r.x_zero = r.borders[3];
1996 r.y_zero = r.borders[0];
1999 XGCValues values;
2001 for (i = 0; i < 3; ++i) {
2002 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2003 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2006 for (i = 0; i < 4; ++i) {
2007 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2008 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2009 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2010 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2014 /* Load the colors in our GCs */
2015 for (i = 0; i < 3; ++i) {
2016 XSetForeground(r.d, r.fgs[i], fgs[i]);
2017 XSetForeground(r.d, r.bgs[i], bgs[i]);
2020 for (i = 0; i < 4; ++i) {
2021 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2022 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2023 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2024 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2027 if (load_font(&r, fontname) == -1)
2028 status = ERR;
2030 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2032 for (i = 0; i < 3; ++i) {
2033 rgba_t c;
2034 XRenderColor xrcolor;
2036 c = *(rgba_t *)&fgs[i];
2037 xrcolor.red = EXPANDBITS(c.rgba.r);
2038 xrcolor.green = EXPANDBITS(c.rgba.g);
2039 xrcolor.blue = EXPANDBITS(c.rgba.b);
2040 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2041 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2044 /* compute prompt dimensions */
2045 ps1extents(&r);
2047 xim_init(&r, &xdb);
2049 #ifdef __OpenBSD__
2050 if (pledge("stdio", "") == -1)
2051 err(1, "pledge");
2052 #endif
2054 /* Cache text height */
2055 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2057 /* Draw the window for the first time */
2058 draw(&r, text, cs);
2060 /* Main loop */
2061 while (status == LOOPING || status == OK_LOOP) {
2062 status = loop(&r, &text, &textlen, cs, lines, vlines);
2064 if (status != ERR)
2065 printf("%s\n", text);
2067 if (!r.multiple_select && status == OK_LOOP)
2068 status = OK;
2071 XUngrabKeyboard(r.d, CurrentTime);
2073 for (i = 0; i < 3; ++i)
2074 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2076 for (i = 0; i < 3; ++i) {
2077 XFreeGC(r.d, r.fgs[i]);
2078 XFreeGC(r.d, r.bgs[i]);
2081 for (i = 0; i < 4; ++i) {
2082 XFreeGC(r.d, r.borders_bg[i]);
2083 XFreeGC(r.d, r.p_borders_bg[i]);
2084 XFreeGC(r.d, r.c_borders_bg[i]);
2085 XFreeGC(r.d, r.ch_borders_bg[i]);
2088 XDestroyIC(r.xic);
2089 XCloseIM(r.xim);
2091 for (i = 0; i < 3; ++i)
2092 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2093 XftFontClose(r.d, r.font);
2094 XftDrawDestroy(r.xftdraw);
2096 free(r.ps1);
2097 free(fontname);
2098 free(text);
2100 free(lines);
2101 free(vlines);
2102 compls_delete(cs);
2104 XFreeColormap(r.d, cmap);
2106 XDestroyWindow(r.d, r.w);
2107 XCloseDisplay(r.d);
2109 return status != OK;