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 "hvap:x:y:P:l:f:w:h:b:B:t:T:c:C:s:S:"
46 #define MIN(a, b) ((a) < (b) ? (a) : (b))
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 // If we don't have it or we don't want an "ignore case" completion
50 // style, fall back to `strstr(3)`
51 #ifndef USE_STRCASESTR
52 # define strcasestr strstr
53 #endif
55 #define INITIAL_ITEMS 64
57 #define check_allocation(a) { \
58 if (a == nil) { \
59 fprintf(stderr, "Could not allocate memory\n"); \
60 abort(); \
61 } \
62 }
64 #define inner_height(r) (r->height - r->border_n - r->border_s)
65 #define inner_width(r) (r->width - r->border_e - r->border_w)
67 // The possible state of the event loop.
68 enum state {LOOPING, OK, ERR};
70 // for the drawing-related function. The text to be rendered could be
71 // the prompt, a completion or a highlighted completion
72 enum text_type {PROMPT, COMPL, COMPL_HIGH};
74 // These are the possible action to be performed after user input.
75 enum action {
76 EXIT,
77 CONFIRM,
78 NEXT_COMPL,
79 PREV_COMPL,
80 DEL_CHAR,
81 DEL_WORD,
82 DEL_LINE,
83 ADD_CHAR,
84 TOGGLE_FIRST_SELECTED
85 };
87 struct rendering {
88 Display *d; // connection to xorg
89 Window w;
90 int width;
91 int height;
92 int padding;
93 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
94 int y_zero; // the same a x_zero, only for the y axis
96 // The four border
97 int border_n;
98 int border_e;
99 int border_s;
100 int border_w;
102 bool horizontal_layout;
104 // the prompt
105 char *ps1;
106 int ps1len;
108 // colors
109 GC prompt;
110 GC prompt_bg;
111 GC completion;
112 GC completion_bg;
113 GC completion_highlighted;
114 GC completion_highlighted_bg;
115 GC border_n_bg;
116 GC border_e_bg;
117 GC border_s_bg;
118 GC border_w_bg;
119 #ifdef USE_XFT
120 XftFont *font;
121 XftDraw *xftdraw;
122 XftColor xft_prompt;
123 XftColor xft_completion;
124 XftColor xft_completion_highlighted;
125 #else
126 XFontSet *font;
127 #endif
128 };
130 // A simple linked list to store the completions.
131 struct completion {
132 char *completion;
133 struct completion *next;
134 };
136 struct completions {
137 struct completion *completions;
138 int selected;
139 int lenght;
140 };
142 // return a newly allocated (and empty) completion list
143 struct completions *compls_new() {
144 struct completions *cs = malloc(sizeof(struct completions));
146 if (cs == nil)
147 return cs;
149 cs->completions = nil;
150 cs->selected = -1;
151 cs->lenght = 0;
152 return cs;
155 struct completion *compl_new() {
156 struct completion *c = malloc(sizeof(struct completion));
157 if (c == nil)
158 return c;
160 c->completion = nil;
161 c->next = nil;
162 return c;
165 // delete ONLY the given completion (i.e. does not free c->next...)
166 void compl_delete(struct completion *c) {
167 free(c);
170 // delete the current completion and the next (c->next) and so on...
171 void compl_delete_rec(struct completion *c) {
172 while (c != nil) {
173 struct completion *t = c->next;
174 free(c);
175 c = t;
179 void compls_delete(struct completions *cs) {
180 if (cs == nil)
181 return;
183 compl_delete_rec(cs->completions);
184 free(cs);
187 // create a completion list from a text and the list of possible
188 // completions (null terminated). Expects a non-null `cs'.
189 void filter(struct completions *cs, char *text, char **lines) {
190 struct completion *c = compl_new();
191 if (c == nil) {
192 return;
195 cs->completions = c;
197 int index = 0;
198 int matching = 0;
200 while (true) {
201 char *l = lines[index];
202 if (l == nil)
203 break;
205 if (strcasestr(l, text) != nil) {
206 matching++;
208 c->next = compl_new();
209 c = c->next;
210 if (c == nil) {
211 compls_delete(cs);
212 return;
214 c->completion = l;
217 index++;
220 struct completion *f = cs->completions->next;
221 compl_delete(cs->completions);
222 cs->completions = f;
223 cs->lenght = matching;
224 cs->selected = -1;
227 // update the given completion, that is: clean the old cs & generate a new one.
228 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
229 compl_delete_rec(cs->completions);
230 filter(cs, text, lines);
231 if (first_selected && cs->lenght > 0)
232 cs->selected = 0;
235 // select the next, or the previous, selection and update some
236 // state. `text' will be updated with the text of the completion and
237 // `textlen' with the new lenght of `text'. If the memory cannot be
238 // allocated, `status' will be set to `ERR'.
239 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
240 if (cs == nil || cs->lenght == 0)
241 return;
243 // if the first is always selected, and the first entry is different
244 // from the text, expand the text and return
245 if (first_selected
246 && cs->selected == 0
247 && strcmp(cs->completions->completion, *text) != 0
248 && !p) {
249 free(*text);
250 *text = strdup(cs->completions->completion);
251 if (text == nil) {
252 *status = ERR;
253 return;
255 *textlen = strlen(*text);
256 return;
259 int index = cs->selected;
261 if (index == -1 && p)
262 index = 0;
263 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
265 struct completion *n = cs->completions;
267 // find the selected item
268 while (index != 0) {
269 index--;
270 n = n->next;
273 free(*text);
274 *text = strdup(n->completion);
275 if (text == nil) {
276 fprintf(stderr, "Memory allocation error!\n");
277 *status = ERR;
278 return;
280 *textlen = strlen(*text);
283 // push the character c at the end of the string pointed by p
284 int pushc(char **p, int maxlen, char c) {
285 int len = strnlen(*p, maxlen);
287 if (!(len < maxlen -2)) {
288 maxlen += maxlen >> 1;
289 char *newptr = realloc(*p, maxlen);
290 if (newptr == nil) { // bad!
291 return -1;
293 *p = newptr;
296 (*p)[len] = c;
297 (*p)[len+1] = '\0';
298 return maxlen;
301 // return the number of character
302 int utf8strnlen(char *s, int maxlen) {
303 int len = 0;
304 while (*s && maxlen > 0) {
305 len += (*s++ & 0xc0) != 0x80;
306 maxlen--;
308 return len;
311 // remove the last *glyph* from the *utf8* string!
312 // this is different from just setting the last byte to 0 (in some
313 // cases ofc). The actual implementation is quite inefficient because
314 // it remove the last byte until the number of glyphs doesn't change
315 void popc(char *p, int maxlen) {
316 int len = strnlen(p, maxlen);
318 if (len == 0)
319 return;
321 int ulen = utf8strnlen(p, maxlen);
322 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
323 len--;
324 p[len] = 0;
328 // If the string is surrounded by quotes (`"`) remove them and replace
329 // every `\"` in the string with `"`
330 char *normalize_str(const char *str) {
331 int len = strlen(str);
332 if (len == 0)
333 return nil;
335 char *s = calloc(len, sizeof(char));
336 check_allocation(s);
337 int p = 0;
338 while (*str) {
339 char c = *str;
340 if (*str == '\\') {
341 if (*(str + 1)) {
342 s[p] = *(str + 1);
343 p++;
344 str += 2; // skip this and the next char
345 continue;
346 } else {
347 break;
350 if (c == '"') {
351 str++; // skip only this char
352 continue;
354 s[p] = c;
355 p++;
356 str++;
358 return s;
361 // read an arbitrary long line from stdin and return a pointer to it
362 // TODO: resize the allocated memory to exactly fit the string once
363 // read?
364 char *readline(bool *eof) {
365 int maxlen = 8;
366 char *str = calloc(maxlen, sizeof(char));
367 if (str == nil) {
368 fprintf(stderr, "Cannot allocate memory!\n");
369 exit(EX_UNAVAILABLE);
372 int c;
373 while((c = getchar()) != EOF) {
374 if (c == '\n')
375 return str;
376 else
377 maxlen = pushc(&str, maxlen, c);
379 if (maxlen == -1) {
380 fprintf(stderr, "Cannot allocate memory!\n");
381 exit(EX_UNAVAILABLE);
384 *eof = true;
385 return str;
388 // read an arbitrary amount of text until an EOF and store it in
389 // lns. `items` is the capacity of lns. It may increase lns with
390 // `realloc(3)` to store more line. Return the number of lines
391 // read. The last item will always be a NULL pointer. It ignore the
392 // "null" (empty) lines
393 int readlines (char ***lns, int items) {
394 bool finished = false;
395 int n = 0;
396 char **lines = *lns;
397 while (true) {
398 lines[n] = readline(&finished);
400 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
401 free(lines[n]);
402 --n; // forget about this line
405 if (finished)
406 break;
408 ++n;
410 if (n == items - 1) {
411 items += items >>1;
412 char **l = realloc(lines, sizeof(char*) * items);
413 check_allocation(l);
414 *lns = l;
415 lines = l;
419 n++;
420 lines[n] = nil;
421 return items;
424 // Compute the dimension of the string str once rendered, return the
425 // width and save the width and the height in ret_width and ret_height
426 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
427 int height;
428 int width;
429 #ifdef USE_XFT
430 XGlyphInfo gi;
431 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
432 /* height = gi.height; */
433 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
434 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
435 height = r->font->ascent - r->font->descent;
436 width = gi.width - gi.x;
437 #else
438 XRectangle rect;
439 XmbTextExtents(*r->font, str, len, nil, &rect);
440 height = rect.height;
441 width = rect.width;
442 #endif
443 if (ret_width != nil) *ret_width = width;
444 if (ret_height != nil) *ret_height = height;
445 return width;
448 // Draw the string str
449 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
450 #ifdef USE_XFT
451 XftColor xftcolor;
452 if (tt == PROMPT) xftcolor = r->xft_prompt;
453 if (tt == COMPL) xftcolor = r->xft_completion;
454 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
456 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
457 #else
458 GC gc;
459 if (tt == PROMPT) gc = r->prompt;
460 if (tt == COMPL) gc = r->completion;
461 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
462 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
463 #endif
466 // Duplicate the string str and substitute every space with a 'n'
467 char *strdupn(char *str) {
468 int len = strlen(str);
470 if (str == nil || len == 0)
471 return nil;
473 char *dup = strdup(str);
474 if (dup == nil)
475 return nil;
477 for (int i = 0; i < len; ++i)
478 if (dup[i] == ' ')
479 dup[i] = 'n';
481 return dup;
484 // |------------------|----------------------------------------------|
485 // | 20 char text | completion | completion | completion | compl |
486 // |------------------|----------------------------------------------|
487 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
488 int prompt_width = 20; // char
490 int width, height;
491 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
492 int start_at = ps1xlen;
494 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
495 start_at = start_at * prompt_width + r->padding;
497 int texty = (height + r->height) >>1;
499 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
501 int text_len = strlen(text);
502 if (text_len > prompt_width)
503 text = text + (text_len - prompt_width);
504 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
505 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
507 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, r->height);
509 struct completion *c = cs->completions;
510 for (int i = 0; c != nil; ++i) {
511 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
512 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
514 int len = strlen(c->completion);
515 int text_width = text_extents(c->completion, len, r, nil, nil);
517 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
519 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
521 start_at += text_width + r->padding * 2;
523 if (start_at > inner_width(r))
524 break; // don't draw completion if the space isn't enough
526 c = c->next;
530 // |-----------------------------------------------------------------|
531 // | prompt |
532 // |-----------------------------------------------------------------|
533 // | completion |
534 // |-----------------------------------------------------------------|
535 // | completion |
536 // |-----------------------------------------------------------------|
537 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
538 int height, width;
539 text_extents("fjpgl", 5, r, nil, &height);
540 int start_at = height + r->padding;
542 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
543 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
545 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
547 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, height + r->padding, r, PROMPT);
548 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, height + r->padding, r, PROMPT);
550 start_at += r->padding;
552 struct completion *c = cs->completions;
553 for (int i = 0; c != nil; ++i){
554 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
555 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
557 int len = strlen(c->completion);
558 text_extents(c->completion, len, r, &width, &height);
559 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
560 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
562 start_at += height + r->padding *2;
564 if (start_at > inner_height(r))
565 break; // don't draw completion if the space isn't enough
567 c = c->next;
571 void draw(struct rendering *r, char *text, struct completions *cs) {
572 if (r->horizontal_layout)
573 draw_horizontally(r, text, cs);
574 else
575 draw_vertically(r, text, cs);
577 // draw the borders
579 if (r->border_w != 0)
580 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
582 if (r->border_e != 0)
583 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
585 if (r->border_n != 0)
586 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
588 if (r->border_s != 0)
589 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
591 // send all the work to x
592 XFlush(r->d);
595 /* Set some WM stuff */
596 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
597 Atom type;
598 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
599 XChangeProperty(
600 d,
601 w,
602 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
603 XInternAtom(d, "ATOM", false),
604 32,
605 PropModeReplace,
606 (unsigned char *)&type,
608 );
610 /* some window managers honor this properties */
611 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
612 XChangeProperty(d,
613 w,
614 XInternAtom(d, "_NET_WM_STATE", false),
615 XInternAtom(d, "ATOM", false),
616 32,
617 PropModeReplace,
618 (unsigned char *)&type,
620 );
622 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
623 XChangeProperty(d,
624 w,
625 XInternAtom(d, "_NET_WM_STATE", false),
626 XInternAtom(d, "ATOM", false),
627 32,
628 PropModeAppend,
629 (unsigned char *)&type,
631 );
633 // setting window hints
634 XClassHint *class_hint = XAllocClassHint();
635 if (class_hint == nil) {
636 fprintf(stderr, "Could not allocate memory for class hint\n");
637 exit(EX_UNAVAILABLE);
639 class_hint->res_name = resname;
640 class_hint->res_class = resclass;
641 XSetClassHint(d, w, class_hint);
642 XFree(class_hint);
644 XSizeHints *size_hint = XAllocSizeHints();
645 if (size_hint == nil) {
646 fprintf(stderr, "Could not allocate memory for size hint\n");
647 exit(EX_UNAVAILABLE);
649 size_hint->flags = PMinSize | PBaseSize;
650 size_hint->min_width = width;
651 size_hint->base_width = width;
652 size_hint->min_height = height;
653 size_hint->base_height = height;
655 XFlush(d);
658 // write the width and height of the window `w' respectively in `width'
659 // and `height'.
660 void get_wh(Display *d, Window *w, int *width, int *height) {
661 XWindowAttributes win_attr;
662 XGetWindowAttributes(d, *w, &win_attr);
663 *height = win_attr.height;
664 *width = win_attr.width;
667 // I know this may seem a little hackish BUT is the only way I managed
668 // to actually grab that goddam keyboard. Only one call to
669 // XGrabKeyboard does not always end up with the keyboard grabbed!
670 int take_keyboard(Display *d, Window w) {
671 int i;
672 for (i = 0; i < 100; i++) {
673 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
674 return 1;
675 usleep(1000);
677 return 0;
680 // release the keyboard.
681 void release_keyboard(Display *d) {
682 XUngrabKeyboard(d, CurrentTime);
685 // Given a string, try to parse it as a number or return
686 // `default_value'.
687 int parse_integer(const char *str, int default_value) {
688 errno = 0;
689 char *ep;
690 long lval = strtol(str, &ep, 10);
691 if (str[0] == '\0' || *ep != '\0') { // NaN
692 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
693 return default_value;
695 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
696 (lval > INT_MAX || lval < INT_MIN)) {
697 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
698 return default_value;
700 return lval;
703 // like parse_integer, but if the value ends with a `%' then its
704 // treated like a percentage (`max' is used to compute the percentage)
705 int parse_int_with_percentage(const char *str, int default_value, int max) {
706 int len = strlen(str);
707 if (len > 0 && str[len-1] == '%') {
708 char *cpy = strdup(str);
709 check_allocation(cpy);
710 cpy[len-1] = '\0';
711 int val = parse_integer(cpy, default_value);
712 free(cpy);
713 return val * max / 100;
715 return parse_integer(str, default_value);
718 // like parse_int_with_percentage but understands some special values
719 // - "middle" that is (max - self) / 2
720 // - "start" that is 0
721 // - "end" that is (max - self)
722 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
723 if (!strcmp(str, "start"))
724 return 0;
725 if (!strcmp(str, "middle"))
726 return (max - self)/2;
727 if (!strcmp(str, "end"))
728 return max-self;
729 return parse_int_with_percentage(str, default_value, max);
732 // parse a string like a css value (for example like the css
733 // margin/padding properties). Will ALWAYS return an array of 4 word
734 // TODO: harden this function!
735 char **parse_csslike(const char *str) {
736 char *s = strdup(str);
737 if (s == nil)
738 return nil;
740 char **ret = malloc(4 * sizeof(char*));
741 if (ret == nil) {
742 free(s);
743 return nil;
746 int i = 0;
747 char *token;
748 while ((token = strsep(&s, " ")) != NULL && i < 4) {
749 ret[i] = strdup(token);
750 i++;
753 if (i == 1)
754 for (int j = 1; j < 4; j++)
755 ret[j] = strdup(ret[0]);
757 if (i == 2) {
758 ret[2] = strdup(ret[0]);
759 ret[3] = strdup(ret[1]);
762 if (i == 3)
763 ret[3] = strdup(ret[1]);
765 // Before we didn't check for the return type of strdup, here we will
767 bool any_null = false;
768 for (int i = 0; i < 4; ++i)
769 any_null = ret[i] == nil || any_null;
771 if (any_null)
772 for (int i = 0; i < 4; ++i)
773 if (ret[i] != nil)
774 free(ret[i]);
776 if (i == 0 || any_null) {
777 free(s);
778 free(ret);
779 return nil;
782 return ret;
785 // Given an event, try to understand what the user wants. If the
786 // return value is ADD_CHAR then `input' is a pointer to a string that
787 // will need to be free'ed.
788 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
789 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
790 return DEL_CHAR;
792 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
793 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
795 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
796 return CONFIRM;
798 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
799 return EXIT;
801 // try to read what the user pressed
802 char str[SYM_BUF_SIZE] = {0};
803 Status s = 0;
804 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
805 if (s == XBufferOverflow) {
806 // should not happen since there are no utf-8 characters larger
807 // than 24bits
808 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
809 return EXIT;
812 if (ev->state & ControlMask) {
813 if (!strcmp(str, "")) // C-u
814 return DEL_LINE;
815 if (!strcmp(str, "")) // C-w
816 return DEL_WORD;
817 if (!strcmp(str, "")) // C-h
818 return DEL_CHAR;
819 if (!strcmp(str, "\r")) // C-m
820 return CONFIRM;
821 if (!strcmp(str, "")) // C-p
822 return PREV_COMPL;
823 if (!strcmp(str, "")) // C-n
824 return NEXT_COMPL;
825 if (!strcmp(str, "")) // C-c
826 return EXIT;
827 if (!strcmp(str, "\t")) // C-i
828 return TOGGLE_FIRST_SELECTED;
831 *input = strdup(str);
832 if (*input == nil) {
833 fprintf(stderr, "Error while allocating memory for key.\n");
834 return EXIT;
837 return ADD_CHAR;
840 // Given the name of the program (argv[0]?) print a small help on stderr
841 void usage(char *prgname) {
842 fprintf(stderr, "Usage: %s [flags]\n", prgname);
843 fprintf(stderr, "\t-a: automatic mode, the first completion is "
844 "always selected;\n");
845 fprintf(stderr, "\t-h: print this help.\n");
848 int main(int argc, char **argv) {
849 #ifdef HAVE_PLEDGE
850 // stdio & rpat: to read and write stdio/stdout
851 // unix: to connect to Xorg
852 pledge("stdio rpath unix", "");
853 #endif
855 // by default the first completion isn't selected
856 bool first_selected = false;
858 // first round of args parsing for early terminating options
859 int ch;
860 while ((ch = getopt(argc, argv, ARGS)) != -1) {
861 switch (ch) {
862 /* case 'a': */
863 /* first_selected = true; */
864 /* break; */
865 case 'h':
866 usage(*argv);
867 return 0;
868 case 'v':
869 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
870 return 0;
871 default:
872 break;
876 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
877 readlines(&lines, INITIAL_ITEMS);
879 setlocale(LC_ALL, getenv("LANG"));
881 enum state status = LOOPING;
883 // where the monitor start (used only with xinerama)
884 int offset_x = 0;
885 int offset_y = 0;
887 // width and height of the window
888 int width = 400;
889 int height = 20;
891 // position on the screen
892 int x = 0;
893 int y = 0;
895 // the default padding
896 int padding = 10;
898 // the default borders
899 int border_n = 0;
900 int border_e = 0;
901 int border_s = 0;
902 int border_w = 0;
904 // the prompt. We duplicate the string so later is easy to free (in
905 // the case the user provide its own prompt)
906 char *ps1 = strdup("$ ");
907 check_allocation(ps1);
909 // same for the font name
910 char *fontname = strdup(default_fontname);
911 check_allocation(fontname);
913 int textlen = 10;
914 char *text = malloc(textlen * sizeof(char));
915 check_allocation(text);
917 /* struct completions *cs = filter(text, lines); */
918 struct completions *cs = compls_new();
919 check_allocation(cs);
921 // start talking to xorg
922 Display *d = XOpenDisplay(nil);
923 if (d == nil) {
924 fprintf(stderr, "Could not open display!\n");
925 return EX_UNAVAILABLE;
928 // get display size
929 // XXX: is getting the default root window dimension correct?
930 XWindowAttributes xwa;
931 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
932 int d_width = xwa.width;
933 int d_height = xwa.height;
935 #ifdef USE_XINERAMA
936 if (XineramaIsActive(d)) {
937 // find the mice
938 int number_of_screens = XScreenCount(d);
939 Window r;
940 Window root;
941 int root_x, root_y, win_x, win_y;
942 unsigned int mask;
943 bool res;
944 for (int i = 0; i < number_of_screens; ++i) {
945 root = XRootWindow(d, i);
946 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
947 if (res) break;
949 if (!res) {
950 fprintf(stderr, "No mouse found.\n");
951 root_x = 0;
952 root_y = 0;
955 // now find in which monitor the mice is on
956 int monitors;
957 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
958 if (info) {
959 for (int i = 0; i < monitors; ++i) {
960 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
961 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
962 offset_x = info[i].x_org;
963 offset_y = info[i].y_org;
964 d_width = info[i].width;
965 d_height = info[i].height;
966 break;
970 XFree(info);
972 #endif
974 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
975 XColor p_fg, p_bg,
976 compl_fg, compl_bg,
977 compl_highlighted_fg, compl_highlighted_bg,
978 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
980 bool horizontal_layout = true;
982 // read resource
983 XrmInitialize();
984 char *xrm = XResourceManagerString(d);
985 XrmDatabase xdb = nil;
986 if (xrm != nil) {
987 xdb = XrmGetStringDatabase(xrm);
988 XrmValue value;
989 char *datatype[20];
991 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
992 fontname = strdup(value.addr);
993 check_allocation(fontname);
995 else
996 fprintf(stderr, "no font defined, using %s\n", fontname);
998 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
999 horizontal_layout = !strcmp(value.addr, "horizontal");
1001 else
1002 fprintf(stderr, "no layout defined, using horizontal\n");
1004 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1005 free(ps1);
1006 ps1 = normalize_str(value.addr);
1007 } else
1008 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1010 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1011 width = parse_int_with_percentage(value.addr, width, d_width);
1012 else
1013 fprintf(stderr, "no width defined, using %d\n", width);
1015 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1016 height = parse_int_with_percentage(value.addr, height, d_height);
1017 else
1018 fprintf(stderr, "no height defined, using %d\n", height);
1020 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1021 x = parse_int_with_pos(value.addr, x, d_width, width);
1022 else
1023 fprintf(stderr, "no x defined, using %d\n", x);
1025 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1026 y = parse_int_with_pos(value.addr, y, d_height, height);
1027 else
1028 fprintf(stderr, "no y defined, using %d\n", y);
1030 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1031 padding = parse_integer(value.addr, padding);
1032 else
1033 fprintf(stderr, "no padding defined, using %d\n", padding);
1035 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1036 char **borders = parse_csslike(value.addr);
1037 if (borders != nil) {
1038 border_n = parse_integer(borders[0], 0);
1039 border_e = parse_integer(borders[1], 0);
1040 border_s = parse_integer(borders[2], 0);
1041 border_w = parse_integer(borders[3], 0);
1042 } else {
1043 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1045 } else {
1046 fprintf(stderr, "no border defined, using 0.\n");
1049 XColor tmp;
1050 // TODO: tmp needs to be free'd after every allocation?
1052 // prompt
1053 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1054 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1055 else
1056 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1058 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1059 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1060 else
1061 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1063 // completion
1064 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1065 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1066 else
1067 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1069 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1070 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1071 else
1072 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1074 // completion highlighted
1075 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1076 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1077 else
1078 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1080 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1081 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1082 else
1083 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1085 // border
1086 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1087 char **colors = parse_csslike(value.addr);
1088 if (colors != nil) {
1089 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1090 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1091 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1092 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1093 } else {
1094 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1096 } else {
1097 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1098 XAllocNamedColor(d, cmap, "white", &borde
1099 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1100 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1102 } else {
1103 XColor tmp;
1104 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1105 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1106 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1107 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1108 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1109 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1110 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1111 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1112 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1115 // second round of args parsing
1116 optind = 0; // reset the option index
1117 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1118 switch (ch) {
1119 case 'a':
1120 first_selected = true;
1121 break;
1122 case 'p': {
1123 char *newprompt = strdup(optarg);
1124 if (newprompt != nil) {
1125 free(ps1);
1126 ps1 = newprompt;
1128 break;
1130 case 'x':
1131 x = parse_int_with_pos(optarg, x, d_width, width);
1132 break;
1133 case 'y':
1134 y = parse_int_with_pos(optarg, y, d_height, height);
1135 break;
1136 case 'P':
1137 padding = parse_integer(optarg, padding);
1138 break;
1139 case 'l':
1140 horizontal_layout = !strcmp(optarg, "horizontal");
1141 break;
1142 case 'f': {
1143 char *newfont = strdup(optarg);
1144 if (newfont != nil) {
1145 free(fontname);
1146 fontname = newfont;
1148 break;
1150 case 'w':
1151 width = parse_int_with_percentage(optarg, width, d_width);
1152 break;
1153 case 'h':
1154 height = parse_int_with_percentage(optarg, height, d_height);
1155 break;
1156 case 'b': {
1157 char **borders = parse_csslike(optarg);
1158 if (borders != nil) {
1159 border_n = parse_integer(borders[0], 0);
1160 border_e = parse_integer(borders[1], 0);
1161 border_s = parse_integer(borders[2], 0);
1162 border_w = parse_integer(borders[3], 0);
1163 } else {
1164 fprintf(stderr, "Error parsing b option\n");
1166 break;
1168 case 'B': {
1169 char **colors = parse_csslike(optarg);
1170 if (colors != nil) {
1171 XColor tmp;
1172 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1173 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1174 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1175 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1176 } else {
1177 fprintf(stderr, "error while parsing B option\n");
1179 break;
1181 case 't': {
1182 XColor tmp;
1183 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1184 break;
1186 case 'T': {
1187 XColor tmp;
1188 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1189 break;
1191 case 'c': {
1192 XColor tmp;
1193 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1194 break;
1196 case 'C': {
1197 XColor tmp;
1198 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1199 break;
1201 case 's': {
1202 XColor tmp;
1203 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1204 break;
1206 case 'S': {
1207 XColor tmp;
1208 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1209 break;
1211 default:
1212 fprintf(stderr, "Unrecognized option %c\n", ch);
1213 status = ERR;
1214 break;
1218 // since only now we know if the first should be selected, update
1219 // the completion here
1220 update_completions(cs, text, lines, first_selected);
1222 // load the font
1223 #ifdef USE_XFT
1224 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1225 #else
1226 char **missing_charset_list;
1227 int missing_charset_count;
1228 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1229 if (font == nil) {
1230 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1231 return EX_UNAVAILABLE;
1233 #endif
1235 // create the window
1236 XSetWindowAttributes attr;
1237 attr.override_redirect = true;
1239 Window w = XCreateWindow(d, // display
1240 DefaultRootWindow(d), // parent
1241 x + offset_x, y + offset_y, // x y
1242 width, height, // w h
1243 0, // border width
1244 DefaultDepth(d, DefaultScreen(d)), // depth
1245 InputOutput, // class
1246 DefaultVisual(d, DefaultScreen(d)), // visual
1247 CWOverrideRedirect, // value mask
1248 &attr);
1250 set_win_atoms_hints(d, w, width, height);
1252 // we want some events
1253 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1255 // make the window appear on the screen
1256 XMapWindow(d, w);
1258 // wait for the MapNotify event (i.e. the event "window rendered")
1259 for (;;) {
1260 XEvent e;
1261 XNextEvent(d, &e);
1262 if (e.type == MapNotify)
1263 break;
1266 // get the *real* width & height after the window was rendered
1267 get_wh(d, &w, &width, &height);
1269 // grab keyboard
1270 take_keyboard(d, w);
1272 // Create some graphics contexts
1273 XGCValues values;
1274 /* values.font = font->fid; */
1276 struct rendering r = {
1277 .d = d,
1278 .w = w,
1279 .width = width,
1280 .height = height,
1281 .padding = padding,
1282 .x_zero = border_w,
1283 .y_zero = border_n,
1284 .border_n = border_n,
1285 .border_e = border_e,
1286 .border_s = border_s,
1287 .border_w = border_w,
1288 .horizontal_layout = horizontal_layout,
1289 .ps1 = ps1,
1290 .ps1len = strlen(ps1),
1291 .prompt = XCreateGC(d, w, 0, &values),
1292 .prompt_bg = XCreateGC(d, w, 0, &values),
1293 .completion = XCreateGC(d, w, 0, &values),
1294 .completion_bg = XCreateGC(d, w, 0, &values),
1295 .completion_highlighted = XCreateGC(d, w, 0, &values),
1296 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1297 .border_n_bg = XCreateGC(d, w, 0, &values),
1298 .border_e_bg = XCreateGC(d, w, 0, &values),
1299 .border_s_bg = XCreateGC(d, w, 0, &values),
1300 .border_w_bg = XCreateGC(d, w, 0, &values),
1301 #ifdef USE_XFT
1302 .font = font,
1303 #else
1304 .font = &font,
1305 #endif
1308 #ifdef USE_XFT
1309 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1311 // prompt
1312 XRenderColor xrcolor;
1313 xrcolor.red = p_fg.red;
1314 xrcolor.green = p_fg.red;
1315 xrcolor.blue = p_fg.red;
1316 xrcolor.alpha = 65535;
1317 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1319 // completion
1320 xrcolor.red = compl_fg.red;
1321 xrcolor.green = compl_fg.green;
1322 xrcolor.blue = compl_fg.blue;
1323 xrcolor.alpha = 65535;
1324 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1326 // completion highlighted
1327 xrcolor.red = compl_highlighted_fg.red;
1328 xrcolor.green = compl_highlighted_fg.green;
1329 xrcolor.blue = compl_highlighted_fg.blue;
1330 xrcolor.alpha = 65535;
1331 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1332 #endif
1334 // load the colors in our GCs
1335 XSetForeground(d, r.prompt, p_fg.pixel);
1336 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1337 XSetForeground(d, r.completion, compl_fg.pixel);
1338 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1339 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1340 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1341 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1342 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1343 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1344 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1346 // open the X input method
1347 XIM xim = XOpenIM(d, xdb, resname, resclass);
1348 check_allocation(xim);
1350 XIMStyles *xis = nil;
1351 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1352 fprintf(stderr, "Input Styles could not be retrieved\n");
1353 return EX_UNAVAILABLE;
1356 XIMStyle bestMatchStyle = 0;
1357 for (int i = 0; i < xis->count_styles; ++i) {
1358 XIMStyle ts = xis->supported_styles[i];
1359 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1360 bestMatchStyle = ts;
1361 break;
1364 XFree(xis);
1366 if (!bestMatchStyle) {
1367 fprintf(stderr, "No matching input style could be determined\n");
1370 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1371 check_allocation(xic);
1373 // draw the window for the first time
1374 draw(&r, text, cs);
1376 // main loop
1377 while (status == LOOPING) {
1378 XEvent e;
1379 XNextEvent(d, &e);
1381 if (XFilterEvent(&e, w))
1382 continue;
1384 switch (e.type) {
1385 case KeymapNotify:
1386 XRefreshKeyboardMapping(&e.xmapping);
1387 break;
1389 case KeyPress: {
1390 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1392 char *input;
1393 switch (parse_event(d, ev, xic, &input)) {
1394 case EXIT:
1395 status = ERR;
1396 break;
1398 case CONFIRM:
1399 status = OK;
1401 // if first_selected is active and the first completion is
1402 // active be sure to 'expand' the text to match the selection
1403 if (first_selected && cs && cs->selected == 0) {
1404 free(text);
1405 text = strdup(cs->completions->completion);
1406 if (text == nil) {
1407 fprintf(stderr, "Memory allocation error");
1408 status = ERR;
1410 textlen = strlen(text);
1412 break;
1414 case PREV_COMPL: {
1415 complete(cs, first_selected, true, &text, &textlen, &status);
1416 break;
1419 case NEXT_COMPL: {
1420 complete(cs, first_selected, false, &text, &textlen, &status);
1421 break;
1424 case DEL_CHAR:
1425 popc(text, textlen);
1426 update_completions(cs, text, lines, first_selected);
1427 break;
1429 case DEL_WORD: {
1430 // `textlen` is the lenght of the allocated string, not the
1431 // lenght of the ACTUAL string
1432 int p = strlen(text) -1;
1433 if (p > 0) { // delete the current char
1434 text[p] = 0;
1435 p--;
1438 // erase the alphanumeric char
1439 while (p >= 0 && isalnum(text[p])) {
1440 text[p] = 0;
1441 p--;
1444 // erase also trailing white spaces
1445 while (p >= 0 && isspace(text[p])) {
1446 text[p] = 0;
1447 p--;
1449 update_completions(cs, text, lines, first_selected);
1450 break;
1453 case DEL_LINE: {
1454 for (int i = 0; i < textlen; ++i)
1455 text[i] = 0;
1456 update_completions(cs, text, lines, first_selected);
1457 break;
1460 case ADD_CHAR: {
1461 int str_len = strlen(input);
1463 // sometimes a strange key is pressed (i.e. ctrl alone),
1464 // so input will be empty. Don't need to update completion
1465 // in this case
1466 if (str_len == 0)
1467 break;
1469 for (int i = 0; i < str_len; ++i) {
1470 textlen = pushc(&text, textlen, input[i]);
1471 if (textlen == -1) {
1472 fprintf(stderr, "Memory allocation error\n");
1473 status = ERR;
1474 break;
1477 if (status != ERR) {
1478 update_completions(cs, text, lines, first_selected);
1479 free(input);
1481 break;
1484 case TOGGLE_FIRST_SELECTED:
1485 first_selected = !first_selected;
1486 if (first_selected && cs->selected < 0)
1487 cs->selected = 0;
1488 if (!first_selected && cs->selected == 0)
1489 cs->selected = -1;
1490 break;
1495 draw(&r, text, cs);
1498 if (status == OK)
1499 printf("%s\n", text);
1501 release_keyboard(r.d);
1503 #ifdef USE_XFT
1504 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1505 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1506 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1507 #endif
1509 free(ps1);
1510 free(fontname);
1511 free(text);
1513 char *l = nil;
1514 char **lns = lines;
1515 while ((l = *lns) != nil) {
1516 free(l);
1517 ++lns;
1520 free(lines);
1521 compls_delete(cs);
1523 XDestroyWindow(r.d, r.w);
1524 XCloseDisplay(r.d);
1526 return status;