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>
13 #include <X11/Xlib.h>
14 #include <X11/Xutil.h> // XLookupString
15 #include <X11/Xresource.h>
16 #include <X11/Xcms.h> // colors
17 #include <X11/keysym.h>
19 #ifdef USE_XINERAMA
20 # include <X11/extensions/Xinerama.h>
21 #endif
23 #ifdef USE_XFT
24 # include <X11/Xft/Xft.h>
25 #endif
27 #ifndef VERSION
28 # define VERSION "unknown"
29 #endif
31 // Comfy
32 #define nil NULL
34 #define resname "MyMenu"
35 #define resclass "mymenu"
37 #define SYM_BUF_SIZE 4
39 #ifdef USE_XFT
40 # define default_fontname "monospace"
41 #else
42 # define default_fontname "fixed"
43 #endif
45 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
52 // If we don't have it or we don't want an "ignore case" completion
53 // style, fall back to `strstr(3)`
54 #ifndef USE_STRCASESTR
55 # define strcasestr strstr
56 #endif
58 // The number of char to read
59 #define STDIN_CHUNKS 64
61 // the number of lines to allocate in advance
62 #define LINES_CHUNK 32
64 // Abort if a is nil
65 #define check_allocation(a) { \
66 if (a == nil) { \
67 fprintf(stderr, "Could not allocate memory\n"); \
68 abort(); \
69 } \
70 }
72 #define inner_height(r) (r->height - r->border_n - r->border_s)
73 #define inner_width(r) (r->width - r->border_e - r->border_w)
75 // The possible state of the event loop.
76 enum state {LOOPING, OK_LOOP, OK, ERR};
78 // for the drawing-related function. The text to be rendered could be
79 // the prompt, a completion or a highlighted completion
80 enum text_type {PROMPT, COMPL, COMPL_HIGH};
82 // These are the possible action to be performed after user input.
83 enum action {
84 EXIT,
85 CONFIRM,
86 CONFIRM_CONTINUE,
87 NEXT_COMPL,
88 PREV_COMPL,
89 DEL_CHAR,
90 DEL_WORD,
91 DEL_LINE,
92 ADD_CHAR,
93 TOGGLE_FIRST_SELECTED
94 };
96 // A big set of values that needs to be carried around (for drawing
97 // functions). A struct to rule them all
98 struct rendering {
99 Display *d; // connection to xorg
100 Window w;
101 int width;
102 int height;
103 int padding;
104 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
105 int y_zero; // the same a x_zero, only for the y axis
107 size_t offset; // a scrolling offset
109 bool free_text;
110 bool first_selected;
111 bool multiple_select;
113 // The four border
114 int border_n;
115 int border_e;
116 int border_s;
117 int border_w;
119 bool horizontal_layout;
121 // the prompt
122 char *ps1;
123 int ps1len;
125 XIC xic;
127 // colors
128 GC prompt;
129 GC prompt_bg;
130 GC completion;
131 GC completion_bg;
132 GC completion_highlighted;
133 GC completion_highlighted_bg;
134 GC border_n_bg;
135 GC border_e_bg;
136 GC border_s_bg;
137 GC border_w_bg;
138 #ifdef USE_XFT
139 XftFont *font;
140 XftDraw *xftdraw;
141 XftColor xft_prompt;
142 XftColor xft_completion;
143 XftColor xft_completion_highlighted;
144 #else
145 XFontSet *font;
146 #endif
147 };
149 struct completion {
150 char *completion;
151 char *rcompletion;
152 };
154 // Wrap the linked list of completions
155 struct completions {
156 struct completion *completions;
157 ssize_t selected;
158 size_t lenght;
159 };
161 // return a newly allocated (and empty) completion list
162 struct completions *compls_new(size_t lenght) {
163 struct completions *cs = malloc(sizeof(struct completions));
165 if (cs == nil)
166 return cs;
168 cs->completions = calloc(lenght, sizeof(struct completion));
169 if (cs->completions == nil) {
170 free(cs);
171 return nil;
174 cs->selected = -1;
175 cs->lenght = lenght;
176 return cs;
179 /* idea stolen from lemonbar. ty lemonboy */
180 typedef union {
181 struct {
182 uint8_t b;
183 uint8_t g;
184 uint8_t r;
185 uint8_t a;
186 };
187 uint32_t v;
188 } rgba_t;
190 // Delete the wrapper and the whole list
191 void compls_delete(struct completions *cs) {
192 if (cs == nil)
193 return;
195 free(cs->completions);
196 free(cs);
199 // create a completion list from a text and the list of possible
200 // completions (null terminated). Expects a non-null `cs'. lines and
201 // vlines should have the same lenght OR vlines is null
202 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
203 size_t index = 0;
204 size_t matching = 0;
206 if (vlines == nil)
207 vlines = lines;
209 while (true) {
210 char *l = vlines[index] != nil ? vlines[index] : lines[index];
211 if (l == nil)
212 break;
214 if (strcasestr(l, text) != nil) {
215 struct completion *c = &cs->completions[matching];
216 c->completion = l;
217 c->rcompletion = lines[index];
218 matching++;
221 index++;
223 cs->lenght = matching;
224 cs->selected = -1;
227 // update the given completion, that is: clean the old cs & generate a new one.
228 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
229 filter(cs, text, lines, vlines);
230 if (first_selected && cs->lenght > 0)
231 cs->selected = 0;
234 // select the next, or the previous, selection and update some
235 // state. `text' will be updated with the text of the completion and
236 // `textlen' with the new lenght of `text'. If the memory cannot be
237 // allocated, `status' will be set to `ERR'.
238 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
239 if (cs == nil || cs->lenght == 0)
240 return;
242 // if the first is always selected, and the first entry is different
243 // from the text, expand the text and return
244 if (first_selected
245 && cs->selected == 0
246 && strcmp(cs->completions->completion, *text) != 0
247 && !p) {
248 free(*text);
249 *text = strdup(cs->completions->completion);
250 if (text == nil) {
251 *status = ERR;
252 return;
254 *textlen = strlen(*text);
255 return;
258 int index = cs->selected;
260 if (index == -1 && p)
261 index = 0;
262 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
264 struct completion *n = &cs->completions[cs->selected];
266 free(*text);
267 *text = strdup(n->completion);
268 if (text == nil) {
269 fprintf(stderr, "Memory allocation error!\n");
270 *status = ERR;
271 return;
273 *textlen = strlen(*text);
276 // push the character c at the end of the string pointed by p
277 int pushc(char **p, int maxlen, char c) {
278 int len = strnlen(*p, maxlen);
280 if (!(len < maxlen -2)) {
281 maxlen += maxlen >> 1;
282 char *newptr = realloc(*p, maxlen);
283 if (newptr == nil) { // bad!
284 return -1;
286 *p = newptr;
289 (*p)[len] = c;
290 (*p)[len+1] = '\0';
291 return maxlen;
294 // remove the last rune from the *utf8* string! This is different from
295 // just setting the last byte to 0 (in some cases ofc). Return a
296 // pointer (e) to the last non zero char. If e < p then p is empty!
297 char* popc(char *p) {
298 int len = strlen(p);
299 if (len == 0)
300 return p;
302 char *e = p + len - 1;
304 do {
305 char c = *e;
306 *e = 0;
307 e--;
309 // if c is a starting byte (11......) or is under U+007F (ascii,
310 // basically) we're done
311 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
312 break;
313 } while (e >= p);
315 return e;
318 // remove the last word plus trailing whitespaces from the give string
319 void popw(char *w) {
320 int len = strlen(w);
321 if (len == 0)
322 return;
324 bool in_word = true;
325 while (true) {
326 char *e = popc(w);
328 if (e < w)
329 return;
331 if (in_word && isspace(*e))
332 in_word = false;
334 if (!in_word && !isspace(*e))
335 return;
339 // If the string is surrounded by quotes (`"`) remove them and replace
340 // every `\"` in the string with `"`
341 char *normalize_str(const char *str) {
342 int len = strlen(str);
343 if (len == 0)
344 return nil;
346 char *s = calloc(len, sizeof(char));
347 check_allocation(s);
348 int p = 0;
349 while (*str) {
350 char c = *str;
351 if (*str == '\\') {
352 if (*(str + 1)) {
353 s[p] = *(str + 1);
354 p++;
355 str += 2; // skip this and the next char
356 continue;
357 } else {
358 break;
361 if (c == '"') {
362 str++; // skip only this char
363 continue;
365 s[p] = c;
366 p++;
367 str++;
369 return s;
372 size_t read_stdin(char **buf) {
373 size_t offset = 0;
374 size_t len = STDIN_CHUNKS;
375 *buf = malloc(len * sizeof(char));
376 if (*buf == nil)
377 goto err;
379 while (true) {
380 ssize_t r = read(0, *buf + offset, STDIN_CHUNKS);
381 if (r < 1)
382 return len;
384 offset += r;
386 len += STDIN_CHUNKS;
387 *buf = realloc(*buf, len);
388 if (*buf == nil)
389 goto err;
391 for (size_t i = offset; i < len; ++i)
392 (*buf)[i] = '\0';
395 err:
396 fprintf(stderr, "Error in allocating memory for stdin.\n");
397 exit(EX_UNAVAILABLE);
400 //
401 size_t readlines(char ***lns, char **buf) {
402 *buf = nil;
403 size_t len = read_stdin(buf);
405 size_t ll = LINES_CHUNK;
406 *lns = malloc(ll * sizeof(char*));
407 size_t lines = 0;
408 bool in_line = false;
409 for (size_t i = 0; i < len; i++) {
410 char c = (*buf)[i];
412 if (c == '\0')
413 break;
415 if (c == '\n')
416 (*buf)[i] = '\0';
418 if (in_line && c == '\n')
419 in_line = false;
421 if (!in_line && c != '\n') {
422 in_line = true;
423 (*lns)[lines] = (*buf) + i;
424 lines++;
426 if (lines == ll) { // resize
427 ll += LINES_CHUNK;
428 *lns = realloc(*lns, ll * sizeof(char*));
429 if (*lns == nil) {
430 fprintf(stderr, "Error in memory allocation.\n");
431 exit(EX_UNAVAILABLE);
437 return lines;
440 // Compute the dimension of the string str once rendered, return the
441 // width and save the width and the height in ret_width and ret_height
442 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
443 int height;
444 int width;
445 #ifdef USE_XFT
446 XGlyphInfo gi;
447 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
448 height = r->font->ascent - r->font->descent;
449 width = gi.width - gi.x;
450 #else
451 XRectangle rect;
452 XmbTextExtents(*r->font, str, len, nil, &rect);
453 height = rect.height;
454 width = rect.width;
455 #endif
456 if (ret_width != nil) *ret_width = width;
457 if (ret_height != nil) *ret_height = height;
458 return width;
461 // Draw the string str
462 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
463 #ifdef USE_XFT
464 XftColor xftcolor;
465 if (tt == PROMPT) xftcolor = r->xft_prompt;
466 if (tt == COMPL) xftcolor = r->xft_completion;
467 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
469 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
470 #else
471 GC gc;
472 if (tt == PROMPT) gc = r->prompt;
473 if (tt == COMPL) gc = r->completion;
474 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
475 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
476 #endif
479 // Duplicate the string str and substitute every space with a 'n'
480 char *strdupn(char *str) {
481 int len = strlen(str);
483 if (str == nil || len == 0)
484 return nil;
486 char *dup = strdup(str);
487 if (dup == nil)
488 return nil;
490 for (int i = 0; i < len; ++i)
491 if (dup[i] == ' ')
492 dup[i] = 'n';
494 return dup;
497 // |------------------|----------------------------------------------|
498 // | 20 char text | completion | completion | completion | compl |
499 // |------------------|----------------------------------------------|
500 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
501 int prompt_width = 20; // char
503 char *ps1dup = strdupn(r->ps1);
504 int width, height;
505 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
506 free(ps1dup);
507 int start_at = ps1xlen;
509 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
510 start_at = start_at * prompt_width + r->padding;
512 int texty = (inner_height(r) + height + r->y_zero) / 2;
514 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
516 int text_len = strlen(text);
517 if (text_len > prompt_width)
518 text = text + (text_len - prompt_width);
519 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
520 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
522 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
524 for (size_t i = r->offset; i < cs->lenght; ++i) {
525 struct completion *c = &cs->completions[i];
527 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
528 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
530 int len = strlen(c->completion);
531 int text_width = text_extents(c->completion, len, r, nil, nil);
533 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
535 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
537 start_at += text_width + r->padding * 2;
539 if (start_at > inner_width(r))
540 break; // don't draw completion if the space isn't enough
544 // |-----------------------------------------------------------------|
545 // | prompt |
546 // |-----------------------------------------------------------------|
547 // | completion |
548 // |-----------------------------------------------------------------|
549 // | completion |
550 // |-----------------------------------------------------------------|
551 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
552 int height, width;
553 text_extents("fjpgl", 5, r, nil, &height);
554 int start_at = r->padding*2 + height;
556 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
557 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
559 char *ps1dup = strdupn(r->ps1);
560 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, nil, nil);
561 free(ps1dup);
563 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
564 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
566 start_at += r->y_zero;
568 for (size_t i = r->offset; i < cs->lenght; ++i){
569 struct completion *c = &cs->completions[i];
570 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
571 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
573 int len = strlen(c->completion);
574 text_extents(c->completion, len, r, &width, &height);
575 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
576 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
578 start_at += height + r->padding *2;
580 if (start_at > inner_height(r))
581 break; // don't draw completion if the space isn't enough
585 void draw(struct rendering *r, char *text, struct completions *cs) {
586 if (r->horizontal_layout)
587 draw_horizontally(r, text, cs);
588 else
589 draw_vertically(r, text, cs);
591 // draw the borders
593 if (r->border_w != 0)
594 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
596 if (r->border_e != 0)
597 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
599 if (r->border_n != 0)
600 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
602 if (r->border_s != 0)
603 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
605 // send all the work to x
606 XFlush(r->d);
609 /* Set some WM stuff */
610 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
611 Atom type;
612 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
613 XChangeProperty(
614 d,
615 w,
616 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
617 XInternAtom(d, "ATOM", false),
618 32,
619 PropModeReplace,
620 (unsigned char *)&type,
622 );
624 /* some window managers honor this properties */
625 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
626 XChangeProperty(d,
627 w,
628 XInternAtom(d, "_NET_WM_STATE", false),
629 XInternAtom(d, "ATOM", false),
630 32,
631 PropModeReplace,
632 (unsigned char *)&type,
634 );
636 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
637 XChangeProperty(d,
638 w,
639 XInternAtom(d, "_NET_WM_STATE", false),
640 XInternAtom(d, "ATOM", false),
641 32,
642 PropModeAppend,
643 (unsigned char *)&type,
645 );
647 // setting window hints
648 XClassHint *class_hint = XAllocClassHint();
649 if (class_hint == nil) {
650 fprintf(stderr, "Could not allocate memory for class hint\n");
651 exit(EX_UNAVAILABLE);
653 class_hint->res_name = resname;
654 class_hint->res_class = resclass;
655 XSetClassHint(d, w, class_hint);
656 XFree(class_hint);
658 XSizeHints *size_hint = XAllocSizeHints();
659 if (size_hint == nil) {
660 fprintf(stderr, "Could not allocate memory for size hint\n");
661 exit(EX_UNAVAILABLE);
663 size_hint->flags = PMinSize | PBaseSize;
664 size_hint->min_width = width;
665 size_hint->base_width = width;
666 size_hint->min_height = height;
667 size_hint->base_height = height;
669 XFlush(d);
672 // write the width and height of the window `w' respectively in `width'
673 // and `height'.
674 void get_wh(Display *d, Window *w, int *width, int *height) {
675 XWindowAttributes win_attr;
676 XGetWindowAttributes(d, *w, &win_attr);
677 *height = win_attr.height;
678 *width = win_attr.width;
681 int grabfocus(Display *d, Window w) {
682 for (int i = 0; i < 100; ++i) {
683 Window focuswin;
684 int revert_to_win;
685 XGetInputFocus(d, &focuswin, &revert_to_win);
686 if (focuswin == w)
687 return true;
688 XSetInputFocus(d, w, RevertToParent, CurrentTime);
689 usleep(1000);
691 return 0;
694 // I know this may seem a little hackish BUT is the only way I managed
695 // to actually grab that goddam keyboard. Only one call to
696 // XGrabKeyboard does not always end up with the keyboard grabbed!
697 int take_keyboard(Display *d, Window w) {
698 int i;
699 for (i = 0; i < 100; i++) {
700 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
701 return 1;
702 usleep(1000);
704 fprintf(stderr, "Cannot grab keyboard\n");
705 return 0;
708 // release the keyboard.
709 void release_keyboard(Display *d) {
710 XUngrabKeyboard(d, CurrentTime);
713 unsigned long parse_color(const char *str, const char *def) {
714 if (str == nil)
715 goto invc;
717 size_t len = strlen(str);
719 // +1 for the '#' at the start, hence 9 and 4 (instead of 8 and 3)
720 if (*str != '#' || len > 9 || len < 4)
721 goto invc;
722 ++str; // skip the '#'
724 char *ep;
725 errno = 0;
726 rgba_t tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
728 if (errno)
729 goto invc;
731 switch (len-1) {
732 case 3:
733 // expand: #rgb -> #rrggbb
734 tmp.v = (tmp.v & 0xf00) * 0x1100
735 | (tmp.v & 0x0f0) * 0x0110
736 | (tmp.v & 0x00f) * 0x0011;
737 case 6:
738 // assume it has 100% opacity
739 tmp.a = 0xff;
740 break;
741 } // colors in aarrggbb format needs no fixes
743 // premultiply the alpha
744 if (tmp.a) {
745 tmp.r = (tmp.r * tmp.a) / 255;
746 tmp.g = (tmp.g * tmp.a) / 255;
747 tmp.b = (tmp.b * tmp.a) / 255;
748 return tmp.v;
751 return 0U;
753 invc:
754 fprintf(stderr, "Invalid color: \"%s\".\n", str);
755 if (def != nil)
756 return parse_color(def, nil);
757 else
758 return 0U;
761 // Given a string, try to parse it as a number or return
762 // `default_value'.
763 int parse_integer(const char *str, int default_value) {
764 errno = 0;
765 char *ep;
766 long lval = strtol(str, &ep, 10);
767 if (str[0] == '\0' || *ep != '\0') { // NaN
768 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
769 return default_value;
771 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
772 (lval > INT_MAX || lval < INT_MIN)) {
773 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
774 return default_value;
776 return lval;
779 // like parse_integer, but if the value ends with a `%' then its
780 // treated like a percentage (`max' is used to compute the percentage)
781 int parse_int_with_percentage(const char *str, int default_value, int max) {
782 int len = strlen(str);
783 if (len > 0 && str[len-1] == '%') {
784 char *cpy = strdup(str);
785 check_allocation(cpy);
786 cpy[len-1] = '\0';
787 int val = parse_integer(cpy, default_value);
788 free(cpy);
789 return val * max / 100;
791 return parse_integer(str, default_value);
794 // like parse_int_with_percentage but understands some special values
795 // - "middle" that is (max - self) / 2
796 // - "start" that is 0
797 // - "end" that is (max - self)
798 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
799 if (!strcmp(str, "start"))
800 return 0;
801 if (!strcmp(str, "middle"))
802 return (max - self)/2;
803 if (!strcmp(str, "end"))
804 return max-self;
805 return parse_int_with_percentage(str, default_value, max);
808 // parse a string like a css value (for example like the css
809 // margin/padding properties). Will ALWAYS return an array of 4 word
810 // TODO: harden this function!
811 char **parse_csslike(const char *str) {
812 char *s = strdup(str);
813 if (s == nil)
814 return nil;
816 char **ret = malloc(4 * sizeof(char*));
817 if (ret == nil) {
818 free(s);
819 return nil;
822 int i = 0;
823 char *token;
824 while ((token = strsep(&s, " ")) != NULL && i < 4) {
825 ret[i] = strdup(token);
826 i++;
829 if (i == 1)
830 for (int j = 1; j < 4; j++)
831 ret[j] = strdup(ret[0]);
833 if (i == 2) {
834 ret[2] = strdup(ret[0]);
835 ret[3] = strdup(ret[1]);
838 if (i == 3)
839 ret[3] = strdup(ret[1]);
841 // Before we didn't check for the return type of strdup, here we will
843 bool any_null = false;
844 for (int i = 0; i < 4; ++i)
845 any_null = ret[i] == nil || any_null;
847 if (any_null)
848 for (int i = 0; i < 4; ++i)
849 if (ret[i] != nil)
850 free(ret[i]);
852 if (i == 0 || any_null) {
853 free(s);
854 free(ret);
855 return nil;
858 return ret;
861 // Given an event, try to understand what the user wants. If the
862 // return value is ADD_CHAR then `input' is a pointer to a string that
863 // will need to be free'ed.
864 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
865 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
866 return DEL_CHAR;
868 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
869 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
871 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
872 return CONFIRM;
874 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
875 return EXIT;
877 // try to read what the user pressed
878 char str[SYM_BUF_SIZE] = {0};
879 Status s = 0;
880 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
881 if (s == XBufferOverflow) {
882 // should not happen since there are no utf-8 characters larger
883 // than 24bits
884 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
885 return EXIT;
888 if (ev->state & ControlMask) {
889 if (!strcmp(str, "")) // C-u
890 return DEL_LINE;
891 if (!strcmp(str, "")) // C-w
892 return DEL_WORD;
893 if (!strcmp(str, "")) // C-h
894 return DEL_CHAR;
895 if (!strcmp(str, "\r")) // C-m
896 return CONFIRM_CONTINUE;
897 if (!strcmp(str, "")) // C-p
898 return PREV_COMPL;
899 if (!strcmp(str, "")) // C-n
900 return NEXT_COMPL;
901 if (!strcmp(str, "")) // C-c
902 return EXIT;
903 if (!strcmp(str, "\t")) // C-i
904 return TOGGLE_FIRST_SELECTED;
907 *input = strdup(str);
908 if (*input == nil) {
909 fprintf(stderr, "Error while allocating memory for key.\n");
910 return EXIT;
913 return ADD_CHAR;
916 // Given the name of the program (argv[0]?) print a small help on stderr
917 void usage(char *prgname) {
918 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
919 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
920 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
921 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
924 // small function used in the event loop
925 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
926 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
927 // if there is something selected expand it and return
928 int index = cs->selected == -1 ? 0 : cs->selected;
929 struct completion *c = cs->completions;
930 while (true) {
931 if (index == 0)
932 break;
933 c++;
934 index--;
936 char *t = c->rcompletion;
937 free(*text);
938 *text = strdup(t);
939 if (*text == nil) {
940 fprintf(stderr, "Memory allocation error\n");
941 *status = ERR;
943 *textlen = strlen(*text);
944 } else {
945 if (!r->free_text) {
946 // cannot accept arbitrary text
947 *status = LOOPING;
952 // event loop
953 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
954 enum state status = LOOPING;
955 while (status == LOOPING) {
956 XEvent e;
957 XNextEvent(r->d, &e);
959 if (XFilterEvent(&e, r->w))
960 continue;
962 switch (e.type) {
963 case KeymapNotify:
964 XRefreshKeyboardMapping(&e.xmapping);
965 break;
967 case FocusIn:
968 // re-grab focus
969 if (e.xfocus.window != r->w)
970 grabfocus(r->d, r->w);
971 break;
973 case VisibilityNotify:
974 if (e.xvisibility.state != VisibilityUnobscured)
975 XRaiseWindow(r->d, r->w);
976 break;
978 case MapNotify:
979 get_wh(r->d, &r->w, &r->width, &r->height);
980 draw(r, *text, cs);
981 break;
983 case KeyPress: {
984 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
986 char *input;
987 switch (parse_event(r->d, ev, r->xic, &input)) {
988 case EXIT:
989 status = ERR;
990 break;
992 case CONFIRM: {
993 status = OK;
994 confirm(&status, r, cs, text, textlen);
995 break;
998 case CONFIRM_CONTINUE: {
999 status = OK_LOOP;
1000 confirm(&status, r, cs, text, textlen);
1001 break;
1004 case PREV_COMPL: {
1005 complete(cs, r->first_selected, true, text, textlen, &status);
1006 r->offset = cs->selected;
1007 break;
1010 case NEXT_COMPL: {
1011 complete(cs, r->first_selected, false, text, textlen, &status);
1012 r->offset = cs->selected;
1013 break;
1016 case DEL_CHAR:
1017 popc(*text);
1018 update_completions(cs, *text, lines, vlines, r->first_selected);
1019 r->offset = 0;
1020 break;
1022 case DEL_WORD: {
1023 popw(*text);
1024 update_completions(cs, *text, lines, vlines, r->first_selected);
1025 break;
1028 case DEL_LINE: {
1029 for (int i = 0; i < *textlen; ++i)
1030 *(*text + i) = 0;
1031 update_completions(cs, *text, lines, vlines, r->first_selected);
1032 r->offset = 0;
1033 break;
1036 case ADD_CHAR: {
1037 int str_len = strlen(input);
1039 // sometimes a strange key is pressed (i.e. ctrl alone),
1040 // so input will be empty. Don't need to update completion
1041 // in this case
1042 if (str_len == 0)
1043 break;
1045 for (int i = 0; i < str_len; ++i) {
1046 *textlen = pushc(text, *textlen, input[i]);
1047 if (*textlen == -1) {
1048 fprintf(stderr, "Memory allocation error\n");
1049 status = ERR;
1050 break;
1053 if (status != ERR) {
1054 update_completions(cs, *text, lines, vlines, r->first_selected);
1055 free(input);
1057 r->offset = 0;
1058 break;
1061 case TOGGLE_FIRST_SELECTED:
1062 r->first_selected = !r->first_selected;
1063 if (r->first_selected && cs->selected < 0)
1064 cs->selected = 0;
1065 if (!r->first_selected && cs->selected == 0)
1066 cs->selected = -1;
1067 break;
1071 case ButtonPress: {
1072 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1073 /* if (ev->button == Button1) { /\* click *\/ */
1074 /* int x = ev->x - r.border_w; */
1075 /* int y = ev->y - r.border_n; */
1076 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1077 /* } */
1079 if (ev->button == Button4) /* scroll up */
1080 r->offset = MAX((ssize_t)r->offset - 1, 0);
1082 if (ev->button == Button5) /* scroll down */
1083 r->offset = MIN(r->offset + 1, cs->lenght - 1);
1085 break;
1089 draw(r, *text, cs);
1092 return status;
1095 int main(int argc, char **argv) {
1096 #ifdef HAVE_PLEDGE
1097 // stdio & rpat: to read and write stdio/stdout
1098 // unix: to connect to Xorg
1099 pledge("stdio rpath unix", "");
1100 #endif
1102 char *sep = nil;
1104 // by default the first completion isn't selected
1105 bool first_selected = false;
1107 // our parent window
1108 char *parent_window_id = nil;
1110 // the user can input arbitrary text
1111 bool free_text = true;
1113 // the user can select multiple entries
1114 bool multiple_select = false;
1116 // first round of args parsing
1117 int ch;
1118 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1119 switch (ch) {
1120 case 'h': // help
1121 usage(*argv);
1122 return 0;
1123 case 'v': // version
1124 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1125 return 0;
1126 case 'e': // embed
1127 parent_window_id = strdup(optarg);
1128 check_allocation(parent_window_id);
1129 break;
1130 case 'd': {
1131 sep = strdup(optarg);
1132 check_allocation(sep);
1134 case 'A': {
1135 free_text = false;
1136 break;
1138 case 'm': {
1139 multiple_select = true;
1140 break;
1142 default:
1143 break;
1147 // read the lines from stdin
1148 char **lines = nil;
1149 char *buf = nil;
1150 size_t nlines = readlines(&lines, &buf);
1152 char **vlines = nil;
1153 if (sep != nil) {
1154 int l = strlen(sep);
1155 vlines = calloc(nlines, sizeof(char*));
1156 check_allocation(vlines);
1158 for (int i = 0; lines[i] != nil; i++) {
1159 char *t = strstr(lines[i], sep);
1160 if (t == nil)
1161 vlines[i] = lines[i];
1162 else
1163 vlines[i] = t + l;
1167 setlocale(LC_ALL, getenv("LANG"));
1169 enum state status = LOOPING;
1171 // where the monitor start (used only with xinerama)
1172 int offset_x = 0;
1173 int offset_y = 0;
1175 // width and height of the window
1176 int width = 400;
1177 int height = 20;
1179 // position on the screen
1180 int x = 0;
1181 int y = 0;
1183 // the default padding
1184 int padding = 10;
1186 // the default borders
1187 int border_n = 0;
1188 int border_e = 0;
1189 int border_s = 0;
1190 int border_w = 0;
1192 // the prompt. We duplicate the string so later is easy to free (in
1193 // the case the user provide its own prompt)
1194 char *ps1 = strdup("$ ");
1195 check_allocation(ps1);
1197 // same for the font name
1198 char *fontname = strdup(default_fontname);
1199 check_allocation(fontname);
1201 int textlen = 10;
1202 char *text = malloc(textlen * sizeof(char));
1203 check_allocation(text);
1205 /* struct completions *cs = filter(text, lines); */
1206 struct completions *cs = compls_new(nlines);
1207 check_allocation(cs);
1209 // start talking to xorg
1210 Display *d = XOpenDisplay(nil);
1211 if (d == nil) {
1212 fprintf(stderr, "Could not open display!\n");
1213 return EX_UNAVAILABLE;
1216 Window parent_window;
1217 bool embed = true;
1218 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1219 parent_window = DefaultRootWindow(d);
1220 embed = false;
1223 // get display size
1224 int d_width;
1225 int d_height;
1226 get_wh(d, &parent_window, &d_width, &d_height);
1228 #ifdef USE_XINERAMA
1229 if (!embed && XineramaIsActive(d)) {
1230 // find the mice
1231 int number_of_screens = XScreenCount(d);
1232 Window r;
1233 Window root;
1234 int root_x, root_y, win_x, win_y;
1235 unsigned int mask;
1236 bool res;
1237 for (int i = 0; i < number_of_screens; ++i) {
1238 root = XRootWindow(d, i);
1239 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1240 if (res) break;
1242 if (!res) {
1243 fprintf(stderr, "No mouse found.\n");
1244 root_x = 0;
1245 root_y = 0;
1248 // now find in which monitor the mice is on
1249 int monitors;
1250 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1251 if (info) {
1252 for (int i = 0; i < monitors; ++i) {
1253 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1254 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1255 offset_x = info[i].x_org;
1256 offset_y = info[i].y_org;
1257 d_width = info[i].width;
1258 d_height = info[i].height;
1259 break;
1263 XFree(info);
1265 #endif
1267 /* Colormap cmap = DefaultColormap(d, DefaultScreen(d)); */
1268 XVisualInfo vinfo;
1269 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1271 Colormap cmap;
1272 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1274 unsigned long p_fg = parse_color("#fff", nil);
1275 unsigned long compl_fg = parse_color("#fff", nil);
1276 unsigned long compl_highlighted_fg = parse_color("#000", nil);
1278 unsigned long p_bg = parse_color("#000", nil);
1279 unsigned long compl_bg = parse_color("#000", nil);
1280 unsigned long compl_highlighted_bg = parse_color("#fff", nil);
1282 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1283 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", nil);
1285 bool horizontal_layout = true;
1287 // read resource
1288 XrmInitialize();
1289 char *xrm = XResourceManagerString(d);
1290 XrmDatabase xdb = nil;
1291 if (xrm != nil) {
1292 xdb = XrmGetStringDatabase(xrm);
1293 XrmValue value;
1294 char *datatype[20];
1296 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1297 free(fontname);
1298 fontname = strdup(value.addr);
1299 check_allocation(fontname);
1300 } else {
1301 fprintf(stderr, "no font defined, using %s\n", fontname);
1304 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1305 horizontal_layout = !strcmp(value.addr, "horizontal");
1306 else
1307 fprintf(stderr, "no layout defined, using horizontal\n");
1309 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1310 free(ps1);
1311 ps1 = normalize_str(value.addr);
1312 } else {
1313 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1316 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1317 width = parse_int_with_percentage(value.addr, width, d_width);
1318 else
1319 fprintf(stderr, "no width defined, using %d\n", width);
1321 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1322 height = parse_int_with_percentage(value.addr, height, d_height);
1323 else
1324 fprintf(stderr, "no height defined, using %d\n", height);
1326 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1327 x = parse_int_with_pos(value.addr, x, d_width, width);
1328 else
1329 fprintf(stderr, "no x defined, using %d\n", x);
1331 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1332 y = parse_int_with_pos(value.addr, y, d_height, height);
1333 else
1334 fprintf(stderr, "no y defined, using %d\n", y);
1336 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1337 padding = parse_integer(value.addr, padding);
1338 else
1339 fprintf(stderr, "no padding defined, using %d\n", padding);
1341 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1342 char **borders = parse_csslike(value.addr);
1343 if (borders != nil) {
1344 border_n = parse_integer(borders[0], 0);
1345 border_e = parse_integer(borders[1], 0);
1346 border_s = parse_integer(borders[2], 0);
1347 border_w = parse_integer(borders[3], 0);
1348 } else {
1349 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1351 } else {
1352 fprintf(stderr, "no border defined, using 0.\n");
1355 /* XColor tmp; */
1356 // TODO: tmp needs to be free'd after every allocation?
1358 // prompt
1359 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1360 p_fg = parse_color(value.addr, "#fff");
1362 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1363 p_bg = parse_color(value.addr, "#000");
1365 // completion
1366 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1367 compl_fg = parse_color(value.addr, "#fff");
1369 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1370 compl_bg = parse_color(value.addr, "#000");
1371 else
1372 compl_bg = parse_color("#000", nil);
1374 // completion highlighted
1375 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1376 compl_highlighted_fg = parse_color(value.addr, "#000");
1378 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1379 compl_highlighted_bg = parse_color(value.addr, "#fff");
1380 else
1381 compl_highlighted_bg = parse_color("#fff", nil);
1383 // border
1384 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1385 char **colors = parse_csslike(value.addr);
1386 if (colors != nil) {
1387 border_n_bg = parse_color(colors[0], "#000");
1388 border_e_bg = parse_color(colors[1], "#000");
1389 border_s_bg = parse_color(colors[2], "#000");
1390 border_w_bg = parse_color(colors[3], "#000");
1391 } else {
1392 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1397 // second round of args parsing
1398 optind = 0; // reset the option index
1399 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1400 switch (ch) {
1401 case 'a':
1402 first_selected = true;
1403 break;
1404 case 'A':
1405 // free_text -- this case was already catched
1406 break;
1407 case 'd':
1408 // separator -- this case was already catched
1409 break;
1410 case 'e':
1411 // (embedding mymenu) this case was already catched.
1412 case 'm':
1413 // (multiple selection) this case was already catched.
1414 break;
1415 case 'p': {
1416 char *newprompt = strdup(optarg);
1417 if (newprompt != nil) {
1418 free(ps1);
1419 ps1 = newprompt;
1421 break;
1423 case 'x':
1424 x = parse_int_with_pos(optarg, x, d_width, width);
1425 break;
1426 case 'y':
1427 y = parse_int_with_pos(optarg, y, d_height, height);
1428 break;
1429 case 'P':
1430 padding = parse_integer(optarg, padding);
1431 break;
1432 case 'l':
1433 horizontal_layout = !strcmp(optarg, "horizontal");
1434 break;
1435 case 'f': {
1436 char *newfont = strdup(optarg);
1437 if (newfont != nil) {
1438 free(fontname);
1439 fontname = newfont;
1441 break;
1443 case 'W':
1444 width = parse_int_with_percentage(optarg, width, d_width);
1445 break;
1446 case 'H':
1447 height = parse_int_with_percentage(optarg, height, d_height);
1448 break;
1449 case 'b': {
1450 char **borders = parse_csslike(optarg);
1451 if (borders != nil) {
1452 border_n = parse_integer(borders[0], 0);
1453 border_e = parse_integer(borders[1], 0);
1454 border_s = parse_integer(borders[2], 0);
1455 border_w = parse_integer(borders[3], 0);
1456 } else {
1457 fprintf(stderr, "Error parsing b option\n");
1459 break;
1461 case 'B': {
1462 char **colors = parse_csslike(optarg);
1463 if (colors != nil) {
1464 border_n_bg = parse_color(colors[0], "#000");
1465 border_e_bg = parse_color(colors[1], "#000");
1466 border_s_bg = parse_color(colors[2], "#000");
1467 border_w_bg = parse_color(colors[3], "#000");
1468 } else {
1469 fprintf(stderr, "error while parsing B option\n");
1471 break;
1473 case 't': {
1474 p_fg = parse_color(optarg, nil);
1475 break;
1477 case 'T': {
1478 p_bg = parse_color(optarg, nil);
1479 break;
1481 case 'c': {
1482 compl_fg = parse_color(optarg, nil);
1483 break;
1485 case 'C': {
1486 compl_bg = parse_color(optarg, nil);
1487 break;
1489 case 's': {
1490 compl_highlighted_fg = parse_color(optarg, nil);
1491 break;
1493 case 'S': {
1494 compl_highlighted_bg = parse_color(optarg, nil);
1495 break;
1497 default:
1498 fprintf(stderr, "Unrecognized option %c\n", ch);
1499 status = ERR;
1500 break;
1504 // since only now we know if the first should be selected, update
1505 // the completion here
1506 update_completions(cs, text, lines, vlines, first_selected);
1508 // load the font
1509 #ifdef USE_XFT
1510 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1511 #else
1512 char **missing_charset_list;
1513 int missing_charset_count;
1514 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1515 if (font == nil) {
1516 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1517 return EX_UNAVAILABLE;
1519 #endif
1521 // create the window
1522 XSetWindowAttributes attr;
1523 attr.colormap = cmap;
1524 attr.override_redirect = true;
1525 attr.border_pixel = 0;
1526 attr.background_pixel = 0x80808080;
1527 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1529 Window w = XCreateWindow(d, // display
1530 parent_window, // parent
1531 x + offset_x, y + offset_y, // x y
1532 width, height, // w h
1533 0, // border width
1534 vinfo.depth, // depth
1535 InputOutput, // class
1536 vinfo.visual, // visual
1537 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, // value mask
1538 &attr);
1540 set_win_atoms_hints(d, w, width, height);
1542 // we want some events
1543 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1544 XMapRaised(d, w);
1546 // if embed, listen for other events as well
1547 if (embed) {
1548 XSelectInput(d, parent_window, FocusChangeMask);
1549 Window *children, parent, root;
1550 unsigned int children_no;
1551 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1552 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1553 XSelectInput(d, children[i], FocusChangeMask);
1554 XFree(children);
1556 grabfocus(d, w);
1559 // grab keyboard
1560 take_keyboard(d, w);
1562 // Create some graphics contexts
1563 XGCValues values;
1564 /* values.font = font->fid; */
1566 struct rendering r = {
1567 .d = d,
1568 .w = w,
1569 .width = width,
1570 .height = height,
1571 .padding = padding,
1572 .x_zero = border_w,
1573 .y_zero = border_n,
1574 .offset = 0,
1575 .free_text = free_text,
1576 .first_selected = first_selected,
1577 .multiple_select = multiple_select,
1578 .border_n = border_n,
1579 .border_e = border_e,
1580 .border_s = border_s,
1581 .border_w = border_w,
1582 .horizontal_layout = horizontal_layout,
1583 .ps1 = ps1,
1584 .ps1len = strlen(ps1),
1585 .prompt = XCreateGC(d, w, 0, &values),
1586 .prompt_bg = XCreateGC(d, w, 0, &values),
1587 .completion = XCreateGC(d, w, 0, &values),
1588 .completion_bg = XCreateGC(d, w, 0, &values),
1589 .completion_highlighted = XCreateGC(d, w, 0, &values),
1590 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1591 .border_n_bg = XCreateGC(d, w, 0, &values),
1592 .border_e_bg = XCreateGC(d, w, 0, &values),
1593 .border_s_bg = XCreateGC(d, w, 0, &values),
1594 .border_w_bg = XCreateGC(d, w, 0, &values),
1595 #ifdef USE_XFT
1596 .font = font,
1597 #else
1598 .font = &font,
1599 #endif
1602 #ifdef USE_XFT
1603 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1606 rgba_t c;
1608 XRenderColor xrcolor;
1610 // prompt
1611 c = *(rgba_t*)&p_fg;
1612 xrcolor.red = EXPANDBITS(c.r);
1613 xrcolor.green = EXPANDBITS(c.g);
1614 xrcolor.blue = EXPANDBITS(c.b);
1615 xrcolor.alpha = EXPANDBITS(c.a);
1616 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1618 // completion
1619 c = *(rgba_t*)&compl_fg;
1620 xrcolor.red = EXPANDBITS(c.r);
1621 xrcolor.green = EXPANDBITS(c.g);
1622 xrcolor.blue = EXPANDBITS(c.b);
1623 xrcolor.alpha = EXPANDBITS(c.a);
1624 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1626 // completion highlighted
1627 c = *(rgba_t*)&compl_highlighted_fg;
1628 xrcolor.red = EXPANDBITS(c.r);
1629 xrcolor.green = EXPANDBITS(c.g);
1630 xrcolor.blue = EXPANDBITS(c.b);
1631 xrcolor.alpha = EXPANDBITS(c.a);
1632 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1634 #endif
1636 // load the colors in our GCs
1637 /* XSetForeground(d, r.prompt, p_fg.pixel); */
1638 XSetForeground(d, r.prompt, p_fg);
1639 XSetForeground(d, r.prompt_bg, p_bg);
1640 /* XSetForeground(d, r.completion, compl_fg.pixel); */
1641 XSetForeground(d, r.completion, compl_fg);
1642 XSetForeground(d, r.completion_bg, compl_bg);
1643 /* XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel); */
1644 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1645 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1646 XSetForeground(d, r.border_n_bg, border_n_bg);
1647 XSetForeground(d, r.border_e_bg, border_e_bg);
1648 XSetForeground(d, r.border_s_bg, border_s_bg);
1649 XSetForeground(d, r.border_w_bg, border_w_bg);
1651 // open the X input method
1652 XIM xim = XOpenIM(d, xdb, resname, resclass);
1653 check_allocation(xim);
1655 XIMStyles *xis = nil;
1656 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1657 fprintf(stderr, "Input Styles could not be retrieved\n");
1658 return EX_UNAVAILABLE;
1661 XIMStyle bestMatchStyle = 0;
1662 for (int i = 0; i < xis->count_styles; ++i) {
1663 XIMStyle ts = xis->supported_styles[i];
1664 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1665 bestMatchStyle = ts;
1666 break;
1669 XFree(xis);
1671 if (!bestMatchStyle) {
1672 fprintf(stderr, "No matching input style could be determined\n");
1675 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1676 check_allocation(r.xic);
1678 // draw the window for the first time
1679 draw(&r, text, cs);
1681 // main loop
1682 while (status == LOOPING || status == OK_LOOP) {
1683 status = loop(&r, &text, &textlen, cs, lines, vlines);
1685 if (status != ERR)
1686 printf("%s\n", text);
1688 if (!multiple_select && status == OK_LOOP)
1689 status = OK;
1692 release_keyboard(r.d);
1694 #ifdef USE_XFT
1695 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1696 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1697 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1698 #endif
1700 free(ps1);
1701 free(fontname);
1702 free(text);
1704 free(buf);
1705 free(lines);
1706 free(vlines);
1707 compls_delete(cs);
1709 XDestroyWindow(r.d, r.w);
1710 XCloseDisplay(r.d);
1712 return status != OK;