Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #ifndef VERSION
27 # define VERSION "unknown"
28 #endif
30 // Comfy
31 #define nil NULL
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
38 #ifdef USE_XFT
39 # define default_fontname "monospace"
40 #else
41 # define default_fontname "fixed"
42 #endif
44 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:"
46 #define MIN(a, b) ((a) < (b) ? (a) : (b))
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 #define EXPANDBITS(x) ((0xffff * x) / 0xff)
51 // If we don't have it or we don't want an "ignore case" completion
52 // style, fall back to `strstr(3)`
53 #ifndef USE_STRCASESTR
54 # define strcasestr strstr
55 #endif
57 // The initial number of items to read
58 #define INITIAL_ITEMS 64
60 // Abort if a is nil
61 #define check_allocation(a) { \
62 if (a == nil) { \
63 fprintf(stderr, "Could not allocate memory\n"); \
64 abort(); \
65 } \
66 }
68 #define inner_height(r) (r->height - r->border_n - r->border_s)
69 #define inner_width(r) (r->width - r->border_e - r->border_w)
71 // The possible state of the event loop.
72 enum state {LOOPING, OK_LOOP, OK, ERR};
74 // for the drawing-related function. The text to be rendered could be
75 // the prompt, a completion or a highlighted completion
76 enum text_type {PROMPT, COMPL, COMPL_HIGH};
78 // These are the possible action to be performed after user input.
79 enum action {
80 EXIT,
81 CONFIRM,
82 CONFIRM_CONTINUE,
83 NEXT_COMPL,
84 PREV_COMPL,
85 DEL_CHAR,
86 DEL_WORD,
87 DEL_LINE,
88 ADD_CHAR,
89 TOGGLE_FIRST_SELECTED
90 };
92 // A big set of values that needs to be carried around (for drawing
93 // functions). A struct to rule them all
94 struct rendering {
95 Display *d; // connection to xorg
96 Window w;
97 int width;
98 int height;
99 int padding;
100 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
101 int y_zero; // the same a x_zero, only for the y axis
103 size_t offset; // a scrolling offset
105 bool free_text;
106 bool first_selected;
107 bool multiple_select;
109 // The four border
110 int border_n;
111 int border_e;
112 int border_s;
113 int border_w;
115 bool horizontal_layout;
117 // the prompt
118 char *ps1;
119 int ps1len;
121 XIC xic;
123 // colors
124 GC prompt;
125 GC prompt_bg;
126 GC completion;
127 GC completion_bg;
128 GC completion_highlighted;
129 GC completion_highlighted_bg;
130 GC border_n_bg;
131 GC border_e_bg;
132 GC border_s_bg;
133 GC border_w_bg;
134 #ifdef USE_XFT
135 XftFont *font;
136 XftDraw *xftdraw;
137 XftColor xft_prompt;
138 XftColor xft_completion;
139 XftColor xft_completion_highlighted;
140 #else
141 XFontSet *font;
142 #endif
143 };
145 struct completion {
146 char *completion;
147 char *rcompletion;
148 };
150 // Wrap the linked list of completions
151 struct completions {
152 struct completion *completions;
153 ssize_t selected;
154 size_t lenght;
155 };
157 // return a newly allocated (and empty) completion list
158 struct completions *compls_new(size_t lenght) {
159 struct completions *cs = malloc(sizeof(struct completions));
161 if (cs == nil)
162 return cs;
164 cs->completions = calloc(lenght, sizeof(struct completion));
165 if (cs->completions == nil) {
166 free(cs);
167 return nil;
170 cs->selected = -1;
171 cs->lenght = lenght;
172 return cs;
175 /* idea stolen from lemonbar. ty lemonboy */
176 typedef union {
177 struct {
178 uint8_t b;
179 uint8_t g;
180 uint8_t r;
181 uint8_t a;
182 };
183 uint32_t v;
184 } rgba_t;
186 // Delete the wrapper and the whole list
187 void compls_delete(struct completions *cs) {
188 if (cs == nil)
189 return;
191 free(cs->completions);
192 free(cs);
195 // create a completion list from a text and the list of possible
196 // completions (null terminated). Expects a non-null `cs'. lines and
197 // vlines should have the same lenght OR vlines is null
198 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
199 size_t index = 0;
200 size_t matching = 0;
202 if (vlines == nil)
203 vlines = lines;
205 while (true) {
206 char *l = vlines[index] != nil ? vlines[index] : lines[index];
207 if (l == nil)
208 break;
210 if (strcasestr(l, text) != nil) {
211 struct completion *c = &cs->completions[matching];
212 c->completion = l;
213 c->rcompletion = lines[index];
214 matching++;
217 index++;
219 cs->lenght = matching;
220 cs->selected = -1;
223 // update the given completion, that is: clean the old cs & generate a new one.
224 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
225 filter(cs, text, lines, vlines);
226 if (first_selected && cs->lenght > 0)
227 cs->selected = 0;
230 // select the next, or the previous, selection and update some
231 // state. `text' will be updated with the text of the completion and
232 // `textlen' with the new lenght of `text'. If the memory cannot be
233 // allocated, `status' will be set to `ERR'.
234 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
235 if (cs == nil || cs->lenght == 0)
236 return;
238 // if the first is always selected, and the first entry is different
239 // from the text, expand the text and return
240 if (first_selected
241 && cs->selected == 0
242 && strcmp(cs->completions->completion, *text) != 0
243 && !p) {
244 free(*text);
245 *text = strdup(cs->completions->completion);
246 if (text == nil) {
247 *status = ERR;
248 return;
250 *textlen = strlen(*text);
251 return;
254 int index = cs->selected;
256 if (index == -1 && p)
257 index = 0;
258 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
260 struct completion *n = &cs->completions[cs->selected];
262 free(*text);
263 *text = strdup(n->completion);
264 if (text == nil) {
265 fprintf(stderr, "Memory allocation error!\n");
266 *status = ERR;
267 return;
269 *textlen = strlen(*text);
272 // push the character c at the end of the string pointed by p
273 int pushc(char **p, int maxlen, char c) {
274 int len = strnlen(*p, maxlen);
276 if (!(len < maxlen -2)) {
277 maxlen += maxlen >> 1;
278 char *newptr = realloc(*p, maxlen);
279 if (newptr == nil) { // bad!
280 return -1;
282 *p = newptr;
285 (*p)[len] = c;
286 (*p)[len+1] = '\0';
287 return maxlen;
290 // remove the last rune from the *utf8* string! This is different from
291 // just setting the last byte to 0 (in some cases ofc). Return a
292 // pointer (e) to the last non zero char. If e < p then p is empty!
293 char* popc(char *p) {
294 int len = strlen(p);
295 if (len == 0)
296 return p;
298 char *e = p + len - 1;
300 do {
301 char c = *e;
302 *e = 0;
303 e--;
305 // if c is a starting byte (11......) or is under U+007F (ascii,
306 // basically) we're done
307 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
308 break;
309 } while (e >= p);
311 return e;
314 // remove the last word plus trailing whitespaces from the give string
315 void popw(char *w) {
316 int len = strlen(w);
317 if (len == 0)
318 return;
320 bool in_word = true;
321 while (true) {
322 char *e = popc(w);
324 if (e < w)
325 return;
327 if (in_word && isspace(*e))
328 in_word = false;
330 if (!in_word && !isspace(*e))
331 return;
335 // If the string is surrounded by quotes (`"`) remove them and replace
336 // every `\"` in the string with `"`
337 char *normalize_str(const char *str) {
338 int len = strlen(str);
339 if (len == 0)
340 return nil;
342 char *s = calloc(len, sizeof(char));
343 check_allocation(s);
344 int p = 0;
345 while (*str) {
346 char c = *str;
347 if (*str == '\\') {
348 if (*(str + 1)) {
349 s[p] = *(str + 1);
350 p++;
351 str += 2; // skip this and the next char
352 continue;
353 } else {
354 break;
357 if (c == '"') {
358 str++; // skip only this char
359 continue;
361 s[p] = c;
362 p++;
363 str++;
365 return s;
368 // read an arbitrary amount of text until an EOF and store it in
369 // lns. `items` is the capacity of lns. It may increase lns with
370 // `realloc(3)` to store more line. Return the number of lines
371 // read. The last item will always be a NULL pointer. It ignore the
372 // "null" (empty) lines
373 size_t readlines(char ***lns, size_t items) {
374 size_t n = 0;
375 char **lines = *lns;
376 while (true) {
377 size_t linelen = 0;
378 ssize_t l = getline(lines + n, &linelen, stdin);
380 if (l == -1) {
381 break;
384 if (linelen == 0 || lines[n][0] == '\n') {
385 free(lines[n]);
386 lines[n] = nil;
387 continue; // forget about this line
390 strtok(lines[n], "\n"); // get rid of the \n
392 ++n;
394 if (n == items - 1) {
395 items += items >>1;
396 char **l = realloc(lines, sizeof(char*) * items);
397 check_allocation(l);
398 *lns = l;
399 lines = l;
403 n++;
404 lines[n] = nil;
405 return items;
408 // Compute the dimension of the string str once rendered, return the
409 // width and save the width and the height in ret_width and ret_height
410 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
411 int height;
412 int width;
413 #ifdef USE_XFT
414 XGlyphInfo gi;
415 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
416 height = r->font->ascent - r->font->descent;
417 width = gi.width - gi.x;
418 #else
419 XRectangle rect;
420 XmbTextExtents(*r->font, str, len, nil, &rect);
421 height = rect.height;
422 width = rect.width;
423 #endif
424 if (ret_width != nil) *ret_width = width;
425 if (ret_height != nil) *ret_height = height;
426 return width;
429 // Draw the string str
430 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
431 #ifdef USE_XFT
432 XftColor xftcolor;
433 if (tt == PROMPT) xftcolor = r->xft_prompt;
434 if (tt == COMPL) xftcolor = r->xft_completion;
435 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
437 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
438 #else
439 GC gc;
440 if (tt == PROMPT) gc = r->prompt;
441 if (tt == COMPL) gc = r->completion;
442 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
443 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
444 #endif
447 // Duplicate the string str and substitute every space with a 'n'
448 char *strdupn(char *str) {
449 int len = strlen(str);
451 if (str == nil || len == 0)
452 return nil;
454 char *dup = strdup(str);
455 if (dup == nil)
456 return nil;
458 for (int i = 0; i < len; ++i)
459 if (dup[i] == ' ')
460 dup[i] = 'n';
462 return dup;
465 // |------------------|----------------------------------------------|
466 // | 20 char text | completion | completion | completion | compl |
467 // |------------------|----------------------------------------------|
468 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
469 int prompt_width = 20; // char
471 char *ps1dup = strdupn(r->ps1);
472 int width, height;
473 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, &width, &height);
474 free(ps1dup);
475 int start_at = ps1xlen;
477 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
478 start_at = start_at * prompt_width + r->padding;
480 int texty = (inner_height(r) + height + r->y_zero) / 2;
482 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
484 int text_len = strlen(text);
485 if (text_len > prompt_width)
486 text = text + (text_len - prompt_width);
487 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
488 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
490 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
492 for (size_t i = r->offset; i < cs->lenght; ++i) {
493 struct completion *c = &cs->completions[i];
495 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
496 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
498 int len = strlen(c->completion);
499 int text_width = text_extents(c->completion, len, r, nil, nil);
501 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
503 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
505 start_at += text_width + r->padding * 2;
507 if (start_at > inner_width(r))
508 break; // don't draw completion if the space isn't enough
512 // |-----------------------------------------------------------------|
513 // | prompt |
514 // |-----------------------------------------------------------------|
515 // | completion |
516 // |-----------------------------------------------------------------|
517 // | completion |
518 // |-----------------------------------------------------------------|
519 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
520 int height, width;
521 text_extents("fjpgl", 5, r, nil, &height);
522 int start_at = r->padding*2 + height;
524 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
525 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
527 char *ps1dup = strdupn(r->ps1);
528 int ps1xlen = text_extents(ps1dup != nil ? ps1dup : r->ps1, r->ps1len, r, nil, nil);
529 free(ps1dup);
531 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
532 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
534 start_at += r->y_zero;
536 for (size_t i = r->offset; i < cs->lenght; ++i){
537 struct completion *c = &cs->completions[i];
538 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
539 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
541 int len = strlen(c->completion);
542 text_extents(c->completion, len, r, &width, &height);
543 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
544 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
546 start_at += height + r->padding *2;
548 if (start_at > inner_height(r))
549 break; // don't draw completion if the space isn't enough
553 void draw(struct rendering *r, char *text, struct completions *cs) {
554 if (r->horizontal_layout)
555 draw_horizontally(r, text, cs);
556 else
557 draw_vertically(r, text, cs);
559 // draw the borders
561 if (r->border_w != 0)
562 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
564 if (r->border_e != 0)
565 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
567 if (r->border_n != 0)
568 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
570 if (r->border_s != 0)
571 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
573 // send all the work to x
574 XFlush(r->d);
577 /* Set some WM stuff */
578 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
579 Atom type;
580 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
581 XChangeProperty(
582 d,
583 w,
584 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
585 XInternAtom(d, "ATOM", false),
586 32,
587 PropModeReplace,
588 (unsigned char *)&type,
590 );
592 /* some window managers honor this properties */
593 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
594 XChangeProperty(d,
595 w,
596 XInternAtom(d, "_NET_WM_STATE", false),
597 XInternAtom(d, "ATOM", false),
598 32,
599 PropModeReplace,
600 (unsigned char *)&type,
602 );
604 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
605 XChangeProperty(d,
606 w,
607 XInternAtom(d, "_NET_WM_STATE", false),
608 XInternAtom(d, "ATOM", false),
609 32,
610 PropModeAppend,
611 (unsigned char *)&type,
613 );
615 // setting window hints
616 XClassHint *class_hint = XAllocClassHint();
617 if (class_hint == nil) {
618 fprintf(stderr, "Could not allocate memory for class hint\n");
619 exit(EX_UNAVAILABLE);
621 class_hint->res_name = resname;
622 class_hint->res_class = resclass;
623 XSetClassHint(d, w, class_hint);
624 XFree(class_hint);
626 XSizeHints *size_hint = XAllocSizeHints();
627 if (size_hint == nil) {
628 fprintf(stderr, "Could not allocate memory for size hint\n");
629 exit(EX_UNAVAILABLE);
631 size_hint->flags = PMinSize | PBaseSize;
632 size_hint->min_width = width;
633 size_hint->base_width = width;
634 size_hint->min_height = height;
635 size_hint->base_height = height;
637 XFlush(d);
640 // write the width and height of the window `w' respectively in `width'
641 // and `height'.
642 void get_wh(Display *d, Window *w, int *width, int *height) {
643 XWindowAttributes win_attr;
644 XGetWindowAttributes(d, *w, &win_attr);
645 *height = win_attr.height;
646 *width = win_attr.width;
649 int grabfocus(Display *d, Window w) {
650 for (int i = 0; i < 100; ++i) {
651 Window focuswin;
652 int revert_to_win;
653 XGetInputFocus(d, &focuswin, &revert_to_win);
654 if (focuswin == w)
655 return true;
656 XSetInputFocus(d, w, RevertToParent, CurrentTime);
657 usleep(1000);
659 return 0;
662 // I know this may seem a little hackish BUT is the only way I managed
663 // to actually grab that goddam keyboard. Only one call to
664 // XGrabKeyboard does not always end up with the keyboard grabbed!
665 int take_keyboard(Display *d, Window w) {
666 int i;
667 for (i = 0; i < 100; i++) {
668 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
669 return 1;
670 usleep(1000);
672 fprintf(stderr, "Cannot grab keyboard\n");
673 return 0;
676 // release the keyboard.
677 void release_keyboard(Display *d) {
678 XUngrabKeyboard(d, CurrentTime);
681 unsigned long parse_color(const char *str, const char *def) {
682 if (str == nil)
683 goto invc;
685 size_t len = strlen(str);
687 // +1 for the '#' at the start, hence 9 and 4 (instead of 8 and 3)
688 if (*str != '#' || len > 9 || len < 4)
689 goto invc;
690 ++str; // skip the '#'
692 char *ep;
693 errno = 0;
694 rgba_t tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
696 if (errno)
697 goto invc;
699 switch (len-1) {
700 case 3:
701 // expand: #rgb -> #rrggbb
702 tmp.v = (tmp.v & 0xf00) * 0x1100
703 | (tmp.v & 0x0f0) * 0x0110
704 | (tmp.v & 0x00f) * 0x0011;
705 case 6:
706 // assume it has 100% opacity
707 tmp.a = 0xff;
708 break;
709 } // colors in aarrggbb format needs no fixes
711 // premultiply the alpha
712 if (tmp.a) {
713 tmp.r = (tmp.r * tmp.a) / 255;
714 tmp.g = (tmp.g * tmp.a) / 255;
715 tmp.b = (tmp.b * tmp.a) / 255;
716 return tmp.v;
719 return 0U;
721 invc:
722 fprintf(stderr, "Invalid color: \"%s\".\n", str);
723 if (def != nil)
724 return parse_color(def, nil);
725 else
726 return 0U;
729 // Given a string, try to parse it as a number or return
730 // `default_value'.
731 int parse_integer(const char *str, int default_value) {
732 errno = 0;
733 char *ep;
734 long lval = strtol(str, &ep, 10);
735 if (str[0] == '\0' || *ep != '\0') { // NaN
736 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
737 return default_value;
739 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
740 (lval > INT_MAX || lval < INT_MIN)) {
741 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
742 return default_value;
744 return lval;
747 // like parse_integer, but if the value ends with a `%' then its
748 // treated like a percentage (`max' is used to compute the percentage)
749 int parse_int_with_percentage(const char *str, int default_value, int max) {
750 int len = strlen(str);
751 if (len > 0 && str[len-1] == '%') {
752 char *cpy = strdup(str);
753 check_allocation(cpy);
754 cpy[len-1] = '\0';
755 int val = parse_integer(cpy, default_value);
756 free(cpy);
757 return val * max / 100;
759 return parse_integer(str, default_value);
762 // like parse_int_with_percentage but understands some special values
763 // - "middle" that is (max - self) / 2
764 // - "start" that is 0
765 // - "end" that is (max - self)
766 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
767 if (!strcmp(str, "start"))
768 return 0;
769 if (!strcmp(str, "middle"))
770 return (max - self)/2;
771 if (!strcmp(str, "end"))
772 return max-self;
773 return parse_int_with_percentage(str, default_value, max);
776 // parse a string like a css value (for example like the css
777 // margin/padding properties). Will ALWAYS return an array of 4 word
778 // TODO: harden this function!
779 char **parse_csslike(const char *str) {
780 char *s = strdup(str);
781 if (s == nil)
782 return nil;
784 char **ret = malloc(4 * sizeof(char*));
785 if (ret == nil) {
786 free(s);
787 return nil;
790 int i = 0;
791 char *token;
792 while ((token = strsep(&s, " ")) != NULL && i < 4) {
793 ret[i] = strdup(token);
794 i++;
797 if (i == 1)
798 for (int j = 1; j < 4; j++)
799 ret[j] = strdup(ret[0]);
801 if (i == 2) {
802 ret[2] = strdup(ret[0]);
803 ret[3] = strdup(ret[1]);
806 if (i == 3)
807 ret[3] = strdup(ret[1]);
809 // Before we didn't check for the return type of strdup, here we will
811 bool any_null = false;
812 for (int i = 0; i < 4; ++i)
813 any_null = ret[i] == nil || any_null;
815 if (any_null)
816 for (int i = 0; i < 4; ++i)
817 if (ret[i] != nil)
818 free(ret[i]);
820 if (i == 0 || any_null) {
821 free(s);
822 free(ret);
823 return nil;
826 return ret;
829 // Given an event, try to understand what the user wants. If the
830 // return value is ADD_CHAR then `input' is a pointer to a string that
831 // will need to be free'ed.
832 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
833 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
834 return DEL_CHAR;
836 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
837 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
839 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
840 return CONFIRM;
842 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
843 return EXIT;
845 // try to read what the user pressed
846 char str[SYM_BUF_SIZE] = {0};
847 Status s = 0;
848 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
849 if (s == XBufferOverflow) {
850 // should not happen since there are no utf-8 characters larger
851 // than 24bits
852 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
853 return EXIT;
856 if (ev->state & ControlMask) {
857 if (!strcmp(str, "")) // C-u
858 return DEL_LINE;
859 if (!strcmp(str, "")) // C-w
860 return DEL_WORD;
861 if (!strcmp(str, "")) // C-h
862 return DEL_CHAR;
863 if (!strcmp(str, "\r")) // C-m
864 return CONFIRM_CONTINUE;
865 if (!strcmp(str, "")) // C-p
866 return PREV_COMPL;
867 if (!strcmp(str, "")) // C-n
868 return NEXT_COMPL;
869 if (!strcmp(str, "")) // C-c
870 return EXIT;
871 if (!strcmp(str, "\t")) // C-i
872 return TOGGLE_FIRST_SELECTED;
875 *input = strdup(str);
876 if (*input == nil) {
877 fprintf(stderr, "Error while allocating memory for key.\n");
878 return EXIT;
881 return ADD_CHAR;
884 // Given the name of the program (argv[0]?) print a small help on stderr
885 void usage(char *prgname) {
886 fprintf(stderr, "%s [-Aamvh] [-B colors] [-b borders] [-C color] [-c color]\n"
887 " [-d separator] [-e window] [-f font] [-H height] [-l layout]\n"
888 " [-P padding] [-p prompt] [-T color] [-t color] [-S color]\n"
889 " [-s color] [-W width] [-x coord] [-y coord]\n", prgname);
892 // small function used in the event loop
893 void confirm(enum state *status, struct rendering *r, struct completions *cs, char **text, int *textlen) {
894 if ((cs->selected != -1) || (cs->lenght > 0 && r->first_selected)) {
895 // if there is something selected expand it and return
896 int index = cs->selected == -1 ? 0 : cs->selected;
897 struct completion *c = cs->completions;
898 while (true) {
899 if (index == 0)
900 break;
901 c++;
902 index--;
904 char *t = c->rcompletion;
905 free(*text);
906 *text = strdup(t);
907 if (*text == nil) {
908 fprintf(stderr, "Memory allocation error\n");
909 *status = ERR;
911 *textlen = strlen(*text);
912 } else {
913 if (!r->free_text) {
914 // cannot accept arbitrary text
915 *status = LOOPING;
920 // event loop
921 enum state loop(struct rendering *r, char **text, int *textlen, struct completions *cs, char **lines, char **vlines) {
922 enum state status = LOOPING;
923 while (status == LOOPING) {
924 XEvent e;
925 XNextEvent(r->d, &e);
927 if (XFilterEvent(&e, r->w))
928 continue;
930 switch (e.type) {
931 case KeymapNotify:
932 XRefreshKeyboardMapping(&e.xmapping);
933 break;
935 case FocusIn:
936 // re-grab focus
937 if (e.xfocus.window != r->w)
938 grabfocus(r->d, r->w);
939 break;
941 case VisibilityNotify:
942 if (e.xvisibility.state != VisibilityUnobscured)
943 XRaiseWindow(r->d, r->w);
944 break;
946 case MapNotify:
947 get_wh(r->d, &r->w, &r->width, &r->height);
948 draw(r, *text, cs);
949 break;
951 case KeyPress: {
952 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
954 char *input;
955 switch (parse_event(r->d, ev, r->xic, &input)) {
956 case EXIT:
957 status = ERR;
958 break;
960 case CONFIRM: {
961 status = OK;
962 confirm(&status, r, cs, text, textlen);
963 break;
966 case CONFIRM_CONTINUE: {
967 status = OK_LOOP;
968 confirm(&status, r, cs, text, textlen);
969 break;
972 case PREV_COMPL: {
973 complete(cs, r->first_selected, true, text, textlen, &status);
974 r->offset = cs->selected;
975 break;
978 case NEXT_COMPL: {
979 complete(cs, r->first_selected, false, text, textlen, &status);
980 r->offset = cs->selected;
981 break;
984 case DEL_CHAR:
985 popc(*text);
986 update_completions(cs, *text, lines, vlines, r->first_selected);
987 r->offset = 0;
988 break;
990 case DEL_WORD: {
991 popw(*text);
992 update_completions(cs, *text, lines, vlines, r->first_selected);
993 break;
996 case DEL_LINE: {
997 for (int i = 0; i < *textlen; ++i)
998 *(*text + i) = 0;
999 update_completions(cs, *text, lines, vlines, r->first_selected);
1000 r->offset = 0;
1001 break;
1004 case ADD_CHAR: {
1005 int str_len = strlen(input);
1007 // sometimes a strange key is pressed (i.e. ctrl alone),
1008 // so input will be empty. Don't need to update completion
1009 // in this case
1010 if (str_len == 0)
1011 break;
1013 for (int i = 0; i < str_len; ++i) {
1014 *textlen = pushc(text, *textlen, input[i]);
1015 if (*textlen == -1) {
1016 fprintf(stderr, "Memory allocation error\n");
1017 status = ERR;
1018 break;
1021 if (status != ERR) {
1022 update_completions(cs, *text, lines, vlines, r->first_selected);
1023 free(input);
1025 r->offset = 0;
1026 break;
1029 case TOGGLE_FIRST_SELECTED:
1030 r->first_selected = !r->first_selected;
1031 if (r->first_selected && cs->selected < 0)
1032 cs->selected = 0;
1033 if (!r->first_selected && cs->selected == 0)
1034 cs->selected = -1;
1035 break;
1039 case ButtonPress: {
1040 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1041 /* if (ev->button == Button1) { /\* click *\/ */
1042 /* int x = ev->x - r.border_w; */
1043 /* int y = ev->y - r.border_n; */
1044 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1045 /* } */
1047 if (ev->button == Button4) /* scroll up */
1048 r->offset = MAX((ssize_t)r->offset - 1, 0);
1050 if (ev->button == Button5) /* scroll down */
1051 r->offset = MIN(r->offset + 1, cs->lenght - 1);
1053 break;
1057 draw(r, *text, cs);
1060 return status;
1063 int main(int argc, char **argv) {
1064 #ifdef HAVE_PLEDGE
1065 // stdio & rpat: to read and write stdio/stdout
1066 // unix: to connect to Xorg
1067 pledge("stdio rpath unix", "");
1068 #endif
1070 char *sep = nil;
1072 // by default the first completion isn't selected
1073 bool first_selected = false;
1075 // our parent window
1076 char *parent_window_id = nil;
1078 // the user can input arbitrary text
1079 bool free_text = true;
1081 // the user can select multiple entries
1082 bool multiple_select = false;
1084 // first round of args parsing
1085 int ch;
1086 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1087 switch (ch) {
1088 case 'h': // help
1089 usage(*argv);
1090 return 0;
1091 case 'v': // version
1092 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1093 return 0;
1094 case 'e': // embed
1095 parent_window_id = strdup(optarg);
1096 check_allocation(parent_window_id);
1097 break;
1098 case 'd': {
1099 sep = strdup(optarg);
1100 check_allocation(sep);
1102 case 'A': {
1103 free_text = false;
1104 break;
1106 case 'm': {
1107 multiple_select = true;
1108 break;
1110 default:
1111 break;
1115 // read the lines from stdin
1116 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
1117 check_allocation(lines);
1118 size_t nlines = readlines(&lines, INITIAL_ITEMS);
1119 char **vlines = nil;
1120 if (sep != nil) {
1121 int l = strlen(sep);
1122 vlines = calloc(nlines, sizeof(char*));
1123 check_allocation(vlines);
1125 for (int i = 0; lines[i] != nil; i++) {
1126 char *t = strstr(lines[i], sep);
1127 if (t == nil)
1128 vlines[i] = lines[i];
1129 else
1130 vlines[i] = t + l;
1134 setlocale(LC_ALL, getenv("LANG"));
1136 enum state status = LOOPING;
1138 // where the monitor start (used only with xinerama)
1139 int offset_x = 0;
1140 int offset_y = 0;
1142 // width and height of the window
1143 int width = 400;
1144 int height = 20;
1146 // position on the screen
1147 int x = 0;
1148 int y = 0;
1150 // the default padding
1151 int padding = 10;
1153 // the default borders
1154 int border_n = 0;
1155 int border_e = 0;
1156 int border_s = 0;
1157 int border_w = 0;
1159 // the prompt. We duplicate the string so later is easy to free (in
1160 // the case the user provide its own prompt)
1161 char *ps1 = strdup("$ ");
1162 check_allocation(ps1);
1164 // same for the font name
1165 char *fontname = strdup(default_fontname);
1166 check_allocation(fontname);
1168 int textlen = 10;
1169 char *text = malloc(textlen * sizeof(char));
1170 check_allocation(text);
1172 /* struct completions *cs = filter(text, lines); */
1173 struct completions *cs = compls_new(nlines);
1174 check_allocation(cs);
1176 // start talking to xorg
1177 Display *d = XOpenDisplay(nil);
1178 if (d == nil) {
1179 fprintf(stderr, "Could not open display!\n");
1180 return EX_UNAVAILABLE;
1183 Window parent_window;
1184 bool embed = true;
1185 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1186 parent_window = DefaultRootWindow(d);
1187 embed = false;
1190 // get display size
1191 int d_width;
1192 int d_height;
1193 get_wh(d, &parent_window, &d_width, &d_height);
1195 #ifdef USE_XINERAMA
1196 if (!embed && XineramaIsActive(d)) {
1197 // find the mice
1198 int number_of_screens = XScreenCount(d);
1199 Window r;
1200 Window root;
1201 int root_x, root_y, win_x, win_y;
1202 unsigned int mask;
1203 bool res;
1204 for (int i = 0; i < number_of_screens; ++i) {
1205 root = XRootWindow(d, i);
1206 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1207 if (res) break;
1209 if (!res) {
1210 fprintf(stderr, "No mouse found.\n");
1211 root_x = 0;
1212 root_y = 0;
1215 // now find in which monitor the mice is on
1216 int monitors;
1217 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1218 if (info) {
1219 for (int i = 0; i < monitors; ++i) {
1220 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1221 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1222 offset_x = info[i].x_org;
1223 offset_y = info[i].y_org;
1224 d_width = info[i].width;
1225 d_height = info[i].height;
1226 break;
1230 XFree(info);
1232 #endif
1234 /* Colormap cmap = DefaultColormap(d, DefaultScreen(d)); */
1235 XVisualInfo vinfo;
1236 XMatchVisualInfo(d, DefaultScreen(d), 32, TrueColor, &vinfo);
1238 Colormap cmap;
1239 cmap = XCreateColormap(d, XDefaultRootWindow(d), vinfo.visual, AllocNone);
1241 unsigned long p_fg = parse_color("#fff", nil);
1242 unsigned long compl_fg = parse_color("#fff", nil);
1243 unsigned long compl_highlighted_fg = parse_color("#000", nil);
1245 unsigned long p_bg = parse_color("#000", nil);
1246 unsigned long compl_bg = parse_color("#000", nil);
1247 unsigned long compl_highlighted_bg = parse_color("#fff", nil);
1249 unsigned long border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1250 border_n_bg = border_e_bg = border_s_bg = border_w_bg = parse_color("#000", nil);
1252 bool horizontal_layout = true;
1254 // read resource
1255 XrmInitialize();
1256 char *xrm = XResourceManagerString(d);
1257 XrmDatabase xdb = nil;
1258 if (xrm != nil) {
1259 xdb = XrmGetStringDatabase(xrm);
1260 XrmValue value;
1261 char *datatype[20];
1263 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1264 free(fontname);
1265 fontname = strdup(value.addr);
1266 check_allocation(fontname);
1267 } else {
1268 fprintf(stderr, "no font defined, using %s\n", fontname);
1271 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1272 horizontal_layout = !strcmp(value.addr, "horizontal");
1273 else
1274 fprintf(stderr, "no layout defined, using horizontal\n");
1276 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1277 free(ps1);
1278 ps1 = normalize_str(value.addr);
1279 } else {
1280 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1283 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1284 width = parse_int_with_percentage(value.addr, width, d_width);
1285 else
1286 fprintf(stderr, "no width defined, using %d\n", width);
1288 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1289 height = parse_int_with_percentage(value.addr, height, d_height);
1290 else
1291 fprintf(stderr, "no height defined, using %d\n", height);
1293 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1294 x = parse_int_with_pos(value.addr, x, d_width, width);
1295 else
1296 fprintf(stderr, "no x defined, using %d\n", x);
1298 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1299 y = parse_int_with_pos(value.addr, y, d_height, height);
1300 else
1301 fprintf(stderr, "no y defined, using %d\n", y);
1303 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1304 padding = parse_integer(value.addr, padding);
1305 else
1306 fprintf(stderr, "no padding defined, using %d\n", padding);
1308 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1309 char **borders = parse_csslike(value.addr);
1310 if (borders != nil) {
1311 border_n = parse_integer(borders[0], 0);
1312 border_e = parse_integer(borders[1], 0);
1313 border_s = parse_integer(borders[2], 0);
1314 border_w = parse_integer(borders[3], 0);
1315 } else {
1316 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1318 } else {
1319 fprintf(stderr, "no border defined, using 0.\n");
1322 /* XColor tmp; */
1323 // TODO: tmp needs to be free'd after every allocation?
1325 // prompt
1326 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1327 p_fg = parse_color(value.addr, "#fff");
1329 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1330 p_bg = parse_color(value.addr, "#000");
1332 // completion
1333 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1334 compl_fg = parse_color(value.addr, "#fff");
1336 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1337 compl_bg = parse_color(value.addr, "#000");
1338 else
1339 compl_bg = parse_color("#000", nil);
1341 // completion highlighted
1342 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1343 compl_highlighted_fg = parse_color(value.addr, "#000");
1345 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1346 compl_highlighted_bg = parse_color(value.addr, "#fff");
1347 else
1348 compl_highlighted_bg = parse_color("#fff", nil);
1350 // border
1351 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1352 char **colors = parse_csslike(value.addr);
1353 if (colors != nil) {
1354 border_n_bg = parse_color(colors[0], "#000");
1355 border_e_bg = parse_color(colors[1], "#000");
1356 border_s_bg = parse_color(colors[2], "#000");
1357 border_w_bg = parse_color(colors[3], "#000");
1358 } else {
1359 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1364 // second round of args parsing
1365 optind = 0; // reset the option index
1366 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1367 switch (ch) {
1368 case 'a':
1369 first_selected = true;
1370 break;
1371 case 'A':
1372 // free_text -- this case was already catched
1373 break;
1374 case 'd':
1375 // separator -- this case was already catched
1376 break;
1377 case 'e':
1378 // (embedding mymenu) this case was already catched.
1379 case 'm':
1380 // (multiple selection) this case was already catched.
1381 break;
1382 case 'p': {
1383 char *newprompt = strdup(optarg);
1384 if (newprompt != nil) {
1385 free(ps1);
1386 ps1 = newprompt;
1388 break;
1390 case 'x':
1391 x = parse_int_with_pos(optarg, x, d_width, width);
1392 break;
1393 case 'y':
1394 y = parse_int_with_pos(optarg, y, d_height, height);
1395 break;
1396 case 'P':
1397 padding = parse_integer(optarg, padding);
1398 break;
1399 case 'l':
1400 horizontal_layout = !strcmp(optarg, "horizontal");
1401 break;
1402 case 'f': {
1403 char *newfont = strdup(optarg);
1404 if (newfont != nil) {
1405 free(fontname);
1406 fontname = newfont;
1408 break;
1410 case 'W':
1411 width = parse_int_with_percentage(optarg, width, d_width);
1412 break;
1413 case 'H':
1414 height = parse_int_with_percentage(optarg, height, d_height);
1415 break;
1416 case 'b': {
1417 char **borders = parse_csslike(optarg);
1418 if (borders != nil) {
1419 border_n = parse_integer(borders[0], 0);
1420 border_e = parse_integer(borders[1], 0);
1421 border_s = parse_integer(borders[2], 0);
1422 border_w = parse_integer(borders[3], 0);
1423 } else {
1424 fprintf(stderr, "Error parsing b option\n");
1426 break;
1428 case 'B': {
1429 char **colors = parse_csslike(optarg);
1430 if (colors != nil) {
1431 border_n_bg = parse_color(colors[0], "#000");
1432 border_e_bg = parse_color(colors[1], "#000");
1433 border_s_bg = parse_color(colors[2], "#000");
1434 border_w_bg = parse_color(colors[3], "#000");
1435 } else {
1436 fprintf(stderr, "error while parsing B option\n");
1438 break;
1440 case 't': {
1441 p_fg = parse_color(optarg, nil);
1442 break;
1444 case 'T': {
1445 p_bg = parse_color(optarg, nil);
1446 break;
1448 case 'c': {
1449 compl_fg = parse_color(optarg, nil);
1450 break;
1452 case 'C': {
1453 compl_bg = parse_color(optarg, nil);
1454 break;
1456 case 's': {
1457 compl_highlighted_fg = parse_color(optarg, nil);
1458 break;
1460 case 'S': {
1461 compl_highlighted_bg = parse_color(optarg, nil);
1462 break;
1464 default:
1465 fprintf(stderr, "Unrecognized option %c\n", ch);
1466 status = ERR;
1467 break;
1471 // since only now we know if the first should be selected, update
1472 // the completion here
1473 update_completions(cs, text, lines, vlines, first_selected);
1475 // load the font
1476 #ifdef USE_XFT
1477 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1478 #else
1479 char **missing_charset_list;
1480 int missing_charset_count;
1481 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1482 if (font == nil) {
1483 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1484 return EX_UNAVAILABLE;
1486 #endif
1488 // create the window
1489 XSetWindowAttributes attr;
1490 attr.colormap = cmap;
1491 attr.override_redirect = true;
1492 attr.border_pixel = 0;
1493 attr.background_pixel = 0x80808080;
1494 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1496 Window w = XCreateWindow(d, // display
1497 parent_window, // parent
1498 x + offset_x, y + offset_y, // x y
1499 width, height, // w h
1500 0, // border width
1501 vinfo.depth, // depth
1502 InputOutput, // class
1503 vinfo.visual, // visual
1504 CWBorderPixel | CWBackPixel | CWColormap | CWEventMask | CWOverrideRedirect, // value mask
1505 &attr);
1507 set_win_atoms_hints(d, w, width, height);
1509 // we want some events
1510 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1511 XMapRaised(d, w);
1513 // if embed, listen for other events as well
1514 if (embed) {
1515 XSelectInput(d, parent_window, FocusChangeMask);
1516 Window *children, parent, root;
1517 unsigned int children_no;
1518 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1519 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1520 XSelectInput(d, children[i], FocusChangeMask);
1521 XFree(children);
1523 grabfocus(d, w);
1526 // grab keyboard
1527 take_keyboard(d, w);
1529 // Create some graphics contexts
1530 XGCValues values;
1531 /* values.font = font->fid; */
1533 struct rendering r = {
1534 .d = d,
1535 .w = w,
1536 .width = width,
1537 .height = height,
1538 .padding = padding,
1539 .x_zero = border_w,
1540 .y_zero = border_n,
1541 .offset = 0,
1542 .free_text = free_text,
1543 .first_selected = first_selected,
1544 .multiple_select = multiple_select,
1545 .border_n = border_n,
1546 .border_e = border_e,
1547 .border_s = border_s,
1548 .border_w = border_w,
1549 .horizontal_layout = horizontal_layout,
1550 .ps1 = ps1,
1551 .ps1len = strlen(ps1),
1552 .prompt = XCreateGC(d, w, 0, &values),
1553 .prompt_bg = XCreateGC(d, w, 0, &values),
1554 .completion = XCreateGC(d, w, 0, &values),
1555 .completion_bg = XCreateGC(d, w, 0, &values),
1556 .completion_highlighted = XCreateGC(d, w, 0, &values),
1557 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1558 .border_n_bg = XCreateGC(d, w, 0, &values),
1559 .border_e_bg = XCreateGC(d, w, 0, &values),
1560 .border_s_bg = XCreateGC(d, w, 0, &values),
1561 .border_w_bg = XCreateGC(d, w, 0, &values),
1562 #ifdef USE_XFT
1563 .font = font,
1564 #else
1565 .font = &font,
1566 #endif
1569 #ifdef USE_XFT
1570 r.xftdraw = XftDrawCreate(d, w, vinfo.visual, DefaultColormap(d, 0));
1573 rgba_t c;
1575 XRenderColor xrcolor;
1577 // prompt
1578 c = *(rgba_t*)&p_fg;
1579 xrcolor.red = EXPANDBITS(c.r);
1580 xrcolor.green = EXPANDBITS(c.g);
1581 xrcolor.blue = EXPANDBITS(c.b);
1582 xrcolor.alpha = EXPANDBITS(c.a);
1583 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1585 // completion
1586 c = *(rgba_t*)&compl_fg;
1587 xrcolor.red = EXPANDBITS(c.r);
1588 xrcolor.green = EXPANDBITS(c.g);
1589 xrcolor.blue = EXPANDBITS(c.b);
1590 xrcolor.alpha = EXPANDBITS(c.a);
1591 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1593 // completion highlighted
1594 c = *(rgba_t*)&compl_highlighted_fg;
1595 xrcolor.red = EXPANDBITS(c.r);
1596 xrcolor.green = EXPANDBITS(c.g);
1597 xrcolor.blue = EXPANDBITS(c.b);
1598 xrcolor.alpha = EXPANDBITS(c.a);
1599 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1601 #endif
1603 // load the colors in our GCs
1604 /* XSetForeground(d, r.prompt, p_fg.pixel); */
1605 XSetForeground(d, r.prompt, p_fg);
1606 XSetForeground(d, r.prompt_bg, p_bg);
1607 /* XSetForeground(d, r.completion, compl_fg.pixel); */
1608 XSetForeground(d, r.completion, compl_fg);
1609 XSetForeground(d, r.completion_bg, compl_bg);
1610 /* XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel); */
1611 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg);
1612 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg);
1613 XSetForeground(d, r.border_n_bg, border_n_bg);
1614 XSetForeground(d, r.border_e_bg, border_e_bg);
1615 XSetForeground(d, r.border_s_bg, border_s_bg);
1616 XSetForeground(d, r.border_w_bg, border_w_bg);
1618 // open the X input method
1619 XIM xim = XOpenIM(d, xdb, resname, resclass);
1620 check_allocation(xim);
1622 XIMStyles *xis = nil;
1623 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1624 fprintf(stderr, "Input Styles could not be retrieved\n");
1625 return EX_UNAVAILABLE;
1628 XIMStyle bestMatchStyle = 0;
1629 for (int i = 0; i < xis->count_styles; ++i) {
1630 XIMStyle ts = xis->supported_styles[i];
1631 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1632 bestMatchStyle = ts;
1633 break;
1636 XFree(xis);
1638 if (!bestMatchStyle) {
1639 fprintf(stderr, "No matching input style could be determined\n");
1642 r.xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1643 check_allocation(r.xic);
1645 // draw the window for the first time
1646 draw(&r, text, cs);
1648 // main loop
1649 while (status == LOOPING || status == OK_LOOP) {
1650 status = loop(&r, &text, &textlen, cs, lines, vlines);
1652 if (status != ERR)
1653 printf("%s\n", text);
1655 if (!multiple_select && status == OK_LOOP)
1656 status = OK;
1659 release_keyboard(r.d);
1661 #ifdef USE_XFT
1662 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1663 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1664 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1665 #endif
1667 free(ps1);
1668 free(fontname);
1669 free(text);
1671 char *l = nil;
1672 char **lns = lines;
1673 while ((l = *lns) != nil) {
1674 free(l);
1675 ++lns;
1678 free(lines);
1679 free(vlines);
1680 compls_delete(cs);
1682 XDestroyWindow(r.d, r.w);
1683 XCloseDisplay(r.d);
1685 return status != OK;