2 * Copyright (c) 2018, 2019, 2020, 2022 Omar Polo <op@omarpolo.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include <ctype.h> /* isalnum */
21 #include <locale.h> /* setlocale */
25 #include <string.h> /* strdup, strlen */
31 #include <X11/Xresource.h>
32 #include <X11/Xutil.h>
33 #include <X11/keysym.h>
34 #include <X11/Xft/Xft.h>
36 #include <X11/extensions/Xinerama.h>
38 #define RESNAME "MyMenu"
39 #define RESCLASS "mymenu"
41 #define SYM_BUF_SIZE 4
43 #define DEFFONT "monospace"
45 #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:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
52 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
53 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
55 /* The states of the event loop */
56 enum state { LOOPING, OK_LOOP, OK, ERR };
59 * For the drawing-related function. The text to be rendere could be
60 * the prompt, a completion or a highlighted completion
62 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
64 /* These are the possible action to be performed after user input. */
76 TOGGLE_FIRST_SELECTED,
81 /* A big set of values that needs to be carried around for drawing. A
82 * big struct to rule them all */
84 Display *d; /* Connection to xorg */
92 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
94 int y_zero; /* like x_zero but for the y axis */
96 int offset; /* scroll offset */
100 short multiple_select;
102 /* four border width */
108 short horizontal_layout;
113 int ps1w; /* ps1 width */
114 int ps1h; /* ps1 height */
116 int text_height; /* cache for the vertical layout */
129 XftColor xft_colors[3];
137 * The X (or Y, depending on the layour) at which the item is
143 /* Wrap the linked list of completions */
145 struct completion *completions;
150 /* idea stolen from lemonbar; ty lemonboy */
161 /* Return a newly allocated (and empty) completion list */
163 compls_new(size_t length)
165 struct completions *cs = malloc(sizeof(struct completions));
170 cs->completions = calloc(length, sizeof(struct completion));
171 if (cs->completions == NULL) {
181 /* Delete the wrapper and the whole list */
183 compls_delete(struct completions *cs)
188 free(cs->completions);
193 * Create a completion list from a text and the list of possible
194 * completions (null terminated). Expects a non-null `cs'. `lines' and
195 * `vlines' should have the same length OR `vlines' is NULL.
198 filter(struct completions *cs, char *text, char **lines, char **vlines)
208 if (lines[index] == NULL)
211 l = vlines[index] != NULL ? vlines[index] : lines[index];
213 if (strcasestr(l, text) != NULL) {
214 struct completion *c = &cs->completions[matching];
216 c->rcompletion = lines[index];
222 cs->length = matching;
226 /* Update the given completion */
228 update_completions(struct completions *cs, char *text, char **lines,
229 char **vlines, short first_selected)
231 filter(cs, text, lines, vlines);
232 if (first_selected && cs->length > 0)
237 * Select the next or previous selection and update some state. `text'
238 * will be updated with the text of the completion and `textlen' with
239 * the new length. If the memory cannot be allocated `status' will be
243 complete(struct completions *cs, short first_selected, short p,
244 char **text, int *textlen, enum state *status)
246 struct completion *n;
249 if (cs == NULL || cs->length == 0)
253 * If the first is always selected and the first entry is
254 * different from the text, expand the text and return
256 if (first_selected &&
258 strcmp(cs->completions->completion, *text) != 0 &&
261 *text = strdup(cs->completions->completion);
266 *textlen = strlen(*text);
270 index = cs->selected;
272 if (index == -1 && p)
274 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
277 n = &cs->completions[cs->selected];
280 *text = strdup(n->completion);
282 fprintf(stderr, "Memory allocation error!\n");
286 *textlen = strlen(*text);
289 /* Push the character c at the end of the string pointed by p */
291 pushc(char **p, int maxlen, char c)
295 len = strnlen(*p, maxlen);
296 if (!(len < maxlen - 2)) {
299 maxlen += maxlen >> 1;
300 newptr = realloc(*p, maxlen);
301 if (newptr == NULL) /* bad */
307 (*p)[len + 1] = '\0';
312 * Remove the last rune from the *UTF-8* string! This is different
313 * from just setting the last byte to 0 (in some cases ofc). Return a
314 * pointer (e) to the last nonzero char. If e < p then p is empty!
334 * If c is a starting byte (11......) or is under
337 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
344 /* Remove the last word plus trailing white spaces from the given string */
351 if ((len = strlen(w)) == 0)
360 if (in_word && isspace(*e))
363 if (!in_word && !isspace(*e))
369 * If the string is surrounded by quates (`"') remove them and replace
370 * every `\"' in the string with a single double-quote.
373 normalize_str(const char *str)
378 if ((len = strlen(str)) == 0)
381 if ((s = calloc(len, sizeof(char))) == NULL)
392 str += 2; /* skip this and the next char */
398 str++; /* skip only this char */
410 readlines(size_t *lineslen)
412 size_t len = 0, cap = 0;
415 char *line = NULL, **lines = NULL;
417 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
418 if (linelen != 0 && line[linelen-1] == '\n')
419 line[linelen-1] = '\0';
425 newcap = MAX(cap * 1.5, 32);
426 t = recallocarray(lines, cap, newcap, sizeof(char *));
428 err(1, "recallocarray");
433 if ((lines[len++] = strdup(line)) == NULL)
446 * Compute the dimensions of the string str once rendered.
447 * It'll return the width and set ret_width and ret_height if not NULL
450 text_extents(char *str, int len, struct rendering *r, int *ret_width,
455 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
456 height = r->font->ascent - r->font->descent;
457 width = gi.width - gi.x;
459 if (ret_width != NULL)
461 if (ret_height != NULL)
462 *ret_height = height;
467 draw_string(char *str, int len, int x, int y, struct rendering *r,
472 xftcolor = r->xft_colors[0];
474 xftcolor = r->xft_colors[1];
475 if (tt == COMPL_HIGH)
476 xftcolor = r->xft_colors[2];
478 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
481 /* Duplicate the string and substitute every space with a 'n` */
487 if (str == NULL || *str == '\0')
490 if ((dup = strdup(str)) == NULL)
493 for (t = dup; *t; ++t) {
502 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
503 enum obj_type t, char *text)
505 GC *border_color, bg;
506 int *padding, *borders;
507 int ret = 0, inner_width, inner_height, x;
511 border_color = r->p_borders_bg;
512 padding = r->p_padding;
513 borders = r->p_borders;
517 border_color = r->c_borders_bg;
518 padding = r->c_padding;
519 borders = r->c_borders;
523 border_color = r->ch_borders_bg;
524 padding = r->ch_padding;
525 borders = r->ch_borders;
530 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
532 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
533 inner_height = padding[0] + r->text_height + padding[2];
536 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
540 XFillRectangle(r->d, r->w, border_color[1],
541 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
544 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
545 y + borders[0] + padding[0] + r->text_height + padding[2],
546 r->width, borders[2]);
549 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
553 x = r->x_zero + borders[3];
555 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
558 y += padding[0] + r->text_height;
560 if (prefix != NULL) {
561 draw_string(prefix, strlen(prefix), x, y, r, t);
564 draw_string(text, strlen(text), x, y, r, t);
570 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
571 enum obj_type t, char *text)
573 GC *border_color, bg;
574 int *padding, *borders;
575 int ret = 0, inner_width, inner_height, y, text_width;
579 border_color = r->p_borders_bg;
580 padding = r->p_padding;
581 borders = r->p_borders;
585 border_color = r->c_borders_bg;
586 padding = r->c_padding;
587 borders = r->c_borders;
591 border_color = r->ch_borders_bg;
592 padding = r->ch_padding;
593 borders = r->ch_borders;
598 if (padding[0] < 0 || padding[2] < 0) {
599 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
603 padding[2] = padding[0];
606 /* If they are still lesser than 0, set 'em to 0 */
607 if (padding[0] < 0 || padding[2] < 0)
608 padding[0] = padding[2] = 0;
610 /* Get the text width */
611 text_extents(text, strlen(text), r, &text_width, NULL);
613 text_width += prefix_width;
615 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
617 inner_width = padding[3] + text_width + padding[1];
618 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
621 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
625 XFillRectangle(r->d, r->w, border_color[1],
626 x + borders[3] + inner_width, r->y_zero, borders[1],
630 XFillRectangle(r->d, r->w, border_color[2], x,
631 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
635 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
640 y = r->y_zero + borders[0];
641 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
644 y += padding[0] + r->text_height;
646 if (prefix != NULL) {
647 draw_string(prefix, strlen(prefix), x, y, r, t);
650 draw_string(text, strlen(text), x, y, r, t);
656 * ,-----------------------------------------------------------------,
657 * | 20 char text | completion | completion | completion | compl |
658 * `-----------------------------------------------------------------'
661 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
666 /* Draw the prompt */
667 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
669 for (i = r->offset; i < cs->length; ++i) {
672 if (cs->selected == (ssize_t)i)
677 cs->completions[i].offset = x;
679 x += draw_h_box(r, x, NULL, 0, t,
680 cs->completions[i].completion);
682 if (x > INNER_WIDTH(r))
686 for (i += 1; i < cs->length; ++i)
687 cs->completions[i].offset = -1;
691 * ,-----------------------------------------------------------------,
693 * |-----------------------------------------------------------------|
695 * |-----------------------------------------------------------------|
697 * `-----------------------------------------------------------------'
700 draw_vertically(struct rendering *r, char *text, struct completions *cs)
705 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
707 for (i = r->offset; i < cs->length; ++i) {
710 if (cs->selected == (ssize_t)i)
715 cs->completions[i].offset = y;
717 y += draw_v_box(r, y, NULL, 0, t,
718 cs->completions[i].completion);
720 if (y > INNER_HEIGHT(r))
724 for (i += 1; i < cs->length; ++i)
725 cs->completions[i].offset = -1;
729 draw(struct rendering *r, char *text, struct completions *cs)
731 /* Draw the background */
732 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
733 INNER_WIDTH(r), INNER_HEIGHT(r));
735 /* Draw the contents */
736 if (r->horizontal_layout)
737 draw_horizontally(r, text, cs);
739 draw_vertically(r, text, cs);
741 /* Draw the borders */
742 if (r->borders[0] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
746 if (r->borders[1] != 0)
747 XFillRectangle(r->d, r->w, r->borders_bg[1],
748 r->width - r->borders[1], 0, r->borders[1],
751 if (r->borders[2] != 0)
752 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
753 r->height - r->borders[2], r->width, r->borders[2]);
755 if (r->borders[3] != 0)
756 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
757 r->borders[3], r->height);
763 /* Set some WM stuff */
765 set_win_atoms_hints(Display *d, Window w, int width, int height)
768 XClassHint *class_hint;
769 XSizeHints *size_hint;
771 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
772 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
773 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
774 (unsigned char *)&type, 1);
776 /* some window managers honor this properties */
777 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
778 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
779 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
780 (unsigned char *)&type, 1);
782 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
783 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
784 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
785 (unsigned char *)&type, 1);
787 /* Setting window hints */
788 class_hint = XAllocClassHint();
789 if (class_hint == NULL) {
790 fprintf(stderr, "Could not allocate memory for class hint\n");
791 exit(EX_UNAVAILABLE);
794 class_hint->res_name = RESNAME;
795 class_hint->res_class = RESCLASS;
796 XSetClassHint(d, w, class_hint);
799 size_hint = XAllocSizeHints();
800 if (size_hint == NULL) {
801 fprintf(stderr, "Could not allocate memory for size hint\n");
802 exit(EX_UNAVAILABLE);
805 size_hint->flags = PMinSize | PBaseSize;
806 size_hint->min_width = width;
807 size_hint->base_width = width;
808 size_hint->min_height = height;
809 size_hint->base_height = height;
814 /* Get the width and height of the window `w' */
816 get_wh(Display *d, Window *w, int *width, int *height)
818 XWindowAttributes win_attr;
820 XGetWindowAttributes(d, *w, &win_attr);
821 *height = win_attr.height;
822 *width = win_attr.width;
825 /* find the current xinerama monitor if possible */
827 findmonitor(Display *d, int *x, int *y, int *width, int *height)
829 XineramaScreenInfo *info;
832 int screens, monitors, i;
833 int rootx, rooty, winx, winy;
837 if (!XineramaIsActive(d))
840 screens = XScreenCount(d);
841 for (i = 0; i < screens; ++i) {
842 root = XRootWindow(d, i);
843 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
852 /* Now find in which monitor the mice is */
853 info = XineramaQueryScreens(d, &monitors);
857 for (i = 0; i < monitors; ++i) {
858 if (info[i].x_org <= rootx &&
859 rootx <= (info[i].x_org + info[i].width) &&
860 info[i].y_org <= rooty &&
861 rooty <= (info[i].y_org + info[i].height)) {
864 *width = info[i].width;
865 *height = info[i].height;
874 grabfocus(Display *d, Window w)
877 for (i = 0; i < 100; ++i) {
881 XGetInputFocus(d, &focuswin, &revert_to_win);
886 XSetInputFocus(d, w, RevertToParent, CurrentTime);
893 * I know this may seem a little hackish BUT is the only way I managed
894 * to actually grab that goddam keyboard. Only one call to
895 * XGrabKeyboard does not always end up with the keyboard grabbed!
898 take_keyboard(Display *d, Window w)
901 for (i = 0; i < 100; i++) {
902 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
903 CurrentTime) == GrabSuccess)
907 fprintf(stderr, "Cannot grab keyboard\n");
912 parse_color(const char *str, const char *def)
923 /* +1 for the # ath the start */
924 if (*str != '#' || len > 9 || len < 4)
926 ++str; /* skip the # */
929 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
936 /* expand #rgb -> #rrggbb */
937 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
938 | (tmp.v & 0x00f) * 0x0011;
940 /* assume 0xff opacity */
943 } /* colors in #aarrggbb need no adjustments */
945 /* premultiply the alpha */
947 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
948 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
949 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
956 fprintf(stderr, "Invalid color: \"%s\".\n", str);
958 return parse_color(def, NULL);
964 * Given a string try to parse it as a number or return `def'.
967 parse_integer(const char *str, int def)
972 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
973 if (errstr != NULL) {
974 warnx("'%s' is %s; using %d as default", str, errstr, def);
982 * Like parse_integer but recognize the percentages (i.e. strings
986 parse_int_with_percentage(const char *str, int default_value, int max)
988 int len = strlen(str);
990 if (len > 0 && str[len - 1] == '%') {
994 if ((cpy = strdup(str)) == NULL)
998 val = parse_integer(cpy, default_value);
1000 return val * max / 100;
1003 return parse_integer(str, default_value);
1007 get_mouse_coords(Display *d, int *x, int *y)
1014 root = DefaultRootWindow(d);
1016 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1017 for (i = 0; i < ScreenCount(d); ++i) {
1018 if (root == RootWindow(d, i))
1025 * Like parse_int_with_percentage but understands some special values:
1026 * - middle that is (max-self)/2
1029 * - end that is (max-self)
1030 * - mx x coordinate of the mouse
1031 * - my y coordinate of the mouse
1034 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1037 if (!strcmp(str, "start"))
1039 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1040 return (max - self) / 2;
1041 if (!strcmp(str, "end"))
1043 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1046 get_mouse_coords(d, &x, &y);
1047 if (!strcmp(str, "mx"))
1052 return parse_int_with_percentage(str, default_value, max);
1055 /* Parse a string like a CSS value. */
1056 /* TODO: harden a bit this function */
1058 parse_csslike(const char *str, char **ret)
1064 memset(ret, 0, 4 * sizeof(*ret));
1070 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1071 ret[i] = strdup(token);
1074 for (j = 1; j < 4; j++)
1075 ret[j] = strdup(ret[0]);
1078 ret[2] = strdup(ret[0]);
1079 ret[3] = strdup(ret[1]);
1083 ret[3] = strdup(ret[1]);
1086 * before we didn't check for the return type of strdup, here
1091 for (i = 0; i < 4; ++i)
1092 any_null = ret[i] == NULL || any_null;
1095 for (i = 0; i < 4; ++i)
1098 if (i == 0 || any_null) {
1107 * Given an event, try to understand what the users wants. If the
1108 * return value is ADD_CHAR then `input' is a pointer to a string that
1109 * will need to be free'ed later.
1112 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1114 char str[SYM_BUF_SIZE] = { 0 };
1117 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1120 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1121 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1123 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1126 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1129 /* Try to read what key was pressed */
1131 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1132 if (s == XBufferOverflow) {
1134 "Buffer overflow when trying to create keyboard "
1139 if (ev->state & ControlMask) {
1140 if (!strcmp(str, "")) /* C-u */
1142 if (!strcmp(str, "")) /* C-w */
1144 if (!strcmp(str, "")) /* C-h */
1146 if (!strcmp(str, "\r")) /* C-m */
1147 return CONFIRM_CONTINUE;
1148 if (!strcmp(str, "")) /* C-p */
1150 if (!strcmp(str, "")) /* C-n */
1152 if (!strcmp(str, "")) /* C-c */
1154 if (!strcmp(str, "\t")) /* C-i */
1155 return TOGGLE_FIRST_SELECTED;
1158 *input = strdup(str);
1159 if (*input == NULL) {
1160 fprintf(stderr, "Error while allocating memory for key.\n");
1168 confirm(enum state *status, struct rendering *r, struct completions *cs,
1169 char **text, int *textlen)
1171 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1172 /* if there is something selected expand it and return */
1173 int index = cs->selected == -1 ? 0 : cs->selected;
1174 struct completion *c = cs->completions;
1188 if (*text == NULL) {
1189 fprintf(stderr, "Memory allocation error\n");
1193 *textlen = strlen(*text);
1197 if (!r->free_text) /* cannot accept arbitrary text */
1202 * cs: completion list
1203 * offset: the offset of the click
1204 * first: the first (rendered) item
1205 * def: the default action
1208 select_clicked(struct completions *cs, size_t offset, size_t first,
1211 ssize_t selected = first;
1214 if (cs->length == 0)
1217 if (offset < cs->completions[selected].offset)
1220 /* skip the first entry */
1221 for (selected += 1; selected < cs->length; ++selected) {
1222 if (cs->completions[selected].offset == -1)
1225 if (offset < cs->completions[selected].offset) {
1226 cs->selected = selected - 1;
1233 cs->selected = selected - 1;
1239 handle_mouse(struct rendering *r, struct completions *cs,
1240 XButtonPressedEvent *e)
1244 if (r->horizontal_layout)
1249 switch (e->button) {
1251 return select_clicked(cs, off, r->offset, CONFIRM);
1254 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1268 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1269 char **lines, char **vlines)
1273 enum state status = LOOPING;
1276 while (status == LOOPING) {
1278 XNextEvent(r->d, &e);
1280 if (XFilterEvent(&e, r->w))
1285 XRefreshKeyboardMapping(&e.xmapping);
1290 if (e.xfocus.window != r->w)
1291 grabfocus(r->d, r->w);
1294 case VisibilityNotify:
1295 if (e.xvisibility.state != VisibilityUnobscured)
1296 XRaiseWindow(r->d, r->w);
1300 get_wh(r->d, &r->w, &r->width, &r->height);
1306 if (e.type == KeyPress)
1307 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1310 a = handle_mouse(r, cs,
1311 (XButtonPressedEvent *)&e);
1323 confirm(&status, r, cs, text, textlen);
1326 case CONFIRM_CONTINUE:
1328 confirm(&status, r, cs, text, textlen);
1332 complete(cs, r->first_selected, 1, text,
1334 r->offset = cs->selected;
1338 complete(cs, r->first_selected, 0, text,
1340 r->offset = cs->selected;
1345 update_completions(cs, *text, lines, vlines,
1352 update_completions(cs, *text, lines, vlines,
1357 for (i = 0; i < *textlen; ++i)
1359 update_completions(cs, *text, lines, vlines,
1367 str_len = strlen(input);
1370 * sometimes a strange key is pressed
1371 * i.e. ctrl alone), so input will be
1372 * empty. Don't need to update
1373 * completion in that case
1378 for (i = 0; i < str_len; ++i) {
1379 *textlen = pushc(text, *textlen,
1381 if (*textlen == -1) {
1383 "Memory allocation "
1390 if (status != ERR) {
1391 update_completions(cs, *text, lines,
1392 vlines, r->first_selected);
1400 case TOGGLE_FIRST_SELECTED:
1401 r->first_selected = !r->first_selected;
1402 if (r->first_selected && cs->selected < 0)
1404 if (!r->first_selected && cs->selected == 0)
1409 r->offset = MIN(r->offset + 1, cs->length - 1);
1413 r->offset = MAX((ssize_t)r->offset - 1, 0);
1425 load_font(struct rendering *r, const char *fontname)
1427 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1432 xim_init(struct rendering *r, XrmDatabase *xdb)
1434 XIMStyle best_match_style;
1438 /* Open the X input method */
1439 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1442 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1443 fprintf(stderr, "Input Styles could not be retrieved\n");
1444 exit(EX_UNAVAILABLE);
1447 best_match_style = 0;
1448 for (i = 0; i < xis->count_styles; ++i) {
1449 XIMStyle ts = xis->supported_styles[i];
1450 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1451 best_match_style = ts;
1457 if (!best_match_style)
1459 "No matching input style could be determined\n");
1461 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1462 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1464 err(1, "XCreateIC");
1468 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1469 XVisualInfo vinfo, int x, int y, int ox, int oy,
1470 unsigned long background_pixel)
1472 XSetWindowAttributes attr;
1473 unsigned long vmask;
1475 /* Create the window */
1476 attr.colormap = cmap;
1477 attr.override_redirect = 1;
1478 attr.border_pixel = 0;
1479 attr.background_pixel = background_pixel;
1480 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1481 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1483 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1486 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1487 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1491 ps1extents(struct rendering *r)
1494 dup = strdupn(r->ps1);
1495 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1500 usage(char *prgname)
1503 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1504 " [-d separator] [-e window] [-f font] [-G color] [-g "
1506 " [-H height] [-I color] [-i size] [-J color] [-j "
1507 "size] [-l layout]\n"
1508 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1510 " [-t color] [-W width] [-x coord] [-y coord]\n",
1515 main(int argc, char **argv)
1517 struct completions *cs;
1522 Window parent_window;
1524 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1525 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1526 ch_borders_bg[4]; /* N E S W */
1527 enum state status = LOOPING;
1529 int offset_x = 0, offset_y = 0;
1531 int textlen, d_width, d_height;
1533 const char *sep = NULL;
1534 const char *parent_window_id = NULL;
1536 char **lines, **vlines;
1537 char *fontname, *text, *xrm;
1539 setlocale(LC_ALL, getenv("LANG"));
1541 for (i = 0; i < 4; ++i) {
1542 /* default paddings */
1543 r.p_padding[i] = 10;
1544 r.c_padding[i] = 10;
1545 r.ch_padding[i] = 10;
1547 /* default borders */
1551 r.ch_borders[i] = 0;
1554 r.first_selected = 0;
1556 r.multiple_select = 0;
1559 /* default width and height */
1564 * The prompt. We duplicate the string so later is easy to
1565 * free (in the case it's been overwritten by the user)
1567 if ((r.ps1 = strdup("$ ")) == NULL)
1570 /* same for the font name */
1571 if ((fontname = strdup(DEFFONT)) == NULL)
1574 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1576 case 'h': /* help */
1579 case 'v': /* version */
1580 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1582 case 'e': /* embed */
1583 if ((parent_window_id = strdup(optarg)) == NULL)
1587 if ((sep = strdup(optarg)) == NULL)
1594 r.multiple_select = 1;
1601 lines = readlines(&nlines);
1607 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1610 for (i = 0; i < nlines; i++) {
1612 t = strstr(lines[i], sep);
1614 vlines[i] = lines[i];
1621 if ((text = malloc(textlen * sizeof(char))) == NULL)
1624 /* struct completions *cs = filter(text, lines); */
1625 if ((cs = compls_new(nlines)) == NULL)
1626 err(1, "compls_new");
1628 /* start talking to xorg */
1629 r.d = XOpenDisplay(NULL);
1631 fprintf(stderr, "Could not open display!\n");
1632 return EX_UNAVAILABLE;
1636 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1637 parent_window = DefaultRootWindow(r.d);
1641 /* get display size */
1642 get_wh(r.d, &parent_window, &d_width, &d_height);
1645 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1647 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1648 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1651 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1652 fgs[2] = parse_color("#000", NULL);
1654 bgs[0] = bgs[1] = parse_color("#000", NULL);
1655 bgs[2] = parse_color("#fff", NULL);
1657 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1658 parse_color("#000", NULL);
1660 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1661 = parse_color("#000", NULL);
1662 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1663 = parse_color("#000", NULL);
1664 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1665 = parse_color("#000", NULL);
1667 r.horizontal_layout = 1;
1669 /* Read the resources */
1671 xrm = XResourceManagerString(r.d);
1677 xdb = XrmGetStringDatabase(xrm);
1679 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1681 if ((fontname = strdup(value.addr)) == NULL)
1684 fprintf(stderr, "no font defined, using %s\n", fontname);
1687 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1688 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1690 fprintf(stderr, "no layout defined, using horizontal\n");
1692 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1694 r.ps1 = normalize_str(value.addr);
1697 "no prompt defined, using \"%s\" as "
1702 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1703 if (parse_csslike(value.addr, tmp) == -1)
1704 err(1, "parse_csslike");
1705 for (i = 0; i < 4; ++i) {
1706 r.p_borders[i] = parse_integer(tmp[i], 0);
1711 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1712 if (parse_csslike(value.addr, tmp) == -1)
1713 err(1, "parse_csslike");
1715 for (i = 0; i < 4; ++i) {
1716 p_borders_bg[i] = parse_color(tmp[i], "#000");
1721 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1722 if (parse_csslike(value.addr, tmp) == -1)
1723 err(1, "parse_csslike");
1725 for (i = 0; i < 4; ++i) {
1726 r.p_padding[i] = parse_integer(tmp[i], 0);
1731 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1732 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1734 fprintf(stderr, "no width defined, using %d\n", r.width);
1736 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1737 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1739 fprintf(stderr, "no height defined, using %d\n", r.height);
1741 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1742 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1744 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1745 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1747 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1748 if (parse_csslike(value.addr, tmp) == -1)
1749 err(1, "parse_csslike");
1751 for (i = 0; i < 4; ++i) {
1752 r.borders[i] = parse_int_with_percentage(tmp[i], 0,
1753 (i % 2) == 0 ? d_height : d_width);
1759 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1760 fgs[0] = parse_color(value.addr, "#fff");
1762 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1763 bgs[0] = parse_color(value.addr, "#000");
1766 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1767 fgs[1] = parse_color(value.addr, "#fff");
1769 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1770 bgs[1] = parse_color(value.addr, "#000");
1772 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1773 if (parse_csslike(value.addr, tmp) == -1)
1774 err(1, "parse_csslike");
1776 for (i = 0; i < 4; ++i) {
1777 r.c_padding[i] = parse_integer(tmp[i], 0);
1782 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1783 if (parse_csslike(value.addr, tmp) == -1)
1784 err(1, "parse_csslike");
1786 for (i = 0; i < 4; ++i) {
1787 r.c_borders[i] = parse_integer(tmp[i], 0);
1792 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1793 if (parse_csslike(value.addr, tmp) == -1)
1794 err(1, "parse_csslike");
1796 for (i = 0; i < 4; ++i) {
1797 c_borders_bg[i] = parse_color(tmp[i], "#000");
1802 /* Completion Highlighted */
1804 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1805 fgs[2] = parse_color(value.addr, "#000");
1808 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1809 bgs[2] = parse_color(value.addr, "#fff");
1812 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1813 if (parse_csslike(value.addr, tmp) == -1)
1814 err(1, "parse_csslike");
1816 for (i = 0; i < 4; ++i) {
1817 r.ch_padding[i] = parse_integer(tmp[i], 0);
1822 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1824 if (parse_csslike(value.addr, tmp) == -1)
1825 err(1, "parse_csslike");
1827 for (i = 0; i < 4; ++i) {
1828 r.ch_borders[i] = parse_integer(tmp[i], 0);
1833 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1835 if (parse_csslike(value.addr, tmp) == -1)
1836 err(1, "parse_csslike");
1838 for (i = 0; i < 4; ++i) {
1839 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1845 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1846 if (parse_csslike(value.addr, tmp) == -1)
1847 err(1, "parse_csslike");
1849 for (i = 0; i < 4; ++i) {
1850 borders_bg[i] = parse_color(tmp[i], "#000");
1856 /* Second round of args parsing */
1857 optind = 0; /* reset the option index */
1858 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1861 r.first_selected = 1;
1864 /* free_text -- already catched */
1866 /* separator -- this case was already catched */
1868 /* embedding mymenu this case was already catched. */
1870 /* multiple selection this case was already catched.
1875 newprompt = strdup(optarg);
1876 if (newprompt != NULL) {
1883 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1886 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1889 if (parse_csslike(optarg, tmp) == -1)
1890 err(1, "parse_csslike");
1891 for (i = 0; i < 4; ++i)
1892 r.p_padding[i] = parse_integer(tmp[i], 0);
1895 if (parse_csslike(optarg, tmp) == -1)
1896 err(1, "parse_csslike");
1897 for (i = 0; i < 4; ++i)
1898 p_borders_bg[i] = parse_color(tmp[i], "#000");
1901 if (parse_csslike(optarg, tmp) == -1)
1902 err(1, "parse_csslike");
1903 for (i = 0; i < 4; ++i)
1904 r.p_borders[i] = parse_integer(tmp[i], 0);
1907 if (parse_csslike(optarg, tmp) == -1)
1908 err(1, "parse_csslike");
1909 for (i = 0; i < 4; ++i)
1910 c_borders_bg[i] = parse_color(tmp[i], "#000");
1913 if (parse_csslike(optarg, tmp) == -1)
1914 err(1, "parse_csslike");
1915 for (i = 0; i < 4; ++i)
1916 r.c_borders[i] = parse_integer(tmp[i], 0);
1919 if (parse_csslike(optarg, tmp) == -1)
1920 err(1, "parse_csslike");
1921 for (i = 0; i < 4; ++i)
1922 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1925 if (parse_csslike(optarg, tmp) == -1)
1926 err(1, "parse_csslike");
1927 for (i = 0; i < 4; ++i)
1928 r.ch_borders[i] = parse_integer(tmp[i], 0);
1931 r.horizontal_layout = !strcmp(optarg, "horizontal");
1935 if ((newfont = strdup(optarg)) != NULL) {
1942 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1945 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1948 if (parse_csslike(optarg, tmp) == -1)
1949 err(1, "parse_csslike");
1950 for (i = 0; i < 4; ++i)
1951 r.borders[i] = parse_integer(tmp[i], 0);
1954 if (parse_csslike(optarg, tmp) == -1)
1955 err(1, "parse_csslike");
1956 for (i = 0; i < 4; ++i)
1957 borders_bg[i] = parse_color(tmp[i], "#000");
1960 fgs[0] = parse_color(optarg, NULL);
1963 bgs[0] = parse_color(optarg, NULL);
1966 fgs[1] = parse_color(optarg, NULL);
1969 bgs[1] = parse_color(optarg, NULL);
1972 fgs[2] = parse_color(optarg, NULL);
1975 bgs[2] = parse_color(optarg, NULL);
1978 fprintf(stderr, "Unrecognized option %c\n", ch);
1984 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1985 fprintf(stderr, "height, width, x or y are lesser than 0.");
1989 /* since only now we know if the first should be selected,
1990 * update the completion here */
1991 update_completions(cs, text, lines, vlines, r.first_selected);
1993 /* update the prompt lenght, only now we surely know the length of it
1995 r.ps1len = strlen(r.ps1);
1997 /* Create the window */
1998 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1999 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2000 XMapRaised(r.d, r.w);
2002 /* If embed, listen for other events as well */
2004 Window *children, parent, root;
2005 unsigned int children_no;
2007 XSelectInput(r.d, parent_window, FocusChangeMask);
2008 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2010 for (i = 0; i < children_no && children[i] != r.w; ++i)
2011 XSelectInput(r.d, children[i], FocusChangeMask);
2014 grabfocus(r.d, r.w);
2017 take_keyboard(r.d, r.w);
2019 r.x_zero = r.borders[3];
2020 r.y_zero = r.borders[0];
2025 for (i = 0; i < 3; ++i) {
2026 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2027 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2030 for (i = 0; i < 4; ++i) {
2031 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2032 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2033 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2034 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2038 /* Load the colors in our GCs */
2039 for (i = 0; i < 3; ++i) {
2040 XSetForeground(r.d, r.fgs[i], fgs[i]);
2041 XSetForeground(r.d, r.bgs[i], bgs[i]);
2044 for (i = 0; i < 4; ++i) {
2045 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2046 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2047 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2048 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2051 if (load_font(&r, fontname) == -1)
2054 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2056 for (i = 0; i < 3; ++i) {
2058 XRenderColor xrcolor;
2060 c = *(rgba_t *)&fgs[i];
2061 xrcolor.red = EXPANDBITS(c.rgba.r);
2062 xrcolor.green = EXPANDBITS(c.rgba.g);
2063 xrcolor.blue = EXPANDBITS(c.rgba.b);
2064 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2065 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2068 /* compute prompt dimensions */
2074 if (pledge("stdio", "") == -1)
2078 /* Cache text height */
2079 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2081 /* Draw the window for the first time */
2085 while (status == LOOPING || status == OK_LOOP) {
2086 status = loop(&r, &text, &textlen, cs, lines, vlines);
2089 printf("%s\n", text);
2091 if (!r.multiple_select && status == OK_LOOP)
2095 XUngrabKeyboard(r.d, CurrentTime);
2097 for (i = 0; i < 3; ++i)
2098 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2100 for (i = 0; i < 3; ++i) {
2101 XFreeGC(r.d, r.fgs[i]);
2102 XFreeGC(r.d, r.bgs[i]);
2105 for (i = 0; i < 4; ++i) {
2106 XFreeGC(r.d, r.borders_bg[i]);
2107 XFreeGC(r.d, r.p_borders_bg[i]);
2108 XFreeGC(r.d, r.c_borders_bg[i]);
2109 XFreeGC(r.d, r.ch_borders_bg[i]);
2115 for (i = 0; i < 3; ++i)
2116 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2117 XftFontClose(r.d, r.font);
2118 XftDrawDestroy(r.xftdraw);
2128 XFreeColormap(r.d, cmap);
2130 XDestroyWindow(r.d, r.w);
2133 return status != OK;