Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #ifndef VERSION
27 # define VERSION "unknown"
28 #endif
30 // Comfy
31 #define nil NULL
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
38 #ifdef USE_XFT
39 # define default_fontname "monospace"
40 #else
41 # define default_fontname "fixed"
42 #endif
44 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
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
53 #endif
55 // The initial number of items to read
56 #define INITIAL_ITEMS 64
58 // Abort if a is nil
59 #define check_allocation(a) { \
60 if (a == nil) { \
61 fprintf(stderr, "Could not allocate memory\n"); \
62 abort(); \
63 } \
64 }
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_LOOP, 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.
77 enum action {
78 EXIT,
79 CONFIRM,
80 CONFIRM_CONTINUE,
81 NEXT_COMPL,
82 PREV_COMPL,
83 DEL_CHAR,
84 DEL_WORD,
85 DEL_LINE,
86 ADD_CHAR,
87 TOGGLE_FIRST_SELECTED
88 };
90 // A big set of values that needs to be carried around (for drawing
91 // functions). A struct to rule them all
92 struct rendering {
93 Display *d; // connection to xorg
94 Window w;
95 int width;
96 int height;
97 int padding;
98 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
99 int y_zero; // the same a x_zero, only for the y axis
101 size_t offset; // a scrolling offset
103 bool free_text;
104 bool first_selected;
105 bool multiple_select;
107 // The four border
108 int border_n;
109 int border_e;
110 int border_s;
111 int border_w;
113 bool horizontal_layout;
115 // the prompt
116 char *ps1;
117 int ps1len;
119 XIC xic;
121 // colors
122 GC prompt;
123 GC prompt_bg;
124 GC completion;
125 GC completion_bg;
126 GC completion_highlighted;
127 GC completion_highlighted_bg;
128 GC border_n_bg;
129 GC border_e_bg;
130 GC border_s_bg;
131 GC border_w_bg;
132 #ifdef USE_XFT
133 XftFont *font;
134 XftDraw *xftdraw;
135 XftColor xft_prompt;
136 XftColor xft_completion;
137 XftColor xft_completion_highlighted;
138 #else
139 XFontSet *font;
140 #endif
141 };
143 struct completion {
144 char *completion;
145 char *rcompletion;
146 };
148 // Wrap the linked list of completions
149 struct completions {
150 struct completion *completions;
151 ssize_t selected;
152 size_t lenght;
153 };
155 // return a newly allocated (and empty) completion list
156 struct completions *compls_new(size_t lenght) {
157 struct completions *cs = malloc(sizeof(struct completions));
159 if (cs == nil)
160 return cs;
162 cs->completions = calloc(lenght, sizeof(struct completion));
163 if (cs->completions == nil) {
164 free(cs);
165 return nil;
168 cs->selected = -1;
169 cs->lenght = lenght;
170 return cs;
173 // Delete the wrapper and the whole list
174 void compls_delete(struct completions *cs) {
175 if (cs == nil)
176 return;
178 free(cs->completions);
179 free(cs);
182 // create a completion list from a text and the list of possible
183 // completions (null terminated). Expects a non-null `cs'. lines and
184 // vlines should have the same lenght OR vlines is null
185 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
186 size_t index = 0;
187 size_t matching = 0;
189 if (vlines == nil)
190 vlines = lines;
192 while (true) {
193 char *l = vlines[index] != nil ? vlines[index] : lines[index];
194 if (l == nil)
195 break;
197 if (strcasestr(l, text) != nil) {
198 struct completion *c = &cs->completions[matching];
199 c->completion = l;
200 c->rcompletion = lines[index];
201 matching++;
204 index++;
206 cs->lenght = matching;
207 cs->selected = -1;
210 // update the given completion, that is: clean the old cs & generate a new one.
211 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
212 filter(cs, text, lines, vlines);
213 if (first_selected && cs->lenght > 0)
214 cs->selected = 0;
217 // select the next, or the previous, selection and update some
218 // state. `text' will be updated with the text of the completion and
219 // `textlen' with the new lenght of `text'. If the memory cannot be
220 // allocated, `status' will be set to `ERR'.
221 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
222 if (cs == nil || cs->lenght == 0)
223 return;
225 // if the first is always selected, and the first entry is different
226 // from the text, expand the text and return
227 if (first_selected
228 && cs->selected == 0
229 && strcmp(cs->completions->completion, *text) != 0
230 && !p) {
231 free(*text);
232 *text = strdup(cs->completions->completion);
233 if (text == nil) {
234 *status = ERR;
235 return;
237 *textlen = strlen(*text);
238 return;
241 int index = cs->selected;
243 if (index == -1 && p)
244 index = 0;
245 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
247 struct completion *n = &cs->completions[cs->selected];
249 free(*text);
250 *text = strdup(n->completion);
251 if (text == nil) {
252 fprintf(stderr, "Memory allocation error!\n");
253 *status = ERR;
254 return;
256 *textlen = strlen(*text);
259 // push the character c at the end of the string pointed by p
260 int pushc(char **p, int maxlen, char c) {
261 int len = strnlen(*p, maxlen);
263 if (!(len < maxlen -2)) {
264 maxlen += maxlen >> 1;
265 char *newptr = realloc(*p, maxlen);
266 if (newptr == nil) { // bad!
267 return -1;
269 *p = newptr;
272 (*p)[len] = c;
273 (*p)[len+1] = '\0';
274 return maxlen;
277 // remove the last rune from the *utf8* string! This is different from
278 // just setting the last byte to 0 (in some cases ofc). Return a
279 // pointer (e) to the last non zero char. If e < p then p is empty!
280 char* popc(char *p) {
281 int len = strlen(p);
282 if (len == 0)
283 return p;
285 char *e = p + len - 1;
287 do {
288 char c = *e;
289 *e = 0;
290 e--;
292 // if c is a starting byte (11......) or is under U+007F (ascii,
293 // basically) we're done
294 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
295 break;
296 } while (e >= p);
298 return e;
301 // remove the last word plus trailing whitespaces from the give string
302 void popw(char *w) {
303 int len = strlen(w);
304 if (len == 0)
305 return;
307 bool in_word = true;
308 while (true) {
309 char *e = popc(w);
311 if (e < w)
312 return;
314 if (in_word && isspace(*e))
315 in_word = false;
317 if (!in_word && !isspace(*e))
318 return;
322 // If the string is surrounded by quotes (`"`) remove them and replace
323 // every `\"` in the string with `"`
324 char *normalize_str(const char *str) {
325 int len = strlen(str);
326 if (len == 0)
327 return nil;
329 char *s = calloc(len, sizeof(char));
330 check_allocation(s);
331 int p = 0;
332 while (*str) {
333 char c = *str;
334 if (*str == '\\') {
335 if (*(str + 1)) {
336 s[p] = *(str + 1);
337 p++;
338 str += 2; // skip this and the next char
339 continue;
340 } else {
341 break;
344 if (c == '"') {
345 str++; // skip only this char
346 continue;
348 s[p] = c;
349 p++;
350 str++;
352 return s;
355 // read an arbitrary amount of text until an EOF and store it in
356 // lns. `items` is the capacity of lns. It may increase lns with
357 // `realloc(3)` to store more line. Return the number of lines
358 // read. The last item will always be a NULL pointer. It ignore the
359 // "null" (empty) lines
360 size_t readlines(char ***lns, size_t items) {
361 size_t n = 0;
362 char **lines = *lns;
363 while (true) {
364 size_t linelen = 0;
365 ssize_t l = getline(lines + n, &linelen, stdin);
367 if (l == -1) {
368 break;
371 if (linelen == 0 || lines[n][0] == '\n') {
372 free(lines[n]);
373 lines[n] = nil;
374 continue; // forget about this line
377 strtok(lines[n], "\n"); // get rid of the \n
379 ++n;
381 if (n == items - 1) {
382 items += items >>1;
383 char **l = realloc(lines, sizeof(char*) * items);
384 check_allocation(l);
385 *lns = l;
386 lines = l;
390 n++;
391 lines[n] = nil;
392 return items;
395 // Compute the dimension of the string str once rendered, return the
396 // width and save the width and the height in ret_width and ret_height
397 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
398 int height;
399 int width;
400 #ifdef USE_XFT
401 XGlyphInfo gi;
402 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
403 height = r->font->ascent - r->font->descent;
404 width = gi.width - gi.x;
405 #else
406 XRectangle rect;
407 XmbTextExtents(*r->font, str, len, nil, &rect);
408 height = rect.height;
409 width = rect.width;
410 #endif
411 if (ret_width != nil) *ret_width = width;
412 if (ret_height != nil) *ret_height = height;
413 return width;
416 // Draw the string str
417 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
418 #ifdef USE_XFT
419 XftColor xftcolor;
420 if (tt == PROMPT) xftcolor = r->xft_prompt;
421 if (tt == COMPL) xftcolor = r->xft_completion;
422 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
424 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
425 #else
426 GC gc;
427 if (tt == PROMPT) gc = r->prompt;
428 if (tt == COMPL) gc = r->completion;
429 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
430 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
431 #endif
434 // Duplicate the string str and substitute every space with a 'n'
435 char *strdupn(char *str) {
436 int len = strlen(str);
438 if (str == nil || len == 0)
439 return nil;
441 char *dup = strdup(str);
442 if (dup == nil)
443 return nil;
445 for (int i = 0; i < len; ++i)
446 if (dup[i] == ' ')
447 dup[i] = 'n';
449 return dup;
452 // |------------------|----------------------------------------------|
453 // | 20 char text | completion | completion | completion | compl |
454 // |------------------|----------------------------------------------|
455 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
456 int prompt_width = 20; // char
458 int width, height;
459 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
460 int start_at = ps1xlen;
462 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
463 start_at = start_at * prompt_width + r->padding;
465 int texty = (inner_height(r) + height + r->y_zero) / 2;
467 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
469 int text_len = strlen(text);
470 if (text_len > prompt_width)
471 text = text + (text_len - prompt_width);
472 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
473 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
475 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
477 for (size_t i = r->offset; i < cs->lenght; ++i) {
478 struct completion *c = &cs->completions[i];
480 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
481 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
483 int len = strlen(c->completion);
484 int text_width = text_extents(c->completion, len, r, nil, nil);
486 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
488 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
490 start_at += text_width + r->padding * 2;
492 if (start_at > inner_width(r))
493 break; // don't draw completion if the space isn't enough
497 // |-----------------------------------------------------------------|
498 // | prompt |
499 // |-----------------------------------------------------------------|
500 // | completion |
501 // |-----------------------------------------------------------------|
502 // | completion |
503 // |-----------------------------------------------------------------|
504 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
505 int height, width;
506 text_extents("fjpgl", 5, r, nil, &height);
507 int start_at = r->padding*2 + height;
509 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
510 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
512 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
514 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
515 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
517 start_at += r->y_zero;
519 for (size_t i = r->offset; i < cs->lenght; ++i){
520 struct completion *c = &cs->completions[i];
521 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
522 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
524 int len = strlen(c->completion);
525 text_extents(c->completion, len, r, &width, &height);
526 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
527 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
529 start_at += height + r->padding *2;
531 if (start_at > inner_height(r))
532 break; // don't draw completion if the space isn't enough
536 void draw(struct rendering *r, char *text, struct completions *cs) {
537 if (r->horizontal_layout)
538 draw_horizontally(r, text, cs);
539 else
540 draw_vertically(r, text, cs);
542 // draw the borders
544 if (r->border_w != 0)
545 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
547 if (r->border_e != 0)
548 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
550 if (r->border_n != 0)
551 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
553 if (r->border_s != 0)
554 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
556 // send all the work to x
557 XFlush(r->d);
560 /* Set some WM stuff */
561 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
562 Atom type;
563 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
564 XChangeProperty(
565 d,
566 w,
567 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
568 XInternAtom(d, "ATOM", false),
569 32,
570 PropModeReplace,
571 (unsigned char *)&type,
573 );
575 /* some window managers honor this properties */
576 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
577 XChangeProperty(d,
578 w,
579 XInternAtom(d, "_NET_WM_STATE", false),
580 XInternAtom(d, "ATOM", false),
581 32,
582 PropModeReplace,
583 (unsigned char *)&type,
585 );
587 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
588 XChangeProperty(d,
589 w,
590 XInternAtom(d, "_NET_WM_STATE", false),
591 XInternAtom(d, "ATOM", false),
592 32,
593 PropModeAppend,
594 (unsigned char *)&type,
596 );
598 // setting window hints
599 XClassHint *class_hint = XAllocClassHint();
600 if (class_hint == nil) {
601 fprintf(stderr, "Could not allocate memory for class hint\n");
602 exit(EX_UNAVAILABLE);
604 class_hint->res_name = resname;
605 class_hint->res_class = resclass;
606 XSetClassHint(d, w, class_hint);
607 XFree(class_hint);
609 XSizeHints *size_hint = XAllocSizeHints();
610 if (size_hint == nil) {
611 fprintf(stderr, "Could not allocate memory for size hint\n");
612 exit(EX_UNAVAILABLE);
614 size_hint->flags = PMinSize | PBaseSize;
615 size_hint->min_width = width;
616 size_hint->base_width = width;
617 size_hint->min_height = height;
618 size_hint->base_height = height;
620 XFlush(d);
623 // write the width and height of the window `w' respectively in `width'
624 // and `height'.
625 void get_wh(Display *d, Window *w, int *width, int *height) {
626 XWindowAttributes win_attr;
627 XGetWindowAttributes(d, *w, &win_attr);
628 *height = win_attr.height;
629 *width = win_attr.width;
632 int grabfocus(Display *d, Window w) {
633 for (int i = 0; i < 100; ++i) {
634 Window focuswin;
635 int revert_to_win;
636 XGetInputFocus(d, &focuswin, &revert_to_win);
637 if (focuswin == w)
638 return true;
639 XSetInputFocus(d, w, RevertToParent, CurrentTime);
640 usleep(1000);
642 return 0;
645 // I know this may seem a little hackish BUT is the only way I managed
646 // to actually grab that goddam keyboard. Only one call to
647 // XGrabKeyboard does not always end up with the keyboard grabbed!
648 int take_keyboard(Display *d, Window w) {
649 int i;
650 for (i = 0; i < 100; i++) {
651 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
652 return 1;
653 usleep(1000);
655 fprintf(stderr, "Cannot grab keyboard\n");
656 return 0;
659 // release the keyboard.
660 void release_keyboard(Display *d) {
661 XUngrabKeyboard(d, CurrentTime);
664 // Given a string, try to parse it as a number or return
665 // `default_value'.
666 int parse_integer(const char *str, int default_value) {
667 errno = 0;
668 char *ep;
669 long lval = strtol(str, &ep, 10);
670 if (str[0] == '\0' || *ep != '\0') { // NaN
671 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
672 return default_value;
674 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
675 (lval > INT_MAX || lval < INT_MIN)) {
676 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
677 return default_value;
679 return lval;
682 // like parse_integer, but if the value ends with a `%' then its
683 // treated like a percentage (`max' is used to compute the percentage)
684 int parse_int_with_percentage(const char *str, int default_value, int max) {
685 int len = strlen(str);
686 if (len > 0 && str[len-1] == '%') {
687 char *cpy = strdup(str);
688 check_allocation(cpy);
689 cpy[len-1] = '\0';
690 int val = parse_integer(cpy, default_value);
691 free(cpy);
692 return val * max / 100;
694 return parse_integer(str, default_value);
697 // like parse_int_with_percentage but understands some special values
698 // - "middle" that is (max - self) / 2
699 // - "start" that is 0
700 // - "end" that is (max - self)
701 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
702 if (!strcmp(str, "start"))
703 return 0;
704 if (!strcmp(str, "middle"))
705 return (max - self)/2;
706 if (!strcmp(str, "end"))
707 return max-self;
708 return parse_int_with_percentage(str, default_value, max);
711 // parse a string like a css value (for example like the css
712 // margin/padding properties). Will ALWAYS return an array of 4 word
713 // TODO: harden this function!
714 char **parse_csslike(const char *str) {
715 char *s = strdup(str);
716 if (s == nil)
717 return nil;
719 char **ret = malloc(4 * sizeof(char*));
720 if (ret == nil) {
721 free(s);
722 return nil;
725 int i = 0;
726 char *token;
727 while ((token = strsep(&s, " ")) != NULL && i < 4) {
728 ret[i] = strdup(token);
729 i++;
732 if (i == 1)
733 for (int j = 1; j < 4; j++)
734 ret[j] = strdup(ret[0]);
736 if (i == 2) {
737 ret[2] = strdup(ret[0]);
738 ret[3] = strdup(ret[1]);
741 if (i == 3)
742 ret[3] = strdup(ret[1]);
744 // Before we didn't check for the return type of strdup, here we will
746 bool any_null = false;
747 for (int i = 0; i < 4; ++i)
748 any_null = ret[i] == nil || any_null;
750 if (any_null)
751 for (int i = 0; i < 4; ++i)
752 if (ret[i] != nil)
753 free(ret[i]);
755 if (i == 0 || any_null) {
756 free(s);
757 free(ret);
758 return nil;
761 return ret;
764 // Given an event, try to understand what the user wants. If the
765 // return value is ADD_CHAR then `input' is a pointer to a string that
766 // will need to be free'ed.
767 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
768 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
769 return DEL_CHAR;
771 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
772 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
774 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
775 return CONFIRM;
777 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
778 return EXIT;
780 // try to read what the user pressed
781 char str[SYM_BUF_SIZE] = {0};
782 Status s = 0;
783 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
784 if (s == XBufferOverflow) {
785 // should not happen since there are no utf-8 characters larger
786 // than 24bits
787 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
788 return EXIT;
791 if (ev->state & ControlMask) {
792 if (!strcmp(str, "")) // C-u
793 return DEL_LINE;
794 if (!strcmp(str, "")) // C-w
795 return DEL_WORD;
796 if (!strcmp(str, "")) // C-h
797 return DEL_CHAR;
798 if (!strcmp(str, "\r")) // C-m
799 return CONFIRM_CONTINUE;
800 if (!strcmp(str, "")) // C-p
801 return PREV_COMPL;
802 if (!strcmp(str, "")) // C-n
803 return NEXT_COMPL;
804 if (!strcmp(str, "")) // C-c
805 return EXIT;
806 if (!strcmp(str, "\t")) // C-i
807 return TOGGLE_FIRST_SELECTED;
810 *input = strdup(str);
811 if (*input == nil) {
812 fprintf(stderr, "Error while allocating memory for key.\n");
813 return EXIT;
816 return ADD_CHAR;
819 // Given the name of the program (argv[0]?) print a small help on stderr
820 void usage(char *prgname) {
821 fprintf(stderr, "%s [-hvam] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
822 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
823 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
824 " [-e window_id]\n", prgname);
827 // small function used in the event loop
828 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
829 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
830 // if there is something selected expand it and return
831 int index = cs->selected == -1 ? 0 : cs->selected;
832 struct completion *c = cs->completions;
833 while (true) {
834 if (index == 0)
835 break;
836 c++;
837 index--;
839 char *t = c->rcompletion;
840 free(*text);
841 *text = strdup(t);
842 if (*text == nil) {
843 fprintf(stderr, "Memory allocation error\n");
844 *status = ERR;
846 *textlen = strlen(*text);
847 } else {
848 if (!r->free_text) {
849 // cannot accept arbitrary text
850 *status = LOOPING;
855 // event loop
856 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
857 enum state status = LOOPING;
858 while (status == LOOPING) {
859 XEvent e;
860 XNextEvent(r->d, &e);
862 if (XFilterEvent(&e, r->w))
863 continue;
865 switch (e.type) {
866 case KeymapNotify:
867 XRefreshKeyboardMapping(&e.xmapping);
868 break;
870 case FocusIn:
871 // re-grab focus
872 if (e.xfocus.window != r->w)
873 grabfocus(r->d, r->w);
874 break;
876 case VisibilityNotify:
877 if (e.xvisibility.state != VisibilityUnobscured)
878 XRaiseWindow(r->d, r->w);
879 break;
881 case MapNotify:
882 get_wh(r->d, &r->w, &r->width, &r->height);
883 draw(r, *text, cs);
884 break;
886 case KeyPress: {
887 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
889 char *input;
890 switch (parse_event(r->d, ev, r->xic, &input)) {
891 case EXIT:
892 status = ERR;
893 break;
895 case CONFIRM: {
896 status = OK;
897 confirm(&status, r, cs, text, textlen);
898 break;
901 case CONFIRM_CONTINUE: {
902 status = OK_LOOP;
903 confirm(&status, r, cs, text, textlen);
904 break;
907 case PREV_COMPL: {
908 complete(cs, r->first_selected, true, text, textlen, &status);
909 r->offset = cs->selected;
910 break;
913 case NEXT_COMPL: {
914 complete(cs, r->first_selected, false, text, textlen, &status);
915 r->offset = cs->selected;
916 break;
919 case DEL_CHAR:
920 popc(*text);
921 update_completions(cs, *text, lines, vlines, r->first_selected);
922 r->offset = 0;
923 break;
925 case DEL_WORD: {
926 popw(*text);
927 update_completions(cs, *text, lines, vlines, r->first_selected);
928 break;
931 case DEL_LINE: {
932 for (int i = 0; i < *textlen; ++i)
933 *text[i] = 0;
934 update_completions(cs, *text, lines, vlines, r->first_selected);
935 r->offset = 0;
936 break;
939 case ADD_CHAR: {
940 int str_len = strlen(input);
942 // sometimes a strange key is pressed (i.e. ctrl alone),
943 // so input will be empty. Don't need to update completion
944 // in this case
945 if (str_len == 0)
946 break;
948 for (int i = 0; i < str_len; ++i) {
949 *textlen = pushc(text, *textlen, input[i]);
950 if (*textlen == -1) {
951 fprintf(stderr, "Memory allocation error\n");
952 status = ERR;
953 break;
956 if (status != ERR) {
957 update_completions(cs, *text, lines, vlines, r->first_selected);
958 free(input);
960 r->offset = 0;
961 break;
964 case TOGGLE_FIRST_SELECTED:
965 r->first_selected = !r->first_selected;
966 if (r->first_selected && cs->selected < 0)
967 cs->selected = 0;
968 if (!r->first_selected && cs->selected == 0)
969 cs->selected = -1;
970 break;
974 case ButtonPress: {
975 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
976 /* if (ev->button == Button1) { /\* click *\/ */
977 /* int x = ev->x - r.border_w; */
978 /* int y = ev->y - r.border_n; */
979 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
980 /* } */
982 if (ev->button == Button4) /* scroll up */
983 r->offset = MAX((ssize_t)r->offset - 1, 0);
985 if (ev->button == Button5) /* scroll down */
986 r->offset = MIN(r->offset + 1, cs->lenght - 1);
988 break;
992 draw(r, *text, cs);
995 return status;
998 int main(int argc, char **argv) {
999 #ifdef HAVE_PLEDGE
1000 // stdio & rpat: to read and write stdio/stdout
1001 // unix: to connect to Xorg
1002 pledge("stdio rpath unix", "");
1003 #endif
1005 char *sep = nil;
1007 // by default the first completion isn't selected
1008 bool first_selected = false;
1010 // our parent window
1011 char *parent_window_id = nil;
1013 // the user can input arbitrary text
1014 bool free_text = true;
1016 // the user can select multiple entries
1017 bool multiple_select = false;
1019 // first round of args parsing
1020 int ch;
1021 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1022 switch (ch) {
1023 case 'h': // help
1024 usage(*argv);
1025 return 0;
1026 case 'v': // version
1027 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1028 return 0;
1029 case 'e': // embed
1030 parent_window_id = strdup(optarg);
1031 check_allocation(parent_window_id);
1032 break;
1033 case 'd': {
1034 sep = strdup(optarg);
1035 check_allocation(sep);
1037 case 'A': {
1038 free_text = false;
1039 break;
1041 case 'm': {
1042 multiple_select = true;
1043 break;
1045 default:
1046 break;
1050 // read the lines from stdin
1051 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
1052 check_allocation(lines);
1053 size_t nlines = readlines(&lines, INITIAL_ITEMS);
1054 char **vlines = nil;
1055 if (sep != nil) {
1056 int l = strlen(sep);
1057 vlines = calloc(nlines, sizeof(char*));
1058 check_allocation(vlines);
1060 for (int i = 0; lines[i] != nil; i++) {
1061 char *t = strstr(lines[i], sep);
1062 if (t == nil)
1063 vlines[i] = lines[i];
1064 else
1065 vlines[i] = t + l;
1069 setlocale(LC_ALL, getenv("LANG"));
1071 enum state status = LOOPING;
1073 // where the monitor start (used only with xinerama)
1074 int offset_x = 0;
1075 int offset_y = 0;
1077 // width and height of the window
1078 int width = 400;
1079 int height = 20;
1081 // position on the screen
1082 int x = 0;
1083 int y = 0;
1085 // the default padding
1086 int padding = 10;
1088 // the default borders
1089 int border_n = 0;
1090 int border_e = 0;
1091 int border_s = 0;
1092 int border_w = 0;
1094 // the prompt. We duplicate the string so later is easy to free (in
1095 // the case the user provide its own prompt)
1096 char *ps1 = strdup("$ ");
1097 check_allocation(ps1);
1099 // same for the font name
1100 char *fontname = strdup(default_fontname);
1101 check_allocation(fontname);
1103 int textlen = 10;
1104 char *text = malloc(textlen * sizeof(char));
1105 check_allocation(text);
1107 /* struct completions *cs = filter(text, lines); */
1108 struct completions *cs = compls_new(nlines);
1109 check_allocation(cs);
1111 // start talking to xorg
1112 Display *d = XOpenDisplay(nil);
1113 if (d == nil) {
1114 fprintf(stderr, "Could not open display!\n");
1115 return EX_UNAVAILABLE;
1118 Window parent_window;
1119 bool embed = true;
1120 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1121 parent_window = DefaultRootWindow(d);
1122 embed = false;
1125 // get display size
1126 int d_width;
1127 int d_height;
1128 get_wh(d, &parent_window, &d_width, &d_height);
1130 #ifdef USE_XINERAMA
1131 if (!embed && XineramaIsActive(d)) {
1132 // find the mice
1133 int number_of_screens = XScreenCount(d);
1134 Window r;
1135 Window root;
1136 int root_x, root_y, win_x, win_y;
1137 unsigned int mask;
1138 bool res;
1139 for (int i = 0; i < number_of_screens; ++i) {
1140 root = XRootWindow(d, i);
1141 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1142 if (res) break;
1144 if (!res) {
1145 fprintf(stderr, "No mouse found.\n");
1146 root_x = 0;
1147 root_y = 0;
1150 // now find in which monitor the mice is on
1151 int monitors;
1152 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1153 if (info) {
1154 for (int i = 0; i < monitors; ++i) {
1155 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1156 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1157 offset_x = info[i].x_org;
1158 offset_y = info[i].y_org;
1159 d_width = info[i].width;
1160 d_height = info[i].height;
1161 break;
1165 XFree(info);
1167 #endif
1169 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1170 XColor p_fg, p_bg,
1171 compl_fg, compl_bg,
1172 compl_highlighted_fg, compl_highlighted_bg,
1173 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1175 bool horizontal_layout = true;
1177 // read resource
1178 XrmInitialize();
1179 char *xrm = XResourceManagerString(d);
1180 XrmDatabase xdb = nil;
1181 if (xrm != nil) {
1182 xdb = XrmGetStringDatabase(xrm);
1183 XrmValue value;
1184 char *datatype[20];
1186 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1187 fontname = strdup(value.addr);
1188 check_allocation(fontname);
1189 } else {
1190 fprintf(stderr, "no font defined, using %s\n", fontname);
1193 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1194 horizontal_layout = !strcmp(value.addr, "horizontal");
1195 else
1196 fprintf(stderr, "no layout defined, using horizontal\n");
1198 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1199 free(ps1);
1200 ps1 = normalize_str(value.addr);
1201 } else {
1202 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1205 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1206 width = parse_int_with_percentage(value.addr, width, d_width);
1207 else
1208 fprintf(stderr, "no width defined, using %d\n", width);
1210 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1211 height = parse_int_with_percentage(value.addr, height, d_height);
1212 else
1213 fprintf(stderr, "no height defined, using %d\n", height);
1215 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1216 x = parse_int_with_pos(value.addr, x, d_width, width);
1217 else
1218 fprintf(stderr, "no x defined, using %d\n", x);
1220 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1221 y = parse_int_with_pos(value.addr, y, d_height, height);
1222 else
1223 fprintf(stderr, "no y defined, using %d\n", y);
1225 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1226 padding = parse_integer(value.addr, padding);
1227 else
1228 fprintf(stderr, "no padding defined, using %d\n", padding);
1230 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1231 char **borders = parse_csslike(value.addr);
1232 if (borders != nil) {
1233 border_n = parse_integer(borders[0], 0);
1234 border_e = parse_integer(borders[1], 0);
1235 border_s = parse_integer(borders[2], 0);
1236 border_w = parse_integer(borders[3], 0);
1237 } else {
1238 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1240 } else {
1241 fprintf(stderr, "no border defined, using 0.\n");
1244 XColor tmp;
1245 // TODO: tmp needs to be free'd after every allocation?
1247 // prompt
1248 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1249 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1250 else
1251 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1253 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1254 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1255 else
1256 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1258 // completion
1259 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1260 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1261 else
1262 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1264 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1265 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1266 else
1267 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1269 // completion highlighted
1270 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1271 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1272 else
1273 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1275 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1276 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1277 else
1278 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1280 // border
1281 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1282 char **colors = parse_csslike(value.addr);
1283 if (colors != nil) {
1284 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1285 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1286 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1287 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1288 } else {
1289 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1291 } else {
1292 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1293 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1294 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1295 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1297 } else {
1298 XColor tmp;
1299 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1300 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1301 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1302 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1303 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1304 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1305 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1306 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1307 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1310 // second round of args parsing
1311 optind = 0; // reset the option index
1312 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1313 switch (ch) {
1314 case 'a':
1315 first_selected = true;
1316 break;
1317 case 'A':
1318 // free_text -- this case was already catched
1319 break;
1320 case 'd':
1321 // separator -- this case was already catched
1322 break;
1323 case 'e':
1324 // (embedding mymenu) this case was already catched.
1325 case 'm':
1326 // (multiple selection) this case was already catched.
1327 break;
1328 case 'p': {
1329 char *newprompt = strdup(optarg);
1330 if (newprompt != nil) {
1331 free(ps1);
1332 ps1 = newprompt;
1334 break;
1336 case 'x':
1337 x = parse_int_with_pos(optarg, x, d_width, width);
1338 break;
1339 case 'y':
1340 y = parse_int_with_pos(optarg, y, d_height, height);
1341 break;
1342 case 'P':
1343 padding = parse_integer(optarg, padding);
1344 break;
1345 case 'l':
1346 horizontal_layout = !strcmp(optarg, "horizontal");
1347 break;
1348 case 'f': {
1349 char *newfont = strdup(optarg);
1350 if (newfont != nil) {
1351 free(fontname);
1352 fontname = newfont;
1354 break;
1356 case 'W':
1357 width = parse_int_with_percentage(optarg, width, d_width);
1358 break;
1359 case 'H':
1360 height = parse_int_with_percentage(optarg, height, d_height);
1361 break;
1362 case 'b': {
1363 char **borders = parse_csslike(optarg);
1364 if (borders != nil) {
1365 border_n = parse_integer(borders[0], 0);
1366 border_e = parse_integer(borders[1], 0);
1367 border_s = parse_integer(borders[2], 0);
1368 border_w = parse_integer(borders[3], 0);
1369 } else {
1370 fprintf(stderr, "Error parsing b option\n");
1372 break;
1374 case 'B': {
1375 char **colors = parse_csslike(optarg);
1376 if (colors != nil) {
1377 XColor tmp;
1378 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1379 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1380 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1381 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1382 } else {
1383 fprintf(stderr, "error while parsing B option\n");
1385 break;
1387 case 't': {
1388 XColor tmp;
1389 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1390 break;
1392 case 'T': {
1393 XColor tmp;
1394 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1395 break;
1397 case 'c': {
1398 XColor tmp;
1399 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1400 break;
1402 case 'C': {
1403 XColor tmp;
1404 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1405 break;
1407 case 's': {
1408 XColor tmp;
1409 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1410 break;
1412 case 'S': {
1413 XColor tmp;
1414 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1415 break;
1417 default:
1418 fprintf(stderr, "Unrecognized option %c\n", ch);
1419 status = ERR;
1420 break;
1424 // since only now we know if the first should be selected, update
1425 // the completion here
1426 update_completions(cs, text, lines, vlines, first_selected);
1428 // load the font
1429 #ifdef USE_XFT
1430 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1431 #else
1432 char **missing_charset_list;
1433 int missing_charset_count;
1434 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1435 if (font == nil) {
1436 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1437 return EX_UNAVAILABLE;
1439 #endif
1441 // create the window
1442 XSetWindowAttributes attr;
1443 attr.override_redirect = true;
1444 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1446 Window w = XCreateWindow(d, // display
1447 parent_window, // parent
1448 x + offset_x, y + offset_y, // x y
1449 width, height, // w h
1450 0, // border width
1451 CopyFromParent, // depth
1452 InputOutput, // class
1453 CopyFromParent, // visual
1454 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1455 &attr);
1457 set_win_atoms_hints(d, w, width, height);
1459 // we want some events
1460 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1461 XMapRaised(d, w);
1463 // if embed, listen for other events as well
1464 if (embed) {
1465 XSelectInput(d, parent_window, FocusChangeMask);
1466 Window *children, parent, root;
1467 unsigned int children_no;
1468 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1469 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1470 XSelectInput(d, children[i], FocusChangeMask);
1471 XFree(children);
1473 grabfocus(d, w);
1476 // grab keyboard
1477 take_keyboard(d, w);
1479 // Create some graphics contexts
1480 XGCValues values;
1481 /* values.font = font->fid; */
1483 struct rendering r = {
1484 .d = d,
1485 .w = w,
1486 .width = width,
1487 .height = height,
1488 .padding = padding,
1489 .x_zero = border_w,
1490 .y_zero = border_n,
1491 .offset = 0,
1492 .free_text = free_text,
1493 .first_selected = first_selected,
1494 .multiple_select = multiple_select,
1495 .border_n = border_n,
1496 .border_e = border_e,
1497 .border_s = border_s,
1498 .border_w = border_w,
1499 .horizontal_layout = horizontal_layout,
1500 .ps1 = ps1,
1501 .ps1len = strlen(ps1),
1502 .prompt = XCreateGC(d, w, 0, &values),
1503 .prompt_bg = XCreateGC(d, w, 0, &values),
1504 .completion = XCreateGC(d, w, 0, &values),
1505 .completion_bg = XCreateGC(d, w, 0, &values),
1506 .completion_highlighted = XCreateGC(d, w, 0, &values),
1507 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1508 .border_n_bg = XCreateGC(d, w, 0, &values),
1509 .border_e_bg = XCreateGC(d, w, 0, &values),
1510 .border_s_bg = XCreateGC(d, w, 0, &values),
1511 .border_w_bg = XCreateGC(d, w, 0, &values),
1512 #ifdef USE_XFT
1513 .font = font,
1514 #else
1515 .font = &font,
1516 #endif
1519 #ifdef USE_XFT
1520 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1522 // prompt
1523 XRenderColor xrcolor;
1524 xrcolor.red = p_fg.red;
1525 xrcolor.green = p_fg.red;
1526 xrcolor.blue = p_fg.red;
1527 xrcolor.alpha = 65535;
1528 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1530 // completion
1531 xrcolor.red = compl_fg.red;
1532 xrcolor.green = compl_fg.green;
1533 xrcolor.blue = compl_fg.blue;
1534 xrcolor.alpha = 65535;
1535 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1537 // completion highlighted
1538 xrcolor.red = compl_highlighted_fg.red;
1539 xrcolor.green = compl_highlighted_fg.green;
1540 xrcolor.blue = compl_highlighted_fg.blue;
1541 xrcolor.alpha = 65535;
1542 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1543 #endif
1545 // load the colors in our GCs
1546 XSetForeground(d, r.prompt, p_fg.pixel);
1547 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1548 XSetForeground(d, r.completion, compl_fg.pixel);
1549 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1550 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1551 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1552 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1553 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1554 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1555 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1557 // open the X input method
1558 XIM xim = XOpenIM(d, xdb, resname, resclass);
1559 check_allocation(xim);
1561 XIMStyles *xis = nil;
1562 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1563 fprintf(stderr, "Input Styles could not be retrieved\n");
1564 return EX_UNAVAILABLE;
1567 XIMStyle bestMatchStyle = 0;
1568 for (int i = 0; i < xis->count_styles; ++i) {
1569 XIMStyle ts = xis->supported_styles[i];
1570 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1571 bestMatchStyle = ts;
1572 break;
1575 XFree(xis);
1577 if (!bestMatchStyle) {
1578 fprintf(stderr, "No matching input style could be determined\n");
1581 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1582 check_allocation(r.xic);
1584 // draw the window for the first time
1585 draw(&r, text, cs);
1587 // main loop
1588 while (status == LOOPING || status == OK_LOOP) {
1589 status = loop(&r, &text, &textlen, cs, lines, vlines);
1591 if (status != ERR)
1592 printf("%s\n", text);
1594 if (!multiple_select && status == OK_LOOP)
1595 status = OK;
1598 release_keyboard(r.d);
1600 #ifdef USE_XFT
1601 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1602 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1603 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1604 #endif
1606 free(ps1);
1607 free(fontname);
1608 free(text);
1610 char *l = nil;
1611 char **lns = lines;
1612 while ((l = *lns) != nil) {
1613 free(l);
1614 ++lns;
1617 free(lines);
1618 free(vlines);
1619 compls_delete(cs);
1621 XDestroyWindow(r.d, r.w);
1622 XCloseDisplay(r.d);
1624 return status != OK;