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 if (lines[index] == nil)
212 break;
214 char *l = vlines[index] != nil ? vlines[index] : lines[index];
216 if (strcasestr(l, text) != nil) {
217 struct completion *c = &cs->completions[matching];
218 c->completion = l;
219 c->rcompletion = lines[index];
220 matching++;
223 index++;
225 cs->lenght = matching;
226 cs->selected = -1;
229 // update the given completion, that is: clean the old cs & generate a new one.
230 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
231 filter(cs, text, lines, vlines);
232 if (first_selected && cs->lenght > 0)
233 cs->selected = 0;
236 // select the next, or the previous, selection and update some
237 // state. `text' will be updated with the text of the completion and
238 // `textlen' with the new lenght of `text'. If the memory cannot be
239 // allocated, `status' will be set to `ERR'.
240 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
241 if (cs == nil || cs->lenght == 0)
242 return;
244 // if the first is always selected, and the first entry is different
245 // from the text, expand the text and return
246 if (first_selected
247 && cs->selected == 0
248 && strcmp(cs->completions->completion, *text) != 0
249 && !p) {
250 free(*text);
251 *text = strdup(cs->completions->completion);
252 if (text == nil) {
253 *status = ERR;
254 return;
256 *textlen = strlen(*text);
257 return;
260 int index = cs->selected;
262 if (index == -1 && p)
263 index = 0;
264 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
266 struct completion *n = &cs->completions[cs->selected];
268 free(*text);
269 *text = strdup(n->completion);
270 if (text == nil) {
271 fprintf(stderr, "Memory allocation error!\n");
272 *status = ERR;
273 return;
275 *textlen = strlen(*text);
278 // push the character c at the end of the string pointed by p
279 int pushc(char **p, int maxlen, char c) {
280 int len = strnlen(*p, maxlen);
282 if (!(len < maxlen -2)) {
283 maxlen += maxlen >> 1;
284 char *newptr = realloc(*p, maxlen);
285 if (newptr == nil) { // bad!
286 return -1;
288 *p = newptr;
291 (*p)[len] = c;
292 (*p)[len+1] = '\0';
293 return maxlen;
296 // remove the last rune from the *utf8* string! This is different from
297 // just setting the last byte to 0 (in some cases ofc). Return a
298 // pointer (e) to the last non zero char. If e < p then p is empty!
299 char* popc(char *p) {
300 int len = strlen(p);
301 if (len == 0)
302 return p;
304 char *e = p + len - 1;
306 do {
307 char c = *e;
308 *e = 0;
309 e--;
311 // if c is a starting byte (11......) or is under U+007F (ascii,
312 // basically) we're done
313 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
314 break;
315 } while (e >= p);
317 return e;
320 // remove the last word plus trailing whitespaces from the give string
321 void popw(char *w) {
322 int len = strlen(w);
323 if (len == 0)
324 return;
326 bool in_word = true;
327 while (true) {
328 char *e = popc(w);
330 if (e < w)
331 return;
333 if (in_word && isspace(*e))
334 in_word = false;
336 if (!in_word && !isspace(*e))
337 return;
341 // If the string is surrounded by quotes (`"`) remove them and replace
342 // every `\"` in the string with `"`
343 char *normalize_str(const char *str) {
344 int len = strlen(str);
345 if (len == 0)
346 return nil;
348 char *s = calloc(len, sizeof(char));
349 check_allocation(s);
350 int p = 0;
351 while (*str) {
352 char c = *str;
353 if (*str == '\\') {
354 if (*(str + 1)) {
355 s[p] = *(str + 1);
356 p++;
357 str += 2; // skip this and the next char
358 continue;
359 } else {
360 break;
363 if (c == '"') {
364 str++; // skip only this char
365 continue;
367 s[p] = c;
368 p++;
369 str++;
371 return s;
374 size_t read_stdin(char **buf) {
375 size_t offset = 0;
376 size_t len = STDIN_CHUNKS;
377 *buf = malloc(len * sizeof(char));
378 if (*buf == nil)
379 goto err;
381 while (true) {
382 ssize_t r = read(0, *buf + offset, STDIN_CHUNKS);
383 if (r < 1)
384 return len;
386 offset += r;
388 len += STDIN_CHUNKS;
389 *buf = realloc(*buf, len);
390 if (*buf == nil)
391 goto err;
393 for (size_t i = offset; i < len; ++i)
394 (*buf)[i] = '\0';
397 err:
398 fprintf(stderr, "Error in allocating memory for stdin.\n");
399 exit(EX_UNAVAILABLE);
402 //
403 size_t readlines(char ***lns, char **buf) {
404 *buf = nil;
405 size_t len = read_stdin(buf);
407 size_t ll = LINES_CHUNK;
408 *lns = malloc(ll * sizeof(char*));
409 if (*lns == nil) goto err;
411 size_t lines = 0;
412 bool in_line = false;
413 for (size_t i = 0; i < len; i++) {
414 char c = (*buf)[i];
416 if (c == '\0')
417 break;
419 if (c == '\n')
420 (*buf)[i] = '\0';
422 if (in_line && c == '\n')
423 in_line = false;
425 if (!in_line && c != '\n') {
426 in_line = true;
427 (*lns)[lines] = (*buf) + i;
428 lines++;
430 if (lines == ll) { // resize
431 ll += LINES_CHUNK;
432 *lns = realloc(*lns, ll * sizeof(char*));
433 if (*lns == nil) goto err;
438 (*lns)[lines] = nil;
440 return lines;
442 err:
443 fprintf(stderr, "Error in memory allocation.\n");
444 exit(EX_UNAVAILABLE);
447 // Compute the dimension of the string str once rendered, return the
448 // width and save the width and the height in ret_width and ret_height
449 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
450 int height;
451 int width;
452 #ifdef USE_XFT
453 XGlyphInfo gi;
454 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
455 height = r->font->ascent - r->font->descent;
456 width = gi.width - gi.x;
457 #else
458 XRectangle rect;
459 XmbTextExtents(*r->font, str, len, nil, &rect);
460 height = rect.height;
461 width = rect.width;
462 #endif
463 if (ret_width != nil) *ret_width = width;
464 if (ret_height != nil) *ret_height = height;
465 return width;
468 // Draw the string str
469 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
470 #ifdef USE_XFT
471 XftColor xftcolor;
472 if (tt == PROMPT) xftcolor = r->xft_prompt;
473 if (tt == COMPL) xftcolor = r->xft_completion;
474 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
476 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
477 #else
478 GC gc;
479 if (tt == PROMPT) gc = r->prompt;
480 if (tt == COMPL) gc = r->completion;
481 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
482 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
483 #endif
486 // Duplicate the string str and substitute every space with a 'n'
487 char *strdupn(char *str) {
488 int len = strlen(str);
490 if (str == nil || len == 0)
491 return nil;
493 char *dup = strdup(str);
494 if (dup == nil)
495 return nil;
497 for (int i = 0; i < len; ++i)
498 if (dup[i] == ' ')
499 dup[i] = 'n';
501 return dup;
504 // |------------------|----------------------------------------------|
505 // | 20 char text | completion | completion | completion | compl |
506 // |------------------|----------------------------------------------|
507 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
508 int prompt_width = 20; // char
510 char *ps1dup = strdupn(r->ps1);
511 int width, height;
512 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
513 free(ps1dup);
514 int start_at = ps1xlen;
516 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
517 start_at = start_at * prompt_width + r->padding;
519 int texty = (inner_height(r) + height + r->y_zero) / 2;
521 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
523 int text_len = strlen(text);
524 if (text_len > prompt_width)
525 text = text + (text_len - prompt_width);
526 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
527 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
529 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
531 for (size_t i = r->offset; i < cs->lenght; ++i) {
532 struct completion *c = &cs->completions[i];
534 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
535 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
537 int len = strlen(c->completion);
538 int text_width = text_extents(c->completion, len, r, nil, nil);
540 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
542 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
544 start_at += text_width + r->padding * 2;
546 if (start_at > inner_width(r))
547 break; // don't draw completion if the space isn't enough
551 // |-----------------------------------------------------------------|
552 // | prompt |
553 // |-----------------------------------------------------------------|
554 // | completion |
555 // |-----------------------------------------------------------------|
556 // | completion |
557 // |-----------------------------------------------------------------|
558 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
559 int height, width;
560 text_extents("fjpgl", 5, r, nil, &height);
561 int start_at = r->padding*2 + height;
563 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
564 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
566 char *ps1dup = strdupn(r->ps1);
567 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, nil, nil);
568 free(ps1dup);
570 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
571 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
573 start_at += r->y_zero;
575 for (size_t i = r->offset; i < cs->lenght; ++i){
576 struct completion *c = &cs->completions[i];
577 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
578 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
580 int len = strlen(c->completion);
581 text_extents(c->completion, len, r, &width, &height);
582 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
583 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
585 start_at += height + r->padding *2;
587 if (start_at > inner_height(r))
588 break; // don't draw completion if the space isn't enough
592 void draw(struct rendering *r, char *text, struct completions *cs) {
593 if (r->horizontal_layout)
594 draw_horizontally(r, text, cs);
595 else
596 draw_vertically(r, text, cs);
598 // draw the borders
600 if (r->border_w != 0)
601 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
603 if (r->border_e != 0)
604 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
606 if (r->border_n != 0)
607 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
609 if (r->border_s != 0)
610 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
612 // send all the work to x
613 XFlush(r->d);
616 /* Set some WM stuff */
617 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
618 Atom type;
619 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
620 XChangeProperty(
621 d,
622 w,
623 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
624 XInternAtom(d, "ATOM", false),
625 32,
626 PropModeReplace,
627 (unsigned char *)&type,
629 );
631 /* some window managers honor this properties */
632 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
633 XChangeProperty(d,
634 w,
635 XInternAtom(d, "_NET_WM_STATE", false),
636 XInternAtom(d, "ATOM", false),
637 32,
638 PropModeReplace,
639 (unsigned char *)&type,
641 );
643 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
644 XChangeProperty(d,
645 w,
646 XInternAtom(d, "_NET_WM_STATE", false),
647 XInternAtom(d, "ATOM", false),
648 32,
649 PropModeAppend,
650 (unsigned char *)&type,
652 );
654 // setting window hints
655 XClassHint *class_hint = XAllocClassHint();
656 if (class_hint == nil) {
657 fprintf(stderr, "Could not allocate memory for class hint\n");
658 exit(EX_UNAVAILABLE);
660 class_hint->res_name = resname;
661 class_hint->res_class = resclass;
662 XSetClassHint(d, w, class_hint);
663 XFree(class_hint);
665 XSizeHints *size_hint = XAllocSizeHints();
666 if (size_hint == nil) {
667 fprintf(stderr, "Could not allocate memory for size hint\n");
668 exit(EX_UNAVAILABLE);
670 size_hint->flags = PMinSize | PBaseSize;
671 size_hint->min_width = width;
672 size_hint->base_width = width;
673 size_hint->min_height = height;
674 size_hint->base_height = height;
676 XFlush(d);
679 // write the width and height of the window `w' respectively in `width'
680 // and `height'.
681 void get_wh(Display *d, Window *w, int *width, int *height) {
682 XWindowAttributes win_attr;
683 XGetWindowAttributes(d, *w, &win_attr);
684 *height = win_attr.height;
685 *width = win_attr.width;
688 int grabfocus(Display *d, Window w) {
689 for (int i = 0; i < 100; ++i) {
690 Window focuswin;
691 int revert_to_win;
692 XGetInputFocus(d, &focuswin, &revert_to_win);
693 if (focuswin == w)
694 return true;
695 XSetInputFocus(d, w, RevertToParent, CurrentTime);
696 usleep(1000);
698 return 0;
701 // I know this may seem a little hackish BUT is the only way I managed
702 // to actually grab that goddam keyboard. Only one call to
703 // XGrabKeyboard does not always end up with the keyboard grabbed!
704 int take_keyboard(Display *d, Window w) {
705 int i;
706 for (i = 0; i < 100; i++) {
707 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
708 return 1;
709 usleep(1000);
711 fprintf(stderr, "Cannot grab keyboard\n");
712 return 0;
715 // release the keyboard.
716 void release_keyboard(Display *d) {
717 XUngrabKeyboard(d, CurrentTime);
720 unsigned long parse_color(const char *str, const char *def) {
721 if (str == nil)
722 goto invc;
724 size_t len = strlen(str);
726 // +1 for the '#' at the start, hence 9 and 4 (instead of 8 and 3)
727 if (*str != '#' || len > 9 || len < 4)
728 goto invc;
729 ++str; // skip the '#'
731 char *ep;
732 errno = 0;
733 rgba_t tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
735 if (errno)
736 goto invc;
738 switch (len-1) {
739 case 3:
740 // expand: #rgb -> #rrggbb
741 tmp.v = (tmp.v & 0xf00) * 0x1100
742 | (tmp.v & 0x0f0) * 0x0110
743 | (tmp.v & 0x00f) * 0x0011;
744 case 6:
745 // assume it has 100% opacity
746 tmp.a = 0xff;
747 break;
748 } // colors in aarrggbb format needs no fixes
750 // premultiply the alpha
751 if (tmp.a) {
752 tmp.r = (tmp.r * tmp.a) / 255;
753 tmp.g = (tmp.g * tmp.a) / 255;
754 tmp.b = (tmp.b * tmp.a) / 255;
755 return tmp.v;
758 return 0U;
760 invc:
761 fprintf(stderr, "Invalid color: \"%s\".\n", str);
762 if (def != nil)
763 return parse_color(def, nil);
764 else
765 return 0U;
768 // Given a string, try to parse it as a number or return
769 // `default_value'.
770 int parse_integer(const char *str, int default_value) {
771 errno = 0;
772 char *ep;
773 long lval = strtol(str, &ep, 10);
774 if (str[0] == '\0' || *ep != '\0') { // NaN
775 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
776 return default_value;
778 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
779 (lval > INT_MAX || lval < INT_MIN)) {
780 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
781 return default_value;
783 return lval;
786 // like parse_integer, but if the value ends with a `%' then its
787 // treated like a percentage (`max' is used to compute the percentage)
788 int parse_int_with_percentage(const char *str, int default_value, int max) {
789 int len = strlen(str);
790 if (len > 0 && str[len-1] == '%') {
791 char *cpy = strdup(str);
792 check_allocation(cpy);
793 cpy[len-1] = '\0';
794 int val = parse_integer(cpy, default_value);
795 free(cpy);
796 return val * max / 100;
798 return parse_integer(str, default_value);
801 // like parse_int_with_percentage but understands some special values
802 // - "middle" that is (max - self) / 2
803 // - "start" that is 0
804 // - "end" that is (max - self)
805 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
806 if (!strcmp(str, "start"))
807 return 0;
808 if (!strcmp(str, "middle"))
809 return (max - self)/2;
810 if (!strcmp(str, "end"))
811 return max-self;
812 return parse_int_with_percentage(str, default_value, max);
815 // parse a string like a css value (for example like the css
816 // margin/padding properties). Will ALWAYS return an array of 4 word
817 // TODO: harden this function!
818 char **parse_csslike(const char *str) {
819 char *s = strdup(str);
820 if (s == nil)
821 return nil;
823 char **ret = malloc(4 * sizeof(char*));
824 if (ret == nil) {
825 free(s);
826 return nil;
829 int i = 0;
830 char *token;
831 while ((token = strsep(&s, " ")) != NULL && i < 4) {
832 ret[i] = strdup(token);
833 i++;
836 if (i == 1)
837 for (int j = 1; j < 4; j++)
838 ret[j] = strdup(ret[0]);
840 if (i == 2) {
841 ret[2] = strdup(ret[0]);
842 ret[3] = strdup(ret[1]);
845 if (i == 3)
846 ret[3] = strdup(ret[1]);
848 // Before we didn't check for the return type of strdup, here we will
850 bool any_null = false;
851 for (int i = 0; i < 4; ++i)
852 any_null = ret[i] == nil || any_null;
854 if (any_null)
855 for (int i = 0; i < 4; ++i)
856 if (ret[i] != nil)
857 free(ret[i]);
859 if (i == 0 || any_null) {
860 free(s);
861 free(ret);
862 return nil;
865 return ret;
868 // Given an event, try to understand what the user wants. If the
869 // return value is ADD_CHAR then `input' is a pointer to a string that
870 // will need to be free'ed.
871 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
872 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
873 return DEL_CHAR;
875 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
876 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
878 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
879 return CONFIRM;
881 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
882 return EXIT;
884 // try to read what the user pressed
885 char str[SYM_BUF_SIZE] = {0};
886 Status s = 0;
887 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
888 if (s == XBufferOverflow) {
889 // should not happen since there are no utf-8 characters larger
890 // than 24bits
891 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
892 return EXIT;
895 if (ev->state & ControlMask) {
896 if (!strcmp(str, "")) // C-u
897 return DEL_LINE;
898 if (!strcmp(str, "")) // C-w
899 return DEL_WORD;
900 if (!strcmp(str, "")) // C-h
901 return DEL_CHAR;
902 if (!strcmp(str, "\r")) // C-m
903 return CONFIRM_CONTINUE;
904 if (!strcmp(str, "")) // C-p
905 return PREV_COMPL;
906 if (!strcmp(str, "")) // C-n
907 return NEXT_COMPL;
908 if (!strcmp(str, "")) // C-c
909 return EXIT;
910 if (!strcmp(str, "\t")) // C-i
911 return TOGGLE_FIRST_SELECTED;
914 *input = strdup(str);
915 if (*input == nil) {
916 fprintf(stderr, "Error while allocating memory for key.\n");
917 return EXIT;
920 return ADD_CHAR;
923 // Given the name of the program (argv[0]?) print a small help on stderr
924 void usage(char *prgname) {
925 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
926 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
927 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
928 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
931 // small function used in the event loop
932 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
933 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
934 // if there is something selected expand it and return
935 int index = cs->selected == -1 ? 0 : cs->selected;
936 struct completion *c = cs->completions;
937 while (true) {
938 if (index == 0)
939 break;
940 c++;
941 index--;
943 char *t = c->rcompletion;
944 free(*text);
945 *text = strdup(t);
946 if (*text == nil) {
947 fprintf(stderr, "Memory allocation error\n");
948 *status = ERR;
950 *textlen = strlen(*text);
951 } else {
952 if (!r->free_text) {
953 // cannot accept arbitrary text
954 *status = LOOPING;
959 // event loop
960 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
961 enum state status = LOOPING;
962 while (status == LOOPING) {
963 XEvent e;
964 XNextEvent(r->d, &e);
966 if (XFilterEvent(&e, r->w))
967 continue;
969 switch (e.type) {
970 case KeymapNotify:
971 XRefreshKeyboardMapping(&e.xmapping);
972 break;
974 case FocusIn:
975 // re-grab focus
976 if (e.xfocus.window != r->w)
977 grabfocus(r->d, r->w);
978 break;
980 case VisibilityNotify:
981 if (e.xvisibility.state != VisibilityUnobscured)
982 XRaiseWindow(r->d, r->w);
983 break;
985 case MapNotify:
986 get_wh(r->d, &r->w, &r->width, &r->height);
987 draw(r, *text, cs);
988 break;
990 case KeyPress: {
991 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
993 char *input;
994 switch (parse_event(r->d, ev, r->xic, &input)) {
995 case EXIT:
996 status = ERR;
997 break;
999 case CONFIRM: {
1000 status = OK;
1001 confirm(&status, r, cs, text, textlen);
1002 break;
1005 case CONFIRM_CONTINUE: {
1006 status = OK_LOOP;
1007 confirm(&status, r, cs, text, textlen);
1008 break;
1011 case PREV_COMPL: {
1012 complete(cs, r->first_selected, true, text, textlen, &status);
1013 r->offset = cs->selected;
1014 break;
1017 case NEXT_COMPL: {
1018 complete(cs, r->first_selected, false, text, textlen, &status);
1019 r->offset = cs->selected;
1020 break;
1023 case DEL_CHAR:
1024 popc(*text);
1025 update_completions(cs, *text, lines, vlines, r->first_selected);
1026 r->offset = 0;
1027 break;
1029 case DEL_WORD: {
1030 popw(*text);
1031 update_completions(cs, *text, lines, vlines, r->first_selected);
1032 break;
1035 case DEL_LINE: {
1036 for (int i = 0; i < *textlen; ++i)
1037 *(*text + i) = 0;
1038 update_completions(cs, *text, lines, vlines, r->first_selected);
1039 r->offset = 0;
1040 break;
1043 case ADD_CHAR: {
1044 int str_len = strlen(input);
1046 // sometimes a strange key is pressed (i.e. ctrl alone),
1047 // so input will be empty. Don't need to update completion
1048 // in this case
1049 if (str_len == 0)
1050 break;
1052 for (int i = 0; i < str_len; ++i) {
1053 *textlen = pushc(text, *textlen, input[i]);
1054 if (*textlen == -1) {
1055 fprintf(stderr, "Memory allocation error\n");
1056 status = ERR;
1057 break;
1060 if (status != ERR) {
1061 update_completions(cs, *text, lines, vlines, r->first_selected);
1062 free(input);
1064 r->offset = 0;
1065 break;
1068 case TOGGLE_FIRST_SELECTED:
1069 r->first_selected = !r->first_selected;
1070 if (r->first_selected && cs->selected < 0)
1071 cs->selected = 0;
1072 if (!r->first_selected && cs->selected == 0)
1073 cs->selected = -1;
1074 break;
1078 case ButtonPress: {
1079 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1080 /* if (ev->button == Button1) { /\* click *\/ */
1081 /* int x = ev->x - r.border_w; */
1082 /* int y = ev->y - r.border_n; */
1083 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1084 /* } */
1086 if (ev->button == Button4) /* scroll up */
1087 r->offset = MAX((ssize_t)r->offset - 1, 0);
1089 if (ev->button == Button5) /* scroll down */
1090 r->offset = MIN(r->offset + 1, cs->lenght - 1);
1092 break;
1096 draw(r, *text, cs);
1099 return status;
1102 int main(int argc, char **argv) {
1103 #ifdef __OpenBSD__
1104 // stdio & rpat: to read and write stdio/stdout
1105 // unix: to connect to Xorg
1106 pledge("stdio rpath unix", "");
1107 #endif
1109 char *sep = nil;
1111 // by default the first completion isn't selected
1112 bool first_selected = false;
1114 // our parent window
1115 char *parent_window_id = nil;
1117 // the user can input arbitrary text
1118 bool free_text = true;
1120 // the user can select multiple entries
1121 bool multiple_select = false;
1123 // first round of args parsing
1124 int ch;
1125 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1126 switch (ch) {
1127 case 'h': // help
1128 usage(*argv);
1129 return 0;
1130 case 'v': // version
1131 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1132 return 0;
1133 case 'e': // embed
1134 parent_window_id = strdup(optarg);
1135 check_allocation(parent_window_id);
1136 break;
1137 case 'd': {
1138 sep = strdup(optarg);
1139 check_allocation(sep);
1141 case 'A': {
1142 free_text = false;
1143 break;
1145 case 'm': {
1146 multiple_select = true;
1147 break;
1149 default:
1150 break;
1154 // read the lines from stdin
1155 char **lines = nil;
1156 char *buf = nil;
1157 size_t nlines = readlines(&lines, &buf);
1159 char **vlines = nil;
1160 if (sep != nil) {
1161 int l = strlen(sep);
1162 vlines = calloc(nlines, sizeof(char*));
1163 check_allocation(vlines);
1165 for (size_t i = 0; i < nlines; i++) {
1166 char *t = strstr(lines[i], sep);
1167 if (t == nil)
1168 vlines[i] = lines[i];
1169 else
1170 vlines[i] = t + l;
1174 setlocale(LC_ALL, getenv("LANG"));
1176 enum state status = LOOPING;
1178 // where the monitor start (used only with xinerama)
1179 int offset_x = 0;
1180 int offset_y = 0;
1182 // width and height of the window
1183 int width = 400;
1184 int height = 20;
1186 // position on the screen
1187 int x = 0;
1188 int y = 0;
1190 // the default padding
1191 int padding = 10;
1193 // the default borders
1194 int border_n = 0;
1195 int border_e = 0;
1196 int border_s = 0;
1197 int border_w = 0;
1199 // the prompt. We duplicate the string so later is easy to free (in
1200 // the case the user provide its own prompt)
1201 char *ps1 = strdup("$ ");
1202 check_allocation(ps1);
1204 // same for the font name
1205 char *fontname = strdup(default_fontname);
1206 check_allocation(fontname);
1208 int textlen = 10;
1209 char *text = malloc(textlen * sizeof(char));
1210 check_allocation(text);
1212 /* struct completions *cs = filter(text, lines); */
1213 struct completions *cs = compls_new(nlines);
1214 check_allocation(cs);
1216 // start talking to xorg
1217 Display *d = XOpenDisplay(nil);
1218 if (d == nil) {
1219 fprintf(stderr, "Could not open display!\n");
1220 return EX_UNAVAILABLE;
1223 Window parent_window;
1224 bool embed = true;
1225 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1226 parent_window = DefaultRootWindow(d);
1227 embed = false;
1230 // get display size
1231 int d_width;
1232 int d_height;
1233 get_wh(d, &parent_window, &d_width, &d_height);
1235 #ifdef USE_XINERAMA
1236 if (!embed && XineramaIsActive(d)) {
1237 // find the mice
1238 int number_of_screens = XScreenCount(d);
1239 Window r;
1240 Window root;
1241 int root_x, root_y, win_x, win_y;
1242 unsigned int mask;
1243 bool res;
1244 for (int i = 0; i < number_of_screens; ++i) {
1245 root = XRootWindow(d, i);
1246 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1247 if (res) break;
1249 if (!res) {
1250 fprintf(stderr, "No mouse found.\n");
1251 root_x = 0;
1252 root_y = 0;
1255 // now find in which monitor the mice is on
1256 int monitors;
1257 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1258 if (info) {
1259 for (int i = 0; i < monitors; ++i) {
1260 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1261 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1262 offset_x = info[i].x_org;
1263 offset_y = info[i].y_org;
1264 d_width = info[i].width;
1265 d_height = info[i].height;
1266 break;
1270 XFree(info);
1272 #endif
1274 /* Colormap cmap = DefaultColormap(d, DefaultScreen(d)); */
1275 XVisualInfo vinfo;
1276 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1278 Colormap cmap;
1279 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1281 unsigned long p_fg = parse_color("#fff", nil);
1282 unsigned long compl_fg = parse_color("#fff", nil);
1283 unsigned long compl_highlighted_fg = parse_color("#000", nil);
1285 unsigned long p_bg = parse_color("#000", nil);
1286 unsigned long compl_bg = parse_color("#000", nil);
1287 unsigned long compl_highlighted_bg = parse_color("#fff", nil);
1289 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1290 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", nil);
1292 bool horizontal_layout = true;
1294 // read resource
1295 XrmInitialize();
1296 char *xrm = XResourceManagerString(d);
1297 XrmDatabase xdb = nil;
1298 if (xrm != nil) {
1299 xdb = XrmGetStringDatabase(xrm);
1300 XrmValue value;
1301 char *datatype[20];
1303 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1304 free(fontname);
1305 fontname = strdup(value.addr);
1306 check_allocation(fontname);
1307 } else {
1308 fprintf(stderr, "no font defined, using %s\n", fontname);
1311 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1312 horizontal_layout = !strcmp(value.addr, "horizontal");
1313 else
1314 fprintf(stderr, "no layout defined, using horizontal\n");
1316 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1317 free(ps1);
1318 ps1 = normalize_str(value.addr);
1319 } else {
1320 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1323 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1324 width = parse_int_with_percentage(value.addr, width, d_width);
1325 else
1326 fprintf(stderr, "no width defined, using %d\n", width);
1328 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1329 height = parse_int_with_percentage(value.addr, height, d_height);
1330 else
1331 fprintf(stderr, "no height defined, using %d\n", height);
1333 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1334 x = parse_int_with_pos(value.addr, x, d_width, width);
1335 else
1336 fprintf(stderr, "no x defined, using %d\n", x);
1338 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1339 y = parse_int_with_pos(value.addr, y, d_height, height);
1340 else
1341 fprintf(stderr, "no y defined, using %d\n", y);
1343 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1344 padding = parse_integer(value.addr, padding);
1345 else
1346 fprintf(stderr, "no padding defined, using %d\n", padding);
1348 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1349 char **borders = parse_csslike(value.addr);
1350 if (borders != nil) {
1351 border_n = parse_integer(borders[0], 0);
1352 border_e = parse_integer(borders[1], 0);
1353 border_s = parse_integer(borders[2], 0);
1354 border_w = parse_integer(borders[3], 0);
1355 } else {
1356 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1358 } else {
1359 fprintf(stderr, "no border defined, using 0.\n");
1362 /* XColor tmp; */
1363 // TODO: tmp needs to be free'd after every allocation?
1365 // prompt
1366 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1367 p_fg = parse_color(value.addr, "#fff");
1369 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1370 p_bg = parse_color(value.addr, "#000");
1372 // completion
1373 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1374 compl_fg = parse_color(value.addr, "#fff");
1376 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1377 compl_bg = parse_color(value.addr, "#000");
1378 else
1379 compl_bg = parse_color("#000", nil);
1381 // completion highlighted
1382 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1383 compl_highlighted_fg = parse_color(value.addr, "#000");
1385 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1386 compl_highlighted_bg = parse_color(value.addr, "#fff");
1387 else
1388 compl_highlighted_bg = parse_color("#fff", nil);
1390 // border
1391 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1392 char **colors = parse_csslike(value.addr);
1393 if (colors != nil) {
1394 border_n_bg = parse_color(colors[0], "#000");
1395 border_e_bg = parse_color(colors[1], "#000");
1396 border_s_bg = parse_color(colors[2], "#000");
1397 border_w_bg = parse_color(colors[3], "#000");
1398 } else {
1399 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1404 // second round of args parsing
1405 optind = 0; // reset the option index
1406 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1407 switch (ch) {
1408 case 'a':
1409 first_selected = true;
1410 break;
1411 case 'A':
1412 // free_text -- this case was already catched
1413 break;
1414 case 'd':
1415 // separator -- this case was already catched
1416 break;
1417 case 'e':
1418 // (embedding mymenu) this case was already catched.
1419 case 'm':
1420 // (multiple selection) this case was already catched.
1421 break;
1422 case 'p': {
1423 char *newprompt = strdup(optarg);
1424 if (newprompt != nil) {
1425 free(ps1);
1426 ps1 = newprompt;
1428 break;
1430 case 'x':
1431 x = parse_int_with_pos(optarg, x, d_width, width);
1432 break;
1433 case 'y':
1434 y = parse_int_with_pos(optarg, y, d_height, height);
1435 break;
1436 case 'P':
1437 padding = parse_integer(optarg, padding);
1438 break;
1439 case 'l':
1440 horizontal_layout = !strcmp(optarg, "horizontal");
1441 break;
1442 case 'f': {
1443 char *newfont = strdup(optarg);
1444 if (newfont != nil) {
1445 free(fontname);
1446 fontname = newfont;
1448 break;
1450 case 'W':
1451 width = parse_int_with_percentage(optarg, width, d_width);
1452 break;
1453 case 'H':
1454 height = parse_int_with_percentage(optarg, height, d_height);
1455 break;
1456 case 'b': {
1457 char **borders = parse_csslike(optarg);
1458 if (borders != nil) {
1459 border_n = parse_integer(borders[0], 0);
1460 border_e = parse_integer(borders[1], 0);
1461 border_s = parse_integer(borders[2], 0);
1462 border_w = parse_integer(borders[3], 0);
1463 } else {
1464 fprintf(stderr, "Error parsing b option\n");
1466 break;
1468 case 'B': {
1469 char **colors = parse_csslike(optarg);
1470 if (colors != nil) {
1471 border_n_bg = parse_color(colors[0], "#000");
1472 border_e_bg = parse_color(colors[1], "#000");
1473 border_s_bg = parse_color(colors[2], "#000");
1474 border_w_bg = parse_color(colors[3], "#000");
1475 } else {
1476 fprintf(stderr, "error while parsing B option\n");
1478 break;
1480 case 't': {
1481 p_fg = parse_color(optarg, nil);
1482 break;
1484 case 'T': {
1485 p_bg = parse_color(optarg, nil);
1486 break;
1488 case 'c': {
1489 compl_fg = parse_color(optarg, nil);
1490 break;
1492 case 'C': {
1493 compl_bg = parse_color(optarg, nil);
1494 break;
1496 case 's': {
1497 compl_highlighted_fg = parse_color(optarg, nil);
1498 break;
1500 case 'S': {
1501 compl_highlighted_bg = parse_color(optarg, nil);
1502 break;
1504 default:
1505 fprintf(stderr, "Unrecognized option %c\n", ch);
1506 status = ERR;
1507 break;
1511 // since only now we know if the first should be selected, update
1512 // the completion here
1513 update_completions(cs, text, lines, vlines, first_selected);
1515 // load the font
1516 #ifdef USE_XFT
1517 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1518 #else
1519 char **missing_charset_list;
1520 int missing_charset_count;
1521 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1522 if (font == nil) {
1523 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1524 return EX_UNAVAILABLE;
1526 #endif
1528 // create the window
1529 XSetWindowAttributes attr;
1530 attr.colormap = cmap;
1531 attr.override_redirect = true;
1532 attr.border_pixel = 0;
1533 attr.background_pixel = 0x80808080;
1534 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1536 Window w = XCreateWindow(d, // display
1537 parent_window, // parent
1538 x + offset_x, y + offset_y, // x y
1539 width, height, // w h
1540 0, // border width
1541 vinfo.depth, // depth
1542 InputOutput, // class
1543 vinfo.visual, // visual
1544 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, // value mask
1545 &attr);
1547 set_win_atoms_hints(d, w, width, height);
1549 // we want some events
1550 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1551 XMapRaised(d, w);
1553 // if embed, listen for other events as well
1554 if (embed) {
1555 XSelectInput(d, parent_window, FocusChangeMask);
1556 Window *children, parent, root;
1557 unsigned int children_no;
1558 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1559 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1560 XSelectInput(d, children[i], FocusChangeMask);
1561 XFree(children);
1563 grabfocus(d, w);
1566 // grab keyboard
1567 take_keyboard(d, w);
1569 // Create some graphics contexts
1570 XGCValues values;
1571 /* values.font = font->fid; */
1573 struct rendering r = {
1574 .d = d,
1575 .w = w,
1576 .width = width,
1577 .height = height,
1578 .padding = padding,
1579 .x_zero = border_w,
1580 .y_zero = border_n,
1581 .offset = 0,
1582 .free_text = free_text,
1583 .first_selected = first_selected,
1584 .multiple_select = multiple_select,
1585 .border_n = border_n,
1586 .border_e = border_e,
1587 .border_s = border_s,
1588 .border_w = border_w,
1589 .horizontal_layout = horizontal_layout,
1590 .ps1 = ps1,
1591 .ps1len = strlen(ps1),
1592 .prompt = XCreateGC(d, w, 0, &values),
1593 .prompt_bg = XCreateGC(d, w, 0, &values),
1594 .completion = XCreateGC(d, w, 0, &values),
1595 .completion_bg = XCreateGC(d, w, 0, &values),
1596 .completion_highlighted = XCreateGC(d, w, 0, &values),
1597 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1598 .border_n_bg = XCreateGC(d, w, 0, &values),
1599 .border_e_bg = XCreateGC(d, w, 0, &values),
1600 .border_s_bg = XCreateGC(d, w, 0, &values),
1601 .border_w_bg = XCreateGC(d, w, 0, &values),
1602 #ifdef USE_XFT
1603 .font = font,
1604 #else
1605 .font = &font,
1606 #endif
1609 #ifdef USE_XFT
1610 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1613 rgba_t c;
1615 XRenderColor xrcolor;
1617 // prompt
1618 c = *(rgba_t*)&p_fg;
1619 xrcolor.red = EXPANDBITS(c.r);
1620 xrcolor.green = EXPANDBITS(c.g);
1621 xrcolor.blue = EXPANDBITS(c.b);
1622 xrcolor.alpha = EXPANDBITS(c.a);
1623 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1625 // completion
1626 c = *(rgba_t*)&compl_fg;
1627 xrcolor.red = EXPANDBITS(c.r);
1628 xrcolor.green = EXPANDBITS(c.g);
1629 xrcolor.blue = EXPANDBITS(c.b);
1630 xrcolor.alpha = EXPANDBITS(c.a);
1631 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1633 // completion highlighted
1634 c = *(rgba_t*)&compl_highlighted_fg;
1635 xrcolor.red = EXPANDBITS(c.r);
1636 xrcolor.green = EXPANDBITS(c.g);
1637 xrcolor.blue = EXPANDBITS(c.b);
1638 xrcolor.alpha = EXPANDBITS(c.a);
1639 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1641 #endif
1643 // load the colors in our GCs
1644 /* XSetForeground(d, r.prompt, p_fg.pixel); */
1645 XSetForeground(d, r.prompt, p_fg);
1646 XSetForeground(d, r.prompt_bg, p_bg);
1647 /* XSetForeground(d, r.completion, compl_fg.pixel); */
1648 XSetForeground(d, r.completion, compl_fg);
1649 XSetForeground(d, r.completion_bg, compl_bg);
1650 /* XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel); */
1651 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1652 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1653 XSetForeground(d, r.border_n_bg, border_n_bg);
1654 XSetForeground(d, r.border_e_bg, border_e_bg);
1655 XSetForeground(d, r.border_s_bg, border_s_bg);
1656 XSetForeground(d, r.border_w_bg, border_w_bg);
1658 // open the X input method
1659 XIM xim = XOpenIM(d, xdb, resname, resclass);
1660 check_allocation(xim);
1662 XIMStyles *xis = nil;
1663 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1664 fprintf(stderr, "Input Styles could not be retrieved\n");
1665 return EX_UNAVAILABLE;
1668 XIMStyle bestMatchStyle = 0;
1669 for (int i = 0; i < xis->count_styles; ++i) {
1670 XIMStyle ts = xis->supported_styles[i];
1671 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1672 bestMatchStyle = ts;
1673 break;
1676 XFree(xis);
1678 if (!bestMatchStyle) {
1679 fprintf(stderr, "No matching input style could be determined\n");
1682 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1683 check_allocation(r.xic);
1685 // draw the window for the first time
1686 draw(&r, text, cs);
1688 // main loop
1689 while (status == LOOPING || status == OK_LOOP) {
1690 status = loop(&r, &text, &textlen, cs, lines, vlines);
1692 if (status != ERR)
1693 printf("%s\n", text);
1695 if (!multiple_select && status == OK_LOOP)
1696 status = OK;
1699 release_keyboard(r.d);
1701 #ifdef USE_XFT
1702 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1703 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1704 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1705 #endif
1707 free(ps1);
1708 free(fontname);
1709 free(text);
1711 free(buf);
1712 free(lines);
1713 free(vlines);
1714 compls_delete(cs);
1716 XDestroyWindow(r.d, r.w);
1717 XCloseDisplay(r.d);
1719 return status != OK;