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 MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 // If we don't have it or we don't want an "ignore case" completion
48 // style, fall back to `strstr(3)`
49 #ifndef USE_STRCASESTR
50 # define strcasestr strstr
51 #endif
53 #define INITIAL_ITEMS 64
55 #define check_allocation(a) { \
56 if (a == nil) { \
57 fprintf(stderr, "Could not allocate memory\n"); \
58 abort(); \
59 } \
60 }
62 #define inner_height(r) (r->height - r->border_n - r->border_s)
63 #define inner_width(r) (r->width - r->border_e - r->border_w)
65 // The possible state of the event loop.
66 enum state {LOOPING, OK, ERR};
68 // for the drawing-related function. The text to be rendered could be
69 // the prompt, a completion or a highlighted completion
70 enum text_type {PROMPT, COMPL, COMPL_HIGH};
72 // These are the possible action to be performed after user input.
73 enum action {
74 EXIT,
75 CONFIRM,
76 NEXT_COMPL,
77 PREV_COMPL,
78 DEL_CHAR,
79 DEL_WORD,
80 DEL_LINE,
81 ADD_CHAR,
82 TOGGLE_FIRST_SELECTED
83 };
85 struct rendering {
86 Display *d; // connection to xorg
87 Window w;
88 int width;
89 int height;
90 int padding;
91 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
92 int y_zero; // the same a x_zero, only for the y axis
94 // The four border
95 int border_n;
96 int border_e;
97 int border_s;
98 int border_w;
100 bool horizontal_layout;
102 // the prompt
103 char *ps1;
104 int ps1len;
106 // colors
107 GC prompt;
108 GC prompt_bg;
109 GC completion;
110 GC completion_bg;
111 GC completion_highlighted;
112 GC completion_highlighted_bg;
113 GC border_n_bg;
114 GC border_e_bg;
115 GC border_s_bg;
116 GC border_w_bg;
117 #ifdef USE_XFT
118 XftFont *font;
119 XftDraw *xftdraw;
120 XftColor xft_prompt;
121 XftColor xft_completion;
122 XftColor xft_completion_highlighted;
123 #else
124 XFontSet *font;
125 #endif
126 };
128 // A simple linked list to store the completions.
129 struct completion {
130 char *completion;
131 struct completion *next;
132 };
134 struct completions {
135 struct completion *completions;
136 int selected;
137 int lenght;
138 };
140 // return a newly allocated (and empty) completion list
141 struct completions *compls_new() {
142 struct completions *cs = malloc(sizeof(struct completions));
144 if (cs == nil)
145 return cs;
147 cs->completions = nil;
148 cs->selected = -1;
149 cs->lenght = 0;
150 return cs;
153 struct completion *compl_new() {
154 struct completion *c = malloc(sizeof(struct completion));
155 if (c == nil)
156 return c;
158 c->completion = nil;
159 c->next = nil;
160 return c;
163 // delete ONLY the given completion (i.e. does not free c->next...)
164 void compl_delete(struct completion *c) {
165 free(c);
168 // delete the current completion and the next (c->next) and so on...
169 void compl_delete_rec(struct completion *c) {
170 while (c != nil) {
171 struct completion *t = c->next;
172 free(c);
173 c = t;
177 void compls_delete(struct completions *cs) {
178 if (cs == nil)
179 return;
181 compl_delete_rec(cs->completions);
182 free(cs);
185 // create a completion list from a text and the list of possible
186 // completions (null terminated). Expects a non-null `cs'.
187 void filter(struct completions *cs, char *text, char **lines) {
188 struct completion *c = compl_new();
189 if (c == nil) {
190 return;
193 cs->completions = c;
195 int index = 0;
196 int matching = 0;
198 while (true) {
199 char *l = lines[index];
200 if (l == nil)
201 break;
203 if (strcasestr(l, text) != nil) {
204 matching++;
206 c->next = compl_new();
207 c = c->next;
208 if (c == nil) {
209 compls_delete(cs);
210 return;
212 c->completion = l;
215 index++;
218 struct completion *f = cs->completions->next;
219 compl_delete(cs->completions);
220 cs->completions = f;
221 cs->lenght = matching;
222 cs->selected = -1;
225 // update the given completion, that is: clean the old cs & generate a new one.
226 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
227 compl_delete_rec(cs->completions);
228 filter(cs, text, lines);
229 if (first_selected && cs->lenght > 0)
230 cs->selected = 0;
233 // select the next, or the previous, selection and update some
234 // state. `text' will be updated with the text of the completion and
235 // `textlen' with the new lenght of `text'. If the memory cannot be
236 // allocated, `status' will be set to `ERR'.
237 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
238 if (cs == nil || cs->lenght == 0)
239 return;
241 // if the first is always selected, and the first entry is different
242 // from the text, expand the text and return
243 if (first_selected
244 && cs->selected == 0
245 && strcmp(cs->completions->completion, *text) != 0
246 && !p) {
247 free(*text);
248 *text = strdup(cs->completions->completion);
249 if (text == nil) {
250 *status = ERR;
251 return;
253 *textlen = strlen(*text);
254 return;
257 int index = cs->selected;
259 if (index == -1 && p)
260 index = 0;
261 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
263 struct completion *n = cs->completions;
265 // find the selected item
266 while (index != 0) {
267 index--;
268 n = n->next;
271 free(*text);
272 *text = strdup(n->completion);
273 if (text == nil) {
274 fprintf(stderr, "Memory allocation error!\n");
275 *status = ERR;
276 return;
278 *textlen = strlen(*text);
281 // push the character c at the end of the string pointed by p
282 int pushc(char **p, int maxlen, char c) {
283 int len = strnlen(*p, maxlen);
285 if (!(len < maxlen -2)) {
286 maxlen += maxlen >> 1;
287 char *newptr = realloc(*p, maxlen);
288 if (newptr == nil) { // bad!
289 return -1;
291 *p = newptr;
294 (*p)[len] = c;
295 (*p)[len+1] = '\0';
296 return maxlen;
299 // return the number of character
300 int utf8strnlen(char *s, int maxlen) {
301 int len = 0;
302 while (*s && maxlen > 0) {
303 len += (*s++ & 0xc0) != 0x80;
304 maxlen--;
306 return len;
309 // remove the last *glyph* from the *utf8* string!
310 // this is different from just setting the last byte to 0 (in some
311 // cases ofc). The actual implementation is quite inefficient because
312 // it remove the last byte until the number of glyphs doesn't change
313 void popc(char *p, int maxlen) {
314 int len = strnlen(p, maxlen);
316 if (len == 0)
317 return;
319 int ulen = utf8strnlen(p, maxlen);
320 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
321 len--;
322 p[len] = 0;
326 // If the string is surrounded by quotes (`"`) remove them and replace
327 // every `\"` in the string with `"`
328 char *normalize_str(const char *str) {
329 int len = strlen(str);
330 if (len == 0)
331 return nil;
333 char *s = calloc(len, sizeof(char));
334 check_allocation(s);
335 int p = 0;
336 while (*str) {
337 char c = *str;
338 if (*str == '\\') {
339 if (*(str + 1)) {
340 s[p] = *(str + 1);
341 p++;
342 str += 2; // skip this and the next char
343 continue;
344 } else {
345 break;
348 if (c == '"') {
349 str++; // skip only this char
350 continue;
352 s[p] = c;
353 p++;
354 str++;
356 return s;
359 // read an arbitrary long line from stdin and return a pointer to it
360 // TODO: resize the allocated memory to exactly fit the string once
361 // read?
362 char *readline(bool *eof) {
363 int maxlen = 8;
364 char *str = calloc(maxlen, sizeof(char));
365 if (str == nil) {
366 fprintf(stderr, "Cannot allocate memory!\n");
367 exit(EX_UNAVAILABLE);
370 int c;
371 while((c = getchar()) != EOF) {
372 if (c == '\n')
373 return str;
374 else
375 maxlen = pushc(&str, maxlen, c);
377 if (maxlen == -1) {
378 fprintf(stderr, "Cannot allocate memory!\n");
379 exit(EX_UNAVAILABLE);
382 *eof = true;
383 return str;
386 // read an arbitrary amount of text until an EOF and store it in
387 // lns. `items` is the capacity of lns. It may increase lns with
388 // `realloc(3)` to store more line. Return the number of lines
389 // read. The last item will always be a NULL pointer. It ignore the
390 // "null" (empty) lines
391 int readlines (char ***lns, int items) {
392 bool finished = false;
393 int n = 0;
394 char **lines = *lns;
395 while (true) {
396 lines[n] = readline(&finished);
398 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
399 free(lines[n]);
400 --n; // forget about this line
403 if (finished)
404 break;
406 ++n;
408 if (n == items - 1) {
409 items += items >>1;
410 char **l = realloc(lines, sizeof(char*) * items);
411 check_allocation(l);
412 *lns = l;
413 lines = l;
417 n++;
418 lines[n] = nil;
419 return items;
422 // Compute the dimension of the string str once rendered, return the
423 // width and save the width and the height in ret_width and ret_height
424 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
425 int height;
426 int width;
427 #ifdef USE_XFT
428 XGlyphInfo gi;
429 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
430 /* height = gi.height; */
431 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
432 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
433 height = r->font->ascent - r->font->descent;
434 width = gi.width - gi.x;
435 #else
436 XRectangle rect;
437 XmbTextExtents(*r->font, str, len, nil, &rect);
438 height = rect.height;
439 width = rect.width;
440 #endif
441 if (ret_width != nil) *ret_width = width;
442 if (ret_height != nil) *ret_height = height;
443 return width;
446 // Draw the string str
447 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
448 #ifdef USE_XFT
449 XftColor xftcolor;
450 if (tt == PROMPT) xftcolor = r->xft_prompt;
451 if (tt == COMPL) xftcolor = r->xft_completion;
452 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
454 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
455 #else
456 GC gc;
457 if (tt == PROMPT) gc = r->prompt;
458 if (tt == COMPL) gc = r->completion;
459 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
460 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
461 #endif
464 // Duplicate the string str and substitute every space with a 'n'
465 char *strdupn(char *str) {
466 int len = strlen(str);
468 if (str == nil || len == 0)
469 return nil;
471 char *dup = strdup(str);
472 if (dup == nil)
473 return nil;
475 for (int i = 0; i < len; ++i)
476 if (dup[i] == ' ')
477 dup[i] = 'n';
479 return dup;
482 // |------------------|----------------------------------------------|
483 // | 20 char text | completion | completion | completion | compl |
484 // |------------------|----------------------------------------------|
485 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
486 int prompt_width = 20; // char
488 int width, height;
489 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
490 int start_at = ps1xlen;
492 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
493 start_at = start_at * prompt_width + r->padding;
495 int texty = (height + r->height) >>1;
497 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
499 int text_len = strlen(text);
500 if (text_len > prompt_width)
501 text = text + (text_len - prompt_width);
502 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
503 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
505 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, r->height);
507 struct completion *c = cs->completions;
508 for (int i = 0; c != nil; ++i) {
509 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
510 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
512 int len = strlen(c->completion);
513 int text_width = text_extents(c->completion, len, r, nil, nil);
515 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
517 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
519 start_at += text_width + r->padding * 2;
521 if (start_at > inner_width(r))
522 break; // don't draw completion if the space isn't enough
524 c = c->next;
528 // |-----------------------------------------------------------------|
529 // | prompt |
530 // |-----------------------------------------------------------------|
531 // | completion |
532 // |-----------------------------------------------------------------|
533 // | completion |
534 // |-----------------------------------------------------------------|
535 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
536 int height, width;
537 text_extents("fjpgl", 5, r, nil, &height);
538 int start_at = height + r->padding;
540 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
541 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
543 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
545 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, height + r->padding, r, PROMPT);
546 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, height + r->padding, r, PROMPT);
548 start_at += r->padding;
550 struct completion *c = cs->completions;
551 for (int i = 0; c != nil; ++i){
552 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
553 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
555 int len = strlen(c->completion);
556 text_extents(c->completion, len, r, &width, &height);
557 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
558 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
560 start_at += height + r->padding *2;
562 if (start_at > inner_height(r))
563 break; // don't draw completion if the space isn't enough
565 c = c->next;
569 void draw(struct rendering *r, char *text, struct completions *cs) {
570 if (r->horizontal_layout)
571 draw_horizontally(r, text, cs);
572 else
573 draw_vertically(r, text, cs);
575 // draw the borders
577 if (r->border_w != 0)
578 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
580 if (r->border_e != 0)
581 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
583 if (r->border_n != 0)
584 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
586 if (r->border_s != 0)
587 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
589 // send all the work to x
590 XFlush(r->d);
593 /* Set some WM stuff */
594 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
595 Atom type;
596 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
597 XChangeProperty(
598 d,
599 w,
600 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
601 XInternAtom(d, "ATOM", false),
602 32,
603 PropModeReplace,
604 (unsigned char *)&type,
606 );
608 /* some window managers honor this properties */
609 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
610 XChangeProperty(d,
611 w,
612 XInternAtom(d, "_NET_WM_STATE", false),
613 XInternAtom(d, "ATOM", false),
614 32,
615 PropModeReplace,
616 (unsigned char *)&type,
618 );
620 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
621 XChangeProperty(d,
622 w,
623 XInternAtom(d, "_NET_WM_STATE", false),
624 XInternAtom(d, "ATOM", false),
625 32,
626 PropModeAppend,
627 (unsigned char *)&type,
629 );
631 // setting window hints
632 XClassHint *class_hint = XAllocClassHint();
633 if (class_hint == nil) {
634 fprintf(stderr, "Could not allocate memory for class hint\n");
635 exit(EX_UNAVAILABLE);
637 class_hint->res_name = resname;
638 class_hint->res_class = resclass;
639 XSetClassHint(d, w, class_hint);
640 XFree(class_hint);
642 XSizeHints *size_hint = XAllocSizeHints();
643 if (size_hint == nil) {
644 fprintf(stderr, "Could not allocate memory for size hint\n");
645 exit(EX_UNAVAILABLE);
647 size_hint->flags = PMinSize | PBaseSize;
648 size_hint->min_width = width;
649 size_hint->base_width = width;
650 size_hint->min_height = height;
651 size_hint->base_height = height;
653 XFlush(d);
656 // write the width and height of the window `w' respectively in `width'
657 // and `height'.
658 void get_wh(Display *d, Window *w, int *width, int *height) {
659 XWindowAttributes win_attr;
660 XGetWindowAttributes(d, *w, &win_attr);
661 *height = win_attr.height;
662 *width = win_attr.width;
665 // I know this may seem a little hackish BUT is the only way I managed
666 // to actually grab that goddam keyboard. Only one call to
667 // XGrabKeyboard does not always end up with the keyboard grabbed!
668 int take_keyboard(Display *d, Window w) {
669 int i;
670 for (i = 0; i < 100; i++) {
671 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
672 return 1;
673 usleep(1000);
675 return 0;
678 // release the keyboard.
679 void release_keyboard(Display *d) {
680 XUngrabKeyboard(d, CurrentTime);
683 // Given a string, try to parse it as a number or return
684 // `default_value'.
685 int parse_integer(const char *str, int default_value) {
686 errno = 0;
687 char *ep;
688 long lval = strtol(str, &ep, 10);
689 if (str[0] == '\0' || *ep != '\0') { // NaN
690 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
691 return default_value;
693 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
694 (lval > INT_MAX || lval < INT_MIN)) {
695 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
696 return default_value;
698 return lval;
701 // like parse_integer, but if the value ends with a `%' then its
702 // treated like a percentage (`max' is used to compute the percentage)
703 int parse_int_with_percentage(const char *str, int default_value, int max) {
704 int len = strlen(str);
705 if (len > 0 && str[len-1] == '%') {
706 char *cpy = strdup(str);
707 check_allocation(cpy);
708 cpy[len-1] = '\0';
709 int val = parse_integer(cpy, default_value);
710 free(cpy);
711 return val * max / 100;
713 return parse_integer(str, default_value);
716 // like parse_int_with_percentage but understands some special values
717 // - "middle" that is (max - self) / 2
718 // - "start" that is 0
719 // - "end" that is (max - self)
720 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
721 if (!strcmp(str, "start"))
722 return 0;
723 if (!strcmp(str, "middle"))
724 return (max - self)/2;
725 if (!strcmp(str, "end"))
726 return max-self;
727 return parse_int_with_percentage(str, default_value, max);
730 // parse a string like a css value (for example like the css
731 // margin/padding properties). Will ALWAYS return an array of 4 word
732 // TODO: harden this function!
733 char **parse_csslike(const char *str) {
734 char *s = strdup(str);
735 if (s == nil)
736 return nil;
738 char **ret = malloc(4 * sizeof(char*));
739 if (ret == nil) {
740 free(s);
741 return nil;
744 int i = 0;
745 char *token;
746 while ((token = strsep(&s, " ")) != NULL && i < 4) {
747 ret[i] = strdup(token);
748 i++;
751 if (i == 1)
752 for (int j = 1; j < 4; j++)
753 ret[j] = strdup(ret[0]);
755 if (i == 2) {
756 ret[2] = strdup(ret[0]);
757 ret[3] = strdup(ret[1]);
760 if (i == 3)
761 ret[3] = strdup(ret[1]);
763 // Before we didn't check for the return type of strdup, here we will
765 bool any_null = false;
766 for (int i = 0; i < 4; ++i)
767 any_null = ret[i] == nil || any_null;
769 if (any_null)
770 for (int i = 0; i < 4; ++i)
771 if (ret[i] != nil)
772 free(ret[i]);
774 if (i == 0 || any_null) {
775 free(s);
776 free(ret);
777 return nil;
780 return ret;
783 // Given an event, try to understand what the user wants. If the
784 // return value is ADD_CHAR then `input' is a pointer to a string that
785 // will need to be free'ed.
786 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
787 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
788 return DEL_CHAR;
790 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
791 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
793 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
794 return CONFIRM;
796 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
797 return EXIT;
799 // try to read what the user pressed
800 char str[SYM_BUF_SIZE] = {0};
801 Status s = 0;
802 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
803 if (s == XBufferOverflow) {
804 // should not happen since there are no utf-8 characters larger
805 // than 24bits
806 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
807 return EXIT;
810 if (ev->state & ControlMask) {
811 if (!strcmp(str, "")) // C-u
812 return DEL_LINE;
813 if (!strcmp(str, "")) // C-w
814 return DEL_WORD;
815 if (!strcmp(str, "")) // C-h
816 return DEL_CHAR;
817 if (!strcmp(str, "\r")) // C-m
818 return CONFIRM;
819 if (!strcmp(str, "")) // C-p
820 return PREV_COMPL;
821 if (!strcmp(str, "")) // C-n
822 return NEXT_COMPL;
823 if (!strcmp(str, "")) // C-c
824 return EXIT;
825 if (!strcmp(str, "\t")) // C-i
826 return TOGGLE_FIRST_SELECTED;
829 *input = strdup(str);
830 if (*input == nil) {
831 fprintf(stderr, "Error while allocating memory for key.\n");
832 return EXIT;
835 return ADD_CHAR;
838 // Given the name of the program (argv[0]?) print a small help on stderr
839 void usage(char *prgname) {
840 fprintf(stderr, "Usage: %s [flags]\n", prgname);
841 fprintf(stderr, "\t-a: automatic mode, the first completion is "
842 "always selected;\n");
843 fprintf(stderr, "\t-h: print this help.\n");
846 int main(int argc, char **argv) {
847 #ifdef HAVE_PLEDGE
848 // stdio & rpat: to read and write stdio/stdout
849 // unix: to connect to Xorg
850 pledge("stdio rpath unix", "");
851 #endif
853 // by default the first completion isn't selected
854 bool first_selected = false;
856 // parse the command line options
857 int ch;
858 while ((ch = getopt(argc, argv, "ahv")) != -1) {
859 switch (ch) {
860 case 'a':
861 first_selected = true;
862 break;
863 case 'h':
864 usage(*argv);
865 return 0;
866 case 'v':
867 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
868 return 0;
869 default:
870 usage(*argv);
871 return EX_USAGE;
875 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
876 readlines(&lines, INITIAL_ITEMS);
878 setlocale(LC_ALL, getenv("LANG"));
880 enum state status = LOOPING;
882 // where the monitor start (used only with xinerama)
883 int offset_x = 0;
884 int offset_y = 0;
886 // width and height of the window
887 int width = 400;
888 int height = 20;
890 // position on the screen
891 int x = 0;
892 int y = 0;
894 // the default padding
895 int padding = 10;
897 // the default borders
898 int border_n = 0;
899 int border_e = 0;
900 int border_s = 0;
901 int border_w = 0;
903 // the prompt. We duplicate the string so later is easy to free (in
904 // the case the user provide its own prompt)
905 char *ps1 = strdup("$ ");
906 check_allocation(ps1);
908 // same for the font name
909 char *fontname = strdup(default_fontname);
910 check_allocation(fontname);
912 int textlen = 10;
913 char *text = malloc(textlen * sizeof(char));
914 check_allocation(text);
916 /* struct completions *cs = filter(text, lines); */
917 struct completions *cs = compls_new();
918 check_allocation(cs);
920 update_completions(cs, text, lines, first_selected);
922 // start talking to xorg
923 Display *d = XOpenDisplay(nil);
924 if (d == nil) {
925 fprintf(stderr, "Could not open display!\n");
926 return EX_UNAVAILABLE;
929 // get display size
930 // XXX: is getting the default root window dimension correct?
931 XWindowAttributes xwa;
932 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
933 int d_width = xwa.width;
934 int d_height = xwa.height;
936 #ifdef USE_XINERAMA
937 if (XineramaIsActive(d)) {
938 // find the mice
939 int number_of_screens = XScreenCount(d);
940 Window r;
941 Window root;
942 int root_x, root_y, win_x, win_y;
943 unsigned int mask;
944 bool res;
945 for (int i = 0; i < number_of_screens; ++i) {
946 root = XRootWindow(d, i);
947 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
948 if (res) break;
950 if (!res) {
951 fprintf(stderr, "No mouse found.\n");
952 root_x = 0;
953 root_y = 0;
956 // now find in which monitor the mice is on
957 int monitors;
958 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
959 if (info) {
960 for (int i = 0; i < monitors; ++i) {
961 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
962 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
963 offset_x = info[i].x_org;
964 offset_y = info[i].y_org;
965 d_width = info[i].width;
966 d_height = info[i].height;
967 break;
971 XFree(info);
973 #endif
975 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
976 XColor p_fg, p_bg,
977 compl_fg, compl_bg,
978 compl_highlighted_fg, compl_highlighted_bg,
979 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
981 bool horizontal_layout = true;
983 // read resource
984 XrmInitialize();
985 char *xrm = XResourceManagerString(d);
986 XrmDatabase xdb = nil;
987 if (xrm != nil) {
988 xdb = XrmGetStringDatabase(xrm);
989 XrmValue value;
990 char *datatype[20];
992 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
993 fontname = strdup(value.addr);
994 check_allocation(fontname);
996 else
997 fprintf(stderr, "no font defined, using %s\n", fontname);
999 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
1000 char *v = strdup(value.addr);
1001 check_allocation(v);
1002 horizontal_layout = !strcmp(v, "horizontal");
1003 free(v);
1005 else
1006 fprintf(stderr, "no layout defined, using horizontal\n");
1008 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1009 free(ps1);
1010 ps1 = normalize_str(value.addr);
1011 } else
1012 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1014 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1015 width = parse_int_with_percentage(value.addr, width, d_width);
1016 else
1017 fprintf(stderr, "no width defined, using %d\n", width);
1019 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1020 height = parse_int_with_percentage(value.addr, height, d_height);
1021 else
1022 fprintf(stderr, "no height defined, using %d\n", height);
1024 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1025 x = parse_int_with_pos(value.addr, x, d_width, width);
1026 else
1027 fprintf(stderr, "no x defined, using %d\n", x);
1029 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1030 y = parse_int_with_pos(value.addr, y, d_height, height);
1031 else
1032 fprintf(stderr, "no y defined, using %d\n", y);
1034 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1035 padding = parse_integer(value.addr, padding);
1036 else
1037 fprintf(stderr, "no padding defined, using %d\n", padding);
1039 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1040 char **borders = parse_csslike(value.addr);
1041 if (borders != nil) {
1042 border_n = parse_integer(borders[0], 0);
1043 border_e = parse_integer(borders[1], 0);
1044 border_s = parse_integer(borders[2], 0);
1045 border_w = parse_integer(borders[3], 0);
1046 } else {
1047 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1049 } else {
1050 fprintf(stderr, "no border defined, using 0.\n");
1053 XColor tmp;
1054 // TODO: tmp needs to be free'd after every allocation?
1056 // prompt
1057 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1058 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1059 else
1060 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1062 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1063 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1064 else
1065 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1067 // completion
1068 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1069 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1070 else
1071 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1073 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1074 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1075 else
1076 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1078 // completion highlighted
1079 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1080 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1081 else
1082 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1084 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1085 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1086 else
1087 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1089 // border
1090 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1091 char **colors = parse_csslike(value.addr);
1092 if (colors != nil) {
1093 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1094 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1095 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1096 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1097 } else {
1098 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1100 } else {
1101 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1102 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1103 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1104 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1106 } else {
1107 XColor tmp;
1108 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1109 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1110 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1111 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1112 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1113 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1114 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1115 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1116 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1119 // load the font
1120 #ifdef USE_XFT
1121 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1122 #else
1123 char **missing_charset_list;
1124 int missing_charset_count;
1125 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1126 if (font == nil) {
1127 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1128 return EX_UNAVAILABLE;
1130 #endif
1132 // create the window
1133 XSetWindowAttributes attr;
1134 attr.override_redirect = true;
1136 Window w = XCreateWindow(d, // display
1137 DefaultRootWindow(d), // parent
1138 x + offset_x, y + offset_y, // x y
1139 width, height, // w h
1140 0, // border width
1141 DefaultDepth(d, DefaultScreen(d)), // depth
1142 InputOutput, // class
1143 DefaultVisual(d, DefaultScreen(d)), // visual
1144 CWOverrideRedirect, // value mask
1145 &attr);
1147 set_win_atoms_hints(d, w, width, height);
1149 // we want some events
1150 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1152 // make the window appear on the screen
1153 XMapWindow(d, w);
1155 // wait for the MapNotify event (i.e. the event "window rendered")
1156 for (;;) {
1157 XEvent e;
1158 XNextEvent(d, &e);
1159 if (e.type == MapNotify)
1160 break;
1163 // get the *real* width & height after the window was rendered
1164 get_wh(d, &w, &width, &height);
1166 // grab keyboard
1167 take_keyboard(d, w);
1169 // Create some graphics contexts
1170 XGCValues values;
1171 /* values.font = font->fid; */
1173 struct rendering r = {
1174 .d = d,
1175 .w = w,
1176 .width = width,
1177 .height = height,
1178 .padding = padding,
1179 .x_zero = border_w,
1180 .y_zero = border_n,
1181 .border_n = border_n,
1182 .border_e = border_e,
1183 .border_s = border_s,
1184 .border_w = border_w,
1185 .horizontal_layout = horizontal_layout,
1186 .ps1 = ps1,
1187 .ps1len = strlen(ps1),
1188 .prompt = XCreateGC(d, w, 0, &values),
1189 .prompt_bg = XCreateGC(d, w, 0, &values),
1190 .completion = XCreateGC(d, w, 0, &values),
1191 .completion_bg = XCreateGC(d, w, 0, &values),
1192 .completion_highlighted = XCreateGC(d, w, 0, &values),
1193 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1194 .border_n_bg = XCreateGC(d, w, 0, &values),
1195 .border_e_bg = XCreateGC(d, w, 0, &values),
1196 .border_s_bg = XCreateGC(d, w, 0, &values),
1197 .border_w_bg = XCreateGC(d, w, 0, &values),
1198 #ifdef USE_XFT
1199 .font = font,
1200 #else
1201 .font = &font,
1202 #endif
1205 #ifdef USE_XFT
1206 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1208 // prompt
1209 XRenderColor xrcolor;
1210 xrcolor.red = p_fg.red;
1211 xrcolor.green = p_fg.red;
1212 xrcolor.blue = p_fg.red;
1213 xrcolor.alpha = 65535;
1214 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1216 // completion
1217 xrcolor.red = compl_fg.red;
1218 xrcolor.green = compl_fg.green;
1219 xrcolor.blue = compl_fg.blue;
1220 xrcolor.alpha = 65535;
1221 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1223 // completion highlighted
1224 xrcolor.red = compl_highlighted_fg.red;
1225 xrcolor.green = compl_highlighted_fg.green;
1226 xrcolor.blue = compl_highlighted_fg.blue;
1227 xrcolor.alpha = 65535;
1228 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1229 #endif
1231 // load the colors in our GCs
1232 XSetForeground(d, r.prompt, p_fg.pixel);
1233 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1234 XSetForeground(d, r.completion, compl_fg.pixel);
1235 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1236 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1237 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1238 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1239 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1240 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1241 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1243 // open the X input method
1244 XIM xim = XOpenIM(d, xdb, resname, resclass);
1245 check_allocation(xim);
1247 XIMStyles *xis = nil;
1248 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1249 fprintf(stderr, "Input Styles could not be retrieved\n");
1250 return EX_UNAVAILABLE;
1253 XIMStyle bestMatchStyle = 0;
1254 for (int i = 0; i < xis->count_styles; ++i) {
1255 XIMStyle ts = xis->supported_styles[i];
1256 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1257 bestMatchStyle = ts;
1258 break;
1261 XFree(xis);
1263 if (!bestMatchStyle) {
1264 fprintf(stderr, "No matching input style could be determined\n");
1267 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1268 check_allocation(xic);
1270 // draw the window for the first time
1271 draw(&r, text, cs);
1273 // main loop
1274 while (status == LOOPING) {
1275 XEvent e;
1276 XNextEvent(d, &e);
1278 if (XFilterEvent(&e, w))
1279 continue;
1281 switch (e.type) {
1282 case KeymapNotify:
1283 XRefreshKeyboardMapping(&e.xmapping);
1284 break;
1286 case KeyPress: {
1287 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1289 char *input;
1290 switch (parse_event(d, ev, xic, &input)) {
1291 case EXIT:
1292 status = ERR;
1293 break;
1295 case CONFIRM:
1296 status = OK;
1298 // if first_selected is active and the first completion is
1299 // active be sure to 'expand' the text to match the selection
1300 if (first_selected && cs && cs->selected == 0) {
1301 free(text);
1302 text = strdup(cs->completions->completion);
1303 if (text == nil) {
1304 fprintf(stderr, "Memory allocation error");
1305 status = ERR;
1307 textlen = strlen(text);
1309 break;
1311 case PREV_COMPL: {
1312 complete(cs, first_selected, true, &text, &textlen, &status);
1313 break;
1316 case NEXT_COMPL: {
1317 complete(cs, first_selected, false, &text, &textlen, &status);
1318 break;
1321 case DEL_CHAR:
1322 popc(text, textlen);
1323 update_completions(cs, text, lines, first_selected);
1324 break;
1326 case DEL_WORD: {
1327 // `textlen` is the lenght of the allocated string, not the
1328 // lenght of the ACTUAL string
1329 int p = strlen(text) -1;
1330 if (p > 0) { // delete the current char
1331 text[p] = 0;
1332 p--;
1335 // erase the alphanumeric char
1336 while (p >= 0 && isalnum(text[p])) {
1337 text[p] = 0;
1338 p--;
1341 // erase also trailing white spaces
1342 while (p >= 0 && isspace(text[p])) {
1343 text[p] = 0;
1344 p--;
1346 update_completions(cs, text, lines, first_selected);
1347 break;
1350 case DEL_LINE: {
1351 for (int i = 0; i < textlen; ++i)
1352 text[i] = 0;
1353 update_completions(cs, text, lines, first_selected);
1354 break;
1357 case ADD_CHAR: {
1358 int str_len = strlen(input);
1360 // sometimes a strange key is pressed (i.e. ctrl alone),
1361 // so input will be empty. Don't need to update completion
1362 // in this case
1363 if (str_len == 0)
1364 break;
1366 for (int i = 0; i < str_len; ++i) {
1367 textlen = pushc(&text, textlen, input[i]);
1368 if (textlen == -1) {
1369 fprintf(stderr, "Memory allocation error\n");
1370 status = ERR;
1371 break;
1374 if (status != ERR) {
1375 update_completions(cs, text, lines, first_selected);
1376 free(input);
1378 break;
1381 case TOGGLE_FIRST_SELECTED:
1382 first_selected = !first_selected;
1383 if (first_selected && cs->selected < 0)
1384 cs->selected = 0;
1385 if (!first_selected && cs->selected == 0)
1386 cs->selected = -1;
1387 break;
1392 draw(&r, text, cs);
1395 if (status == OK)
1396 printf("%s\n", text);
1398 release_keyboard(r.d);
1400 #ifdef USE_XFT
1401 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1402 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1403 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1404 #endif
1406 free(ps1);
1407 free(fontname);
1408 free(text);
1410 char *l = nil;
1411 char **lns = lines;
1412 while ((l = *lns) != nil) {
1413 free(l);
1414 ++lns;
1417 free(lines);
1418 compls_delete(cs);
1420 XDestroyWindow(r.d, r.w);
1421 XCloseDisplay(r.d);
1423 return status;