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 check_allocation(a) { \
54 if (a == nil) { \
55 fprintf(stderr, "Could not allocate memory\n"); \
56 abort(); \
57 } \
58 }
60 // The possible state of the event loop.
61 enum state {LOOPING, OK, ERR};
63 // for the drawing-related function. The text to be rendered could be
64 // the prompt, a completion or a highlighted completion
65 enum text_type {PROMPT, COMPL, COMPL_HIGH};
67 // These are the possible action to be performed after user input.
68 enum action {
69 EXIT,
70 CONFIRM,
71 NEXT_COMPL,
72 PREV_COMPL,
73 DEL_CHAR,
74 DEL_WORD,
75 DEL_LINE,
76 ADD_CHAR,
77 TOGGLE_FIRST_SELECTED
78 };
80 struct rendering {
81 Display *d;
82 Window w;
83 int width;
84 int height;
85 int padding;
86 bool horizontal_layout;
87 char *ps1;
88 int ps1len;
89 GC prompt;
90 GC prompt_bg;
91 GC completion;
92 GC completion_bg;
93 GC completion_highlighted;
94 GC completion_highlighted_bg;
95 #ifdef USE_XFT
96 XftFont *font;
97 XftDraw *xftdraw;
98 XftColor xft_prompt;
99 XftColor xft_completion;
100 XftColor xft_completion_highlighted;
101 #else
102 XFontSet *font;
103 #endif
104 };
106 // A simple linked list to store the completions.
107 struct completions {
108 char *completion;
109 bool selected;
110 struct completions *next;
111 };
113 // return a newly allocated (and empty) completion list
114 struct completions *compl_new() {
115 struct completions *c = malloc(sizeof(struct completions));
117 if (c == nil)
118 return c;
120 c->completion = nil;
121 c->selected = false;
122 c->next = nil;
123 return c;
126 // delete ONLY the given completion (i.e. does not free c->next...)
127 void compl_delete(struct completions *c) {
128 free(c);
131 // delete all completion
132 void compl_delete_rec(struct completions *c) {
133 while (c != nil) {
134 struct completions *t = c->next;
135 free(c);
136 c = t;
140 // given a completion list, select the next completion and return the
141 // element that is selected
142 struct completions *compl_select_next(struct completions *c) {
143 if (c == nil)
144 return nil;
146 struct completions *orig = c;
147 while (c != nil) {
148 if (c->selected) {
149 c->selected = false;
150 if (c->next != nil) {
151 // the current one is selected and the next one exists
152 c->next->selected = true;
153 return c->next;
154 } else {
155 // the current one is selected and the next one is nil,
156 // select the first one
157 orig->selected = true;
158 return orig;
161 c = c->next;
164 orig->selected = true;
165 return orig;
168 // given a completion list, select the previous and return the element
169 // that is selected
170 struct completions *compl_select_prev(struct completions *c) {
171 if (c == nil)
172 return nil;
174 struct completions *last = nil;
176 if (c->selected) { // if the first is selected, select the last one
177 c->selected = false;
178 while (c != nil) {
179 if (c->next == nil) {
180 c->selected = true;
181 return c;
183 c = c->next;
187 // if the selected one is inside the list, select the previous one
188 while (c != nil) {
189 if (c->next == nil) { // if c is the last, save it for later
190 last = c;
193 if (c->next && c->next->selected) {
194 c->selected = true;
195 c->next->selected = false;
196 return c;
198 c = c->next;
201 // if nothing were selected, select the last one
202 if (c != nil)
203 c->selected = true;
204 return c;
207 // create a completion list from a text and the list of possible completions
208 struct completions *filter(char *text, char **lines) {
209 int i = 0;
210 struct completions *root = compl_new();
211 struct completions *c = root;
212 if (c == nil)
213 return nil;
215 for (;;) {
216 char *l = lines[i];
217 if (l == nil)
218 break;
220 if (strcasestr(l, text) != nil) {
221 c->next = compl_new();
222 c = c->next;
223 if (c == nil) {
224 compl_delete_rec(root);
225 return nil;
227 c->completion = l;
230 ++i;
233 struct completions *r = root->next;
234 compl_delete(root);
235 return r;
238 // update the given completion, that is: clean the old cs & generate a new one.
239 struct completions *update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
240 compl_delete_rec(cs);
241 cs = filter(text, lines);
242 if (first_selected && cs != nil)
243 cs->selected = true;
244 return cs;
247 // select the next, or the previous, selection and update some
248 // state. `text' will be updated with the text of the completion and
249 // `textlen' with the new lenght of `text'. If the memory cannot be
250 // allocated, `status' will be set to `ERR'.
251 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
252 // if the first is always selected, and the first entry is different
253 // from the text, expand the text and return
254 if (first_selected
255 && cs != nil
256 && cs->selected
257 && strcmp(cs->completion, *text) != 0
258 && !p) {
259 free(*text);
260 *text = strdup(cs->completion);
261 if (text == nil) {
262 fprintf(stderr, "Memory allocation error!\n");
263 *status = ERR;
264 return;
266 *textlen = strlen(*text);
267 return;
270 struct completions *n = p
271 ? compl_select_prev(cs)
272 : compl_select_next(cs);
274 if (n != nil) {
275 free(*text);
276 *text = strdup(n->completion);
277 if (text == nil) {
278 fprintf(stderr, "Memory allocation error!\n");
279 *status = ERR;
280 return;
282 *textlen = strlen(*text);
287 // push the character c at the end of the string pointed by p
288 int pushc(char **p, int maxlen, char c) {
289 int len = strnlen(*p, maxlen);
291 if (!(len < maxlen -2)) {
292 maxlen += maxlen >> 1;
293 char *newptr = realloc(*p, maxlen);
294 if (newptr == nil) { // bad!
295 return -1;
297 *p = newptr;
300 (*p)[len] = c;
301 (*p)[len+1] = '\0';
302 return maxlen;
305 // return the number of character
306 int utf8strnlen(char *s, int maxlen) {
307 int len = 0;
308 while (*s && maxlen > 0) {
309 len += (*s++ & 0xc0) != 0x80;
310 maxlen--;
312 return len;
315 // remove the last *glyph* from the *utf8* string!
316 // this is different from just setting the last byte to 0 (in some
317 // cases ofc). The actual implementation is quite inefficient because
318 // it remove the last byte until the number of glyphs doesn't change
319 void popc(char *p, int maxlen) {
320 int len = strnlen(p, maxlen);
322 if (len == 0)
323 return;
325 int ulen = utf8strnlen(p, maxlen);
326 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
327 len--;
328 p[len] = 0;
332 // If the string is surrounded by quotes (`"`) remove them and replace
333 // every `\"` in the string with `"`
334 char *normalize_str(const char *str) {
335 int len = strlen(str);
336 if (len == 0)
337 return nil;
339 char *s = calloc(len, sizeof(char));
340 check_allocation(s);
341 int p = 0;
342 while (*str) {
343 char c = *str;
344 if (*str == '\\') {
345 if (*(str + 1)) {
346 s[p] = *(str + 1);
347 p++;
348 str += 2; // skip this and the next char
349 continue;
350 } else {
351 break;
354 if (c == '"') {
355 str++; // skip only this char
356 continue;
358 s[p] = c;
359 p++;
360 str++;
362 return s;
365 // read an arbitrary long line from stdin and return a pointer to it
366 // TODO: resize the allocated memory to exactly fit the string once
367 // read?
368 char *readline(bool *eof) {
369 int maxlen = 8;
370 char *str = calloc(maxlen, sizeof(char));
371 if (str == nil) {
372 fprintf(stderr, "Cannot allocate memory!\n");
373 exit(EX_UNAVAILABLE);
376 int c;
377 while((c = getchar()) != EOF) {
378 if (c == '\n')
379 return str;
380 else
381 maxlen = pushc(&str, maxlen, c);
383 if (maxlen == -1) {
384 fprintf(stderr, "Cannot allocate memory!\n");
385 exit(EX_UNAVAILABLE);
388 *eof = true;
389 return str;
392 // read an arbitrary amount of text until an EOF and store it in
393 // lns. `items` is the capacity of lns. It may increase lns with
394 // `realloc(3)` to store more line. Return the number of lines
395 // read. The last item will always be a NULL pointer. It ignore the
396 // "null" (empty) lines
397 int readlines (char ***lns, int items) {
398 bool finished = false;
399 int n = 0;
400 char **lines = *lns;
401 while (true) {
402 lines[n] = readline(&finished);
404 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
405 free(lines[n]);
406 --n; // forget about this line
409 if (finished)
410 break;
412 ++n;
414 if (n == items - 1) {
415 items += items >>1;
416 char **l = realloc(lines, sizeof(char*) * items);
417 check_allocation(l);
418 *lns = l;
419 lines = l;
423 n++;
424 lines[n] = nil;
425 return items;
428 // Compute the dimension of the string str once rendered, return the
429 // width and save the width and the height in ret_width and ret_height
430 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
431 int height;
432 int width;
433 #ifdef USE_XFT
434 XGlyphInfo gi;
435 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
436 /* height = gi.height; */
437 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
438 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
439 height = r->font->ascent - r->font->descent;
440 width = gi.width - gi.x;
441 #else
442 XRectangle rect;
443 XmbTextExtents(*r->font, str, len, nil, &rect);
444 height = rect.height;
445 width = rect.width;
446 #endif
447 if (ret_width != nil) *ret_width = width;
448 if (ret_height != nil) *ret_height = height;
449 return width;
452 // Draw the string str
453 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
454 #ifdef USE_XFT
455 XftColor xftcolor;
456 if (tt == PROMPT) xftcolor = r->xft_prompt;
457 if (tt == COMPL) xftcolor = r->xft_completion;
458 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
460 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
461 #else
462 GC gc;
463 if (tt == PROMPT) gc = r->prompt;
464 if (tt == COMPL) gc = r->completion;
465 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
466 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
467 #endif
470 // Duplicate the string str and substitute every space with a 'n'
471 char *strdupn(char *str) {
472 int len = strlen(str);
474 if (str == nil || len == 0)
475 return nil;
477 char *dup = strdup(str);
478 if (dup == nil)
479 return nil;
481 for (int i = 0; i < len; ++i)
482 if (dup[i] == ' ')
483 dup[i] = 'n';
485 return dup;
488 // |------------------|----------------------------------------------|
489 // | 20 char text | completion | completion | completion | compl |
490 // |------------------|----------------------------------------------|
491 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
492 int prompt_width = 20; // char
494 int width, height;
495 char *ps1_dup = strdupn(r->ps1);
496 if (ps1_dup == nil)
497 return;
499 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
500 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
501 free(ps1_dup);
502 int start_at = ps1xlen;
504 start_at = text_extents("n", 1, r, nil, nil);
505 start_at = start_at * prompt_width + r->padding;
507 int texty = (height + r->height) >>1;
509 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
511 int text_len = strlen(text);
512 if (text_len > prompt_width)
513 text = text + (text_len - prompt_width);
514 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
515 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
517 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
519 while (cs != nil) {
520 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
521 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
523 int len = strlen(cs->completion);
524 int text_width = text_extents(cs->completion, len, r, nil, nil);
526 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
528 draw_string(cs->completion, len, start_at + r->padding, texty, r, tt);
530 start_at += text_width + r->padding * 2;
532 if (start_at > r->width)
533 break; // don't draw completion if the space isn't enough
535 cs = cs->next;
538 XFlush(r->d);
541 // |-----------------------------------------------------------------|
542 // | prompt |
543 // |-----------------------------------------------------------------|
544 // | completion |
545 // |-----------------------------------------------------------------|
546 // | completion |
547 // |-----------------------------------------------------------------|
548 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
549 int height, width;
550 text_extents("fjpgl", 5, r, nil, &height);
551 int start_at = height + r->padding;
553 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
554 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
556 char *ps1_dup = strdupn(r->ps1);
557 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
558 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
559 free(ps1_dup);
561 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
562 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
563 start_at += r->padding;
565 while (cs != nil) {
566 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
567 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
569 int len = strlen(cs->completion);
570 text_extents(cs->completion, len, r, &width, &height);
571 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
572 draw_string(cs->completion, len, r->padding, start_at + height + r->padding, r, tt);
574 start_at += height + r->padding *2;
576 if (start_at > r->height)
577 break; // don't draw completion if the space isn't enough
579 cs = cs->next;
582 XFlush(r->d);
585 void draw(struct rendering *r, char *text, struct completions *cs) {
586 if (r->horizontal_layout)
587 draw_horizontally(r, text, cs);
588 else
589 draw_vertically(r, text, cs);
592 /* Set some WM stuff */
593 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
594 Atom type;
595 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
596 XChangeProperty(
597 d,
598 w,
599 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
600 XInternAtom(d, "ATOM", false),
601 32,
602 PropModeReplace,
603 (unsigned char *)&type,
605 );
607 /* some window managers honor this properties */
608 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
609 XChangeProperty(d,
610 w,
611 XInternAtom(d, "_NET_WM_STATE", false),
612 XInternAtom(d, "ATOM", false),
613 32,
614 PropModeReplace,
615 (unsigned char *)&type,
617 );
619 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
620 XChangeProperty(d,
621 w,
622 XInternAtom(d, "_NET_WM_STATE", false),
623 XInternAtom(d, "ATOM", false),
624 32,
625 PropModeAppend,
626 (unsigned char *)&type,
628 );
630 // setting window hints
631 XClassHint *class_hint = XAllocClassHint();
632 if (class_hint == nil) {
633 fprintf(stderr, "Could not allocate memory for class hint\n");
634 exit(EX_UNAVAILABLE);
636 class_hint->res_name = resname;
637 class_hint->res_class = resclass;
638 XSetClassHint(d, w, class_hint);
639 XFree(class_hint);
641 XSizeHints *size_hint = XAllocSizeHints();
642 if (size_hint == nil) {
643 fprintf(stderr, "Could not allocate memory for size hint\n");
644 exit(EX_UNAVAILABLE);
646 size_hint->flags = PMinSize | PBaseSize;
647 size_hint->min_width = width;
648 size_hint->base_width = width;
649 size_hint->min_height = height;
650 size_hint->base_height = height;
652 XFlush(d);
655 // write the width and height of the window `w' respectively in `width'
656 // and `height'.
657 void get_wh(Display *d, Window *w, int *width, int *height) {
658 XWindowAttributes win_attr;
659 XGetWindowAttributes(d, *w, &win_attr);
660 *height = win_attr.height;
661 *width = win_attr.width;
664 // I know this may seem a little hackish BUT is the only way I managed
665 // to actually grab that goddam keyboard. Only one call to
666 // XGrabKeyboard does not always end up with the keyboard grabbed!
667 int take_keyboard(Display *d, Window w) {
668 int i;
669 for (i = 0; i < 100; i++) {
670 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
671 return 1;
672 usleep(1000);
674 return 0;
677 // release the keyboard.
678 void release_keyboard(Display *d) {
679 XUngrabKeyboard(d, CurrentTime);
682 // Given a string, try to parse it as a number or return
683 // `default_value'.
684 int parse_integer(const char *str, int default_value) {
685 errno = 0;
686 char *ep;
687 long lval = strtol(str, &ep, 10);
688 if (str[0] == '\0' || *ep != '\0') { // NaN
689 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
690 return default_value;
692 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
693 (lval > INT_MAX || lval < INT_MIN)) {
694 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
695 return default_value;
697 return lval;
700 // like parse_integer, but if the value ends with a `%' then its
701 // treated like a percentage (`max' is used to compute the percentage)
702 int parse_int_with_percentage(const char *str, int default_value, int max) {
703 int len = strlen(str);
704 if (len > 0 && str[len-1] == '%') {
705 char *cpy = strdup(str);
706 check_allocation(cpy);
707 cpy[len-1] = '\0';
708 int val = parse_integer(cpy, default_value);
709 free(cpy);
710 return val * max / 100;
712 return parse_integer(str, default_value);
715 // like parse_int_with_percentage but understands the special value
716 // "middle" that is (max - self) / 2
717 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
718 if (!strcmp(str, "middle")) {
719 return (max - self)/2;
721 return parse_int_with_percentage(str, default_value, max);
724 // Given the name of the program (argv[0]?) print a small help on stderr
725 void usage(char *prgname) {
726 fprintf(stderr, "Usage: %s [flags]\n", prgname);
727 fprintf(stderr, "\t-a: automatic mode, the first completion is "
728 "always selected;\n");
729 fprintf(stderr, "\t-h: print this help.\n");
732 // Given an event, try to understand what the user wants. If the
733 // return value is ADD_CHAR then `input' is a pointer to a string that
734 // will need to be free'ed.
735 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
736 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
737 return DEL_CHAR;
739 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
740 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
742 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
743 return CONFIRM;
745 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
746 return EXIT;
748 // try to read what the user pressed
749 int symbol = 0;
750 Status s = 0;
751 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
752 if (s == XBufferOverflow) {
753 // should not happen since there are no utf-8 characters larger
754 // than 24bits
755 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
756 return EXIT;
758 char *str = (char*)&symbol;
760 if (ev->state & ControlMask) {
761 if (!strcmp(str, "")) // C-u
762 return DEL_LINE;
763 if (!strcmp(str, "")) // C-w
764 return DEL_WORD;
765 if (!strcmp(str, "")) // C-h
766 return DEL_CHAR;
767 if (!strcmp(str, "\r")) // C-m
768 return CONFIRM;
769 if (!strcmp(str, "")) // C-p
770 return PREV_COMPL;
771 if (!strcmp(str, "")) // C-n
772 return NEXT_COMPL;
773 if (!strcmp(str, "")) // C-c
774 return EXIT;
775 if (!strcmp(str, "\t")) // C-i
776 return TOGGLE_FIRST_SELECTED;
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 padding 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 #ifdef USE_XFT
1045 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1046 #else
1047 char **missing_charset_list;
1048 int missing_charset_count;
1049 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1050 if (font == nil) {
1051 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1052 return EX_UNAVAILABLE;
1054 #endif
1056 // create the window
1057 XSetWindowAttributes attr;
1058 attr.override_redirect = true;
1060 Window w = XCreateWindow(d, // display
1061 DefaultRootWindow(d), // parent
1062 x + offset_x, y + offset_y, // x y
1063 width, height, // w h
1064 0, // border width
1065 DefaultDepth(d, DefaultScreen(d)), // depth
1066 InputOutput, // class
1067 DefaultVisual(d, DefaultScreen(d)), // visual
1068 CWOverrideRedirect, // value mask
1069 &attr);
1071 set_win_atoms_hints(d, w, width, height);
1073 // we want some events
1074 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1076 // make the window appear on the screen
1077 XMapWindow(d, w);
1079 // wait for the MapNotify event (i.e. the event "window rendered")
1080 for (;;) {
1081 XEvent e;
1082 XNextEvent(d, &e);
1083 if (e.type == MapNotify)
1084 break;
1087 // get the *real* width & height after the window was rendered
1088 get_wh(d, &w, &width, &height);
1090 // grab keyboard
1091 take_keyboard(d, w);
1093 // Create some graphics contexts
1094 XGCValues values;
1095 /* values.font = font->fid; */
1097 struct rendering r = {
1098 .d = d,
1099 .w = w,
1100 #ifdef USE_XFT
1101 .font = font,
1102 #else
1103 .font = &font,
1104 #endif
1105 .prompt = XCreateGC(d, w, 0, &values),
1106 .prompt_bg = XCreateGC(d, w, 0, &values),
1107 .completion = XCreateGC(d, w, 0, &values),
1108 .completion_bg = XCreateGC(d, w, 0, &values),
1109 .completion_highlighted = XCreateGC(d, w, 0, &values),
1110 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1111 .width = width,
1112 .height = height,
1113 .padding = padding,
1114 .horizontal_layout = horizontal_layout,
1115 .ps1 = ps1,
1116 .ps1len = strlen(ps1)
1119 #ifdef USE_XFT
1120 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1122 // prompt
1123 XRenderColor xrcolor;
1124 xrcolor.red = p_fg.red;
1125 xrcolor.green = p_fg.red;
1126 xrcolor.blue = p_fg.red;
1127 xrcolor.alpha = 65535;
1128 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1130 // completion
1131 xrcolor.red = compl_fg.red;
1132 xrcolor.green = compl_fg.green;
1133 xrcolor.blue = compl_fg.blue;
1134 xrcolor.alpha = 65535;
1135 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1137 // completion highlighted
1138 xrcolor.red = compl_highlighted_fg.red;
1139 xrcolor.green = compl_highlighted_fg.green;
1140 xrcolor.blue = compl_highlighted_fg.blue;
1141 xrcolor.alpha = 65535;
1142 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1143 #endif
1145 // load the colors in our GCs
1146 XSetForeground(d, r.prompt, p_fg.pixel);
1147 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1148 XSetForeground(d, r.completion, compl_fg.pixel);
1149 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1150 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1151 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1153 // open the X input method
1154 XIM xim = XOpenIM(d, xdb, resname, resclass);
1155 check_allocation(xim);
1157 XIMStyles *xis = nil;
1158 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1159 fprintf(stderr, "Input Styles could not be retrieved\n");
1160 return EX_UNAVAILABLE;
1163 XIMStyle bestMatchStyle = 0;
1164 for (int i = 0; i < xis->count_styles; ++i) {
1165 XIMStyle ts = xis->supported_styles[i];
1166 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1167 bestMatchStyle = ts;
1168 break;
1171 XFree(xis);
1173 if (!bestMatchStyle) {
1174 fprintf(stderr, "No matching input style could be determined\n");
1177 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1178 check_allocation(xic);
1180 // draw the window for the first time
1181 draw(&r, text, cs);
1183 // main loop
1184 while (status == LOOPING) {
1185 XEvent e;
1186 XNextEvent(d, &e);
1188 if (XFilterEvent(&e, w))
1189 continue;
1191 switch (e.type) {
1192 case KeymapNotify:
1193 XRefreshKeyboardMapping(&e.xmapping);
1194 break;
1196 case KeyPress: {
1197 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1199 char *input;
1200 switch (parse_event(d, ev, xic, &input)) {
1201 case EXIT:
1202 status = ERR;
1203 break;
1205 case CONFIRM:
1206 status = OK;
1208 // if first_selected is active and the first completion is
1209 // active be sure to 'expand' the text to match the selection
1210 if (first_selected && cs && cs->selected) {
1211 free(text);
1212 text = strdup(cs->completion);
1213 if (text == nil) {
1214 fprintf(stderr, "Memory allocation error");
1215 status = ERR;
1217 textlen = strlen(text);
1219 break;
1221 case PREV_COMPL: {
1222 complete(cs, first_selected, true, &text, &textlen, &status);
1223 break;
1226 case NEXT_COMPL: {
1227 complete(cs, first_selected, false, &text, &textlen, &status);
1228 break;
1231 case DEL_CHAR:
1232 popc(text, textlen);
1233 cs = update_completions(cs, text, lines, first_selected);
1234 break;
1236 case DEL_WORD: {
1237 // `textlen` is the lenght of the allocated string, not the
1238 // lenght of the ACTUAL string
1239 int p = strlen(text) -1;
1240 if (p > 0) { // delete the current char
1241 text[p] = 0;
1242 p--;
1245 // erase the alphanumeric char
1246 while (p >= 0 && isalnum(text[p])) {
1247 text[p] = 0;
1248 p--;
1251 // erase also trailing white spaces
1252 while (p >= 0 && isspace(text[p])) {
1253 text[p] = 0;
1254 p--;
1256 cs = update_completions(cs, text, lines, first_selected);
1257 break;
1260 case DEL_LINE: {
1261 for (int i = 0; i < textlen; ++i)
1262 text[i] = 0;
1263 cs = update_completions(cs, text, lines, first_selected);
1264 break;
1267 case ADD_CHAR: {
1268 int str_len = strlen(input);
1269 for (int i = 0; i < str_len; ++i) {
1270 textlen = pushc(&text, textlen, input[i]);
1271 if (textlen == -1) {
1272 fprintf(stderr, "Memory allocation error\n");
1273 status = ERR;
1274 break;
1276 cs = update_completions(cs, text, lines, first_selected);
1277 free(input);
1279 break;
1282 case TOGGLE_FIRST_SELECTED:
1283 first_selected = !first_selected;
1284 if (cs)
1285 cs->selected = !cs->selected;
1286 break;
1290 default:
1291 fprintf(stderr, "Unknown event %d\n", e.type);
1294 draw(&r, text, cs);
1297 if (status == OK)
1298 printf("%s\n", text);
1300 return exit_cleanup(&r, ps1, fontname, text, lines, cs, status == OK ? 0 : 1);