Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #ifndef VERSION
27 # define VERSION "unknown"
28 #endif
30 // Comfy
31 #define nil NULL
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
38 #ifdef USE_XFT
39 # define default_fontname "monospace"
40 #else
41 # define default_fontname "fixed"
42 #endif
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
47 // modulo operator
48 #define mod(a, b) (a < 0 ? (a % b + b) : (a % b))
50 // If we don't have it or we don't want an "ignore case" completion
51 // style, fall back to `strstr(3)`
52 #ifndef USE_STRCASESTR
53 # define strcasestr strstr
54 #endif
56 #define INITIAL_ITEMS 64
58 #define check_allocation(a) { \
59 if (a == nil) { \
60 fprintf(stderr, "Could not allocate memory\n"); \
61 abort(); \
62 } \
63 }
65 // The possible state of the event loop.
66 enum state {LOOPING, OK, ERR};
68 // for the drawing-related function. The text to be rendered could be
69 // the prompt, a completion or a highlighted completion
70 enum text_type {PROMPT, COMPL, COMPL_HIGH};
72 // These are the possible action to be performed after user input.
73 enum action {
74 EXIT,
75 CONFIRM,
76 NEXT_COMPL,
77 PREV_COMPL,
78 DEL_CHAR,
79 DEL_WORD,
80 DEL_LINE,
81 ADD_CHAR,
82 TOGGLE_FIRST_SELECTED
83 };
85 struct rendering {
86 Display *d;
87 Window w;
88 int width;
89 int height;
90 int padding;
91 bool horizontal_layout;
92 char *ps1;
93 int ps1len;
94 GC prompt;
95 GC prompt_bg;
96 GC completion;
97 GC completion_bg;
98 GC completion_highlighted;
99 GC completion_highlighted_bg;
100 #ifdef USE_XFT
101 XftFont *font;
102 XftDraw *xftdraw;
103 XftColor xft_prompt;
104 XftColor xft_completion;
105 XftColor xft_completion_highlighted;
106 #else
107 XFontSet *font;
108 #endif
109 };
111 // A simple linked list to store the completions.
112 struct completion {
113 char *completion;
114 struct completion *next;
115 };
117 struct completions {
118 struct completion *completions;
119 int selected;
120 int lenght;
121 };
123 // return a newly allocated (and empty) completion list
124 struct completions *compls_new() {
125 struct completions *cs = malloc(sizeof(struct completions));
127 if (cs == nil)
128 return cs;
130 cs->completions = nil;
131 cs->selected = -1;
132 cs->lenght = 0;
133 return cs;
136 struct completion *compl_new() {
137 struct completion *c = malloc(sizeof(struct completion));
138 if (c == nil)
139 return c;
141 c->completion = nil;
142 c->next = nil;
143 return c;
146 // delete ONLY the given completion (i.e. does not free c->next...)
147 void compl_delete(struct completion *c) {
148 free(c);
151 // delete the current completion and the next (c->next) and so on...
152 void compl_delete_rec(struct completion *c) {
153 while (c != nil) {
154 struct completion *t = c->next;
155 free(c);
156 c = t;
160 void compls_delete(struct completions *cs) {
161 if (cs == nil)
162 return;
164 compl_delete_rec(cs->completions);
165 free(cs);
168 // create a completion list from a text and the list of possible
169 // completions (null terminated). Expects a non-null `cs'.
170 void filter(struct completions *cs, char *text, char **lines) {
171 struct completion *c = compl_new();
172 if (c == nil) {
173 return;
176 cs->completions = c;
178 int index = 0;
179 int matching = 0;
181 while (true) {
182 char *l = lines[index];
183 if (l == nil)
184 break;
186 if (strcasestr(l, text) != nil) {
187 matching++;
189 c->next = compl_new();
190 c = c->next;
191 if (c == nil) {
192 compls_delete(cs);
193 return;
195 c->completion = l;
198 index++;
201 struct completion *f = cs->completions->next;
202 compl_delete(cs->completions);
203 cs->completions = f;
204 cs->lenght = matching;
205 cs->selected = -1;
208 // update the given completion, that is: clean the old cs & generate a new one.
209 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
210 compl_delete_rec(cs->completions);
211 filter(cs, text, lines);
212 if (first_selected && cs->lenght > 0)
213 cs->selected = 0;
216 // select the next, or the previous, selection and update some
217 // state. `text' will be updated with the text of the completion and
218 // `textlen' with the new lenght of `text'. If the memory cannot be
219 // allocated, `status' will be set to `ERR'.
220 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
221 if (cs == nil || cs->lenght == 0)
222 return;
224 // if the first is always selected, and the first entry is different
225 // from the text, expand the text and return
226 if (first_selected
227 && cs->selected == 0
228 && strcmp(cs->completions->completion, *text) != 0
229 && !p) {
230 free(*text);
231 *text = strdup(cs->completions->completion);
232 if (text == nil) {
233 *status = ERR;
234 return;
236 *textlen = strlen(*text);
237 return;
240 int index = cs->selected;
242 if (index == -1 && p)
243 index = 0;
244 index = cs->selected = mod((p ? index - 1 : index + 1), cs->lenght);
246 struct completion *n = cs->completions;
248 // find the selected item
249 while (index != 0) {
250 index--;
251 n = n->next;
254 free(*text);
255 *text = strdup(n->completion);
256 if (text == nil) {
257 fprintf(stderr, "Memory allocation error!\n");
258 *status = ERR;
259 return;
261 *textlen = strlen(*text);
264 // push the character c at the end of the string pointed by p
265 int pushc(char **p, int maxlen, char c) {
266 int len = strnlen(*p, maxlen);
268 if (!(len < maxlen -2)) {
269 maxlen += maxlen >> 1;
270 char *newptr = realloc(*p, maxlen);
271 if (newptr == nil) { // bad!
272 return -1;
274 *p = newptr;
277 (*p)[len] = c;
278 (*p)[len+1] = '\0';
279 return maxlen;
282 // return the number of character
283 int utf8strnlen(char *s, int maxlen) {
284 int len = 0;
285 while (*s && maxlen > 0) {
286 len += (*s++ & 0xc0) != 0x80;
287 maxlen--;
289 return len;
292 // remove the last *glyph* from the *utf8* string!
293 // this is different from just setting the last byte to 0 (in some
294 // cases ofc). The actual implementation is quite inefficient because
295 // it remove the last byte until the number of glyphs doesn't change
296 void popc(char *p, int maxlen) {
297 int len = strnlen(p, maxlen);
299 if (len == 0)
300 return;
302 int ulen = utf8strnlen(p, maxlen);
303 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
304 len--;
305 p[len] = 0;
309 // If the string is surrounded by quotes (`"`) remove them and replace
310 // every `\"` in the string with `"`
311 char *normalize_str(const char *str) {
312 int len = strlen(str);
313 if (len == 0)
314 return nil;
316 char *s = calloc(len, sizeof(char));
317 check_allocation(s);
318 int p = 0;
319 while (*str) {
320 char c = *str;
321 if (*str == '\\') {
322 if (*(str + 1)) {
323 s[p] = *(str + 1);
324 p++;
325 str += 2; // skip this and the next char
326 continue;
327 } else {
328 break;
331 if (c == '"') {
332 str++; // skip only this char
333 continue;
335 s[p] = c;
336 p++;
337 str++;
339 return s;
342 // read an arbitrary long line from stdin and return a pointer to it
343 // TODO: resize the allocated memory to exactly fit the string once
344 // read?
345 char *readline(bool *eof) {
346 int maxlen = 8;
347 char *str = calloc(maxlen, sizeof(char));
348 if (str == nil) {
349 fprintf(stderr, "Cannot allocate memory!\n");
350 exit(EX_UNAVAILABLE);
353 int c;
354 while((c = getchar()) != EOF) {
355 if (c == '\n')
356 return str;
357 else
358 maxlen = pushc(&str, maxlen, c);
360 if (maxlen == -1) {
361 fprintf(stderr, "Cannot allocate memory!\n");
362 exit(EX_UNAVAILABLE);
365 *eof = true;
366 return str;
369 // read an arbitrary amount of text until an EOF and store it in
370 // lns. `items` is the capacity of lns. It may increase lns with
371 // `realloc(3)` to store more line. Return the number of lines
372 // read. The last item will always be a NULL pointer. It ignore the
373 // "null" (empty) lines
374 int readlines (char ***lns, int items) {
375 bool finished = false;
376 int n = 0;
377 char **lines = *lns;
378 while (true) {
379 lines[n] = readline(&finished);
381 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
382 free(lines[n]);
383 --n; // forget about this line
386 if (finished)
387 break;
389 ++n;
391 if (n == items - 1) {
392 items += items >>1;
393 char **l = realloc(lines, sizeof(char*) * items);
394 check_allocation(l);
395 *lns = l;
396 lines = l;
400 n++;
401 lines[n] = nil;
402 return items;
405 // Compute the dimension of the string str once rendered, return the
406 // width and save the width and the height in ret_width and ret_height
407 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
408 int height;
409 int width;
410 #ifdef USE_XFT
411 XGlyphInfo gi;
412 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
413 /* height = gi.height; */
414 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
415 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
416 height = r->font->ascent - r->font->descent;
417 width = gi.width - gi.x;
418 #else
419 XRectangle rect;
420 XmbTextExtents(*r->font, str, len, nil, &rect);
421 height = rect.height;
422 width = rect.width;
423 #endif
424 if (ret_width != nil) *ret_width = width;
425 if (ret_height != nil) *ret_height = height;
426 return width;
429 // Draw the string str
430 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
431 #ifdef USE_XFT
432 XftColor xftcolor;
433 if (tt == PROMPT) xftcolor = r->xft_prompt;
434 if (tt == COMPL) xftcolor = r->xft_completion;
435 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
437 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
438 #else
439 GC gc;
440 if (tt == PROMPT) gc = r->prompt;
441 if (tt == COMPL) gc = r->completion;
442 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
443 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
444 #endif
447 // Duplicate the string str and substitute every space with a 'n'
448 char *strdupn(char *str) {
449 int len = strlen(str);
451 if (str == nil || len == 0)
452 return nil;
454 char *dup = strdup(str);
455 if (dup == nil)
456 return nil;
458 for (int i = 0; i < len; ++i)
459 if (dup[i] == ' ')
460 dup[i] = 'n';
462 return dup;
465 // |------------------|----------------------------------------------|
466 // | 20 char text | completion | completion | completion | compl |
467 // |------------------|----------------------------------------------|
468 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
469 int prompt_width = 20; // char
471 int width, height;
472 char *ps1_dup = strdupn(r->ps1);
473 if (ps1_dup == nil)
474 return;
476 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
477 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
478 free(ps1_dup);
479 int start_at = ps1xlen;
481 start_at = text_extents("n", 1, r, nil, nil);
482 start_at = start_at * prompt_width + r->padding;
484 int texty = (height + r->height) >>1;
486 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
488 int text_len = strlen(text);
489 if (text_len > prompt_width)
490 text = text + (text_len - prompt_width);
491 draw_string(r->ps1, r->ps1len, r->padding, texty, r, PROMPT);
492 draw_string(text, MIN(text_len, prompt_width), r->padding + ps1xlen, texty, r, PROMPT);
494 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
496 struct completion *c = cs->completions;
497 for (int i = 0; c != nil; ++i) {
498 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
499 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
501 int len = strlen(c->completion);
502 int text_width = text_extents(c->completion, len, r, nil, nil);
504 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + r->padding*2, r->height);
506 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
508 start_at += text_width + r->padding * 2;
510 if (start_at > r->width)
511 break; // don't draw completion if the space isn't enough
513 c = c->next;
516 XFlush(r->d);
519 // |-----------------------------------------------------------------|
520 // | prompt |
521 // |-----------------------------------------------------------------|
522 // | completion |
523 // |-----------------------------------------------------------------|
524 // | completion |
525 // |-----------------------------------------------------------------|
526 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
527 int height, width;
528 text_extents("fjpgl", 5, r, nil, &height);
529 int start_at = height + r->padding;
531 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
532 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
534 char *ps1_dup = strdupn(r->ps1);
535 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
536 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
537 free(ps1_dup);
539 draw_string(r->ps1, r->ps1len, r->padding, height + r->padding, r, PROMPT);
540 draw_string(text, strlen(text), r->padding + ps1xlen, height + r->padding, r, PROMPT);
541 start_at += r->padding;
543 struct completion *c = cs->completions;
544 for (int i = 0; c != nil; ++i){
545 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
546 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
548 int len = strlen(c->completion);
549 text_extents(c->completion, len, r, &width, &height);
550 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + r->padding*2);
551 draw_string(c->completion, len, r->padding, start_at + height + r->padding, r, tt);
553 start_at += height + r->padding *2;
555 if (start_at > r->height)
556 break; // don't draw completion if the space isn't enough
558 c = c->next;
561 XFlush(r->d);
564 void draw(struct rendering *r, char *text, struct completions *cs) {
565 if (r->horizontal_layout)
566 draw_horizontally(r, text, cs);
567 else
568 draw_vertically(r, text, cs);
571 /* Set some WM stuff */
572 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
573 Atom type;
574 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
575 XChangeProperty(
576 d,
577 w,
578 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
579 XInternAtom(d, "ATOM", false),
580 32,
581 PropModeReplace,
582 (unsigned char *)&type,
584 );
586 /* some window managers honor this properties */
587 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
588 XChangeProperty(d,
589 w,
590 XInternAtom(d, "_NET_WM_STATE", false),
591 XInternAtom(d, "ATOM", false),
592 32,
593 PropModeReplace,
594 (unsigned char *)&type,
596 );
598 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
599 XChangeProperty(d,
600 w,
601 XInternAtom(d, "_NET_WM_STATE", false),
602 XInternAtom(d, "ATOM", false),
603 32,
604 PropModeAppend,
605 (unsigned char *)&type,
607 );
609 // setting window hints
610 XClassHint *class_hint = XAllocClassHint();
611 if (class_hint == nil) {
612 fprintf(stderr, "Could not allocate memory for class hint\n");
613 exit(EX_UNAVAILABLE);
615 class_hint->res_name = resname;
616 class_hint->res_class = resclass;
617 XSetClassHint(d, w, class_hint);
618 XFree(class_hint);
620 XSizeHints *size_hint = XAllocSizeHints();
621 if (size_hint == nil) {
622 fprintf(stderr, "Could not allocate memory for size hint\n");
623 exit(EX_UNAVAILABLE);
625 size_hint->flags = PMinSize | PBaseSize;
626 size_hint->min_width = width;
627 size_hint->base_width = width;
628 size_hint->min_height = height;
629 size_hint->base_height = height;
631 XFlush(d);
634 // write the width and height of the window `w' respectively in `width'
635 // and `height'.
636 void get_wh(Display *d, Window *w, int *width, int *height) {
637 XWindowAttributes win_attr;
638 XGetWindowAttributes(d, *w, &win_attr);
639 *height = win_attr.height;
640 *width = win_attr.width;
643 // I know this may seem a little hackish BUT is the only way I managed
644 // to actually grab that goddam keyboard. Only one call to
645 // XGrabKeyboard does not always end up with the keyboard grabbed!
646 int take_keyboard(Display *d, Window w) {
647 int i;
648 for (i = 0; i < 100; i++) {
649 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
650 return 1;
651 usleep(1000);
653 return 0;
656 // release the keyboard.
657 void release_keyboard(Display *d) {
658 XUngrabKeyboard(d, CurrentTime);
661 // Given a string, try to parse it as a number or return
662 // `default_value'.
663 int parse_integer(const char *str, int default_value) {
664 errno = 0;
665 char *ep;
666 long lval = strtol(str, &ep, 10);
667 if (str[0] == '\0' || *ep != '\0') { // NaN
668 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
669 return default_value;
671 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
672 (lval > INT_MAX || lval < INT_MIN)) {
673 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
674 return default_value;
676 return lval;
679 // like parse_integer, but if the value ends with a `%' then its
680 // treated like a percentage (`max' is used to compute the percentage)
681 int parse_int_with_percentage(const char *str, int default_value, int max) {
682 int len = strlen(str);
683 if (len > 0 && str[len-1] == '%') {
684 char *cpy = strdup(str);
685 check_allocation(cpy);
686 cpy[len-1] = '\0';
687 int val = parse_integer(cpy, default_value);
688 free(cpy);
689 return val * max / 100;
691 return parse_integer(str, default_value);
694 // like parse_int_with_percentage but understands the special value
695 // "middle" that is (max - self) / 2
696 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
697 if (!strcmp(str, "middle")) {
698 return (max - self)/2;
700 return parse_int_with_percentage(str, default_value, max);
703 // Given an event, try to understand what the user wants. If the
704 // return value is ADD_CHAR then `input' is a pointer to a string that
705 // will need to be free'ed.
706 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
707 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
708 return DEL_CHAR;
710 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
711 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
713 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
714 return CONFIRM;
716 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
717 return EXIT;
719 // try to read what the user pressed
720 char str[SYM_BUF_SIZE] = {0};
721 Status s = 0;
722 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
723 if (s == XBufferOverflow) {
724 // should not happen since there are no utf-8 characters larger
725 // than 24bits
726 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
727 return EXIT;
730 if (ev->state & ControlMask) {
731 if (!strcmp(str, "")) // C-u
732 return DEL_LINE;
733 if (!strcmp(str, "")) // C-w
734 return DEL_WORD;
735 if (!strcmp(str, "")) // C-h
736 return DEL_CHAR;
737 if (!strcmp(str, "\r")) // C-m
738 return CONFIRM;
739 if (!strcmp(str, "")) // C-p
740 return PREV_COMPL;
741 if (!strcmp(str, "")) // C-n
742 return NEXT_COMPL;
743 if (!strcmp(str, "")) // C-c
744 return EXIT;
745 if (!strcmp(str, "\t")) // C-i
746 return TOGGLE_FIRST_SELECTED;
749 *input = strdup(str);
750 if (*input == nil) {
751 fprintf(stderr, "Error while allocating memory for key.\n");
752 return EXIT;
755 return ADD_CHAR;
758 // Given the name of the program (argv[0]?) print a small help on stderr
759 void usage(char *prgname) {
760 fprintf(stderr, "Usage: %s [flags]\n", prgname);
761 fprintf(stderr, "\t-a: automatic mode, the first completion is "
762 "always selected;\n");
763 fprintf(stderr, "\t-h: print this help.\n");
766 int main(int argc, char **argv) {
767 #ifdef HAVE_PLEDGE
768 // stdio & rpat: to read and write stdio/stdout
769 // unix: to connect to Xorg
770 pledge("stdio rpath unix", "");
771 #endif
773 // by default the first completion isn't selected
774 bool first_selected = false;
776 // parse the command line options
777 int ch;
778 while ((ch = getopt(argc, argv, "ahv")) != -1) {
779 switch (ch) {
780 case 'a':
781 first_selected = true;
782 break;
783 case 'h':
784 usage(*argv);
785 return 0;
786 case 'v':
787 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
788 return 0;
789 default:
790 usage(*argv);
791 return EX_USAGE;
795 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
796 readlines(&lines, INITIAL_ITEMS);
798 setlocale(LC_ALL, getenv("LANG"));
800 enum state status = LOOPING;
802 // where the monitor start (used only with xinerama)
803 int offset_x = 0;
804 int offset_y = 0;
806 // width and height of the window
807 int width = 400;
808 int height = 20;
810 // position on the screen
811 int x = 0;
812 int y = 0;
814 // the default padding
815 int padding = 10;
817 char *ps1 = strdup("$ ");
818 check_allocation(ps1);
820 char *fontname = strdup(default_fontname);
821 check_allocation(fontname);
823 int textlen = 10;
824 char *text = malloc(textlen * sizeof(char));
825 check_allocation(text);
827 /* struct completions *cs = filter(text, lines); */
828 struct completions *cs = compls_new();
829 check_allocation(cs);
831 update_completions(cs, text, lines, first_selected);
833 // start talking to xorg
834 Display *d = XOpenDisplay(nil);
835 if (d == nil) {
836 fprintf(stderr, "Could not open display!\n");
837 return EX_UNAVAILABLE;
840 // get display size
841 // XXX: is getting the default root window dimension correct?
842 XWindowAttributes xwa;
843 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
844 int d_width = xwa.width;
845 int d_height = xwa.height;
847 #ifdef USE_XINERAMA
848 if (XineramaIsActive(d)) {
849 // find the mice
850 int number_of_screens = XScreenCount(d);
851 Window r;
852 Window root;
853 int root_x, root_y, win_x, win_y;
854 unsigned int mask;
855 bool res;
856 for (int i = 0; i < number_of_screens; ++i) {
857 root = XRootWindow(d, i);
858 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
859 if (res) break;
861 if (!res) {
862 fprintf(stderr, "No mouse found.\n");
863 root_x = 0;
864 root_y = 0;
867 // now find in which monitor the mice is on
868 int monitors;
869 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
870 if (info) {
871 for (int i = 0; i < monitors; ++i) {
872 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
873 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
874 offset_x = info[i].x_org;
875 offset_y = info[i].y_org;
876 d_width = info[i].width;
877 d_height = info[i].height;
878 break;
882 XFree(info);
884 #endif
886 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
887 XColor p_fg, p_bg,
888 compl_fg, compl_bg,
889 compl_highlighted_fg, compl_highlighted_bg;
891 bool horizontal_layout = true;
893 // read resource
894 XrmInitialize();
895 char *xrm = XResourceManagerString(d);
896 XrmDatabase xdb = nil;
897 if (xrm != nil) {
898 xdb = XrmGetStringDatabase(xrm);
899 XrmValue value;
900 char *datatype[20];
902 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
903 fontname = strdup(value.addr);
904 check_allocation(fontname);
906 else
907 fprintf(stderr, "no font defined, using %s\n", fontname);
909 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
910 char *v = strdup(value.addr);
911 check_allocation(v);
912 horizontal_layout = !strcmp(v, "horizontal");
913 free(v);
915 else
916 fprintf(stderr, "no layout defined, using horizontal\n");
918 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
919 free(ps1);
920 ps1 = normalize_str(value.addr);
921 } else
922 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
924 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
925 width = parse_int_with_percentage(value.addr, width, d_width);
926 else
927 fprintf(stderr, "no width defined, using %d\n", width);
929 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
930 height = parse_int_with_percentage(value.addr, height, d_height);
931 else
932 fprintf(stderr, "no height defined, using %d\n", height);
934 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
935 x = parse_int_with_middle(value.addr, x, d_width, width);
936 else
937 fprintf(stderr, "no x defined, using %d\n", x);
939 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
940 y = parse_int_with_middle(value.addr, y, d_height, height);
941 else
942 fprintf(stderr, "no y defined, using %d\n", y);
944 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
945 padding = parse_integer(value.addr, padding);
946 else
947 fprintf(stderr, "no padding defined, using %d\n", padding);
949 XColor tmp;
950 // TODO: tmp needs to be free'd after every allocation?
952 // prompt
953 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
954 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
955 else
956 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
958 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
959 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
960 else
961 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
963 // completion
964 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
965 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
966 else
967 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
969 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
970 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
971 else
972 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
974 // completion highlighted
975 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
976 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
977 else
978 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
980 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
981 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
982 else
983 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
984 } else {
985 XColor tmp;
986 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
987 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
988 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
989 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
990 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
991 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
994 // load the font
995 #ifdef USE_XFT
996 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
997 #else
998 char **missing_charset_list;
999 int missing_charset_count;
1000 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1001 if (font == nil) {
1002 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1003 return EX_UNAVAILABLE;
1005 #endif
1007 // create the window
1008 XSetWindowAttributes attr;
1009 attr.override_redirect = true;
1011 Window w = XCreateWindow(d, // display
1012 DefaultRootWindow(d), // parent
1013 x + offset_x, y + offset_y, // x y
1014 width, height, // w h
1015 0, // border width
1016 DefaultDepth(d, DefaultScreen(d)), // depth
1017 InputOutput, // class
1018 DefaultVisual(d, DefaultScreen(d)), // visual
1019 CWOverrideRedirect, // value mask
1020 &attr);
1022 set_win_atoms_hints(d, w, width, height);
1024 // we want some events
1025 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1027 // make the window appear on the screen
1028 XMapWindow(d, w);
1030 // wait for the MapNotify event (i.e. the event "window rendered")
1031 for (;;) {
1032 XEvent e;
1033 XNextEvent(d, &e);
1034 if (e.type == MapNotify)
1035 break;
1038 // get the *real* width & height after the window was rendered
1039 get_wh(d, &w, &width, &height);
1041 // grab keyboard
1042 take_keyboard(d, w);
1044 // Create some graphics contexts
1045 XGCValues values;
1046 /* values.font = font->fid; */
1048 struct rendering r = {
1049 .d = d,
1050 .w = w,
1051 #ifdef USE_XFT
1052 .font = font,
1053 #else
1054 .font = &font,
1055 #endif
1056 .prompt = XCreateGC(d, w, 0, &values),
1057 .prompt_bg = XCreateGC(d, w, 0, &values),
1058 .completion = XCreateGC(d, w, 0, &values),
1059 .completion_bg = XCreateGC(d, w, 0, &values),
1060 .completion_highlighted = XCreateGC(d, w, 0, &values),
1061 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1062 .width = width,
1063 .height = height,
1064 .padding = padding,
1065 .horizontal_layout = horizontal_layout,
1066 .ps1 = ps1,
1067 .ps1len = strlen(ps1)
1070 #ifdef USE_XFT
1071 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1073 // prompt
1074 XRenderColor xrcolor;
1075 xrcolor.red = p_fg.red;
1076 xrcolor.green = p_fg.red;
1077 xrcolor.blue = p_fg.red;
1078 xrcolor.alpha = 65535;
1079 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1081 // completion
1082 xrcolor.red = compl_fg.red;
1083 xrcolor.green = compl_fg.green;
1084 xrcolor.blue = compl_fg.blue;
1085 xrcolor.alpha = 65535;
1086 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1088 // completion highlighted
1089 xrcolor.red = compl_highlighted_fg.red;
1090 xrcolor.green = compl_highlighted_fg.green;
1091 xrcolor.blue = compl_highlighted_fg.blue;
1092 xrcolor.alpha = 65535;
1093 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1094 #endif
1096 // load the colors in our GCs
1097 XSetForeground(d, r.prompt, p_fg.pixel);
1098 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1099 XSetForeground(d, r.completion, compl_fg.pixel);
1100 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1101 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1102 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1104 // open the X input method
1105 XIM xim = XOpenIM(d, xdb, resname, resclass);
1106 check_allocation(xim);
1108 XIMStyles *xis = nil;
1109 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1110 fprintf(stderr, "Input Styles could not be retrieved\n");
1111 return EX_UNAVAILABLE;
1114 XIMStyle bestMatchStyle = 0;
1115 for (int i = 0; i < xis->count_styles; ++i) {
1116 XIMStyle ts = xis->supported_styles[i];
1117 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1118 bestMatchStyle = ts;
1119 break;
1122 XFree(xis);
1124 if (!bestMatchStyle) {
1125 fprintf(stderr, "No matching input style could be determined\n");
1128 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1129 check_allocation(xic);
1131 // draw the window for the first time
1132 draw(&r, text, cs);
1134 // main loop
1135 while (status == LOOPING) {
1136 XEvent e;
1137 XNextEvent(d, &e);
1139 if (XFilterEvent(&e, w))
1140 continue;
1142 switch (e.type) {
1143 case KeymapNotify:
1144 XRefreshKeyboardMapping(&e.xmapping);
1145 break;
1147 case KeyPress: {
1148 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1150 char *input;
1151 switch (parse_event(d, ev, xic, &input)) {
1152 case EXIT:
1153 status = ERR;
1154 break;
1156 case CONFIRM:
1157 status = OK;
1159 // if first_selected is active and the first completion is
1160 // active be sure to 'expand' the text to match the selection
1161 if (first_selected && cs && cs->selected == 0) {
1162 free(text);
1163 text = strdup(cs->completions->completion);
1164 if (text == nil) {
1165 fprintf(stderr, "Memory allocation error");
1166 status = ERR;
1168 textlen = strlen(text);
1170 break;
1172 case PREV_COMPL: {
1173 complete(cs, first_selected, true, &text, &textlen, &status);
1174 break;
1177 case NEXT_COMPL: {
1178 complete(cs, first_selected, false, &text, &textlen, &status);
1179 break;
1182 case DEL_CHAR:
1183 popc(text, textlen);
1184 update_completions(cs, text, lines, first_selected);
1185 break;
1187 case DEL_WORD: {
1188 // `textlen` is the lenght of the allocated string, not the
1189 // lenght of the ACTUAL string
1190 int p = strlen(text) -1;
1191 if (p > 0) { // delete the current char
1192 text[p] = 0;
1193 p--;
1196 // erase the alphanumeric char
1197 while (p >= 0 && isalnum(text[p])) {
1198 text[p] = 0;
1199 p--;
1202 // erase also trailing white spaces
1203 while (p >= 0 && isspace(text[p])) {
1204 text[p] = 0;
1205 p--;
1207 update_completions(cs, text, lines, first_selected);
1208 break;
1211 case DEL_LINE: {
1212 for (int i = 0; i < textlen; ++i)
1213 text[i] = 0;
1214 update_completions(cs, text, lines, first_selected);
1215 break;
1218 case ADD_CHAR: {
1219 int str_len = strlen(input);
1221 // sometimes a strange key is pressed (i.e. ctrl alone),
1222 // so input will be empty. Don't need to update completion
1223 // in this case
1224 if (str_len == 0)
1225 break;
1227 for (int i = 0; i < str_len; ++i) {
1228 textlen = pushc(&text, textlen, input[i]);
1229 if (textlen == -1) {
1230 fprintf(stderr, "Memory allocation error\n");
1231 status = ERR;
1232 break;
1235 if (status != ERR) {
1236 update_completions(cs, text, lines, first_selected);
1237 free(input);
1239 break;
1242 case TOGGLE_FIRST_SELECTED:
1243 first_selected = !first_selected;
1244 if (first_selected && cs->selected < 0)
1245 cs->selected = 0;
1246 if (!first_selected && cs->selected == 0)
1247 cs->selected = -1;
1248 break;
1253 draw(&r, text, cs);
1256 if (status == OK)
1257 printf("%s\n", text);
1259 release_keyboard(r.d);
1261 #ifdef USE_XFT
1262 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1263 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1264 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1265 #endif
1267 free(ps1);
1268 free(fontname);
1269 free(text);
1271 char *l = nil;
1272 char **lns = lines;
1273 while ((l = *lns) != nil) {
1274 free(l);
1275 ++lns;
1278 free(lines);
1279 compls_delete(cs);
1281 XDestroyWindow(r.d, r.w);
1282 XCloseDisplay(r.d);
1284 return status;