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 // modulo operator
48 #define mod(a, b) (a < 0 ? (a % b + b) : (a % b))
50 // If we don't have it or we don't want an "ignore case" completion
51 // style, fall back to `strstr(3)`
52 #ifndef USE_STRCASESTR
53 # define strcasestr strstr
54 #endif
56 #define INITIAL_ITEMS 64
58 #define check_allocation(a) { \
59 if (a == nil) { \
60 fprintf(stderr, "Could not allocate memory\n"); \
61 abort(); \
62 } \
63 }
65 #define inner_height(r) (r->height - r->border_n - r->border_s)
66 #define inner_width(r) (r->width - r->border_e - r->border_w)
68 // The possible state of the event loop.
69 enum state {LOOPING, OK, ERR};
71 // for the drawing-related function. The text to be rendered could be
72 // the prompt, a completion or a highlighted completion
73 enum text_type {PROMPT, COMPL, COMPL_HIGH};
75 // These are the possible action to be performed after user input.
76 enum action {
77 EXIT,
78 CONFIRM,
79 NEXT_COMPL,
80 PREV_COMPL,
81 DEL_CHAR,
82 DEL_WORD,
83 DEL_LINE,
84 ADD_CHAR,
85 TOGGLE_FIRST_SELECTED
86 };
88 struct rendering {
89 Display *d; // connection to xorg
90 Window w;
91 int width;
92 int height;
93 int padding;
94 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
95 int y_zero; // the same a x_zero, only for the y axis
97 // The four border
98 int border_n;
99 int border_e;
100 int border_s;
101 int border_w;
103 bool horizontal_layout;
105 // the prompt
106 char *ps1;
107 int ps1len;
109 // colors
110 GC prompt;
111 GC prompt_bg;
112 GC completion;
113 GC completion_bg;
114 GC completion_highlighted;
115 GC completion_highlighted_bg;
116 GC border_n_bg;
117 GC border_e_bg;
118 GC border_s_bg;
119 GC border_w_bg;
120 #ifdef USE_XFT
121 XftFont *font;
122 XftDraw *xftdraw;
123 XftColor xft_prompt;
124 XftColor xft_completion;
125 XftColor xft_completion_highlighted;
126 #else
127 XFontSet *font;
128 #endif
129 };
131 // A simple linked list to store the completions.
132 struct completion {
133 char *completion;
134 struct completion *next;
135 };
137 struct completions {
138 struct completion *completions;
139 int selected;
140 int lenght;
141 };
143 // return a newly allocated (and empty) completion list
144 struct completions *compls_new() {
145 struct completions *cs = malloc(sizeof(struct completions));
147 if (cs == nil)
148 return cs;
150 cs->completions = nil;
151 cs->selected = -1;
152 cs->lenght = 0;
153 return cs;
156 struct completion *compl_new() {
157 struct completion *c = malloc(sizeof(struct completion));
158 if (c == nil)
159 return c;
161 c->completion = nil;
162 c->next = nil;
163 return c;
166 // delete ONLY the given completion (i.e. does not free c->next...)
167 void compl_delete(struct completion *c) {
168 free(c);
171 // delete the current completion and the next (c->next) and so on...
172 void compl_delete_rec(struct completion *c) {
173 while (c != nil) {
174 struct completion *t = c->next;
175 free(c);
176 c = t;
180 void compls_delete(struct completions *cs) {
181 if (cs == nil)
182 return;
184 compl_delete_rec(cs->completions);
185 free(cs);
188 // create a completion list from a text and the list of possible
189 // completions (null terminated). Expects a non-null `cs'.
190 void filter(struct completions *cs, char *text, char **lines) {
191 struct completion *c = compl_new();
192 if (c == nil) {
193 return;
196 cs->completions = c;
198 int index = 0;
199 int matching = 0;
201 while (true) {
202 char *l = lines[index];
203 if (l == nil)
204 break;
206 if (strcasestr(l, text) != nil) {
207 matching++;
209 c->next = compl_new();
210 c = c->next;
211 if (c == nil) {
212 compls_delete(cs);
213 return;
215 c->completion = l;
218 index++;
221 struct completion *f = cs->completions->next;
222 compl_delete(cs->completions);
223 cs->completions = f;
224 cs->lenght = matching;
225 cs->selected = -1;
228 // update the given completion, that is: clean the old cs & generate a new one.
229 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
230 compl_delete_rec(cs->completions);
231 filter(cs, text, lines);
232 if (first_selected && cs->lenght > 0)
233 cs->selected = 0;
236 // select the next, or the previous, selection and update some
237 // state. `text' will be updated with the text of the completion and
238 // `textlen' with the new lenght of `text'. If the memory cannot be
239 // allocated, `status' will be set to `ERR'.
240 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
241 if (cs == nil || cs->lenght == 0)
242 return;
244 // if the first is always selected, and the first entry is different
245 // from the text, expand the text and return
246 if (first_selected
247 && cs->selected == 0
248 && strcmp(cs->completions->completion, *text) != 0
249 && !p) {
250 free(*text);
251 *text = strdup(cs->completions->completion);
252 if (text == nil) {
253 *status = ERR;
254 return;
256 *textlen = strlen(*text);
257 return;
260 int index = cs->selected;
262 if (index == -1 && p)
263 index = 0;
264 index = cs->selected = mod((p ? index - 1 : index + 1), cs->lenght);
266 struct completion *n = cs->completions;
268 // find the selected item
269 while (index != 0) {
270 index--;
271 n = n->next;
274 free(*text);
275 *text = strdup(n->completion);
276 if (text == nil) {
277 fprintf(stderr, "Memory allocation error!\n");
278 *status = ERR;
279 return;
281 *textlen = strlen(*text);
284 // push the character c at the end of the string pointed by p
285 int pushc(char **p, int maxlen, char c) {
286 int len = strnlen(*p, maxlen);
288 if (!(len < maxlen -2)) {
289 maxlen += maxlen >> 1;
290 char *newptr = realloc(*p, maxlen);
291 if (newptr == nil) { // bad!
292 return -1;
294 *p = newptr;
297 (*p)[len] = c;
298 (*p)[len+1] = '\0';
299 return maxlen;
302 // return the number of character
303 int utf8strnlen(char *s, int maxlen) {
304 int len = 0;
305 while (*s && maxlen > 0) {
306 len += (*s++ & 0xc0) != 0x80;
307 maxlen--;
309 return len;
312 // remove the last *glyph* from the *utf8* string!
313 // this is different from just setting the last byte to 0 (in some
314 // cases ofc). The actual implementation is quite inefficient because
315 // it remove the last byte until the number of glyphs doesn't change
316 void popc(char *p, int maxlen) {
317 int len = strnlen(p, maxlen);
319 if (len == 0)
320 return;
322 int ulen = utf8strnlen(p, maxlen);
323 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
324 len--;
325 p[len] = 0;
329 // If the string is surrounded by quotes (`"`) remove them and replace
330 // every `\"` in the string with `"`
331 char *normalize_str(const char *str) {
332 int len = strlen(str);
333 if (len == 0)
334 return nil;
336 char *s = calloc(len, sizeof(char));
337 check_allocation(s);
338 int p = 0;
339 while (*str) {
340 char c = *str;
341 if (*str == '\\') {
342 if (*(str + 1)) {
343 s[p] = *(str + 1);
344 p++;
345 str += 2; // skip this and the next char
346 continue;
347 } else {
348 break;
351 if (c == '"') {
352 str++; // skip only this char
353 continue;
355 s[p] = c;
356 p++;
357 str++;
359 return s;
362 // read an arbitrary long line from stdin and return a pointer to it
363 // TODO: resize the allocated memory to exactly fit the string once
364 // read?
365 char *readline(bool *eof) {
366 int maxlen = 8;
367 char *str = calloc(maxlen, sizeof(char));
368 if (str == nil) {
369 fprintf(stderr, "Cannot allocate memory!\n");
370 exit(EX_UNAVAILABLE);
373 int c;
374 while((c = getchar()) != EOF) {
375 if (c == '\n')
376 return str;
377 else
378 maxlen = pushc(&str, maxlen, c);
380 if (maxlen == -1) {
381 fprintf(stderr, "Cannot allocate memory!\n");
382 exit(EX_UNAVAILABLE);
385 *eof = true;
386 return str;
389 // read an arbitrary amount of text until an EOF and store it in
390 // lns. `items` is the capacity of lns. It may increase lns with
391 // `realloc(3)` to store more line. Return the number of lines
392 // read. The last item will always be a NULL pointer. It ignore the
393 // "null" (empty) lines
394 int readlines (char ***lns, int items) {
395 bool finished = false;
396 int n = 0;
397 char **lines = *lns;
398 while (true) {
399 lines[n] = readline(&finished);
401 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
402 free(lines[n]);
403 --n; // forget about this line
406 if (finished)
407 break;
409 ++n;
411 if (n == items - 1) {
412 items += items >>1;
413 char **l = realloc(lines, sizeof(char*) * items);
414 check_allocation(l);
415 *lns = l;
416 lines = l;
420 n++;
421 lines[n] = nil;
422 return items;
425 // Compute the dimension of the string str once rendered, return the
426 // width and save the width and the height in ret_width and ret_height
427 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
428 int height;
429 int width;
430 #ifdef USE_XFT
431 XGlyphInfo gi;
432 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
433 /* height = gi.height; */
434 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
435 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
436 height = r->font->ascent - r->font->descent;
437 width = gi.width - gi.x;
438 #else
439 XRectangle rect;
440 XmbTextExtents(*r->font, str, len, nil, &rect);
441 height = rect.height;
442 width = rect.width;
443 #endif
444 if (ret_width != nil) *ret_width = width;
445 if (ret_height != nil) *ret_height = height;
446 return width;
449 // Draw the string str
450 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
451 #ifdef USE_XFT
452 XftColor xftcolor;
453 if (tt == PROMPT) xftcolor = r->xft_prompt;
454 if (tt == COMPL) xftcolor = r->xft_completion;
455 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
457 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
458 #else
459 GC gc;
460 if (tt == PROMPT) gc = r->prompt;
461 if (tt == COMPL) gc = r->completion;
462 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
463 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
464 #endif
467 // Duplicate the string str and substitute every space with a 'n'
468 char *strdupn(char *str) {
469 int len = strlen(str);
471 if (str == nil || len == 0)
472 return nil;
474 char *dup = strdup(str);
475 if (dup == nil)
476 return nil;
478 for (int i = 0; i < len; ++i)
479 if (dup[i] == ' ')
480 dup[i] = 'n';
482 return dup;
485 // |------------------|----------------------------------------------|
486 // | 20 char text | completion | completion | completion | compl |
487 // |------------------|----------------------------------------------|
488 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
489 int prompt_width = 20; // char
491 int width, height;
492 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
493 int start_at = ps1xlen;
495 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
496 start_at = start_at * prompt_width + r->padding;
498 int texty = (height + r->height) >>1;
500 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
502 int text_len = strlen(text);
503 if (text_len > prompt_width)
504 text = text + (text_len - prompt_width);
505 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
506 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
508 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, r->height);
510 struct completion *c = cs->completions;
511 for (int i = 0; c != nil; ++i) {
512 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
513 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
515 int len = strlen(c->completion);
516 int text_width = text_extents(c->completion, len, r, nil, nil);
518 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
520 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
522 start_at += text_width + r->padding * 2;
524 if (start_at > inner_width(r))
525 break; // don't draw completion if the space isn't enough
527 c = c->next;
531 // |-----------------------------------------------------------------|
532 // | prompt |
533 // |-----------------------------------------------------------------|
534 // | completion |
535 // |-----------------------------------------------------------------|
536 // | completion |
537 // |-----------------------------------------------------------------|
538 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
539 int height, width;
540 text_extents("fjpgl", 5, r, nil, &height);
541 int start_at = height + r->padding;
543 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
544 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
546 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
548 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
549 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
551 start_at += r->padding;
553 struct completion *c = cs->completions;
554 for (int i = 0; c != nil; ++i){
555 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
556 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
558 int len = strlen(c->completion);
559 text_extents(c->completion, len, r, &width, &height);
560 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
561 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
563 start_at += height + r->padding *2;
565 if (start_at > inner_height(r))
566 break; // don't draw completion if the space isn't enough
568 c = c->next;
572 void draw(struct rendering *r, char *text, struct completions *cs) {
573 if (r->horizontal_layout)
574 draw_horizontally(r, text, cs);
575 else
576 draw_vertically(r, text, cs);
578 // draw the borders
580 if (r->border_w != 0)
581 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
583 if (r->border_e != 0)
584 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
586 if (r->border_n != 0)
587 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
589 if (r->border_s != 0)
590 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
592 // send all the work to x
593 XFlush(r->d);
596 /* Set some WM stuff */
597 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
598 Atom type;
599 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
600 XChangeProperty(
601 d,
602 w,
603 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
604 XInternAtom(d, "ATOM", false),
605 32,
606 PropModeReplace,
607 (unsigned char *)&type,
609 );
611 /* some window managers honor this properties */
612 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
613 XChangeProperty(d,
614 w,
615 XInternAtom(d, "_NET_WM_STATE", false),
616 XInternAtom(d, "ATOM", false),
617 32,
618 PropModeReplace,
619 (unsigned char *)&type,
621 );
623 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
624 XChangeProperty(d,
625 w,
626 XInternAtom(d, "_NET_WM_STATE", false),
627 XInternAtom(d, "ATOM", false),
628 32,
629 PropModeAppend,
630 (unsigned char *)&type,
632 );
634 // setting window hints
635 XClassHint *class_hint = XAllocClassHint();
636 if (class_hint == nil) {
637 fprintf(stderr, "Could not allocate memory for class hint\n");
638 exit(EX_UNAVAILABLE);
640 class_hint->res_name = resname;
641 class_hint->res_class = resclass;
642 XSetClassHint(d, w, class_hint);
643 XFree(class_hint);
645 XSizeHints *size_hint = XAllocSizeHints();
646 if (size_hint == nil) {
647 fprintf(stderr, "Could not allocate memory for size hint\n");
648 exit(EX_UNAVAILABLE);
650 size_hint->flags = PMinSize | PBaseSize;
651 size_hint->min_width = width;
652 size_hint->base_width = width;
653 size_hint->min_height = height;
654 size_hint->base_height = height;
656 XFlush(d);
659 // write the width and height of the window `w' respectively in `width'
660 // and `height'.
661 void get_wh(Display *d, Window *w, int *width, int *height) {
662 XWindowAttributes win_attr;
663 XGetWindowAttributes(d, *w, &win_attr);
664 *height = win_attr.height;
665 *width = win_attr.width;
668 // I know this may seem a little hackish BUT is the only way I managed
669 // to actually grab that goddam keyboard. Only one call to
670 // XGrabKeyboard does not always end up with the keyboard grabbed!
671 int take_keyboard(Display *d, Window w) {
672 int i;
673 for (i = 0; i < 100; i++) {
674 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
675 return 1;
676 usleep(1000);
678 return 0;
681 // release the keyboard.
682 void release_keyboard(Display *d) {
683 XUngrabKeyboard(d, CurrentTime);
686 // Given a string, try to parse it as a number or return
687 // `default_value'.
688 int parse_integer(const char *str, int default_value) {
689 errno = 0;
690 char *ep;
691 long lval = strtol(str, &ep, 10);
692 if (str[0] == '\0' || *ep != '\0') { // NaN
693 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
694 return default_value;
696 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
697 (lval > INT_MAX || lval < INT_MIN)) {
698 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
699 return default_value;
701 return lval;
704 // like parse_integer, but if the value ends with a `%' then its
705 // treated like a percentage (`max' is used to compute the percentage)
706 int parse_int_with_percentage(const char *str, int default_value, int max) {
707 int len = strlen(str);
708 if (len > 0 && str[len-1] == '%') {
709 char *cpy = strdup(str);
710 check_allocation(cpy);
711 cpy[len-1] = '\0';
712 int val = parse_integer(cpy, default_value);
713 free(cpy);
714 return val * max / 100;
716 return parse_integer(str, default_value);
719 // like parse_int_with_percentage but understands the special value
720 // "middle" that is (max - self) / 2
721 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
722 if (!strcmp(str, "middle")) {
723 return (max - self)/2;
725 return parse_int_with_percentage(str, default_value, max);
728 // parse a string like a css value (for example like the css
729 // margin/padding properties). Will ALWAYS return an array of 4 word
730 // TODO: harden this function!
731 char **parse_csslike(const char *str) {
732 char *s = strdup(str);
733 if (s == nil)
734 return nil;
736 char **ret = malloc(4 * sizeof(char*));
737 if (ret == nil) {
738 free(s);
739 return nil;
742 int i = 0;
743 char *token;
744 while ((token = strsep(&s, " ")) != NULL && i < 4) {
745 ret[i] = strdup(token);
746 i++;
749 if (i == 1)
750 for (int j = 1; j < 4; j++)
751 ret[j] = strdup(ret[0]);
753 if (i == 2) {
754 ret[2] = strdup(ret[0]);
755 ret[3] = strdup(ret[1]);
758 if (i == 3)
759 ret[3] = strdup(ret[1]);
761 // Before we didn't check for the return type of strdup, here we will
763 bool any_null = false;
764 for (int i = 0; i < 4; ++i)
765 any_null = ret[i] == nil || any_null;
767 if (any_null)
768 for (int i = 0; i < 4; ++i)
769 if (ret[i] != nil)
770 free(ret[i]);
772 if (i == 0 || any_null) {
773 free(s);
774 free(ret);
775 return nil;
778 return ret;
781 // Given an event, try to understand what the user wants. If the
782 // return value is ADD_CHAR then `input' is a pointer to a string that
783 // will need to be free'ed.
784 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
785 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
786 return DEL_CHAR;
788 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
789 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
791 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
792 return CONFIRM;
794 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
795 return EXIT;
797 // try to read what the user pressed
798 char str[SYM_BUF_SIZE] = {0};
799 Status s = 0;
800 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
801 if (s == XBufferOverflow) {
802 // should not happen since there are no utf-8 characters larger
803 // than 24bits
804 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
805 return EXIT;
808 if (ev->state & ControlMask) {
809 if (!strcmp(str, "")) // C-u
810 return DEL_LINE;
811 if (!strcmp(str, "")) // C-w
812 return DEL_WORD;
813 if (!strcmp(str, "")) // C-h
814 return DEL_CHAR;
815 if (!strcmp(str, "\r")) // C-m
816 return CONFIRM;
817 if (!strcmp(str, "")) // C-p
818 return PREV_COMPL;
819 if (!strcmp(str, "")) // C-n
820 return NEXT_COMPL;
821 if (!strcmp(str, "")) // C-c
822 return EXIT;
823 if (!strcmp(str, "\t")) // C-i
824 return TOGGLE_FIRST_SELECTED;
827 *input = strdup(str);
828 if (*input == nil) {
829 fprintf(stderr, "Error while allocating memory for key.\n");
830 return EXIT;
833 return ADD_CHAR;
836 // Given the name of the program (argv[0]?) print a small help on stderr
837 void usage(char *prgname) {
838 fprintf(stderr, "Usage: %s [flags]\n", prgname);
839 fprintf(stderr, "\t-a: automatic mode, the first completion is "
840 "always selected;\n");
841 fprintf(stderr, "\t-h: print this help.\n");
844 int main(int argc, char **argv) {
845 #ifdef HAVE_PLEDGE
846 // stdio & rpat: to read and write stdio/stdout
847 // unix: to connect to Xorg
848 pledge("stdio rpath unix", "");
849 #endif
851 // by default the first completion isn't selected
852 bool first_selected = false;
854 // parse the command line options
855 int ch;
856 while ((ch = getopt(argc, argv, "ahv")) != -1) {
857 switch (ch) {
858 case 'a':
859 first_selected = true;
860 break;
861 case 'h':
862 usage(*argv);
863 return 0;
864 case 'v':
865 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
866 return 0;
867 default:
868 usage(*argv);
869 return EX_USAGE;
873 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
874 readlines(&lines, INITIAL_ITEMS);
876 setlocale(LC_ALL, getenv("LANG"));
878 enum state status = LOOPING;
880 // where the monitor start (used only with xinerama)
881 int offset_x = 0;
882 int offset_y = 0;
884 // width and height of the window
885 int width = 400;
886 int height = 20;
888 // position on the screen
889 int x = 0;
890 int y = 0;
892 // the default padding
893 int padding = 10;
895 // the default borders
896 int border_n = 0;
897 int border_e = 0;
898 int border_s = 0;
899 int border_w = 0;
901 // the prompt. We duplicate the string so later is easy to free (in
902 // the case the user provide its own prompt)
903 char *ps1 = strdup("$ ");
904 check_allocation(ps1);
906 // same for the font name
907 char *fontname = strdup(default_fontname);
908 check_allocation(fontname);
910 int textlen = 10;
911 char *text = malloc(textlen * sizeof(char));
912 check_allocation(text);
914 /* struct completions *cs = filter(text, lines); */
915 struct completions *cs = compls_new();
916 check_allocation(cs);
918 update_completions(cs, text, lines, first_selected);
920 // start talking to xorg
921 Display *d = XOpenDisplay(nil);
922 if (d == nil) {
923 fprintf(stderr, "Could not open display!\n");
924 return EX_UNAVAILABLE;
927 // get display size
928 // XXX: is getting the default root window dimension correct?
929 XWindowAttributes xwa;
930 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
931 int d_width = xwa.width;
932 int d_height = xwa.height;
934 #ifdef USE_XINERAMA
935 if (XineramaIsActive(d)) {
936 // find the mice
937 int number_of_screens = XScreenCount(d);
938 Window r;
939 Window root;
940 int root_x, root_y, win_x, win_y;
941 unsigned int mask;
942 bool res;
943 for (int i = 0; i < number_of_screens; ++i) {
944 root = XRootWindow(d, i);
945 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
946 if (res) break;
948 if (!res) {
949 fprintf(stderr, "No mouse found.\n");
950 root_x = 0;
951 root_y = 0;
954 // now find in which monitor the mice is on
955 int monitors;
956 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
957 if (info) {
958 for (int i = 0; i < monitors; ++i) {
959 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
960 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
961 offset_x = info[i].x_org;
962 offset_y = info[i].y_org;
963 d_width = info[i].width;
964 d_height = info[i].height;
965 break;
969 XFree(info);
971 #endif
973 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
974 XColor p_fg, p_bg,
975 compl_fg, compl_bg,
976 compl_highlighted_fg, compl_highlighted_bg,
977 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
979 bool horizontal_layout = true;
981 // read resource
982 XrmInitialize();
983 char *xrm = XResourceManagerString(d);
984 XrmDatabase xdb = nil;
985 if (xrm != nil) {
986 xdb = XrmGetStringDatabase(xrm);
987 XrmValue value;
988 char *datatype[20];
990 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
991 fontname = strdup(value.addr);
992 check_allocation(fontname);
994 else
995 fprintf(stderr, "no font defined, using %s\n", fontname);
997 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
998 char *v = strdup(value.addr);
999 check_allocation(v);
1000 horizontal_layout = !strcmp(v, "horizontal");
1001 free(v);
1003 else
1004 fprintf(stderr, "no layout defined, using horizontal\n");
1006 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1007 free(ps1);
1008 ps1 = normalize_str(value.addr);
1009 } else
1010 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1012 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1013 width = parse_int_with_percentage(value.addr, width, d_width);
1014 else
1015 fprintf(stderr, "no width defined, using %d\n", width);
1017 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1018 height = parse_int_with_percentage(value.addr, height, d_height);
1019 else
1020 fprintf(stderr, "no height defined, using %d\n", height);
1022 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1023 x = parse_int_with_middle(value.addr, x, d_width, width);
1024 else
1025 fprintf(stderr, "no x defined, using %d\n", x);
1027 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1028 y = parse_int_with_middle(value.addr, y, d_height, height);
1029 else
1030 fprintf(stderr, "no y defined, using %d\n", y);
1032 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1033 padding = parse_integer(value.addr, padding);
1034 else
1035 fprintf(stderr, "no padding defined, using %d\n", padding);
1037 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1038 char **borders = parse_csslike(value.addr);
1039 if (borders != nil) {
1040 border_n = parse_integer(borders[0], 0);
1041 border_e = parse_integer(borders[1], 0);
1042 border_s = parse_integer(borders[2], 0);
1043 border_w = parse_integer(borders[3], 0);
1044 } else {
1045 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1047 } else {
1048 fprintf(stderr, "no border defined, using 0.\n");
1051 XColor tmp;
1052 // TODO: tmp needs to be free'd after every allocation?
1054 // prompt
1055 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1056 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1057 else
1058 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1060 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1061 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1062 else
1063 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1065 // completion
1066 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1067 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1068 else
1069 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1071 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1072 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1073 else
1074 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1076 // completion highlighted
1077 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1078 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1079 else
1080 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1082 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1083 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1084 else
1085 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1087 // border
1088 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1089 char **colors = parse_csslike(value.addr);
1090 if (colors != nil) {
1091 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1092 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1093 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1094 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1095 } else {
1096 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1098 } else {
1099 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1100 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1101 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1102 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1104 } else {
1105 XColor tmp;
1106 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1107 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1108 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1109 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1110 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1111 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1112 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1113 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1114 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1117 // load the font
1118 #ifdef USE_XFT
1119 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1120 #else
1121 char **missing_charset_list;
1122 int missing_charset_count;
1123 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1124 if (font == nil) {
1125 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1126 return EX_UNAVAILABLE;
1128 #endif
1130 // create the window
1131 XSetWindowAttributes attr;
1132 attr.override_redirect = true;
1134 Window w = XCreateWindow(d, // display
1135 DefaultRootWindow(d), // parent
1136 x + offset_x, y + offset_y, // x y
1137 width, height, // w h
1138 0, // border width
1139 DefaultDepth(d, DefaultScreen(d)), // depth
1140 InputOutput, // class
1141 DefaultVisual(d, DefaultScreen(d)), // visual
1142 CWOverrideRedirect, // value mask
1143 &attr);
1145 set_win_atoms_hints(d, w, width, height);
1147 // we want some events
1148 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1150 // make the window appear on the screen
1151 XMapWindow(d, w);
1153 // wait for the MapNotify event (i.e. the event "window rendered")
1154 for (;;) {
1155 XEvent e;
1156 XNextEvent(d, &e);
1157 if (e.type == MapNotify)
1158 break;
1161 // get the *real* width & height after the window was rendered
1162 get_wh(d, &w, &width, &height);
1164 // grab keyboard
1165 take_keyboard(d, w);
1167 // Create some graphics contexts
1168 XGCValues values;
1169 /* values.font = font->fid; */
1171 struct rendering r = {
1172 .d = d,
1173 .w = w,
1174 .width = width,
1175 .height = height,
1176 .padding = padding,
1177 .x_zero = border_w,
1178 .y_zero = border_n,
1179 .border_n = border_n,
1180 .border_e = border_e,
1181 .border_s = border_s,
1182 .border_w = border_w,
1183 .horizontal_layout = horizontal_layout,
1184 .ps1 = ps1,
1185 .ps1len = strlen(ps1),
1186 .prompt = XCreateGC(d, w, 0, &values),
1187 .prompt_bg = XCreateGC(d, w, 0, &values),
1188 .completion = XCreateGC(d, w, 0, &values),
1189 .completion_bg = XCreateGC(d, w, 0, &values),
1190 .completion_highlighted = XCreateGC(d, w, 0, &values),
1191 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1192 .border_n_bg = XCreateGC(d, w, 0, &values),
1193 .border_e_bg = XCreateGC(d, w, 0, &values),
1194 .border_s_bg = XCreateGC(d, w, 0, &values),
1195 .border_w_bg = XCreateGC(d, w, 0, &values),
1196 #ifdef USE_XFT
1197 .font = font,
1198 #else
1199 .font = &font,
1200 #endif
1203 #ifdef USE_XFT
1204 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1206 // prompt
1207 XRenderColor xrcolor;
1208 xrcolor.red = p_fg.red;
1209 xrcolor.green = p_fg.red;
1210 xrcolor.blue = p_fg.red;
1211 xrcolor.alpha = 65535;
1212 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1214 // completion
1215 xrcolor.red = compl_fg.red;
1216 xrcolor.green = compl_fg.green;
1217 xrcolor.blue = compl_fg.blue;
1218 xrcolor.alpha = 65535;
1219 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1221 // completion highlighted
1222 xrcolor.red = compl_highlighted_fg.red;
1223 xrcolor.green = compl_highlighted_fg.green;
1224 xrcolor.blue = compl_highlighted_fg.blue;
1225 xrcolor.alpha = 65535;
1226 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1227 #endif
1229 // load the colors in our GCs
1230 XSetForeground(d, r.prompt, p_fg.pixel);
1231 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1232 XSetForeground(d, r.completion, compl_fg.pixel);
1233 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1234 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1235 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1236 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1237 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1238 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1239 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1241 // open the X input method
1242 XIM xim = XOpenIM(d, xdb, resname, resclass);
1243 check_allocation(xim);
1245 XIMStyles *xis = nil;
1246 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1247 fprintf(stderr, "Input Styles could not be retrieved\n");
1248 return EX_UNAVAILABLE;
1251 XIMStyle bestMatchStyle = 0;
1252 for (int i = 0; i < xis->count_styles; ++i) {
1253 XIMStyle ts = xis->supported_styles[i];
1254 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1255 bestMatchStyle = ts;
1256 break;
1259 XFree(xis);
1261 if (!bestMatchStyle) {
1262 fprintf(stderr, "No matching input style could be determined\n");
1265 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1266 check_allocation(xic);
1268 // draw the window for the first time
1269 draw(&r, text, cs);
1271 // main loop
1272 while (status == LOOPING) {
1273 XEvent e;
1274 XNextEvent(d, &e);
1276 if (XFilterEvent(&e, w))
1277 continue;
1279 switch (e.type) {
1280 case KeymapNotify:
1281 XRefreshKeyboardMapping(&e.xmapping);
1282 break;
1284 case KeyPress: {
1285 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1287 char *input;
1288 switch (parse_event(d, ev, xic, &input)) {
1289 case EXIT:
1290 status = ERR;
1291 break;
1293 case CONFIRM:
1294 status = OK;
1296 // if first_selected is active and the first completion is
1297 // active be sure to 'expand' the text to match the selection
1298 if (first_selected && cs && cs->selected == 0) {
1299 free(text);
1300 text = strdup(cs->completions->completion);
1301 if (text == nil) {
1302 fprintf(stderr, "Memory allocation error");
1303 status = ERR;
1305 textlen = strlen(text);
1307 break;
1309 case PREV_COMPL: {
1310 complete(cs, first_selected, true, &text, &textlen, &status);
1311 break;
1314 case NEXT_COMPL: {
1315 complete(cs, first_selected, false, &text, &textlen, &status);
1316 break;
1319 case DEL_CHAR:
1320 popc(text, textlen);
1321 update_completions(cs, text, lines, first_selected);
1322 break;
1324 case DEL_WORD: {
1325 // `textlen` is the lenght of the allocated string, not the
1326 // lenght of the ACTUAL string
1327 int p = strlen(text) -1;
1328 if (p > 0) { // delete the current char
1329 text[p] = 0;
1330 p--;
1333 // erase the alphanumeric char
1334 while (p >= 0 && isalnum(text[p])) {
1335 text[p] = 0;
1336 p--;
1339 // erase also trailing white spaces
1340 while (p >= 0 && isspace(text[p])) {
1341 text[p] = 0;
1342 p--;
1344 update_completions(cs, text, lines, first_selected);
1345 break;
1348 case DEL_LINE: {
1349 for (int i = 0; i < textlen; ++i)
1350 text[i] = 0;
1351 update_completions(cs, text, lines, first_selected);
1352 break;
1355 case ADD_CHAR: {
1356 int str_len = strlen(input);
1358 // sometimes a strange key is pressed (i.e. ctrl alone),
1359 // so input will be empty. Don't need to update completion
1360 // in this case
1361 if (str_len == 0)
1362 break;
1364 for (int i = 0; i < str_len; ++i) {
1365 textlen = pushc(&text, textlen, input[i]);
1366 if (textlen == -1) {
1367 fprintf(stderr, "Memory allocation error\n");
1368 status = ERR;
1369 break;
1372 if (status != ERR) {
1373 update_completions(cs, text, lines, first_selected);
1374 free(input);
1376 break;
1379 case TOGGLE_FIRST_SELECTED:
1380 first_selected = !first_selected;
1381 if (first_selected && cs->selected < 0)
1382 cs->selected = 0;
1383 if (!first_selected && cs->selected == 0)
1384 cs->selected = -1;
1385 break;
1390 draw(&r, text, cs);
1393 if (status == OK)
1394 printf("%s\n", text);
1396 release_keyboard(r.d);
1398 #ifdef USE_XFT
1399 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1400 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1401 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1402 #endif
1404 free(ps1);
1405 free(fontname);
1406 free(text);
1408 char *l = nil;
1409 char **lns = lines;
1410 while ((l = *lns) != nil) {
1411 free(l);
1412 ++lns;
1415 free(lines);
1416 compls_delete(cs);
1418 XDestroyWindow(r.d, r.w);
1419 XCloseDisplay(r.d);
1421 return status;