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 #ifdef USE_XFT
37 # define default_fontname "monospace"
38 #else
39 # define default_fontname "fixed"
40 #endif
42 #define MIN(a, b) ((a) < (b) ? (a) : (b))
43 #define MAX(a, b) ((a) > (b) ? (a) : (b))
45 // If we don't have it or we don't want an "ignore case" completion
46 // style, fall back to `strstr(3)`
47 #ifndef USE_STRCASESTR
48 # define strcasestr strstr
49 #endif
51 #define INITIAL_ITEMS 64
53 #define cannot_allocate_memory { \
54 fprintf(stderr, "Could not allocate memory\n"); \
55 abort(); \
56 }
58 #define check_allocation(a) { \
59 if (a == nil) \
60 cannot_allocate_memory; \
61 }
63 // The possible state of the event loop.
64 enum state {LOOPING, OK, ERR};
66 // for the drawing-related function. The text to be rendered could be
67 // the prompt, a completion or a highlighted completion
68 enum text_type {PROMPT, COMPL, COMPL_HIGH};
70 // These are the possible action to be performed after user input.
71 enum action {
72 EXIT,
73 CONFIRM,
74 NEXT_COMPL,
75 PREV_COMPL,
76 DEL_CHAR,
77 DEL_WORD,
78 DEL_LINE,
79 ADD_CHAR
80 };
82 struct rendering {
83 Display *d;
84 Window w;
85 int width;
86 int height;
87 int padding;
88 bool horizontal_layout;
89 char *ps1;
90 int ps1len;
91 GC prompt;
92 GC prompt_bg;
93 GC completion;
94 GC completion_bg;
95 GC completion_highlighted;
96 GC completion_highlighted_bg;
97 #ifdef USE_XFT
98 XftFont *font;
99 XftDraw *xftdraw;
100 XftColor xft_prompt;
101 XftColor xft_completion;
102 XftColor xft_completion_highlighted;
103 #else
104 XFontSet *font;
105 #endif
106 };
108 // A simple linked list to store the completions.
109 struct completions {
110 char *completion;
111 bool selected;
112 struct completions *next;
113 };
115 // return a newly allocated (and empty) completion list
116 struct completions *compl_new() {
117 struct completions *c = malloc(sizeof(struct completions));
119 if (c == nil)
120 return c;
122 c->completion = nil;
123 c->selected = false;
124 c->next = nil;
125 return c;
128 // delete ONLY the given completion (i.e. does not free c->next...)
129 void compl_delete(struct completions *c) {
130 free(c);
133 // delete all completion
134 void compl_delete_rec(struct completions *c) {
135 while (c != nil) {
136 struct completions *t = c->next;
137 free(c);
138 c = t;
142 // given a completion list, select the next completion and return the
143 // element that is selected
144 struct completions *compl_select_next(struct completions *c) {
145 if (c == nil)
146 return nil;
148 struct completions *orig = c;
149 while (c != nil) {
150 if (c->selected) {
151 c->selected = false;
152 if (c->next != nil) {
153 // the current one is selected and the next one exists
154 c->next->selected = true;
155 return c->next;
156 } else {
157 // the current one is selected and the next one is nil,
158 // select the first one
159 orig->selected = true;
160 return orig;
163 c = c->next;
166 orig->selected = true;
167 return orig;
170 // given a completion list, select the previous and return the element
171 // that is selected
172 struct completions *compl_select_prev(struct completions *c) {
173 if (c == nil)
174 return nil;
176 struct completions *last = nil;
178 if (c->selected) { // if the first is selected, select the last one
179 c->selected = false;
180 while (c != nil) {
181 if (c->next == nil) {
182 c->selected = true;
183 return c;
185 c = c->next;
189 // if the selected one is inside the list, select the previous one
190 while (c != nil) {
191 if (c->next == nil) { // if c is the last, save it for later
192 last = c;
195 if (c->next && c->next->selected) {
196 c->selected = true;
197 c->next->selected = false;
198 return c;
200 c = c->next;
203 // if nothing were selected, select the last one
204 if (c != nil)
205 c->selected = true;
206 return c;
209 // create a completion list from a text and the list of possible completions
210 struct completions *filter(char *text, char **lines) {
211 int i = 0;
212 struct completions *root = compl_new();
213 struct completions *c = root;
214 if (c == nil)
215 return nil;
217 for (;;) {
218 char *l = lines[i];
219 if (l == nil)
220 break;
222 if (strcasestr(l, text) != nil) {
223 c->next = compl_new();
224 c = c->next;
225 if (c == nil) {
226 compl_delete_rec(root);
227 return nil;
229 c->completion = l;
232 ++i;
235 struct completions *r = root->next;
236 compl_delete(root);
237 return r;
240 // update the given completion, that is: clean the old cs & generate a new one.
241 struct completions *update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
242 compl_delete_rec(cs);
243 cs = filter(text, lines);
244 if (first_selected && cs != nil)
245 cs->selected = true;
246 return cs;
249 // select the next, or the previous, selection and update some
250 // state. `text' will be updated with the text of the completion and
251 // `textlen' with the new lenght of `text'. If the memory cannot be
252 // allocated, `status' will be set to `ERR'.
253 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
254 // if the first is always selected, and the first entry is different
255 // from the text, expand the text and return
256 if (first_selected
257 && cs != nil
258 && cs->selected
259 && strcmp(cs->completion, *text) != 0
260 && !p) {
261 free(*text);
262 *text = strdup(cs->completion);
263 if (text == nil) {
264 fprintf(stderr, "Memory allocation error!\n");
265 *status = ERR;
266 return;
268 *textlen = strlen(*text);
269 return;
272 struct completions *n = p
273 ? compl_select_prev(cs)
274 : compl_select_next(cs);
276 if (n != nil) {
277 free(*text);
278 *text = strdup(n->completion);
279 if (text == nil) {
280 fprintf(stderr, "Memory allocation error!\n");
281 *status = ERR;
282 return;
284 *textlen = strlen(*text);
289 // push the character c at the end of the string pointed by p
290 int pushc(char **p, int maxlen, char c) {
291 int len = strnlen(*p, maxlen);
293 if (!(len < maxlen -2)) {
294 maxlen += maxlen >> 1;
295 char *newptr = realloc(*p, maxlen);
296 if (newptr == nil) { // bad!
297 return -1;
299 *p = newptr;
302 (*p)[len] = c;
303 (*p)[len+1] = '\0';
304 return maxlen;
307 // return the number of character
308 int utf8strnlen(char *s, int maxlen) {
309 int len = 0;
310 while (*s && maxlen > 0) {
311 len += (*s++ & 0xc0) != 0x80;
312 maxlen--;
314 return len;
317 // remove the last *glyph* from the *utf8* string!
318 // this is different from just setting the last byte to 0 (in some
319 // cases ofc). The actual implementation is quite inefficient because
320 // it remove the last byte until the number of glyphs doesn't change
321 void popc(char *p, int maxlen) {
322 int len = strnlen(p, maxlen);
324 if (len == 0)
325 return;
327 int ulen = utf8strnlen(p, maxlen);
328 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
329 len--;
330 p[len] = 0;
334 // If the string is surrounded by quotes (`"`) remove them and replace
335 // every `\"` in the string with `"`
336 char *normalize_str(const char *str) {
337 int len = strlen(str);
338 if (len == 0)
339 return nil;
341 char *s = calloc(len, sizeof(char));
342 check_allocation(s);
343 int p = 0;
344 while (*str) {
345 char c = *str;
346 if (*str == '\\') {
347 if (*(str + 1)) {
348 s[p] = *(str + 1);
349 p++;
350 str += 2; // skip this and the next char
351 continue;
352 } else {
353 break;
356 if (c == '"') {
357 str++; // skip only this char
358 continue;
360 s[p] = c;
361 p++;
362 str++;
364 return s;
367 // read an arbitrary long line from stdin and return a pointer to it
368 // TODO: resize the allocated memory to exactly fit the string once
369 // read?
370 char *readline(bool *eof) {
371 int maxlen = 8;
372 char *str = calloc(maxlen, sizeof(char));
373 if (str == nil) {
374 fprintf(stderr, "Cannot allocate memory!\n");
375 exit(EX_UNAVAILABLE);
378 int c;
379 while((c = getchar()) != EOF) {
380 if (c == '\n')
381 return str;
382 else
383 maxlen = pushc(&str, maxlen, c);
385 if (maxlen == -1) {
386 fprintf(stderr, "Cannot allocate memory!\n");
387 exit(EX_UNAVAILABLE);
390 *eof = true;
391 return str;
394 // read an arbitrary amount of text until an EOF and store it in
395 // lns. `items` is the capacity of lns. It may increase lns with
396 // `realloc(3)` to store more line. Return the number of lines
397 // read. The last item will always be a NULL pointer. It ignore the
398 // "null" (empty) lines
399 int readlines (char ***lns, int items) {
400 bool finished = false;
401 int n = 0;
402 char **lines = *lns;
403 while (true) {
404 lines[n] = readline(&finished);
406 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
407 free(lines[n]);
408 --n; // forget about this line
411 if (finished)
412 break;
414 ++n;
416 if (n == items - 1) {
417 items += items >>1;
418 char **l = realloc(lines, sizeof(char*) * items);
419 check_allocation(l);
420 *lns = l;
421 lines = l;
425 n++;
426 lines[n] = nil;
427 return items;
430 // Compute the dimension of the string str once rendered, return the
431 // width and save the width and the height in ret_width and ret_height
432 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
433 int height;
434 int width;
435 #ifdef USE_XFT
436 XGlyphInfo gi;
437 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
438 /* height = gi.height; */
439 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
440 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
441 height = r->font->ascent - r->font->descent;
442 width = gi.width - gi.x;
443 #else
444 XRectangle rect;
445 XmbTextExtents(*r->font, str, len, nil, &rect);
446 height = rect.height;
447 width = rect.width;
448 #endif
449 if (ret_width != nil) *ret_width = width;
450 if (ret_height != nil) *ret_height = height;
451 return width;
454 // Draw the string str
455 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
456 #ifdef USE_XFT
457 XftColor xftcolor;
458 if (tt == PROMPT) xftcolor = r->xft_prompt;
459 if (tt == COMPL) xftcolor = r->xft_completion;
460 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
462 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
463 #else
464 GC gc;
465 if (tt == PROMPT) gc = r->prompt;
466 if (tt == COMPL) gc = r->completion;
467 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
468 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
469 #endif
472 // Duplicate the string str and substitute every space with a 'n'
473 char *strdupn(char *str) {
474 int len = strlen(str);
476 if (str == nil || len == 0)
477 return nil;
479 char *dup = strdup(str);
480 if (dup == nil)
481 return nil;
483 for (int i = 0; i < len; ++i)
484 if (dup[i] == ' ')
485 dup[i] = 'n';
487 return dup;
490 // |------------------|----------------------------------------------|
491 // | 20 char text | completion | completion | completion | compl |
492 // |------------------|----------------------------------------------|
493 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
494 int prompt_width = 20; // char
496 int width, height;
497 char *ps1_dup = strdupn(r->ps1);
498 if (ps1_dup == nil)
499 return;
501 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
502 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
503 free(ps1_dup);
504 int start_at = ps1xlen;
506 start_at = text_extents("n", 1, r, nil, nil);
507 start_at = start_at * prompt_width + r->padding;
509 int texty = (height + r->height) >>1;
511 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
513 int text_len = strlen(text);
514 if (text_len > prompt_width)
515 text = text + (text_len - prompt_width);
516 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
517 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
519 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
521 while (cs != nil) {
522 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
523 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
525 int len = strlen(cs->completion);
526 int text_width = text_extents(cs->completion, len, r, nil, nil);
528 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
530 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
532 start_at += text_width + r->padding * 2;
534 if (start_at > r->width)
535 break; // don't draw completion if the space isn't enough
537 cs = cs->next;
540 XFlush(r->d);
543 // |-----------------------------------------------------------------|
544 // | prompt |
545 // |-----------------------------------------------------------------|
546 // | completion |
547 // |-----------------------------------------------------------------|
548 // | completion |
549 // |-----------------------------------------------------------------|
550 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
551 int height, width;
552 text_extents("fjpgl", 5, r, nil, &height);
553 int start_at = height + r->padding;
555 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
556 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
558 char *ps1_dup = strdupn(r->ps1);
559 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
560 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
561 free(ps1_dup);
563 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
564 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
565 start_at += r->padding;
567 while (cs != nil) {
568 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
569 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
571 int len = strlen(cs->completion);
572 text_extents(cs->completion, len, r, &width, &height);
573 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
574 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
576 start_at += height + r->padding *2;
578 if (start_at > r->height)
579 break; // don't draw completion if the space isn't enough
581 cs = cs->next;
584 XFlush(r->d);
587 void draw(struct rendering *r, char *text, struct completions *cs) {
588 if (r->horizontal_layout)
589 draw_horizontally(r, text, cs);
590 else
591 draw_vertically(r, text, cs);
594 /* Set some WM stuff */
595 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
596 Atom type;
597 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
598 XChangeProperty(
599 d,
600 w,
601 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
602 XInternAtom(d, "ATOM", false),
603 32,
604 PropModeReplace,
605 (unsigned char *)&type,
607 );
609 /* some window managers honor this properties */
610 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
611 XChangeProperty(d,
612 w,
613 XInternAtom(d, "_NET_WM_STATE", false),
614 XInternAtom(d, "ATOM", false),
615 32,
616 PropModeReplace,
617 (unsigned char *)&type,
619 );
621 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
622 XChangeProperty(d,
623 w,
624 XInternAtom(d, "_NET_WM_STATE", false),
625 XInternAtom(d, "ATOM", false),
626 32,
627 PropModeAppend,
628 (unsigned char *)&type,
630 );
632 // setting window hints
633 XClassHint *class_hint = XAllocClassHint();
634 if (class_hint == nil) {
635 fprintf(stderr, "Could not allocate memory for class hint\n");
636 exit(EX_UNAVAILABLE);
638 class_hint->res_name = resname;
639 class_hint->res_class = resclass;
640 XSetClassHint(d, w, class_hint);
641 XFree(class_hint);
643 XSizeHints *size_hint = XAllocSizeHints();
644 if (size_hint == nil) {
645 fprintf(stderr, "Could not allocate memory for size hint\n");
646 exit(EX_UNAVAILABLE);
648 size_hint->flags = PMinSize | PBaseSize;
649 size_hint->min_width = width;
650 size_hint->base_width = width;
651 size_hint->min_height = height;
652 size_hint->base_height = height;
654 XFlush(d);
657 // write the width and height of the window `w' respectively in `width'
658 // and `height'.
659 void get_wh(Display *d, Window *w, int *width, int *height) {
660 XWindowAttributes win_attr;
661 XGetWindowAttributes(d, *w, &win_attr);
662 *height = win_attr.height;
663 *width = win_attr.width;
666 // I know this may seem a little hackish BUT is the only way I managed
667 // to actually grab that goddam keyboard. Only one call to
668 // XGrabKeyboard does not always end up with the keyboard grabbed!
669 int take_keyboard(Display *d, Window w) {
670 int i;
671 for (i = 0; i < 100; i++) {
672 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
673 return 1;
674 usleep(1000);
676 return 0;
679 // release the keyboard.
680 void release_keyboard(Display *d) {
681 XUngrabKeyboard(d, CurrentTime);
684 // Given a string, try to parse it as a number or return
685 // `default_value'.
686 int parse_integer(const char *str, int default_value) {
687 errno = 0;
688 char *ep;
689 long lval = strtol(str, &ep, 10);
690 if (str[0] == '\0' || *ep != '\0') { // NaN
691 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
692 return default_value;
694 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
695 (lval > INT_MAX || lval < INT_MIN)) {
696 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
697 return default_value;
699 return lval;
702 // like parse_integer, but if the value ends with a `%' then its
703 // treated like a percentage (`max' is used to compute the percentage)
704 int parse_int_with_percentage(const char *str, int default_value, int max) {
705 int len = strlen(str);
706 if (len > 0 && str[len-1] == '%') {
707 char *cpy = strdup(str);
708 check_allocation(cpy);
709 cpy[len-1] = '\0';
710 int val = parse_integer(cpy, default_value);
711 free(cpy);
712 return val * max / 100;
714 return parse_integer(str, default_value);
717 // like parse_int_with_percentage but understands the special value
718 // "middle" that is (max - self) / 2
719 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
720 if (!strcmp(str, "middle")) {
721 return (max - self)/2;
723 return parse_int_with_percentage(str, default_value, max);
726 // Given the name of the program (argv[0]?) print a small help on stderr
727 void usage(char *prgname) {
728 fprintf(stderr, "Usage: %s [flags]\n", prgname);
729 fprintf(stderr, "\t-a: automatic mode, the first completion is "
730 "always selected;\n");
731 fprintf(stderr, "\t-h: print this help.\n");
734 // Given an event, try to understand what the user wants. If the
735 // return value is ADD_CHAR then `input' is a pointer to a string that
736 // will need to be free'ed.
737 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
738 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
739 return DEL_CHAR;
741 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
742 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
744 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
745 return CONFIRM;
747 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
748 return EXIT;
750 // try to read what the user pressed
751 int symbol = 0;
752 Status s = 0;
753 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
754 if (s == XBufferOverflow) {
755 // should not happen since there are no utf-8 characters larger
756 // than 24bits
757 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
758 return EXIT;
760 char *str = (char*)&symbol;
762 if (ev->state & ControlMask) {
763 if (!strcmp(str, "")) // C-u
764 return DEL_LINE;
765 if (!strcmp(str, "")) // C-w
766 return DEL_WORD;
767 if (!strcmp(str, "")) // C-h
768 return DEL_CHAR;
769 if (!strcmp(str, "\r")) // C-m
770 return CONFIRM;
771 if (!strcmp(str, "")) // C-p
772 return PREV_COMPL;
773 if (!strcmp(str, "")) // C-n
774 return NEXT_COMPL;
775 if (!strcmp(str, "")) // C-c
776 return EXIT;
779 *input = strdup((char*)&symbol);
780 if (*input == nil) {
781 fprintf(stderr, "Error while allocating memory for key.\n");
782 return EXIT;
785 return ADD_CHAR;
788 // clean up some resources
789 int exit_cleanup(struct rendering *r, char *ps1, char *fontname, char *text, char **lines, struct completions *cs, int status) {
790 release_keyboard(r->d);
792 #ifdef USE_XFT
793 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_prompt);
794 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion);
795 XftColorFree(r->d, DefaultVisual(r->d, 0), DefaultColormap(r->d, 0), &r->xft_completion_highlighted);
796 #endif
798 free(ps1);
799 free(fontname);
800 free(text);
802 char *l = nil;
803 char **lns = lines;
804 while ((l = *lns) != nil) {
805 free(l);
806 ++lns;
808 free(lines);
809 compl_delete(cs);
811 XDestroyWindow(r->d, r->w);
812 XCloseDisplay(r->d);
814 return status;
817 int main(int argc, char **argv) {
818 #ifdef HAVE_PLEDGE
819 // stdio & rpat: to read and write stdio/stdout
820 // unix: to connect to Xorg
821 pledge("stdio rpath unix", "");
822 #endif
824 // by default the first completion isn't selected
825 bool first_selected = false;
827 // parse the command line options
828 int ch;
829 while ((ch = getopt(argc, argv, "ahv")) != -1) {
830 switch (ch) {
831 case 'a':
832 first_selected = true;
833 break;
834 case 'h':
835 usage(*argv);
836 return 0;
837 case 'v':
838 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
839 return 0;
840 default:
841 usage(*argv);
842 return EX_USAGE;
846 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
847 readlines(&lines, INITIAL_ITEMS);
849 setlocale(LC_ALL, getenv("LANG"));
851 enum state status = LOOPING;
853 // where the monitor start (used only with xinerama)
854 int offset_x = 0;
855 int offset_y = 0;
857 // width and height of the window
858 int width = 400;
859 int height = 20;
861 // position on the screen
862 int x = 0;
863 int y = 0;
865 // the default padding
866 int padding = 10;
868 char *ps1 = strdup("$ ");
869 check_allocation(ps1);
871 char *fontname = strdup(default_fontname);
872 check_allocation(fontname);
874 int textlen = 10;
875 char *text = malloc(textlen * sizeof(char));
876 check_allocation(text);
878 /* struct completions *cs = filter(text, lines); */
879 struct completions *cs = nil;
880 cs = update_completions(cs, text, lines, first_selected);
882 // start talking to xorg
883 Display *d = XOpenDisplay(nil);
884 if (d == nil) {
885 fprintf(stderr, "Could not open display!\n");
886 return EX_UNAVAILABLE;
889 // get display size
890 // XXX: is getting the default root window dimension correct?
891 XWindowAttributes xwa;
892 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
893 int d_width = xwa.width;
894 int d_height = xwa.height;
896 #ifdef USE_XINERAMA
897 if (XineramaIsActive(d)) {
898 // find the mice
899 int number_of_screens = XScreenCount(d);
900 Window r;
901 Window root;
902 int root_x, root_y, win_x, win_y;
903 unsigned int mask;
904 bool res;
905 for (int i = 0; i < number_of_screens; ++i) {
906 root = XRootWindow(d, i);
907 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
908 if (res) break;
910 if (!res) {
911 fprintf(stderr, "No mouse found.\n");
912 root_x = 0;
913 root_y = 0;
916 // now find in which monitor the mice is on
917 int monitors;
918 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
919 if (info) {
920 for (int i = 0; i < monitors; ++i) {
921 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
922 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
923 offset_x = info[i].x_org;
924 offset_y = info[i].y_org;
925 d_width = info[i].width;
926 d_height = info[i].height;
927 break;
931 XFree(info);
933 #endif
935 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
936 XColor p_fg, p_bg,
937 compl_fg, compl_bg,
938 compl_highlighted_fg, compl_highlighted_bg;
940 bool horizontal_layout = true;
942 // read resource
943 XrmInitialize();
944 char *xrm = XResourceManagerString(d);
945 XrmDatabase xdb = nil;
946 if (xrm != nil) {
947 xdb = XrmGetStringDatabase(xrm);
948 XrmValue value;
949 char *datatype[20];
951 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
952 fontname = strdup(value.addr);
953 check_allocation(fontname);
955 else
956 fprintf(stderr, "no font defined, using %s\n", fontname);
958 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
959 char *v = strdup(value.addr);
960 check_allocation(v);
961 horizontal_layout = !strcmp(v, "horizontal");
962 free(v);
964 else
965 fprintf(stderr, "no layout defined, using horizontal\n");
967 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
968 free(ps1);
969 ps1 = normalize_str(value.addr);
970 } else
971 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
973 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
974 width = parse_int_with_percentage(value.addr, width, d_width);
975 else
976 fprintf(stderr, "no width defined, using %d\n", width);
978 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
979 height = parse_int_with_percentage(value.addr, height, d_height);
980 else
981 fprintf(stderr, "no height defined, using %d\n", height);
983 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
984 x = parse_int_with_middle(value.addr, x, d_width, width);
985 else
986 fprintf(stderr, "no x defined, using %d\n", x);
988 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
989 y = parse_int_with_middle(value.addr, y, d_height, height);
990 else
991 fprintf(stderr, "no y defined, using %d\n", y);
993 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
994 padding = parse_integer(value.addr, padding);
995 else
996 fprintf(stderr, "no y defined, using %d\n", padding);
998 XColor tmp;
999 // TODO: tmp needs to be free'd after every allocation?
1001 // prompt
1002 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1003 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1004 else
1005 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1007 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1008 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1009 else
1010 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1012 // completion
1013 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1014 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1015 else
1016 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1018 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1019 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1020 else
1021 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1023 // completion highlighted
1024 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1025 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1026 else
1027 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1029 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1030 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1031 else
1032 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1033 } else {
1034 XColor tmp;
1035 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1036 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1037 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1038 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1039 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1040 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1043 // load the font
1044 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
1045 /* if (font == nil) { */
1046 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
1047 /* font = XLoadQueryFont(d, "fixed"); */
1048 /* } */
1049 // load the font
1050 #ifdef USE_XFT
1051 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1052 #else
1053 char **missing_charset_list;
1054 int missing_charset_count;
1055 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1056 if (font == nil) {
1057 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1058 return EX_UNAVAILABLE;
1060 #endif
1062 // create the window
1063 XSetWindowAttributes attr;
1064 attr.override_redirect = true;
1066 Window w = XCreateWindow(d, // display
1067 DefaultRootWindow(d), // parent
1068 x + offset_x, y + offset_y, // x y
1069 width, height, // w h
1070 0, // border width
1071 DefaultDepth(d, DefaultScreen(d)), // depth
1072 InputOutput, // class
1073 DefaultVisual(d, DefaultScreen(d)), // visual
1074 CWOverrideRedirect, // value mask
1075 &attr);
1077 set_win_atoms_hints(d, w, width, height);
1079 // we want some events
1080 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1082 // make the window appear on the screen
1083 XMapWindow(d, w);
1085 // wait for the MapNotify event (i.e. the event "window rendered")
1086 for (;;) {
1087 XEvent e;
1088 XNextEvent(d, &e);
1089 if (e.type == MapNotify)
1090 break;
1093 // get the *real* width & height after the window was rendered
1094 get_wh(d, &w, &width, &height);
1096 // grab keyboard
1097 take_keyboard(d, w);
1099 // Create some graphics contexts
1100 XGCValues values;
1101 /* values.font = font->fid; */
1103 struct rendering r = {
1104 .d = d,
1105 .w = w,
1106 #ifdef USE_XFT
1107 .font = font,
1108 #else
1109 .font = &font,
1110 #endif
1111 .prompt = XCreateGC(d, w, 0, &values),
1112 .prompt_bg = XCreateGC(d, w, 0, &values),
1113 .completion = XCreateGC(d, w, 0, &values),
1114 .completion_bg = XCreateGC(d, w, 0, &values),
1115 .completion_highlighted = XCreateGC(d, w, 0, &values),
1116 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1117 .width = width,
1118 .height = height,
1119 .padding = padding,
1120 .horizontal_layout = horizontal_layout,
1121 .ps1 = ps1,
1122 .ps1len = strlen(ps1)
1125 #ifdef USE_XFT
1126 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1128 // prompt
1129 XRenderColor xrcolor;
1130 xrcolor.red = p_fg.red;
1131 xrcolor.green = p_fg.red;
1132 xrcolor.blue = p_fg.red;
1133 xrcolor.alpha = 65535;
1134 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1136 // completion
1137 xrcolor.red = compl_fg.red;
1138 xrcolor.green = compl_fg.green;
1139 xrcolor.blue = compl_fg.blue;
1140 xrcolor.alpha = 65535;
1141 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1143 // completion highlighted
1144 xrcolor.red = compl_highlighted_fg.red;
1145 xrcolor.green = compl_highlighted_fg.green;
1146 xrcolor.blue = compl_highlighted_fg.blue;
1147 xrcolor.alpha = 65535;
1148 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1149 #endif
1151 // load the colors in our GCs
1152 XSetForeground(d, r.prompt, p_fg.pixel);
1153 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1154 XSetForeground(d, r.completion, compl_fg.pixel);
1155 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1156 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1157 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1159 // open the X input method
1160 XIM xim = XOpenIM(d, xdb, resname, resclass);
1161 check_allocation(xim);
1163 XIMStyles *xis = nil;
1164 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1165 fprintf(stderr, "Input Styles could not be retrieved\n");
1166 return EX_UNAVAILABLE;
1169 XIMStyle bestMatchStyle = 0;
1170 for (int i = 0; i < xis->count_styles; ++i) {
1171 XIMStyle ts = xis->supported_styles[i];
1172 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1173 bestMatchStyle = ts;
1174 break;
1177 XFree(xis);
1179 if (!bestMatchStyle) {
1180 fprintf(stderr, "No matching input style could be determined\n");
1183 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1184 check_allocation(xic);
1186 // draw the window for the first time
1187 draw(&r, text, cs);
1189 // main loop
1190 while (status == LOOPING) {
1191 XEvent e;
1192 XNextEvent(d, &e);
1194 if (XFilterEvent(&e, w))
1195 continue;
1197 switch (e.type) {
1198 case KeymapNotify:
1199 XRefreshKeyboardMapping(&e.xmapping);
1200 break;
1202 case KeyPress: {
1203 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1205 char *input;
1206 switch (parse_event(d, ev, xic, &input)) {
1207 case EXIT:
1208 status = ERR;
1209 break;
1211 case CONFIRM:
1212 status = OK;
1214 // if first_selected is active and the first completion is
1215 // active be sure to 'expand' the text to match the selection
1216 if (first_selected && cs->selected) {
1217 free(text);
1218 text = strdup(cs->completion);
1219 if (text == nil) {
1220 fprintf(stderr, "Memory allocation error");
1221 status = ERR;
1223 textlen = strlen(text);
1225 break;
1227 case PREV_COMPL: {
1228 complete(cs, first_selected, true, &text, &textlen, &status);
1229 break;
1232 case NEXT_COMPL: {
1233 complete(cs, first_selected, false, &text, &textlen, &status);
1234 break;
1237 case DEL_CHAR:
1238 popc(text, textlen);
1239 cs = update_completions(cs, text, lines, first_selected);
1240 break;
1242 case DEL_WORD: {
1243 // `textlen` is the lenght of the allocated string, not the
1244 // lenght of the ACTUAL string
1245 int p = strlen(text) -1;
1246 if (p > 0) { // delete the current char
1247 text[p] = 0;
1248 p--;
1251 // erase the alphanumeric char
1252 while (p >= 0 && isalnum(text[p])) {
1253 text[p] = 0;
1254 p--;
1257 // erase also trailing white spaces
1258 while (p >= 0 && isspace(text[p])) {
1259 text[p] = 0;
1260 p--;
1262 cs = update_completions(cs, text, lines, first_selected);
1263 break;
1266 case DEL_LINE: {
1267 for (int i = 0; i < textlen; ++i)
1268 text[i] = 0;
1269 cs = update_completions(cs, text, lines, first_selected);
1270 break;
1273 case ADD_CHAR: {
1274 int str_len = strlen(input);
1275 for (int i = 0; i < str_len; ++i) {
1276 textlen = pushc(&text, textlen, input[i]);
1277 if (textlen == -1) {
1278 fprintf(stderr, "Memory allocation error\n");
1279 status = ERR;
1280 break;
1282 cs = update_completions(cs, text, lines, first_selected);
1283 free(input);
1287 break;
1292 default:
1293 fprintf(stderr, "Unknown event %d\n", e.type);
1296 draw(&r, text, cs);
1299 if (status == OK)
1300 printf("%s\n", text);
1302 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);