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 #define nil NULL
31 #define resname "MyMenu"
32 #define resclass "mymenu"
34 #ifdef USE_XFT
35 # define default_fontname "monospace"
36 #else
37 # define default_fontname "fixed"
38 #endif
40 #define MIN(a, b) ((a) < (b) ? (a) : (b))
41 #define MAX(a, b) ((a) > (b) ? (a) : (b))
43 // If we don't have it or we don't want an "ignore case" completion
44 // style, fall back to `strstr(3)`
45 #ifndef USE_STRCASESTR
46 # define strcasestr strstr
47 #endif
49 #define INITIAL_ITEMS 64
51 #define cannot_allocate_memory { \
52 fprintf(stderr, "Could not allocate memory\n"); \
53 abort(); \
54 }
56 #define check_allocation(a) { \
57 if (a == nil) \
58 cannot_allocate_memory; \
59 }
61 enum state {LOOPING, OK, ERR};
63 enum text_type {PROMPT, COMPL, COMPL_HIGH};
65 enum action {
66 EXIT,
67 CONFIRM,
68 NEXT_COMPL,
69 PREV_COMPL,
70 DEL_CHAR,
71 DEL_WORD,
72 DEL_LINE,
73 ADD_CHAR
74 };
76 struct rendering {
77 Display *d;
78 Window w;
79 int width;
80 int height;
81 int padding;
82 bool horizontal_layout;
83 char *ps1;
84 int ps1len;
85 GC prompt;
86 GC prompt_bg;
87 GC completion;
88 GC completion_bg;
89 GC completion_highlighted;
90 GC completion_highlighted_bg;
91 #ifdef USE_XFT
92 XftFont *font;
93 XftDraw *xftdraw;
94 XftColor xft_prompt;
95 XftColor xft_completion;
96 XftColor xft_completion_highlighted;
97 #else
98 XFontSet *font;
99 #endif
100 };
102 struct completions {
103 char *completion;
104 bool selected;
105 struct completions *next;
106 };
108 // return a newly allocated (and empty) completion list
109 struct completions *compl_new() {
110 struct completions *c = malloc(sizeof(struct completions));
112 if (c == nil)
113 return c;
115 c->completion = nil;
116 c->selected = false;
117 c->next = nil;
118 return c;
121 // delete ONLY the given completion (i.e. does not free c->next...)
122 void compl_delete(struct completions *c) {
123 free(c);
126 // delete all completion
127 void compl_delete_rec(struct completions *c) {
128 while (c != nil) {
129 struct completions *t = c->next;
130 free(c);
131 c = t;
135 // given a completion list, select the next completion and return the
136 // element that is selected
137 struct completions *compl_select_next(struct completions *c) {
138 if (c == nil)
139 return nil;
141 struct completions *orig = c;
142 while (c != nil) {
143 if (c->selected) {
144 c->selected = false;
145 if (c->next != nil) {
146 // the current one is selected and the next one exists
147 c->next->selected = true;
148 return c->next;
149 } else {
150 // the current one is selected and the next one is nil,
151 // select the first one
152 orig->selected = true;
153 return orig;
156 c = c->next;
159 orig->selected = true;
160 return orig;
163 // given a completion list, select the previous and return the element
164 // that is selected
165 struct completions *compl_select_prev(struct completions *c) {
166 if (c == nil)
167 return nil;
169 struct completions *last = nil;
171 if (c->selected) { // if the first is selected, select the last one
172 c->selected = false;
173 while (c != nil) {
174 if (c->next == nil) {
175 c->selected = true;
176 return c;
178 c = c->next;
182 // if the selected one is inside the list, select the previous one
183 while (c != nil) {
184 if (c->next == nil) { // if c is the last, save it for later
185 last = c;
188 if (c->next && c->next->selected) {
189 c->selected = true;
190 c->next->selected = false;
191 return c;
193 c = c->next;
196 // if nothing were selected, select the last one
197 if (c != nil)
198 c->selected = true;
199 return c;
201 /* if (n || c->selected) { // select the last one */
202 /* c->selected = false; */
203 /* while (cc != nil) { */
204 /* if (cc->next == nil) { */
205 /* cc->selected = true; */
206 /* return cc; */
207 /* } */
208 /* cc = cc->next; */
209 /* } */
210 /* } */
211 /* else // select the previous one */
212 /* while (cc != nil) { */
213 /* if (cc->next != nil && cc->next->selected) { */
214 /* cc->next->selected = false; */
215 /* cc->selected = true; */
216 /* return cc; */
217 /* } */
218 /* cc = cc->next; */
219 /* } */
220 /* return nil; */
223 // create a completion list from a text and the list of possible completions
224 struct completions *filter(char *text, char **lines) {
225 int i = 0;
226 struct completions *root = compl_new();
227 struct completions *c = root;
228 if (c == nil)
229 return nil;
231 for (;;) {
232 char *l = lines[i];
233 if (l == nil)
234 break;
236 if (strcasestr(l, text) != nil) {
237 c->next = compl_new();
238 c = c->next;
239 if (c == nil) {
240 compl_delete_rec(root);
241 return nil;
243 c->completion = l;
246 ++i;
249 struct completions *r = root->next;
250 compl_delete(root);
251 return r;
254 // update the given completion, that is: clean the old cs & generate a new one.
255 struct completions *update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
256 compl_delete_rec(cs);
257 cs = filter(text, lines);
258 if (first_selected && cs != nil)
259 cs->selected = true;
260 return cs;
263 // select the next, or the previous, selection and update some
264 // state. `text' will be updated with the text of the completion and
265 // `textlen' with the new lenght of `text'. If the memory cannot be
266 // allocated, `status' will be set to `ERR'.
267 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
269 // if the first is always selected, and the first entry is different
270 // from the text, expand the text and return
271 if (first_selected
272 && cs != nil
273 && cs->selected
274 && strcmp(cs->completion, *text) != 0
275 && !p) {
276 free(*text);
277 *text = strdup(cs->completion);
278 if (text == nil) {
279 fprintf(stderr, "Memory allocation error!\n");
280 *status = ERR;
281 return;
283 *textlen = strlen(*text);
284 return;
287 struct completions *n = p
288 ? compl_select_prev(cs)
289 : compl_select_next(cs);
291 if (n != nil) {
292 free(*text);
293 *text = strdup(n->completion);
294 if (text == nil) {
295 fprintf(stderr, "Memory allocation error!\n");
296 *status = ERR;
297 return;
299 *textlen = strlen(*text);
304 // push the character c at the end of the string pointed by p
305 int pushc(char **p, int maxlen, char c) {
306 int len = strnlen(*p, maxlen);
308 if (!(len < maxlen -2)) {
309 maxlen += maxlen >> 1;
310 char *newptr = realloc(*p, maxlen);
311 if (newptr == nil) { // bad!
312 return -1;
314 *p = newptr;
317 (*p)[len] = c;
318 (*p)[len+1] = '\0';
319 return maxlen;
322 // return the number of character
323 int utf8strnlen(char *s, int maxlen) {
324 int len = 0;
325 while (*s && maxlen > 0) {
326 len += (*s++ & 0xc0) != 0x80;
327 maxlen--;
329 return len;
332 // remove the last *glyph* from the *utf8* string!
333 // this is different from just setting the last byte to 0 (in some
334 // cases ofc). The actual implementation is quite inefficient because
335 // it remove the last byte until the number of glyphs doesn't change
336 void popc(char *p, int maxlen) {
337 int len = strnlen(p, maxlen);
339 if (len == 0)
340 return;
342 int ulen = utf8strnlen(p, maxlen);
343 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
344 len--;
345 p[len] = 0;
349 // If the string is surrounded by quotes (`"`) remove them and replace
350 // every `\"` in the string with `"`
351 char *normalize_str(const char *str) {
352 int len = strlen(str);
353 if (len == 0)
354 return nil;
356 char *s = calloc(len, sizeof(char));
357 check_allocation(s);
358 int p = 0;
359 while (*str) {
360 char c = *str;
361 if (*str == '\\') {
362 if (*(str + 1)) {
363 s[p] = *(str + 1);
364 p++;
365 str += 2; // skip this and the next char
366 continue;
367 } else {
368 break;
371 if (c == '"') {
372 str++; // skip only this char
373 continue;
375 s[p] = c;
376 p++;
377 str++;
379 return s;
382 // read an arbitrary long line from stdin and return a pointer to it
383 // TODO: resize the allocated memory to exactly fit the string once
384 // read?
385 char *readline(bool *eof) {
386 int maxlen = 8;
387 char *str = calloc(maxlen, sizeof(char));
388 if (str == nil) {
389 fprintf(stderr, "Cannot allocate memory!\n");
390 exit(EX_UNAVAILABLE);
393 int c;
394 while((c = getchar()) != EOF) {
395 if (c == '\n')
396 return str;
397 else
398 maxlen = pushc(&str, maxlen, c);
400 if (maxlen == -1) {
401 fprintf(stderr, "Cannot allocate memory!\n");
402 exit(EX_UNAVAILABLE);
405 *eof = true;
406 return str;
409 // read an arbitrary amount of text until an EOF and store it in
410 // lns. `items` is the capacity of lns. It may increase lns with
411 // `realloc(3)` to store more line. Return the number of lines
412 // read. The last item will always be a NULL pointer. It ignore the
413 // "null" (empty) lines
414 int readlines (char ***lns, int items) {
415 bool finished = false;
416 int n = 0;
417 char **lines = *lns;
418 while (true) {
419 lines[n] = readline(&finished);
421 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
422 free(lines[n]);
423 --n; // forget about this line
426 if (finished)
427 break;
429 ++n;
431 if (n == items - 1) {
432 items += items >>1;
433 char **l = realloc(lines, sizeof(char*) * items);
434 check_allocation(l);
435 *lns = l;
436 lines = l;
440 n++;
441 lines[n] = nil;
442 return items;
445 // Compute the dimension of the string str once rendered, return the
446 // width and save the width and the height in ret_width and ret_height
447 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
448 int height;
449 int width;
450 #ifdef USE_XFT
451 XGlyphInfo gi;
452 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
453 /* height = gi.height; */
454 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
455 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
456 height = r->font->ascent - r->font->descent;
457 width = gi.width - gi.x;
458 #else
459 XRectangle rect;
460 XmbTextExtents(*r->font, str, len, nil, &rect);
461 height = rect.height;
462 width = rect.width;
463 #endif
464 if (ret_width != nil) *ret_width = width;
465 if (ret_height != nil) *ret_height = height;
466 return width;
469 // Draw the string str
470 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
471 #ifdef USE_XFT
472 XftColor xftcolor;
473 if (tt == PROMPT) xftcolor = r->xft_prompt;
474 if (tt == COMPL) xftcolor = r->xft_completion;
475 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
477 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
478 #else
479 GC gc;
480 if (tt == PROMPT) gc = r->prompt;
481 if (tt == COMPL) gc = r->completion;
482 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
483 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
484 #endif
487 // Duplicate the string str and substitute every space with a 'n'
488 char *strdupn(char *str) {
489 int len = strlen(str);
491 if (str == nil || len == 0)
492 return nil;
494 char *dup = strdup(str);
495 if (dup == nil)
496 return nil;
498 for (int i = 0; i < len; ++i)
499 if (dup[i] == ' ')
500 dup[i] = 'n';
502 return dup;
505 // |------------------|----------------------------------------------|
506 // | 20 char text | completion | completion | completion | compl |
507 // |------------------|----------------------------------------------|
508 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
509 int prompt_width = 20; // char
511 int width, height;
512 char *ps1_dup = strdupn(r->ps1);
513 if (ps1_dup == nil)
514 return;
516 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
517 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
518 free(ps1_dup);
519 int start_at = ps1xlen;
521 start_at = text_extents("n", 1, r, nil, nil);
522 start_at = start_at * prompt_width + r->padding;
524 int texty = (height + r->height) >>1;
526 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
528 int text_len = strlen(text);
529 if (text_len > prompt_width)
530 text = text + (text_len - prompt_width);
531 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
532 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
534 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
536 while (cs != nil) {
537 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
538 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
540 int len = strlen(cs->completion);
541 int text_width = text_extents(cs->completion, len, r, nil, nil);
543 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
545 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
547 start_at += text_width + r->padding * 2;
549 if (start_at > r->width)
550 break; // don't draw completion if the space isn't enough
552 cs = cs->next;
555 XFlush(r->d);
558 // |-----------------------------------------------------------------|
559 // | prompt |
560 // |-----------------------------------------------------------------|
561 // | completion |
562 // |-----------------------------------------------------------------|
563 // | completion |
564 // |-----------------------------------------------------------------|
565 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
566 int height, width;
567 text_extents("fjpgl", 5, r, nil, &height);
568 int start_at = height + r->padding;
570 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
571 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
573 char *ps1_dup = strdupn(r->ps1);
574 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
575 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
576 free(ps1_dup);
578 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
579 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
580 start_at += r->padding;
582 while (cs != nil) {
583 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
584 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
586 int len = strlen(cs->completion);
587 text_extents(cs->completion, len, r, &width, &height);
588 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
589 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
591 start_at += height + r->padding *2;
593 if (start_at > r->height)
594 break; // don't draw completion if the space isn't enough
596 cs = cs->next;
599 XFlush(r->d);
602 void draw(struct rendering *r, char *text, struct completions *cs) {
603 if (r->horizontal_layout)
604 draw_horizontally(r, text, cs);
605 else
606 draw_vertically(r, text, cs);
609 /* Set some WM stuff */
610 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
611 Atom type;
612 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
613 XChangeProperty(
614 d,
615 w,
616 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
617 XInternAtom(d, "ATOM", false),
618 32,
619 PropModeReplace,
620 (unsigned char *)&type,
622 );
624 /* some window managers honor this properties */
625 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
626 XChangeProperty(d,
627 w,
628 XInternAtom(d, "_NET_WM_STATE", false),
629 XInternAtom(d, "ATOM", false),
630 32,
631 PropModeReplace,
632 (unsigned char *)&type,
634 );
636 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
637 XChangeProperty(d,
638 w,
639 XInternAtom(d, "_NET_WM_STATE", false),
640 XInternAtom(d, "ATOM", false),
641 32,
642 PropModeAppend,
643 (unsigned char *)&type,
645 );
647 // setting window hints
648 XClassHint *class_hint = XAllocClassHint();
649 if (class_hint == nil) {
650 fprintf(stderr, "Could not allocate memory for class hint\n");
651 exit(EX_UNAVAILABLE);
653 class_hint->res_name = resname;
654 class_hint->res_class = resclass;
655 XSetClassHint(d, w, class_hint);
656 XFree(class_hint);
658 XSizeHints *size_hint = XAllocSizeHints();
659 if (size_hint == nil) {
660 fprintf(stderr, "Could not allocate memory for size hint\n");
661 exit(EX_UNAVAILABLE);
663 size_hint->flags = PMinSize | PBaseSize;
664 size_hint->min_width = width;
665 size_hint->base_width = width;
666 size_hint->min_height = height;
667 size_hint->base_height = height;
669 XFlush(d);
672 void get_wh(Display *d, Window *w, int *width, int *height) {
673 XWindowAttributes win_attr;
674 XGetWindowAttributes(d, *w, &win_attr);
675 *height = win_attr.height;
676 *width = win_attr.width;
679 // I know this may seem a little hackish BUT is the only way I managed
680 // to actually grab that goddam keyboard. Only one call to
681 // XGrabKeyboard does not always end up with the keyboard grabbed!
682 int take_keyboard(Display *d, Window w) {
683 int i;
684 for (i = 0; i < 100; i++) {
685 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
686 return 1;
687 usleep(1000);
689 return 0;
692 // release the keyboard.
693 void release_keyboard(Display *d) {
694 XUngrabKeyboard(d, CurrentTime);
697 int parse_integer(const char *str, int default_value) {
698 errno = 0;
699 char *ep;
700 long lval = strtol(str, &ep, 10);
701 if (str[0] == '\0' || *ep != '\0') { // NaN
702 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
703 return default_value;
705 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
706 (lval > INT_MAX || lval < INT_MIN)) {
707 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
708 return default_value;
710 return lval;
713 // like parse_integer, but if the value ends with a `%' then its
714 // treated like a percentage (`max' is used to compute the percentage)
715 int parse_int_with_percentage(const char *str, int default_value, int max) {
716 int len = strlen(str);
717 if (len > 0 && str[len-1] == '%') {
718 char *cpy = strdup(str);
719 check_allocation(cpy);
720 cpy[len-1] = '\0';
721 int val = parse_integer(cpy, default_value);
722 free(cpy);
723 return val * max / 100;
725 return parse_integer(str, default_value);
728 // like parse_int_with_percentage but understands the special value
729 // "middle" that is (max - self) / 2
730 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
731 if (!strcmp(str, "middle")) {
732 return (max - self)/2;
734 return parse_int_with_percentage(str, default_value, max);
737 // Given the name of the program (argv[0]?) print a small help on stderr
738 void usage(char *prgname) {
739 fprintf(stderr, "Usage: %s [flags]\n", prgname);
740 fprintf(stderr, "\t-a: automatic mode, the first completion is "
741 "always selected;\n");
742 fprintf(stderr, "\t-h: print this help.\n");
745 // Given an event, try to understand what the user wants. If the
746 // return value is ADD_CHAR then `input' is a pointer to a string that
747 // will need to be free'ed.
748 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
749 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
750 return DEL_CHAR;
752 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
753 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
755 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
756 return CONFIRM;
758 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
759 return EXIT;
761 // try to read what the user pressed
762 int symbol = 0;
763 Status s = 0;
764 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
765 if (s == XBufferOverflow) {
766 // should not happen since there are no utf-8 characters larger
767 // than 24bits
768 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
769 return EXIT;
771 char *str = (char*)&symbol;
773 if (ev->state & ControlMask) {
774 if (!strcmp(str, "")) // C-u
775 return DEL_LINE;
776 if (!strcmp(str, "")) // C-w
777 return DEL_WORD;
778 if (!strcmp(str, "")) // C-h
779 return DEL_CHAR;
780 if (!strcmp(str, "\r")) // C-m
781 return CONFIRM;
782 if (!strcmp(str, "")) // C-p
783 return PREV_COMPL;
784 if (!strcmp(str, "")) // C-n
785 return NEXT_COMPL;
786 if (!strcmp(str, "")) // C-c
787 return EXIT;
790 *input = strdup((char*)&symbol);
791 if (*input == nil) {
792 fprintf(stderr, "Error while allocating memory for key.\n");
793 return EXIT;
796 return ADD_CHAR;
799 // clean up some resources
800 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
801 release_keyboard(r->d);
803 #ifdef USE_XFT
804 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
805 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
806 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
807 #endif
809 free(ps1);
810 free(fontname);
811 free(text);
813 char *l = nil;
814 char **lns = lines;
815 while ((l = *lns) != nil) {
816 free(l);
817 ++lns;
819 free(lines);
820 compl_delete(cs);
822 XDestroyWindow(r->d, r->w);
823 XCloseDisplay(r->d);
825 return status;
828 int main(int argc, char **argv) {
829 // by default the first completion isn't selected
830 bool first_selected = false;
832 // parse the command line options
833 int ch;
834 while ((ch = getopt(argc, argv, "ahv")) != -1) {
835 switch (ch) {
836 case 'a':
837 first_selected = true;
838 break;
839 case 'h':
840 usage(*argv);
841 return 0;
842 case 'v':
843 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
844 return 0;
845 default:
846 usage(*argv);
847 return EX_USAGE;
851 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
852 readlines(&lines, INITIAL_ITEMS);
854 setlocale(LC_ALL, getenv("LANG"));
856 enum state status = LOOPING;
858 // where the monitor start (used only with xinerama)
859 int offset_x = 0;
860 int offset_y = 0;
862 // width and height of the window
863 int width = 400;
864 int height = 20;
866 // position on the screen
867 int x = 0;
868 int y = 0;
870 // the default padding
871 int padding = 10;
873 char *ps1 = strdup("$ ");
874 check_allocation(ps1);
876 char *fontname = strdup(default_fontname);
877 check_allocation(fontname);
879 int textlen = 10;
880 char *text = malloc(textlen * sizeof(char));
881 check_allocation(text);
883 /* struct completions *cs = filter(text, lines); */
884 struct completions *cs = nil;
885 cs = update_completions(cs, text, lines, first_selected);
887 // start talking to xorg
888 Display *d = XOpenDisplay(nil);
889 if (d == nil) {
890 fprintf(stderr, "Could not open display!\n");
891 return EX_UNAVAILABLE;
894 // get display size
895 // XXX: is getting the default root window dimension correct?
896 XWindowAttributes xwa;
897 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
898 int d_width = xwa.width;
899 int d_height = xwa.height;
901 #ifdef USE_XINERAMA
902 if (XineramaIsActive(d)) {
903 // find the mice
904 int number_of_screens = XScreenCount(d);
905 Window r;
906 Window root;
907 int root_x, root_y, win_x, win_y;
908 unsigned int mask;
909 bool res;
910 for (int i = 0; i < number_of_screens; ++i) {
911 root = XRootWindow(d, i);
912 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
913 if (res) break;
915 if (!res) {
916 fprintf(stderr, "No mouse found.\n");
917 root_x = 0;
918 root_y = 0;
921 // now find in which monitor the mice is on
922 int monitors;
923 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
924 if (info) {
925 for (int i = 0; i < monitors; ++i) {
926 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
927 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
928 offset_x = info[i].x_org;
929 offset_y = info[i].y_org;
930 d_width = info[i].width;
931 d_height = info[i].height;
932 break;
936 XFree(info);
938 #endif
940 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
941 XColor p_fg, p_bg,
942 compl_fg, compl_bg,
943 compl_highlighted_fg, compl_highlighted_bg;
945 bool horizontal_layout = true;
947 // read resource
948 XrmInitialize();
949 char *xrm = XResourceManagerString(d);
950 XrmDatabase xdb = nil;
951 if (xrm != nil) {
952 xdb = XrmGetStringDatabase(xrm);
953 XrmValue value;
954 char *datatype[20];
956 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
957 fontname = strdup(value.addr);
958 check_allocation(fontname);
960 else
961 fprintf(stderr, "no font defined, using %s\n", fontname);
963 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
964 char *v = strdup(value.addr);
965 check_allocation(v);
966 horizontal_layout = !strcmp(v, "horizontal");
967 free(v);
969 else
970 fprintf(stderr, "no layout defined, using horizontal\n");
972 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
973 free(ps1);
974 ps1 = normalize_str(value.addr);
975 } else
976 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
978 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
979 width = parse_int_with_percentage(value.addr, width, d_width);
980 else
981 fprintf(stderr, "no width defined, using %d\n", width);
983 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
984 height = parse_int_with_percentage(value.addr, height, d_height);
985 else
986 fprintf(stderr, "no height defined, using %d\n", height);
988 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
989 x = parse_int_with_middle(value.addr, x, d_width, width);
990 else
991 fprintf(stderr, "no x defined, using %d\n", x);
993 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
994 y = parse_int_with_middle(value.addr, y, d_height, height);
995 else
996 fprintf(stderr, "no y defined, using %d\n", y);
998 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
999 padding = parse_integer(value.addr, padding);
1000 else
1001 fprintf(stderr, "no y defined, using %d\n", padding);
1003 XColor tmp;
1004 // TODO: tmp needs to be free'd after every allocation?
1006 // prompt
1007 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1008 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1009 else
1010 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1012 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1013 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1014 else
1015 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1017 // completion
1018 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1019 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1020 else
1021 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1023 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1024 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1025 else
1026 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1028 // completion highlighted
1029 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1030 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1031 else
1032 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1034 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1035 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1036 else
1037 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1038 } else {
1039 XColor tmp;
1040 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1041 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1042 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1043 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1044 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1045 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1048 // load the font
1049 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
1050 /* if (font == nil) { */
1051 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
1052 /* font = XLoadQueryFont(d, "fixed"); */
1053 /* } */
1054 // load the font
1055 #ifdef USE_XFT
1056 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1057 #else
1058 char **missing_charset_list;
1059 int missing_charset_count;
1060 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1061 if (font == nil) {
1062 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1063 return EX_UNAVAILABLE;
1065 #endif
1067 // create the window
1068 XSetWindowAttributes attr;
1069 attr.override_redirect = true;
1071 Window w = XCreateWindow(d, // display
1072 DefaultRootWindow(d), // parent
1073 x + offset_x, y + offset_y, // x y
1074 width, height, // w h
1075 0, // border width
1076 DefaultDepth(d, DefaultScreen(d)), // depth
1077 InputOutput, // class
1078 DefaultVisual(d, DefaultScreen(d)), // visual
1079 CWOverrideRedirect, // value mask
1080 &attr);
1082 set_win_atoms_hints(d, w, width, height);
1084 // we want some events
1085 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1087 // make the window appear on the screen
1088 XMapWindow(d, w);
1090 // wait for the MapNotify event (i.e. the event "window rendered")
1091 for (;;) {
1092 XEvent e;
1093 XNextEvent(d, &e);
1094 if (e.type == MapNotify)
1095 break;
1098 // get the *real* width & height after the window was rendered
1099 get_wh(d, &w, &width, &height);
1101 // grab keyboard
1102 take_keyboard(d, w);
1104 // Create some graphics contexts
1105 XGCValues values;
1106 /* values.font = font->fid; */
1108 struct rendering r = {
1109 .d = d,
1110 .w = w,
1111 #ifdef USE_XFT
1112 .font = font,
1113 #else
1114 .font = &font,
1115 #endif
1116 .prompt = XCreateGC(d, w, 0, &values),
1117 .prompt_bg = XCreateGC(d, w, 0, &values),
1118 .completion = XCreateGC(d, w, 0, &values),
1119 .completion_bg = XCreateGC(d, w, 0, &values),
1120 .completion_highlighted = XCreateGC(d, w, 0, &values),
1121 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1122 .width = width,
1123 .height = height,
1124 .padding = padding,
1125 .horizontal_layout = horizontal_layout,
1126 .ps1 = ps1,
1127 .ps1len = strlen(ps1)
1130 #ifdef USE_XFT
1131 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1133 // prompt
1134 XRenderColor xrcolor;
1135 xrcolor.red = p_fg.red;
1136 xrcolor.green = p_fg.red;
1137 xrcolor.blue = p_fg.red;
1138 xrcolor.alpha = 65535;
1139 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1141 // completion
1142 xrcolor.red = compl_fg.red;
1143 xrcolor.green = compl_fg.green;
1144 xrcolor.blue = compl_fg.blue;
1145 xrcolor.alpha = 65535;
1146 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1148 // completion highlighted
1149 xrcolor.red = compl_highlighted_fg.red;
1150 xrcolor.green = compl_highlighted_fg.green;
1151 xrcolor.blue = compl_highlighted_fg.blue;
1152 xrcolor.alpha = 65535;
1153 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1154 #endif
1156 // load the colors in our GCs
1157 XSetForeground(d, r.prompt, p_fg.pixel);
1158 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1159 XSetForeground(d, r.completion, compl_fg.pixel);
1160 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1161 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1162 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1164 // open the X input method
1165 XIM xim = XOpenIM(d, xdb, resname, resclass);
1166 check_allocation(xim);
1168 XIMStyles *xis = nil;
1169 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1170 fprintf(stderr, "Input Styles could not be retrieved\n");
1171 return EX_UNAVAILABLE;
1174 XIMStyle bestMatchStyle = 0;
1175 for (int i = 0; i < xis->count_styles; ++i) {
1176 XIMStyle ts = xis->supported_styles[i];
1177 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1178 bestMatchStyle = ts;
1179 break;
1182 XFree(xis);
1184 if (!bestMatchStyle) {
1185 fprintf(stderr, "No matching input style could be determined\n");
1188 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1189 check_allocation(xic);
1191 // draw the window for the first time
1192 draw(&r, text, cs);
1194 // main loop
1195 while (status == LOOPING) {
1196 XEvent e;
1197 XNextEvent(d, &e);
1199 if (XFilterEvent(&e, w))
1200 continue;
1202 switch (e.type) {
1203 case KeymapNotify:
1204 XRefreshKeyboardMapping(&e.xmapping);
1205 break;
1207 case KeyPress: {
1208 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1210 char *input;
1211 switch (parse_event(d, ev, xic, &input)) {
1212 case EXIT:
1213 status = ERR;
1214 break;
1216 case CONFIRM:
1217 status = OK;
1218 if (first_selected) {
1219 complete(cs, first_selected, false, &text, &textlen, &status);
1221 break;
1223 case PREV_COMPL: {
1224 complete(cs, first_selected, true, &text, &textlen, &status);
1225 break;
1228 case NEXT_COMPL: {
1229 complete(cs, first_selected, false, &text, &textlen, &status);
1230 break;
1233 case DEL_CHAR:
1234 popc(text, textlen);
1235 cs = update_completions(cs, text, lines, first_selected);
1236 break;
1238 case DEL_WORD: {
1239 // `textlen` is the lenght of the allocated string, not the
1240 // lenght of the ACTUAL string
1241 int p = strlen(text) -1;
1242 if (p > 0) { // delete the current char
1243 text[p] = 0;
1244 p--;
1247 // erase the alphanumeric char
1248 while (p >= 0 && isalnum(text[p])) {
1249 text[p] = 0;
1250 p--;
1253 // erase also trailing white spaces
1254 while (p >= 0 && isspace(text[p])) {
1255 text[p] = 0;
1256 p--;
1258 cs = update_completions(cs, text, lines, first_selected);
1259 break;
1262 case DEL_LINE: {
1263 for (int i = 0; i < textlen; ++i)
1264 text[i] = 0;
1265 cs = update_completions(cs, text, lines, first_selected);
1266 break;
1269 case ADD_CHAR: {
1270 int str_len = strlen(input);
1271 for (int i = 0; i < str_len; ++i) {
1272 textlen = pushc(&text, textlen, input[i]);
1273 if (textlen == -1) {
1274 fprintf(stderr, "Memory allocation error\n");
1275 status = ERR;
1276 break;
1278 cs = update_completions(cs, text, lines, first_selected);
1279 free(input);
1284 draw(&r, text, cs);
1285 break;
1287 default:
1288 fprintf(stderr, "Unknown event %d\n", e.type);
1292 if (status == OK)
1293 printf("%s\n", text);
1295 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);