3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
19 # include <X11/extensions/Xinerama.h>
23 # include <X11/Xft/Xft.h>
27 # define VERSION "unknown"
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
39 # define default_fontname "monospace"
41 # define default_fontname "fixed"
44 #define ARGS "hvae:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:A"
46 #define MIN(a, b) ((a) < (b) ? (a) : (b))
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 // If we don't have it or we don't want an "ignore case" completion
50 // style, fall back to `strstr(3)`
51 #ifndef USE_STRCASESTR
52 # define strcasestr strstr
55 // The initial number of items to read
56 #define INITIAL_ITEMS 64
59 #define check_allocation(a) { \
61 fprintf(stderr, "Could not allocate memory\n"); \
66 #define inner_height(r) (r->height - r->border_n - r->border_s)
67 #define inner_width(r) (r->width - r->border_e - r->border_w)
69 // The possible state of the event loop.
70 enum state {LOOPING, OK, ERR};
72 // for the drawing-related function. The text to be rendered could be
73 // the prompt, a completion or a highlighted completion
74 enum text_type {PROMPT, COMPL, COMPL_HIGH};
76 // These are the possible action to be performed after user input.
89 // A big set of values that needs to be carried around (for drawing
90 // functions). A struct to rule them all
92 Display *d; // connection to xorg
97 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
98 int y_zero; // the same a x_zero, only for the y axis
106 bool horizontal_layout;
117 GC completion_highlighted;
118 GC completion_highlighted_bg;
127 XftColor xft_completion;
128 XftColor xft_completion_highlighted;
134 // A simple linked list to store the completions.
138 struct completion *next;
141 // Wrap the linked list of completions
143 struct completion *completions;
148 // return a newly allocated (and empty) completion list
149 struct completions *compls_new() {
150 struct completions *cs = malloc(sizeof(struct completions));
155 cs->completions = nil;
161 // Return a newly allocated (and empty) completion
162 struct completion *compl_new() {
163 struct completion *c = malloc(sizeof(struct completion));
168 c->rcompletion = nil;
173 // delete ONLY the given completion (i.e. does not free c->next...)
174 void compl_delete(struct completion *c) {
178 // delete the current completion and the next (c->next) and so on...
179 void compl_delete_rec(struct completion *c) {
181 struct completion *t = c->next;
187 // Delete the wrapper and the whole list
188 void compls_delete(struct completions *cs) {
192 compl_delete_rec(cs->completions);
196 // create a completion list from a text and the list of possible
197 // completions (null terminated). Expects a non-null `cs'. lines and
198 // vlines should have the same lenght OR vlines is null
199 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
200 struct completion *c = compl_new();
214 char *l = vlines[index] ? vlines[index] : lines[index];
218 if (strcasestr(l, text) != nil) {
221 c->next = compl_new();
228 c->rcompletion = lines[index];
234 struct completion *f = cs->completions->next;
235 compl_delete(cs->completions);
237 cs->lenght = matching;
241 // update the given completion, that is: clean the old cs & generate a new one.
242 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
243 compl_delete_rec(cs->completions);
244 filter(cs, text, lines, vlines);
245 if (first_selected && cs->lenght > 0)
249 // select the next, or the previous, selection and update some
250 // state. `text' will be updated with the text of the completion and
251 // `textlen' with the new lenght of `text'. If the memory cannot be
252 // allocated, `status' will be set to `ERR'.
253 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
254 if (cs == nil || cs->lenght == 0)
257 // if the first is always selected, and the first entry is different
258 // from the text, expand the text and return
261 && strcmp(cs->completions->completion, *text) != 0
264 *text = strdup(cs->completions->completion);
269 *textlen = strlen(*text);
273 int index = cs->selected;
275 if (index == -1 && p)
277 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
279 struct completion *n = cs->completions;
281 // find the selected item
288 *text = strdup(n->completion);
290 fprintf(stderr, "Memory allocation error!\n");
294 *textlen = strlen(*text);
297 // push the character c at the end of the string pointed by p
298 int pushc(char **p, int maxlen, char c) {
299 int len = strnlen(*p, maxlen);
301 if (!(len < maxlen -2)) {
302 maxlen += maxlen >> 1;
303 char *newptr = realloc(*p, maxlen);
304 if (newptr == nil) { // bad!
315 // remove the last rune from the *utf8* string! This is different from
316 // just setting the last byte to 0 (in some cases ofc). Return a
317 // pointer (e) to the last non zero char. If e < p then p is empty!
318 char* popc(char *p) {
323 char *e = p + len - 1;
330 // if c is a starting byte (11......) or is under U+007F (ascii,
331 // basically) we're done
332 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
339 // remove the last word plus trailing whitespaces from the give string
352 if (in_word && isspace(*e))
355 if (!in_word && !isspace(*e))
360 // If the string is surrounded by quotes (`"`) remove them and replace
361 // every `\"` in the string with `"`
362 char *normalize_str(const char *str) {
363 int len = strlen(str);
367 char *s = calloc(len, sizeof(char));
376 str += 2; // skip this and the next char
383 str++; // skip only this char
393 // read an arbitrary amount of text until an EOF and store it in
394 // lns. `items` is the capacity of lns. It may increase lns with
395 // `realloc(3)` to store more line. Return the number of lines
396 // read. The last item will always be a NULL pointer. It ignore the
397 // "null" (empty) lines
398 int readlines(char ***lns, int items) {
403 ssize_t l = getline(lines + n, &linelen, stdin);
409 if (linelen == 0 || lines[n][0] == '\n') {
412 continue; // forget about this line
415 strtok(lines[n], "\n"); // get rid of the \n
419 if (n == items - 1) {
421 char **l = realloc(lines, sizeof(char*) * items);
433 // Compute the dimension of the string str once rendered, return the
434 // width and save the width and the height in ret_width and ret_height
435 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
440 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
441 /* height = gi.height; */
442 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
443 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
444 height = r->font->ascent - r->font->descent;
445 width = gi.width - gi.x;
448 XmbTextExtents(*r->font, str, len, nil, &rect);
449 height = rect.height;
452 if (ret_width != nil) *ret_width = width;
453 if (ret_height != nil) *ret_height = height;
457 // Draw the string str
458 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
461 if (tt == PROMPT) xftcolor = r->xft_prompt;
462 if (tt == COMPL) xftcolor = r->xft_completion;
463 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
465 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
468 if (tt == PROMPT) gc = r->prompt;
469 if (tt == COMPL) gc = r->completion;
470 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
471 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
475 // Duplicate the string str and substitute every space with a 'n'
476 char *strdupn(char *str) {
477 int len = strlen(str);
479 if (str == nil || len == 0)
482 char *dup = strdup(str);
486 for (int i = 0; i < len; ++i)
493 // |------------------|----------------------------------------------|
494 // | 20 char text | completion | completion | completion | compl |
495 // |------------------|----------------------------------------------|
496 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
497 int prompt_width = 20; // char
500 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
501 int start_at = ps1xlen;
503 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
504 start_at = start_at * prompt_width + r->padding;
506 int texty = (inner_height(r) + height + r->y_zero) / 2;
508 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
510 int text_len = strlen(text);
511 if (text_len > prompt_width)
512 text = text + (text_len - prompt_width);
513 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
514 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
516 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
518 struct completion *c = cs->completions;
519 for (int i = 0; c != nil; ++i) {
520 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
521 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
523 int len = strlen(c->completion);
524 int text_width = text_extents(c->completion, len, r, nil, nil);
526 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
528 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
530 start_at += text_width + r->padding * 2;
532 if (start_at > inner_width(r))
533 break; // don't draw completion if the space isn't enough
539 // |-----------------------------------------------------------------|
541 // |-----------------------------------------------------------------|
543 // |-----------------------------------------------------------------|
545 // |-----------------------------------------------------------------|
546 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
548 text_extents("fjpgl", 5, r, nil, &height);
549 int start_at = r->y_zero + r->padding*2 + height;
551 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
552 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
554 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
556 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
557 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
559 struct completion *c = cs->completions;
560 for (int i = 0; c != nil; ++i){
561 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
562 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
564 int len = strlen(c->completion);
565 text_extents(c->completion, len, r, &width, &height);
566 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
567 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
569 start_at += height + r->padding *2;
571 if (start_at > inner_height(r))
572 break; // don't draw completion if the space isn't enough
578 void draw(struct rendering *r, char *text, struct completions *cs) {
579 if (r->horizontal_layout)
580 draw_horizontally(r, text, cs);
582 draw_vertically(r, text, cs);
586 if (r->border_w != 0)
587 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
589 if (r->border_e != 0)
590 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
592 if (r->border_n != 0)
593 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
595 if (r->border_s != 0)
596 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
598 // send all the work to x
602 /* Set some WM stuff */
603 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
605 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
609 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
610 XInternAtom(d, "ATOM", false),
613 (unsigned char *)&type,
617 /* some window managers honor this properties */
618 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
621 XInternAtom(d, "_NET_WM_STATE", false),
622 XInternAtom(d, "ATOM", false),
625 (unsigned char *)&type,
629 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
632 XInternAtom(d, "_NET_WM_STATE", false),
633 XInternAtom(d, "ATOM", false),
636 (unsigned char *)&type,
640 // setting window hints
641 XClassHint *class_hint = XAllocClassHint();
642 if (class_hint == nil) {
643 fprintf(stderr, "Could not allocate memory for class hint\n");
644 exit(EX_UNAVAILABLE);
646 class_hint->res_name = resname;
647 class_hint->res_class = resclass;
648 XSetClassHint(d, w, class_hint);
651 XSizeHints *size_hint = XAllocSizeHints();
652 if (size_hint == nil) {
653 fprintf(stderr, "Could not allocate memory for size hint\n");
654 exit(EX_UNAVAILABLE);
656 size_hint->flags = PMinSize | PBaseSize;
657 size_hint->min_width = width;
658 size_hint->base_width = width;
659 size_hint->min_height = height;
660 size_hint->base_height = height;
665 // write the width and height of the window `w' respectively in `width'
667 void get_wh(Display *d, Window *w, int *width, int *height) {
668 XWindowAttributes win_attr;
669 XGetWindowAttributes(d, *w, &win_attr);
670 *height = win_attr.height;
671 *width = win_attr.width;
674 int grabfocus(Display *d, Window w) {
675 for (int i = 0; i < 100; ++i) {
678 XGetInputFocus(d, &focuswin, &revert_to_win);
681 XSetInputFocus(d, w, RevertToParent, CurrentTime);
687 // I know this may seem a little hackish BUT is the only way I managed
688 // to actually grab that goddam keyboard. Only one call to
689 // XGrabKeyboard does not always end up with the keyboard grabbed!
690 int take_keyboard(Display *d, Window w) {
692 for (i = 0; i < 100; i++) {
693 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
697 fprintf(stderr, "Cannot grab keyboard\n");
701 // release the keyboard.
702 void release_keyboard(Display *d) {
703 XUngrabKeyboard(d, CurrentTime);
706 // Given a string, try to parse it as a number or return
708 int parse_integer(const char *str, int default_value) {
711 long lval = strtol(str, &ep, 10);
712 if (str[0] == '\0' || *ep != '\0') { // NaN
713 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
714 return default_value;
716 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
717 (lval > INT_MAX || lval < INT_MIN)) {
718 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
719 return default_value;
724 // like parse_integer, but if the value ends with a `%' then its
725 // treated like a percentage (`max' is used to compute the percentage)
726 int parse_int_with_percentage(const char *str, int default_value, int max) {
727 int len = strlen(str);
728 if (len > 0 && str[len-1] == '%') {
729 char *cpy = strdup(str);
730 check_allocation(cpy);
732 int val = parse_integer(cpy, default_value);
734 return val * max / 100;
736 return parse_integer(str, default_value);
739 // like parse_int_with_percentage but understands some special values
740 // - "middle" that is (max - self) / 2
741 // - "start" that is 0
742 // - "end" that is (max - self)
743 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
744 if (!strcmp(str, "start"))
746 if (!strcmp(str, "middle"))
747 return (max - self)/2;
748 if (!strcmp(str, "end"))
750 return parse_int_with_percentage(str, default_value, max);
753 // parse a string like a css value (for example like the css
754 // margin/padding properties). Will ALWAYS return an array of 4 word
755 // TODO: harden this function!
756 char **parse_csslike(const char *str) {
757 char *s = strdup(str);
761 char **ret = malloc(4 * sizeof(char*));
769 while ((token = strsep(&s, " ")) != NULL && i < 4) {
770 ret[i] = strdup(token);
775 for (int j = 1; j < 4; j++)
776 ret[j] = strdup(ret[0]);
779 ret[2] = strdup(ret[0]);
780 ret[3] = strdup(ret[1]);
784 ret[3] = strdup(ret[1]);
786 // Before we didn't check for the return type of strdup, here we will
788 bool any_null = false;
789 for (int i = 0; i < 4; ++i)
790 any_null = ret[i] == nil || any_null;
793 for (int i = 0; i < 4; ++i)
797 if (i == 0 || any_null) {
806 // Given an event, try to understand what the user wants. If the
807 // return value is ADD_CHAR then `input' is a pointer to a string that
808 // will need to be free'ed.
809 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
810 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
813 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
814 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
816 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
819 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
822 // try to read what the user pressed
823 char str[SYM_BUF_SIZE] = {0};
825 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
826 if (s == XBufferOverflow) {
827 // should not happen since there are no utf-8 characters larger
829 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
833 if (ev->state & ControlMask) {
834 if (!strcmp(str, "")) // C-u
836 if (!strcmp(str, "")) // C-w
838 if (!strcmp(str, "")) // C-h
840 if (!strcmp(str, "\r")) // C-m
842 if (!strcmp(str, "")) // C-p
844 if (!strcmp(str, "")) // C-n
846 if (!strcmp(str, "")) // C-c
848 if (!strcmp(str, "\t")) // C-i
849 return TOGGLE_FIRST_SELECTED;
852 *input = strdup(str);
854 fprintf(stderr, "Error while allocating memory for key.\n");
861 // Given the name of the program (argv[0]?) print a small help on stderr
862 void usage(char *prgname) {
863 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
864 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
865 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
866 " [-w window_id]\n", prgname);
869 int main(int argc, char **argv) {
871 // stdio & rpat: to read and write stdio/stdout
872 // unix: to connect to Xorg
873 pledge("stdio rpath unix", "");
878 // by default the first completion isn't selected
879 bool first_selected = false;
882 char *parent_window_id = nil;
884 // the user can input arbitrary text
885 bool free_text = true;
887 // first round of args parsing
889 while ((ch = getopt(argc, argv, ARGS)) != -1) {
895 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
898 parent_window_id = strdup(optarg);
899 check_allocation(parent_window_id);
902 sep = strdup(optarg);
903 check_allocation(sep);
914 // read the lines from stdin
915 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
916 check_allocation(lines);
917 int nlines = readlines(&lines, INITIAL_ITEMS);
921 vlines = calloc(nlines, sizeof(char*));
922 check_allocation(vlines);
924 for (int i = 0; lines[i] != nil; i++) {
925 char *t = strstr(lines[i], sep);
927 vlines[i] = lines[i];
933 setlocale(LC_ALL, getenv("LANG"));
935 enum state status = LOOPING;
937 // where the monitor start (used only with xinerama)
941 // width and height of the window
945 // position on the screen
949 // the default padding
952 // the default borders
958 // the prompt. We duplicate the string so later is easy to free (in
959 // the case the user provide its own prompt)
960 char *ps1 = strdup("$ ");
961 check_allocation(ps1);
963 // same for the font name
964 char *fontname = strdup(default_fontname);
965 check_allocation(fontname);
968 char *text = malloc(textlen * sizeof(char));
969 check_allocation(text);
971 /* struct completions *cs = filter(text, lines); */
972 struct completions *cs = compls_new();
973 check_allocation(cs);
975 // start talking to xorg
976 Display *d = XOpenDisplay(nil);
978 fprintf(stderr, "Could not open display!\n");
979 return EX_UNAVAILABLE;
982 Window parent_window;
984 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
985 parent_window = DefaultRootWindow(d);
992 get_wh(d, &parent_window, &d_width, &d_height);
995 if (!embed && XineramaIsActive(d)) {
997 int number_of_screens = XScreenCount(d);
1000 int root_x, root_y, win_x, win_y;
1003 for (int i = 0; i < number_of_screens; ++i) {
1004 root = XRootWindow(d, i);
1005 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1009 fprintf(stderr, "No mouse found.\n");
1014 // now find in which monitor the mice is on
1016 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1018 for (int i = 0; i < monitors; ++i) {
1019 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1020 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1021 offset_x = info[i].x_org;
1022 offset_y = info[i].y_org;
1023 d_width = info[i].width;
1024 d_height = info[i].height;
1033 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1036 compl_highlighted_fg, compl_highlighted_bg,
1037 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1039 bool horizontal_layout = true;
1043 char *xrm = XResourceManagerString(d);
1044 XrmDatabase xdb = nil;
1046 xdb = XrmGetStringDatabase(xrm);
1050 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1051 fontname = strdup(value.addr);
1052 check_allocation(fontname);
1054 fprintf(stderr, "no font defined, using %s\n", fontname);
1057 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1058 horizontal_layout = !strcmp(value.addr, "horizontal");
1060 fprintf(stderr, "no layout defined, using horizontal\n");
1062 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1064 ps1 = normalize_str(value.addr);
1066 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1069 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1070 width = parse_int_with_percentage(value.addr, width, d_width);
1072 fprintf(stderr, "no width defined, using %d\n", width);
1074 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1075 height = parse_int_with_percentage(value.addr, height, d_height);
1077 fprintf(stderr, "no height defined, using %d\n", height);
1079 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1080 x = parse_int_with_pos(value.addr, x, d_width, width);
1082 fprintf(stderr, "no x defined, using %d\n", x);
1084 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1085 y = parse_int_with_pos(value.addr, y, d_height, height);
1087 fprintf(stderr, "no y defined, using %d\n", y);
1089 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1090 padding = parse_integer(value.addr, padding);
1092 fprintf(stderr, "no padding defined, using %d\n", padding);
1094 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1095 char **borders = parse_csslike(value.addr);
1096 if (borders != nil) {
1097 border_n = parse_integer(borders[0], 0);
1098 border_e = parse_integer(borders[1], 0);
1099 border_s = parse_integer(borders[2], 0);
1100 border_w = parse_integer(borders[3], 0);
1102 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1105 fprintf(stderr, "no border defined, using 0.\n");
1109 // TODO: tmp needs to be free'd after every allocation?
1112 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1113 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1115 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1117 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1118 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1120 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1123 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1124 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1126 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1128 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1129 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1131 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1133 // completion highlighted
1134 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1135 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1137 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1139 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1140 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1142 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1145 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1146 char **colors = parse_csslike(value.addr);
1147 if (colors != nil) {
1148 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1149 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1150 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1151 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1153 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1156 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1157 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1158 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1159 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1163 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1164 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1165 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1166 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1167 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1168 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1169 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1170 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1171 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1174 // second round of args parsing
1175 optind = 0; // reset the option index
1176 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1179 first_selected = true;
1182 // free_text -- this case was already catched
1185 // separator -- this case was already catched
1188 // (embedding mymenu) this case was already catched.
1191 char *newprompt = strdup(optarg);
1192 if (newprompt != nil) {
1199 x = parse_int_with_pos(optarg, x, d_width, width);
1202 y = parse_int_with_pos(optarg, y, d_height, height);
1205 padding = parse_integer(optarg, padding);
1208 horizontal_layout = !strcmp(optarg, "horizontal");
1211 char *newfont = strdup(optarg);
1212 if (newfont != nil) {
1219 width = parse_int_with_percentage(optarg, width, d_width);
1222 height = parse_int_with_percentage(optarg, height, d_height);
1225 char **borders = parse_csslike(optarg);
1226 if (borders != nil) {
1227 border_n = parse_integer(borders[0], 0);
1228 border_e = parse_integer(borders[1], 0);
1229 border_s = parse_integer(borders[2], 0);
1230 border_w = parse_integer(borders[3], 0);
1232 fprintf(stderr, "Error parsing b option\n");
1237 char **colors = parse_csslike(optarg);
1238 if (colors != nil) {
1240 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1241 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1242 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1243 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1245 fprintf(stderr, "error while parsing B option\n");
1251 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1256 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1261 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1266 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1271 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1276 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1280 fprintf(stderr, "Unrecognized option %c\n", ch);
1286 // since only now we know if the first should be selected, update
1287 // the completion here
1288 update_completions(cs, text, lines, vlines, first_selected);
1292 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1294 char **missing_charset_list;
1295 int missing_charset_count;
1296 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1298 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1299 return EX_UNAVAILABLE;
1303 // create the window
1304 XSetWindowAttributes attr;
1305 attr.override_redirect = true;
1306 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1308 Window w = XCreateWindow(d, // display
1309 parent_window, // parent
1310 x + offset_x, y + offset_y, // x y
1311 width, height, // w h
1313 CopyFromParent, // depth
1314 InputOutput, // class
1315 CopyFromParent, // visual
1316 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1319 set_win_atoms_hints(d, w, width, height);
1321 // we want some events
1322 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1325 // if embed, listen for other events as well
1327 XSelectInput(d, parent_window, FocusChangeMask);
1328 Window *children, parent, root;
1329 unsigned int children_no;
1330 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1331 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1332 XSelectInput(d, children[i], FocusChangeMask);
1339 take_keyboard(d, w);
1341 // Create some graphics contexts
1343 /* values.font = font->fid; */
1345 struct rendering r = {
1353 .border_n = border_n,
1354 .border_e = border_e,
1355 .border_s = border_s,
1356 .border_w = border_w,
1357 .horizontal_layout = horizontal_layout,
1359 .ps1len = strlen(ps1),
1360 .prompt = XCreateGC(d, w, 0, &values),
1361 .prompt_bg = XCreateGC(d, w, 0, &values),
1362 .completion = XCreateGC(d, w, 0, &values),
1363 .completion_bg = XCreateGC(d, w, 0, &values),
1364 .completion_highlighted = XCreateGC(d, w, 0, &values),
1365 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1366 .border_n_bg = XCreateGC(d, w, 0, &values),
1367 .border_e_bg = XCreateGC(d, w, 0, &values),
1368 .border_s_bg = XCreateGC(d, w, 0, &values),
1369 .border_w_bg = XCreateGC(d, w, 0, &values),
1378 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1381 XRenderColor xrcolor;
1382 xrcolor.red = p_fg.red;
1383 xrcolor.green = p_fg.red;
1384 xrcolor.blue = p_fg.red;
1385 xrcolor.alpha = 65535;
1386 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1389 xrcolor.red = compl_fg.red;
1390 xrcolor.green = compl_fg.green;
1391 xrcolor.blue = compl_fg.blue;
1392 xrcolor.alpha = 65535;
1393 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1395 // completion highlighted
1396 xrcolor.red = compl_highlighted_fg.red;
1397 xrcolor.green = compl_highlighted_fg.green;
1398 xrcolor.blue = compl_highlighted_fg.blue;
1399 xrcolor.alpha = 65535;
1400 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1403 // load the colors in our GCs
1404 XSetForeground(d, r.prompt, p_fg.pixel);
1405 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1406 XSetForeground(d, r.completion, compl_fg.pixel);
1407 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1408 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1409 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1410 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1411 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1412 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1413 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1415 // open the X input method
1416 XIM xim = XOpenIM(d, xdb, resname, resclass);
1417 check_allocation(xim);
1419 XIMStyles *xis = nil;
1420 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1421 fprintf(stderr, "Input Styles could not be retrieved\n");
1422 return EX_UNAVAILABLE;
1425 XIMStyle bestMatchStyle = 0;
1426 for (int i = 0; i < xis->count_styles; ++i) {
1427 XIMStyle ts = xis->supported_styles[i];
1428 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1429 bestMatchStyle = ts;
1435 if (!bestMatchStyle) {
1436 fprintf(stderr, "No matching input style could be determined\n");
1439 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1440 check_allocation(xic);
1442 // draw the window for the first time
1446 while (status == LOOPING) {
1450 if (XFilterEvent(&e, w))
1455 XRefreshKeyboardMapping(&e.xmapping);
1460 if (e.xfocus.window != w)
1464 case VisibilityNotify:
1465 if (e.xvisibility.state != VisibilityUnobscured)
1470 /* fprintf(stderr, "Map Notify!\n"); */
1471 /* TODO: update the computed window and height! */
1472 /* get_wh(d, &w, width, height); */
1477 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1480 switch (parse_event(d, ev, xic, &input)) {
1487 if ((cs->selected != -1) || (cs->lenght > 0 && first_selected)) {
1488 // if there is something selected expand it and return
1489 int index = cs->selected == -1 ? 0 : cs->selected;
1490 struct completion *c = cs->completions;
1497 char *t = c->rcompletion;
1501 fprintf(stderr, "Memory allocation error\n");
1504 textlen = strlen(text);
1507 // cannot accept arbitrary text
1515 complete(cs, first_selected, true, &text, &textlen, &status);
1520 complete(cs, first_selected, false, &text, &textlen, &status);
1526 update_completions(cs, text, lines, vlines, first_selected);
1531 update_completions(cs, text, lines, vlines, first_selected);
1536 for (int i = 0; i < textlen; ++i)
1538 update_completions(cs, text, lines, vlines, first_selected);
1543 int str_len = strlen(input);
1545 // sometimes a strange key is pressed (i.e. ctrl alone),
1546 // so input will be empty. Don't need to update completion
1551 for (int i = 0; i < str_len; ++i) {
1552 textlen = pushc(&text, textlen, input[i]);
1553 if (textlen == -1) {
1554 fprintf(stderr, "Memory allocation error\n");
1559 if (status != ERR) {
1560 update_completions(cs, text, lines, vlines, first_selected);
1566 case TOGGLE_FIRST_SELECTED:
1567 first_selected = !first_selected;
1568 if (first_selected && cs->selected < 0)
1570 if (!first_selected && cs->selected == 0)
1581 printf("%s\n", text);
1583 release_keyboard(r.d);
1586 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1587 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1588 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1597 while ((l = *lns) != nil) {
1606 XDestroyWindow(r.d, r.w);
1609 return status != OK;