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>
11 #include <unistd.h>
12 #include <stdint.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xutil.h> // XLookupString
16 #include <X11/Xresource.h>
17 #include <X11/Xcms.h> // colors
18 #include <X11/keysym.h>
20 #ifdef USE_XINERAMA
21 # include <X11/extensions/Xinerama.h>
22 #endif
24 #ifdef USE_XFT
25 # include <X11/Xft/Xft.h>
26 #endif
28 #ifndef VERSION
29 # define VERSION "unknown"
30 #endif
32 // Comfy
33 #define nil NULL
35 #define resname "MyMenu"
36 #define resclass "mymenu"
38 #define SYM_BUF_SIZE 4
40 #ifdef USE_XFT
41 # define default_fontname "monospace"
42 #else
43 # define default_fontname "fixed"
44 #endif
46 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
51 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
53 // If we don't have it or we don't want an "ignore case" completion
54 // style, fall back to `strstr(3)`
55 #ifndef USE_STRCASESTR
56 # define strcasestr strstr
57 #endif
59 // The number of char to read
60 #define STDIN_CHUNKS 64
62 // the number of lines to allocate in advance
63 #define LINES_CHUNK 32
65 // Abort if a is nil
66 #define check_allocation(a) { \
67 if (a == nil) { \
68 fprintf(stderr, "Could not allocate memory\n"); \
69 abort(); \
70 } \
71 }
73 #define inner_height(r) (r->height - r->border_n - r->border_s)
74 #define inner_width(r) (r->width - r->border_e - r->border_w)
76 // The possible state of the event loop.
77 enum state {LOOPING, OK_LOOP, OK, ERR};
79 // for the drawing-related function. The text to be rendered could be
80 // the prompt, a completion or a highlighted completion
81 enum text_type {PROMPT, COMPL, COMPL_HIGH};
83 // These are the possible action to be performed after user input.
84 enum action {
85 EXIT,
86 CONFIRM,
87 CONFIRM_CONTINUE,
88 NEXT_COMPL,
89 PREV_COMPL,
90 DEL_CHAR,
91 DEL_WORD,
92 DEL_LINE,
93 ADD_CHAR,
94 TOGGLE_FIRST_SELECTED
95 };
97 // A big set of values that needs to be carried around (for drawing
98 // functions). A struct to rule them all
99 struct rendering {
100 Display *d; // connection to xorg
101 Window w;
102 int width;
103 int height;
104 int padding;
105 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
106 int y_zero; // the same a x_zero, only for the y axis
108 size_t offset; // a scrolling offset
110 bool free_text;
111 bool first_selected;
112 bool multiple_select;
114 // The four border
115 int border_n;
116 int border_e;
117 int border_s;
118 int border_w;
120 bool horizontal_layout;
122 // the prompt
123 char *ps1;
124 int ps1len;
126 XIC xic;
128 // colors
129 GC prompt;
130 GC prompt_bg;
131 GC completion;
132 GC completion_bg;
133 GC completion_highlighted;
134 GC completion_highlighted_bg;
135 GC border_n_bg;
136 GC border_e_bg;
137 GC border_s_bg;
138 GC border_w_bg;
139 #ifdef USE_XFT
140 XftFont *font;
141 XftDraw *xftdraw;
142 XftColor xft_prompt;
143 XftColor xft_completion;
144 XftColor xft_completion_highlighted;
145 #else
146 XFontSet *font;
147 #endif
148 };
150 struct completion {
151 char *completion;
152 char *rcompletion;
153 };
155 // Wrap the linked list of completions
156 struct completions {
157 struct completion *completions;
158 ssize_t selected;
159 size_t lenght;
160 };
162 // return a newly allocated (and empty) completion list
163 struct completions *compls_new(size_t lenght) {
164 struct completions *cs = malloc(sizeof(struct completions));
166 if (cs == nil)
167 return cs;
169 cs->completions = calloc(lenght, sizeof(struct completion));
170 if (cs->completions == nil) {
171 free(cs);
172 return nil;
175 cs->selected = -1;
176 cs->lenght = lenght;
177 return cs;
180 /* idea stolen from lemonbar. ty lemonboy */
181 typedef union {
182 struct {
183 uint8_t b;
184 uint8_t g;
185 uint8_t r;
186 uint8_t a;
187 };
188 uint32_t v;
189 } rgba_t;
191 // Delete the wrapper and the whole list
192 void compls_delete(struct completions *cs) {
193 if (cs == nil)
194 return;
196 free(cs->completions);
197 free(cs);
200 // create a completion list from a text and the list of possible
201 // completions (null terminated). Expects a non-null `cs'. lines and
202 // vlines should have the same lenght OR vlines is null
203 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
204 size_t index = 0;
205 size_t matching = 0;
207 if (vlines == nil)
208 vlines = lines;
210 while (true) {
211 char *l = vlines[index] != nil ? vlines[index] : lines[index];
212 if (l == nil)
213 break;
215 if (strcasestr(l, text) != nil) {
216 struct completion *c = &cs->completions[matching];
217 c->completion = l;
218 c->rcompletion = lines[index];
219 matching++;
222 index++;
224 cs->lenght = matching;
225 cs->selected = -1;
228 // update the given completion, that is: clean the old cs & generate a new one.
229 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
230 filter(cs, text, lines, vlines);
231 if (first_selected && cs->lenght > 0)
232 cs->selected = 0;
235 // select the next, or the previous, selection and update some
236 // state. `text' will be updated with the text of the completion and
237 // `textlen' with the new lenght of `text'. If the memory cannot be
238 // allocated, `status' will be set to `ERR'.
239 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
240 if (cs == nil || cs->lenght == 0)
241 return;
243 // if the first is always selected, and the first entry is different
244 // from the text, expand the text and return
245 if (first_selected
246 && cs->selected == 0
247 && strcmp(cs->completions->completion, *text) != 0
248 && !p) {
249 free(*text);
250 *text = strdup(cs->completions->completion);
251 if (text == nil) {
252 *status = ERR;
253 return;
255 *textlen = strlen(*text);
256 return;
259 int index = cs->selected;
261 if (index == -1 && p)
262 index = 0;
263 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
265 struct completion *n = &cs->completions[cs->selected];
267 free(*text);
268 *text = strdup(n->completion);
269 if (text == nil) {
270 fprintf(stderr, "Memory allocation error!\n");
271 *status = ERR;
272 return;
274 *textlen = strlen(*text);
277 // push the character c at the end of the string pointed by p
278 int pushc(char **p, int maxlen, char c) {
279 int len = strnlen(*p, maxlen);
281 if (!(len < maxlen -2)) {
282 maxlen += maxlen >> 1;
283 char *newptr = realloc(*p, maxlen);
284 if (newptr == nil) { // bad!
285 return -1;
287 *p = newptr;
290 (*p)[len] = c;
291 (*p)[len+1] = '\0';
292 return maxlen;
295 // remove the last rune from the *utf8* string! This is different from
296 // just setting the last byte to 0 (in some cases ofc). Return a
297 // pointer (e) to the last non zero char. If e < p then p is empty!
298 char* popc(char *p) {
299 int len = strlen(p);
300 if (len == 0)
301 return p;
303 char *e = p + len - 1;
305 do {
306 char c = *e;
307 *e = 0;
308 e--;
310 // if c is a starting byte (11......) or is under U+007F (ascii,
311 // basically) we're done
312 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
313 break;
314 } while (e >= p);
316 return e;
319 // remove the last word plus trailing whitespaces from the give string
320 void popw(char *w) {
321 int len = strlen(w);
322 if (len == 0)
323 return;
325 bool in_word = true;
326 while (true) {
327 char *e = popc(w);
329 if (e < w)
330 return;
332 if (in_word && isspace(*e))
333 in_word = false;
335 if (!in_word && !isspace(*e))
336 return;
340 // If the string is surrounded by quotes (`"`) remove them and replace
341 // every `\"` in the string with `"`
342 char *normalize_str(const char *str) {
343 int len = strlen(str);
344 if (len == 0)
345 return nil;
347 char *s = calloc(len, sizeof(char));
348 check_allocation(s);
349 int p = 0;
350 while (*str) {
351 char c = *str;
352 if (*str == '\\') {
353 if (*(str + 1)) {
354 s[p] = *(str + 1);
355 p++;
356 str += 2; // skip this and the next char
357 continue;
358 } else {
359 break;
362 if (c == '"') {
363 str++; // skip only this char
364 continue;
366 s[p] = c;
367 p++;
368 str++;
370 return s;
373 size_t read_stdin(char **buf) {
374 size_t offset = 0;
375 size_t len = STDIN_CHUNKS;
376 *buf = malloc(len * sizeof(char));
377 if (*buf == nil)
378 goto err;
380 while (true) {
381 ssize_t r = read(0, *buf + offset, STDIN_CHUNKS);
382 if (r < 1)
383 return len;
385 offset += r;
387 len += STDIN_CHUNKS;
388 *buf = realloc(*buf, len);
389 if (*buf == nil)
390 goto err;
392 for (size_t i = offset; i < len; ++i)
393 (*buf)[i] = '\0';
396 err:
397 fprintf(stderr, "Error in allocating memory for stdin.\n");
398 exit(EX_UNAVAILABLE);
401 //
402 size_t readlines(char ***lns, char **buf) {
403 *buf = nil;
404 size_t len = read_stdin(buf);
406 size_t ll = LINES_CHUNK;
407 *lns = malloc(ll * sizeof(char*));
408 size_t lines = 0;
409 bool in_line = false;
410 for (size_t i = 0; i < len; i++) {
411 char c = (*buf)[i];
413 if (c == '\0')
414 break;
416 if (c == '\n')
417 (*buf)[i] = '\0';
419 if (in_line && c == '\n')
420 in_line = false;
422 if (!in_line && c != '\n') {
423 in_line = true;
424 (*lns)[lines] = (*buf) + i;
425 lines++;
427 if (lines == ll) { // resize
428 ll += LINES_CHUNK;
429 *lns = realloc(*lns, ll * sizeof(char*));
430 if (*lns == nil) {
431 fprintf(stderr, "Error in memory allocation.\n");
432 exit(EX_UNAVAILABLE);
438 return lines;
441 // Compute the dimension of the string str once rendered, return the
442 // width and save the width and the height in ret_width and ret_height
443 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
444 int height;
445 int width;
446 #ifdef USE_XFT
447 XGlyphInfo gi;
448 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
449 height = r->font->ascent - r->font->descent;
450 width = gi.width - gi.x;
451 #else
452 XRectangle rect;
453 XmbTextExtents(*r->font, str, len, nil, &rect);
454 height = rect.height;
455 width = rect.width;
456 #endif
457 if (ret_width != nil) *ret_width = width;
458 if (ret_height != nil) *ret_height = height;
459 return width;
462 // Draw the string str
463 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
464 #ifdef USE_XFT
465 XftColor xftcolor;
466 if (tt == PROMPT) xftcolor = r->xft_prompt;
467 if (tt == COMPL) xftcolor = r->xft_completion;
468 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
470 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
471 #else
472 GC gc;
473 if (tt == PROMPT) gc = r->prompt;
474 if (tt == COMPL) gc = r->completion;
475 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
476 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
477 #endif
480 // Duplicate the string str and substitute every space with a 'n'
481 char *strdupn(char *str) {
482 int len = strlen(str);
484 if (str == nil || len == 0)
485 return nil;
487 char *dup = strdup(str);
488 if (dup == nil)
489 return nil;
491 for (int i = 0; i < len; ++i)
492 if (dup[i] == ' ')
493 dup[i] = 'n';
495 return dup;
498 // |------------------|----------------------------------------------|
499 // | 20 char text | completion | completion | completion | compl |
500 // |------------------|----------------------------------------------|
501 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
502 int prompt_width = 20; // char
504 char *ps1dup = strdupn(r->ps1);
505 int width, height;
506 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
507 free(ps1dup);
508 int start_at = ps1xlen;
510 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
511 start_at = start_at * prompt_width + r->padding;
513 int texty = (inner_height(r) + height + r->y_zero) / 2;
515 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
517 int text_len = strlen(text);
518 if (text_len > prompt_width)
519 text = text + (text_len - prompt_width);
520 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
521 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
523 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
525 for (size_t i = r->offset; i < cs->lenght; ++i) {
526 struct completion *c = &cs->completions[i];
528 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
529 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
531 int len = strlen(c->completion);
532 int text_width = text_extents(c->completion, len, r, nil, nil);
534 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
536 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
538 start_at += text_width + r->padding * 2;
540 if (start_at > inner_width(r))
541 break; // don't draw completion if the space isn't enough
545 // |-----------------------------------------------------------------|
546 // | prompt |
547 // |-----------------------------------------------------------------|
548 // | completion |
549 // |-----------------------------------------------------------------|
550 // | completion |
551 // |-----------------------------------------------------------------|
552 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
553 int height, width;
554 text_extents("fjpgl", 5, r, nil, &height);
555 int start_at = r->padding*2 + height;
557 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
558 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
560 char *ps1dup = strdupn(r->ps1);
561 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, nil, nil);
562 free(ps1dup);
564 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
565 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
567 start_at += r->y_zero;
569 for (size_t i = r->offset; i < cs->lenght; ++i){
570 struct completion *c = &cs->completions[i];
571 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
572 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
574 int len = strlen(c->completion);
575 text_extents(c->completion, len, r, &width, &height);
576 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
577 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
579 start_at += height + r->padding *2;
581 if (start_at > inner_height(r))
582 break; // don't draw completion if the space isn't enough
586 void draw(struct rendering *r, char *text, struct completions *cs) {
587 if (r->horizontal_layout)
588 draw_horizontally(r, text, cs);
589 else
590 draw_vertically(r, text, cs);
592 // draw the borders
594 if (r->border_w != 0)
595 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
597 if (r->border_e != 0)
598 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
600 if (r->border_n != 0)
601 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
603 if (r->border_s != 0)
604 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
606 // send all the work to x
607 XFlush(r->d);
610 /* Set some WM stuff */
611 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
612 Atom type;
613 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
614 XChangeProperty(
615 d,
616 w,
617 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
618 XInternAtom(d, "ATOM", false),
619 32,
620 PropModeReplace,
621 (unsigned char *)&type,
623 );
625 /* some window managers honor this properties */
626 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
627 XChangeProperty(d,
628 w,
629 XInternAtom(d, "_NET_WM_STATE", false),
630 XInternAtom(d, "ATOM", false),
631 32,
632 PropModeReplace,
633 (unsigned char *)&type,
635 );
637 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
638 XChangeProperty(d,
639 w,
640 XInternAtom(d, "_NET_WM_STATE", false),
641 XInternAtom(d, "ATOM", false),
642 32,
643 PropModeAppend,
644 (unsigned char *)&type,
646 );
648 // setting window hints
649 XClassHint *class_hint = XAllocClassHint();
650 if (class_hint == nil) {
651 fprintf(stderr, "Could not allocate memory for class hint\n");
652 exit(EX_UNAVAILABLE);
654 class_hint->res_name = resname;
655 class_hint->res_class = resclass;
656 XSetClassHint(d, w, class_hint);
657 XFree(class_hint);
659 XSizeHints *size_hint = XAllocSizeHints();
660 if (size_hint == nil) {
661 fprintf(stderr, "Could not allocate memory for size hint\n");
662 exit(EX_UNAVAILABLE);
664 size_hint->flags = PMinSize | PBaseSize;
665 size_hint->min_width = width;
666 size_hint->base_width = width;
667 size_hint->min_height = height;
668 size_hint->base_height = height;
670 XFlush(d);
673 // write the width and height of the window `w' respectively in `width'
674 // and `height'.
675 void get_wh(Display *d, Window *w, int *width, int *height) {
676 XWindowAttributes win_attr;
677 XGetWindowAttributes(d, *w, &win_attr);
678 *height = win_attr.height;
679 *width = win_attr.width;
682 int grabfocus(Display *d, Window w) {
683 for (int i = 0; i < 100; ++i) {
684 Window focuswin;
685 int revert_to_win;
686 XGetInputFocus(d, &focuswin, &revert_to_win);
687 if (focuswin == w)
688 return true;
689 XSetInputFocus(d, w, RevertToParent, CurrentTime);
690 usleep(1000);
692 return 0;
695 // I know this may seem a little hackish BUT is the only way I managed
696 // to actually grab that goddam keyboard. Only one call to
697 // XGrabKeyboard does not always end up with the keyboard grabbed!
698 int take_keyboard(Display *d, Window w) {
699 int i;
700 for (i = 0; i < 100; i++) {
701 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
702 return 1;
703 usleep(1000);
705 fprintf(stderr, "Cannot grab keyboard\n");
706 return 0;
709 // release the keyboard.
710 void release_keyboard(Display *d) {
711 XUngrabKeyboard(d, CurrentTime);
714 unsigned long parse_color(const char *str, const char *def) {
715 if (str == nil)
716 goto invc;
718 size_t len = strlen(str);
720 // +1 for the '#' at the start, hence 9 and 4 (instead of 8 and 3)
721 if (*str != '#' || len > 9 || len < 4)
722 goto invc;
723 ++str; // skip the '#'
725 char *ep;
726 errno = 0;
727 rgba_t tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
729 if (errno)
730 goto invc;
732 switch (len-1) {
733 case 3:
734 // expand: #rgb -> #rrggbb
735 tmp.v = (tmp.v & 0xf00) * 0x1100
736 | (tmp.v & 0x0f0) * 0x0110
737 | (tmp.v & 0x00f) * 0x0011;
738 case 6:
739 // assume it has 100% opacity
740 tmp.a = 0xff;
741 break;
742 } // colors in aarrggbb format needs no fixes
744 // premultiply the alpha
745 if (tmp.a) {
746 tmp.r = (tmp.r * tmp.a) / 255;
747 tmp.g = (tmp.g * tmp.a) / 255;
748 tmp.b = (tmp.b * tmp.a) / 255;
749 return tmp.v;
752 return 0U;
754 invc:
755 fprintf(stderr, "Invalid color: \"%s\".\n", str);
756 if (def != nil)
757 return parse_color(def, nil);
758 else
759 return 0U;
762 // Given a string, try to parse it as a number or return
763 // `default_value'.
764 int parse_integer(const char *str, int default_value) {
765 errno = 0;
766 char *ep;
767 long lval = strtol(str, &ep, 10);
768 if (str[0] == '\0' || *ep != '\0') { // NaN
769 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
770 return default_value;
772 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
773 (lval > INT_MAX || lval < INT_MIN)) {
774 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
775 return default_value;
777 return lval;
780 // like parse_integer, but if the value ends with a `%' then its
781 // treated like a percentage (`max' is used to compute the percentage)
782 int parse_int_with_percentage(const char *str, int default_value, int max) {
783 int len = strlen(str);
784 if (len > 0 && str[len-1] == '%') {
785 char *cpy = strdup(str);
786 check_allocation(cpy);
787 cpy[len-1] = '\0';
788 int val = parse_integer(cpy, default_value);
789 free(cpy);
790 return val * max / 100;
792 return parse_integer(str, default_value);
795 // like parse_int_with_percentage but understands some special values
796 // - "middle" that is (max - self) / 2
797 // - "start" that is 0
798 // - "end" that is (max - self)
799 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
800 if (!strcmp(str, "start"))
801 return 0;
802 if (!strcmp(str, "middle"))
803 return (max - self)/2;
804 if (!strcmp(str, "end"))
805 return max-self;
806 return parse_int_with_percentage(str, default_value, max);
809 // parse a string like a css value (for example like the css
810 // margin/padding properties). Will ALWAYS return an array of 4 word
811 // TODO: harden this function!
812 char **parse_csslike(const char *str) {
813 char *s = strdup(str);
814 if (s == nil)
815 return nil;
817 char **ret = malloc(4 * sizeof(char*));
818 if (ret == nil) {
819 free(s);
820 return nil;
823 int i = 0;
824 char *token;
825 while ((token = strsep(&s, " ")) != NULL && i < 4) {
826 ret[i] = strdup(token);
827 i++;
830 if (i == 1)
831 for (int j = 1; j < 4; j++)
832 ret[j] = strdup(ret[0]);
834 if (i == 2) {
835 ret[2] = strdup(ret[0]);
836 ret[3] = strdup(ret[1]);
839 if (i == 3)
840 ret[3] = strdup(ret[1]);
842 // Before we didn't check for the return type of strdup, here we will
844 bool any_null = false;
845 for (int i = 0; i < 4; ++i)
846 any_null = ret[i] == nil || any_null;
848 if (any_null)
849 for (int i = 0; i < 4; ++i)
850 if (ret[i] != nil)
851 free(ret[i]);
853 if (i == 0 || any_null) {
854 free(s);
855 free(ret);
856 return nil;
859 return ret;
862 // Given an event, try to understand what the user wants. If the
863 // return value is ADD_CHAR then `input' is a pointer to a string that
864 // will need to be free'ed.
865 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
866 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
867 return DEL_CHAR;
869 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
870 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
872 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
873 return CONFIRM;
875 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
876 return EXIT;
878 // try to read what the user pressed
879 char str[SYM_BUF_SIZE] = {0};
880 Status s = 0;
881 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
882 if (s == XBufferOverflow) {
883 // should not happen since there are no utf-8 characters larger
884 // than 24bits
885 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
886 return EXIT;
889 if (ev->state & ControlMask) {
890 if (!strcmp(str, "")) // C-u
891 return DEL_LINE;
892 if (!strcmp(str, "")) // C-w
893 return DEL_WORD;
894 if (!strcmp(str, "")) // C-h
895 return DEL_CHAR;
896 if (!strcmp(str, "\r")) // C-m
897 return CONFIRM_CONTINUE;
898 if (!strcmp(str, "")) // C-p
899 return PREV_COMPL;
900 if (!strcmp(str, "")) // C-n
901 return NEXT_COMPL;
902 if (!strcmp(str, "")) // C-c
903 return EXIT;
904 if (!strcmp(str, "\t")) // C-i
905 return TOGGLE_FIRST_SELECTED;
908 *input = strdup(str);
909 if (*input == nil) {
910 fprintf(stderr, "Error while allocating memory for key.\n");
911 return EXIT;
914 return ADD_CHAR;
917 // Given the name of the program (argv[0]?) print a small help on stderr
918 void usage(char *prgname) {
919 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
920 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
921 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
922 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
925 // small function used in the event loop
926 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
927 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
928 // if there is something selected expand it and return
929 int index = cs->selected == -1 ? 0 : cs->selected;
930 struct completion *c = cs->completions;
931 while (true) {
932 if (index == 0)
933 break;
934 c++;
935 index--;
937 char *t = c->rcompletion;
938 free(*text);
939 *text = strdup(t);
940 if (*text == nil) {
941 fprintf(stderr, "Memory allocation error\n");
942 *status = ERR;
944 *textlen = strlen(*text);
945 } else {
946 if (!r->free_text) {
947 // cannot accept arbitrary text
948 *status = LOOPING;
953 // event loop
954 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
955 enum state status = LOOPING;
956 while (status == LOOPING) {
957 XEvent e;
958 XNextEvent(r->d, &e);
960 if (XFilterEvent(&e, r->w))
961 continue;
963 switch (e.type) {
964 case KeymapNotify:
965 XRefreshKeyboardMapping(&e.xmapping);
966 break;
968 case FocusIn:
969 // re-grab focus
970 if (e.xfocus.window != r->w)
971 grabfocus(r->d, r->w);
972 break;
974 case VisibilityNotify:
975 if (e.xvisibility.state != VisibilityUnobscured)
976 XRaiseWindow(r->d, r->w);
977 break;
979 case MapNotify:
980 get_wh(r->d, &r->w, &r->width, &r->height);
981 draw(r, *text, cs);
982 break;
984 case KeyPress: {
985 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
987 char *input;
988 switch (parse_event(r->d, ev, r->xic, &input)) {
989 case EXIT:
990 status = ERR;
991 break;
993 case CONFIRM: {
994 status = OK;
995 confirm(&status, r, cs, text, textlen);
996 break;
999 case CONFIRM_CONTINUE: {
1000 status = OK_LOOP;
1001 confirm(&status, r, cs, text, textlen);
1002 break;
1005 case PREV_COMPL: {
1006 complete(cs, r->first_selected, true, text, textlen, &status);
1007 r->offset = cs->selected;
1008 break;
1011 case NEXT_COMPL: {
1012 complete(cs, r->first_selected, false, text, textlen, &status);
1013 r->offset = cs->selected;
1014 break;
1017 case DEL_CHAR:
1018 popc(*text);
1019 update_completions(cs, *text, lines, vlines, r->first_selected);
1020 r->offset = 0;
1021 break;
1023 case DEL_WORD: {
1024 popw(*text);
1025 update_completions(cs, *text, lines, vlines, r->first_selected);
1026 break;
1029 case DEL_LINE: {
1030 for (int i = 0; i < *textlen; ++i)
1031 *(*text + i) = 0;
1032 update_completions(cs, *text, lines, vlines, r->first_selected);
1033 r->offset = 0;
1034 break;
1037 case ADD_CHAR: {
1038 int str_len = strlen(input);
1040 // sometimes a strange key is pressed (i.e. ctrl alone),
1041 // so input will be empty. Don't need to update completion
1042 // in this case
1043 if (str_len == 0)
1044 break;
1046 for (int i = 0; i < str_len; ++i) {
1047 *textlen = pushc(text, *textlen, input[i]);
1048 if (*textlen == -1) {
1049 fprintf(stderr, "Memory allocation error\n");
1050 status = ERR;
1051 break;
1054 if (status != ERR) {
1055 update_completions(cs, *text, lines, vlines, r->first_selected);
1056 free(input);
1058 r->offset = 0;
1059 break;
1062 case TOGGLE_FIRST_SELECTED:
1063 r->first_selected = !r->first_selected;
1064 if (r->first_selected && cs->selected < 0)
1065 cs->selected = 0;
1066 if (!r->first_selected && cs->selected == 0)
1067 cs->selected = -1;
1068 break;
1072 case ButtonPress: {
1073 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1074 /* if (ev->button == Button1) { /\* click *\/ */
1075 /* int x = ev->x - r.border_w; */
1076 /* int y = ev->y - r.border_n; */
1077 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1078 /* } */
1080 if (ev->button == Button4) /* scroll up */
1081 r->offset = MAX((ssize_t)r->offset - 1, 0);
1083 if (ev->button == Button5) /* scroll down */
1084 r->offset = MIN(r->offset + 1, cs->lenght - 1);
1086 break;
1090 draw(r, *text, cs);
1093 return status;
1096 int main(int argc, char **argv) {
1097 #ifdef __OpenBSD__
1098 // stdio & rpat: to read and write stdio/stdout
1099 // unix: to connect to Xorg
1100 pledge("stdio rpath unix", "");
1101 #endif
1103 char *sep = nil;
1105 // by default the first completion isn't selected
1106 bool first_selected = false;
1108 // our parent window
1109 char *parent_window_id = nil;
1111 // the user can input arbitrary text
1112 bool free_text = true;
1114 // the user can select multiple entries
1115 bool multiple_select = false;
1117 // first round of args parsing
1118 int ch;
1119 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1120 switch (ch) {
1121 case 'h': // help
1122 usage(*argv);
1123 return 0;
1124 case 'v': // version
1125 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1126 return 0;
1127 case 'e': // embed
1128 parent_window_id = strdup(optarg);
1129 check_allocation(parent_window_id);
1130 break;
1131 case 'd': {
1132 sep = strdup(optarg);
1133 check_allocation(sep);
1135 case 'A': {
1136 free_text = false;
1137 break;
1139 case 'm': {
1140 multiple_select = true;
1141 break;
1143 default:
1144 break;
1148 // read the lines from stdin
1149 char **lines = nil;
1150 char *buf = nil;
1151 size_t nlines = readlines(&lines, &buf);
1153 char **vlines = nil;
1154 if (sep != nil) {
1155 int l = strlen(sep);
1156 vlines = calloc(nlines, sizeof(char*));
1157 check_allocation(vlines);
1159 for (int i = 0; lines[i] != nil; i++) {
1160 char *t = strstr(lines[i], sep);
1161 if (t == nil)
1162 vlines[i] = lines[i];
1163 else
1164 vlines[i] = t + l;
1168 setlocale(LC_ALL, getenv("LANG"));
1170 enum state status = LOOPING;
1172 // where the monitor start (used only with xinerama)
1173 int offset_x = 0;
1174 int offset_y = 0;
1176 // width and height of the window
1177 int width = 400;
1178 int height = 20;
1180 // position on the screen
1181 int x = 0;
1182 int y = 0;
1184 // the default padding
1185 int padding = 10;
1187 // the default borders
1188 int border_n = 0;
1189 int border_e = 0;
1190 int border_s = 0;
1191 int border_w = 0;
1193 // the prompt. We duplicate the string so later is easy to free (in
1194 // the case the user provide its own prompt)
1195 char *ps1 = strdup("$ ");
1196 check_allocation(ps1);
1198 // same for the font name
1199 char *fontname = strdup(default_fontname);
1200 check_allocation(fontname);
1202 int textlen = 10;
1203 char *text = malloc(textlen * sizeof(char));
1204 check_allocation(text);
1206 /* struct completions *cs = filter(text, lines); */
1207 struct completions *cs = compls_new(nlines);
1208 check_allocation(cs);
1210 // start talking to xorg
1211 Display *d = XOpenDisplay(nil);
1212 if (d == nil) {
1213 fprintf(stderr, "Could not open display!\n");
1214 return EX_UNAVAILABLE;
1217 Window parent_window;
1218 bool embed = true;
1219 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1220 parent_window = DefaultRootWindow(d);
1221 embed = false;
1224 // get display size
1225 int d_width;
1226 int d_height;
1227 get_wh(d, &parent_window, &d_width, &d_height);
1229 #ifdef USE_XINERAMA
1230 if (!embed && XineramaIsActive(d)) {
1231 // find the mice
1232 int number_of_screens = XScreenCount(d);
1233 Window r;
1234 Window root;
1235 int root_x, root_y, win_x, win_y;
1236 unsigned int mask;
1237 bool res;
1238 for (int i = 0; i < number_of_screens; ++i) {
1239 root = XRootWindow(d, i);
1240 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1241 if (res) break;
1243 if (!res) {
1244 fprintf(stderr, "No mouse found.\n");
1245 root_x = 0;
1246 root_y = 0;
1249 // now find in which monitor the mice is on
1250 int monitors;
1251 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1252 if (info) {
1253 for (int i = 0; i < monitors; ++i) {
1254 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1255 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1256 offset_x = info[i].x_org;
1257 offset_y = info[i].y_org;
1258 d_width = info[i].width;
1259 d_height = info[i].height;
1260 break;
1264 XFree(info);
1266 #endif
1268 /* Colormap cmap = DefaultColormap(d, DefaultScreen(d)); */
1269 XVisualInfo vinfo;
1270 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1272 Colormap cmap;
1273 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1275 unsigned long p_fg = parse_color("#fff", nil);
1276 unsigned long compl_fg = parse_color("#fff", nil);
1277 unsigned long compl_highlighted_fg = parse_color("#000", nil);
1279 unsigned long p_bg = parse_color("#000", nil);
1280 unsigned long compl_bg = parse_color("#000", nil);
1281 unsigned long compl_highlighted_bg = parse_color("#fff", nil);
1283 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1284 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", nil);
1286 bool horizontal_layout = true;
1288 // read resource
1289 XrmInitialize();
1290 char *xrm = XResourceManagerString(d);
1291 XrmDatabase xdb = nil;
1292 if (xrm != nil) {
1293 xdb = XrmGetStringDatabase(xrm);
1294 XrmValue value;
1295 char *datatype[20];
1297 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1298 free(fontname);
1299 fontname = strdup(value.addr);
1300 check_allocation(fontname);
1301 } else {
1302 fprintf(stderr, "no font defined, using %s\n", fontname);
1305 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1306 horizontal_layout = !strcmp(value.addr, "horizontal");
1307 else
1308 fprintf(stderr, "no layout defined, using horizontal\n");
1310 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1311 free(ps1);
1312 ps1 = normalize_str(value.addr);
1313 } else {
1314 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1317 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1318 width = parse_int_with_percentage(value.addr, width, d_width);
1319 else
1320 fprintf(stderr, "no width defined, using %d\n", width);
1322 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1323 height = parse_int_with_percentage(value.addr, height, d_height);
1324 else
1325 fprintf(stderr, "no height defined, using %d\n", height);
1327 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1328 x = parse_int_with_pos(value.addr, x, d_width, width);
1329 else
1330 fprintf(stderr, "no x defined, using %d\n", x);
1332 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1333 y = parse_int_with_pos(value.addr, y, d_height, height);
1334 else
1335 fprintf(stderr, "no y defined, using %d\n", y);
1337 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1338 padding = parse_integer(value.addr, padding);
1339 else
1340 fprintf(stderr, "no padding defined, using %d\n", padding);
1342 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1343 char **borders = parse_csslike(value.addr);
1344 if (borders != nil) {
1345 border_n = parse_integer(borders[0], 0);
1346 border_e = parse_integer(borders[1], 0);
1347 border_s = parse_integer(borders[2], 0);
1348 border_w = parse_integer(borders[3], 0);
1349 } else {
1350 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1352 } else {
1353 fprintf(stderr, "no border defined, using 0.\n");
1356 /* XColor tmp; */
1357 // TODO: tmp needs to be free'd after every allocation?
1359 // prompt
1360 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1361 p_fg = parse_color(value.addr, "#fff");
1363 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1364 p_bg = parse_color(value.addr, "#000");
1366 // completion
1367 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1368 compl_fg = parse_color(value.addr, "#fff");
1370 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1371 compl_bg = parse_color(value.addr, "#000");
1372 else
1373 compl_bg = parse_color("#000", nil);
1375 // completion highlighted
1376 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1377 compl_highlighted_fg = parse_color(value.addr, "#000");
1379 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1380 compl_highlighted_bg = parse_color(value.addr, "#fff");
1381 else
1382 compl_highlighted_bg = parse_color("#fff", nil);
1384 // border
1385 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1386 char **colors = parse_csslike(value.addr);
1387 if (colors != nil) {
1388 border_n_bg = parse_color(colors[0], "#000");
1389 border_e_bg = parse_color(colors[1], "#000");
1390 border_s_bg = parse_color(colors[2], "#000");
1391 border_w_bg = parse_color(colors[3], "#000");
1392 } else {
1393 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1398 // second round of args parsing
1399 optind = 0; // reset the option index
1400 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1401 switch (ch) {
1402 case 'a':
1403 first_selected = true;
1404 break;
1405 case 'A':
1406 // free_text -- this case was already catched
1407 break;
1408 case 'd':
1409 // separator -- this case was already catched
1410 break;
1411 case 'e':
1412 // (embedding mymenu) this case was already catched.
1413 case 'm':
1414 // (multiple selection) this case was already catched.
1415 break;
1416 case 'p': {
1417 char *newprompt = strdup(optarg);
1418 if (newprompt != nil) {
1419 free(ps1);
1420 ps1 = newprompt;
1422 break;
1424 case 'x':
1425 x = parse_int_with_pos(optarg, x, d_width, width);
1426 break;
1427 case 'y':
1428 y = parse_int_with_pos(optarg, y, d_height, height);
1429 break;
1430 case 'P':
1431 padding = parse_integer(optarg, padding);
1432 break;
1433 case 'l':
1434 horizontal_layout = !strcmp(optarg, "horizontal");
1435 break;
1436 case 'f': {
1437 char *newfont = strdup(optarg);
1438 if (newfont != nil) {
1439 free(fontname);
1440 fontname = newfont;
1442 break;
1444 case 'W':
1445 width = parse_int_with_percentage(optarg, width, d_width);
1446 break;
1447 case 'H':
1448 height = parse_int_with_percentage(optarg, height, d_height);
1449 break;
1450 case 'b': {
1451 char **borders = parse_csslike(optarg);
1452 if (borders != nil) {
1453 border_n = parse_integer(borders[0], 0);
1454 border_e = parse_integer(borders[1], 0);
1455 border_s = parse_integer(borders[2], 0);
1456 border_w = parse_integer(borders[3], 0);
1457 } else {
1458 fprintf(stderr, "Error parsing b option\n");
1460 break;
1462 case 'B': {
1463 char **colors = parse_csslike(optarg);
1464 if (colors != nil) {
1465 border_n_bg = parse_color(colors[0], "#000");
1466 border_e_bg = parse_color(colors[1], "#000");
1467 border_s_bg = parse_color(colors[2], "#000");
1468 border_w_bg = parse_color(colors[3], "#000");
1469 } else {
1470 fprintf(stderr, "error while parsing B option\n");
1472 break;
1474 case 't': {
1475 p_fg = parse_color(optarg, nil);
1476 break;
1478 case 'T': {
1479 p_bg = parse_color(optarg, nil);
1480 break;
1482 case 'c': {
1483 compl_fg = parse_color(optarg, nil);
1484 break;
1486 case 'C': {
1487 compl_bg = parse_color(optarg, nil);
1488 break;
1490 case 's': {
1491 compl_highlighted_fg = parse_color(optarg, nil);
1492 break;
1494 case 'S': {
1495 compl_highlighted_bg = parse_color(optarg, nil);
1496 break;
1498 default:
1499 fprintf(stderr, "Unrecognized option %c\n", ch);
1500 status = ERR;
1501 break;
1505 // since only now we know if the first should be selected, update
1506 // the completion here
1507 update_completions(cs, text, lines, vlines, first_selected);
1509 // load the font
1510 #ifdef USE_XFT
1511 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1512 #else
1513 char **missing_charset_list;
1514 int missing_charset_count;
1515 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1516 if (font == nil) {
1517 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1518 return EX_UNAVAILABLE;
1520 #endif
1522 // create the window
1523 XSetWindowAttributes attr;
1524 attr.colormap = cmap;
1525 attr.override_redirect = true;
1526 attr.border_pixel = 0;
1527 attr.background_pixel = 0x80808080;
1528 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1530 Window w = XCreateWindow(d, // display
1531 parent_window, // parent
1532 x + offset_x, y + offset_y, // x y
1533 width, height, // w h
1534 0, // border width
1535 vinfo.depth, // depth
1536 InputOutput, // class
1537 vinfo.visual, // visual
1538 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, // value mask
1539 &attr);
1541 set_win_atoms_hints(d, w, width, height);
1543 // we want some events
1544 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1545 XMapRaised(d, w);
1547 // if embed, listen for other events as well
1548 if (embed) {
1549 XSelectInput(d, parent_window, FocusChangeMask);
1550 Window *children, parent, root;
1551 unsigned int children_no;
1552 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1553 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1554 XSelectInput(d, children[i], FocusChangeMask);
1555 XFree(children);
1557 grabfocus(d, w);
1560 // grab keyboard
1561 take_keyboard(d, w);
1563 // Create some graphics contexts
1564 XGCValues values;
1565 /* values.font = font->fid; */
1567 struct rendering r = {
1568 .d = d,
1569 .w = w,
1570 .width = width,
1571 .height = height,
1572 .padding = padding,
1573 .x_zero = border_w,
1574 .y_zero = border_n,
1575 .offset = 0,
1576 .free_text = free_text,
1577 .first_selected = first_selected,
1578 .multiple_select = multiple_select,
1579 .border_n = border_n,
1580 .border_e = border_e,
1581 .border_s = border_s,
1582 .border_w = border_w,
1583 .horizontal_layout = horizontal_layout,
1584 .ps1 = ps1,
1585 .ps1len = strlen(ps1),
1586 .prompt = XCreateGC(d, w, 0, &values),
1587 .prompt_bg = XCreateGC(d, w, 0, &values),
1588 .completion = XCreateGC(d, w, 0, &values),
1589 .completion_bg = XCreateGC(d, w, 0, &values),
1590 .completion_highlighted = XCreateGC(d, w, 0, &values),
1591 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1592 .border_n_bg = XCreateGC(d, w, 0, &values),
1593 .border_e_bg = XCreateGC(d, w, 0, &values),
1594 .border_s_bg = XCreateGC(d, w, 0, &values),
1595 .border_w_bg = XCreateGC(d, w, 0, &values),
1596 #ifdef USE_XFT
1597 .font = font,
1598 #else
1599 .font = &font,
1600 #endif
1603 #ifdef USE_XFT
1604 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1607 rgba_t c;
1609 XRenderColor xrcolor;
1611 // prompt
1612 c = *(rgba_t*)&p_fg;
1613 xrcolor.red = EXPANDBITS(c.r);
1614 xrcolor.green = EXPANDBITS(c.g);
1615 xrcolor.blue = EXPANDBITS(c.b);
1616 xrcolor.alpha = EXPANDBITS(c.a);
1617 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1619 // completion
1620 c = *(rgba_t*)&compl_fg;
1621 xrcolor.red = EXPANDBITS(c.r);
1622 xrcolor.green = EXPANDBITS(c.g);
1623 xrcolor.blue = EXPANDBITS(c.b);
1624 xrcolor.alpha = EXPANDBITS(c.a);
1625 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1627 // completion highlighted
1628 c = *(rgba_t*)&compl_highlighted_fg;
1629 xrcolor.red = EXPANDBITS(c.r);
1630 xrcolor.green = EXPANDBITS(c.g);
1631 xrcolor.blue = EXPANDBITS(c.b);
1632 xrcolor.alpha = EXPANDBITS(c.a);
1633 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1635 #endif
1637 // load the colors in our GCs
1638 /* XSetForeground(d, r.prompt, p_fg.pixel); */
1639 XSetForeground(d, r.prompt, p_fg);
1640 XSetForeground(d, r.prompt_bg, p_bg);
1641 /* XSetForeground(d, r.completion, compl_fg.pixel); */
1642 XSetForeground(d, r.completion, compl_fg);
1643 XSetForeground(d, r.completion_bg, compl_bg);
1644 /* XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel); */
1645 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1646 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1647 XSetForeground(d, r.border_n_bg, border_n_bg);
1648 XSetForeground(d, r.border_e_bg, border_e_bg);
1649 XSetForeground(d, r.border_s_bg, border_s_bg);
1650 XSetForeground(d, r.border_w_bg, border_w_bg);
1652 // open the X input method
1653 XIM xim = XOpenIM(d, xdb, resname, resclass);
1654 check_allocation(xim);
1656 XIMStyles *xis = nil;
1657 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1658 fprintf(stderr, "Input Styles could not be retrieved\n");
1659 return EX_UNAVAILABLE;
1662 XIMStyle bestMatchStyle = 0;
1663 for (int i = 0; i < xis->count_styles; ++i) {
1664 XIMStyle ts = xis->supported_styles[i];
1665 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1666 bestMatchStyle = ts;
1667 break;
1670 XFree(xis);
1672 if (!bestMatchStyle) {
1673 fprintf(stderr, "No matching input style could be determined\n");
1676 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1677 check_allocation(r.xic);
1679 // draw the window for the first time
1680 draw(&r, text, cs);
1682 // main loop
1683 while (status == LOOPING || status == OK_LOOP) {
1684 status = loop(&r, &text, &textlen, cs, lines, vlines);
1686 if (status != ERR)
1687 printf("%s\n", text);
1689 if (!multiple_select && status == OK_LOOP)
1690 status = OK;
1693 release_keyboard(r.d);
1695 #ifdef USE_XFT
1696 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1697 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1698 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1699 #endif
1701 free(ps1);
1702 free(fontname);
1703 free(text);
1705 free(buf);
1706 free(lines);
1707 free(vlines);
1708 compls_delete(cs);
1710 XDestroyWindow(r.d, r.w);
1711 XCloseDisplay(r.d);
1713 return status != OK;