1 /* mymenu -- simple dmenu alternative */
3 /* Copyright (C) 2018 Omar Polo <omar.polo@europecom.net>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 #include <string.h> // strdup, strnlen, ...
22 #include <ctype.h> // isalnum
23 #include <locale.h> // setlocale
31 #include <X11/Xutil.h> // XLookupString
32 #include <X11/Xresource.h>
33 #include <X11/Xcms.h> // colors
34 #include <X11/keysym.h>
37 # include <X11/extensions/Xinerama.h>
41 #define resname "MyMenu"
42 #define resclass "mymenu"
44 #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
45 #define MAX(a, b) ((a) > (b) ? (a) : (b))
46 #define OVERLAP(a,b,c,d) (((a)==(c) && (b)==(d)) || MIN((a)+(b), (c)+(d)) - MAX((a), (c)) > 0)
47 #define INTERSECT(x,y,w,h,x1,y1,w1,h1) (OVERLAP((x),(w),(x1),(w1)) && OVERLAP((y),(h),(y1),(h1)))
49 #define update_completions(cs, text, lines) { \
51 cs = filter(text, lines); \
55 #define INITIAL_ITEMS 64
58 fprintf(stderr, "TODO! " s "\n"); \
61 #define cannot_allocate_memory { \
62 fprintf(stderr, "Could not allocate memory\n"); \
63 exit(EX_UNAVAILABLE); \
66 #define check_allocation(a) { \
68 cannot_allocate_memory; \
71 enum state {LOOPING, OK, ERR};
80 GC completion_highlighted;
81 GC completion_highlighted_bg;
85 bool horizontal_layout;
91 struct completions *next;
94 struct completions *compl_new() {
95 struct completions *c = malloc(sizeof(struct completions));
106 void compl_delete(struct completions *c) {
110 struct completions *compl_select_next(struct completions *c, bool n) {
118 struct completions *orig = c;
122 if (c->next != nil) {
123 // the current one is selected and the next one exists
124 c->next->selected = true;
127 // the current one is selected and the next one is nill,
128 // select the first one
129 orig->selected = true;
138 struct completions *compl_select_prev(struct completions *c, bool n) {
142 struct completions *cc = c;
144 if (n) // select the last one
146 if (cc->next == nil) {
152 else // select the previous one
154 if (cc->next != nil && cc->next->selected) {
155 cc->next->selected = false;
165 struct completions *filter(char *text, char **lines) {
167 struct completions *root = compl_new();
168 struct completions *c = root;
175 if (strstr(l, text) != nil) {
176 c->next = compl_new();
184 struct completions *r = root->next;
189 // push the character c at the end of the string pointed by p
190 int pushc(char **p, int maxlen, char c) {
191 int len = strnlen(*p, maxlen);
193 if (!(len < maxlen -2)) {
194 maxlen += maxlen >> 1;
195 char *newptr = realloc(*p, maxlen);
196 if (newptr == nil) { // bad!
207 int utf8strnlen(char *s, int maxlen) {
209 while (*s && maxlen > 0) {
210 len += (*s++ & 0xc0) != 0x80;
216 // remove the last *glyph* from the *utf8* string!
217 // this is different from just setting the last byte to 0 (in some
218 // cases ofc). The actual implementation is quite inefficient because
219 // it remove the last char until the number of glyphs doesn't change
220 void popc(char *p, int maxlen) {
221 int len = strnlen(p, maxlen);
226 int ulen = utf8strnlen(p, maxlen);
227 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
233 // read an arbitrary long line from stdin and return a pointer to it
234 // TODO: resize the allocated memory to exactly fit the string once
236 char *readline(bool *eof) {
238 char *str = calloc(maxlen, sizeof(char));
240 fprintf(stderr, "Cannot allocate memory!\n");
241 exit(EX_UNAVAILABLE);
245 while((c = getchar()) != EOF) {
249 maxlen = pushc(&str, maxlen, c);
252 fprintf(stderr, "Cannot allocate memory!\n");
253 exit(EX_UNAVAILABLE);
260 int readlines (char ***lns, int items) {
261 bool finished = false;
265 lines[n] = readline(&finished);
267 if (strlen(lines[n]) == 0 || lines[n][0] == '\n')
268 --n; // forget about this line
275 if (n == items - 1) {
277 char **l = realloc(lines, sizeof(char*) * items);
289 // |------------------|----------------------------------------------|
290 // | 20 char text | completion | completion | completion | compl |
291 // |------------------|----------------------------------------------|
292 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
293 // TODO: make these dynamic?
294 int prompt_width = 20; // char
296 /* int start_at = XTextWidth(r->font, " ", 1) * prompt_width + padding; */
299 int start_at = XmbTextExtents(*r->font, " ", 1, nil, &rect);
300 start_at = start_at * prompt_width + padding;
302 int texty = (rect.height + r->height) >>1;
304 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
306 int text_len = strlen(text);
307 if (text_len > prompt_width)
308 text = text + (text_len - prompt_width);
309 /* XDrawString(r->d, r->w, r->prompt, padding, texty, text, MIN(text_len, prompt_width)); */
310 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, texty, text, MIN(text_len, prompt_width));
312 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
315 GC g = cs->selected ? r->completion_highlighted : r->completion;
316 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
318 int len = strlen(cs->completion);
319 /* int text_width = XTextWidth(r->font, cs->completion, len); */
320 int text_width = XmbTextExtents(*r->font, cs->completion, len, nil, nil);
322 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
324 /* XDrawString(r->d, r->w, g, start_at + padding, texty, cs->completion, len); */
325 Xutf8DrawString(r->d, r->w, *r->font, g, start_at + padding, texty, cs->completion, len);
327 start_at += text_width + padding * 2;
329 if (start_at > r->width)
330 break; // don't draw completion if the space isn't enough
338 // |-----------------------------------------------------------------|
340 // |-----------------------------------------------------------------|
342 // |-----------------------------------------------------------------|
344 // |-----------------------------------------------------------------|
345 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
346 // should be padding and not padding*2, but the text doesn't seem to
347 // be vertically centered otherwise....
348 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
349 int padding = 10; // TODO make this dynamic
352 XmbTextExtents(*r->font, "fjpgl", 5, &rect, nil);
353 int start_at = rect.height + padding*2;
355 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
356 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
357 Xutf8DrawString(r->d, r->w, *r->font, r->prompt, padding, padding*2, text, strlen(text));
360 GC g = cs->selected ? r->completion_highlighted : r->completion;
361 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
363 int len = strlen(cs->completion);
364 XmbTextExtents(*r->font, cs->completion, len, &rect, nil);
365 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, rect.height + padding*2);
366 Xutf8DrawString(r->d, r->w, *r->font, g, padding, start_at + padding*2, cs->completion, len);
368 start_at += rect.height + padding *2;
370 if (start_at > r->height)
371 break; // don't draw completion if the space isn't enough
379 void draw(struct rendering *r, char *text, struct completions *cs) {
380 if (r->horizontal_layout)
381 draw_horizontally(r, text, cs);
383 draw_vertically(r, text, cs);
386 /* Set some WM stuff */
387 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
389 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
393 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
394 XInternAtom(d, "ATOM", false),
397 (unsigned char *)&type,
401 /* some window managers honor this properties */
402 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
405 XInternAtom(d, "_NET_WM_STATE", false),
406 XInternAtom(d, "ATOM", false),
409 (unsigned char *)&type,
413 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
416 XInternAtom(d, "_NET_WM_STATE", false),
417 XInternAtom(d, "ATOM", false),
420 (unsigned char *)&type,
424 // setting window hints
425 XClassHint *class_hint = XAllocClassHint();
426 if (class_hint == nil) {
427 fprintf(stderr, "Could not allocate memory for class hint\n");
428 exit(EX_UNAVAILABLE);
430 class_hint->res_name = "mymenu";
431 class_hint->res_class = "mymenu";
432 XSetClassHint(d, w, class_hint);
435 XSizeHints *size_hint = XAllocSizeHints();
436 if (size_hint == nil) {
437 fprintf(stderr, "Could not allocate memory for size hint\n");
438 exit(EX_UNAVAILABLE);
440 size_hint->min_width = width;
441 size_hint->base_width = width;
442 size_hint->min_height = height;
443 size_hint->base_height = height;
448 void get_wh(Display *d, Window *w, int *width, int *height) {
449 XWindowAttributes win_attr;
450 XGetWindowAttributes(d, *w, &win_attr);
451 *height = win_attr.height;
452 *width = win_attr.width;
455 // I know this may seem a little hackish BUT is the only way I managed
456 // to actually grab that goddam keyboard. Only one call to
457 // XGrabKeyboard does not always end up with the keyboard grabbed!
458 int take_keyboard(Display *d, Window w) {
460 for (i = 0; i < 100; i++) {
461 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
468 void release_keyboard(Display *d) {
469 XUngrabKeyboard(d, CurrentTime);
472 int parse_integer(const char *str, int default_value, int max) {
473 int len = strlen(str);
474 if (len > 0 && str[len-1] == '%') {
475 char *cpy = strdup(str);
476 check_allocation(cpy);
478 int val = parse_integer(cpy, default_value, max);
480 return val * max / 100;
485 long lval = strtol(str, &ep, 10);
486 if (str[0] == '\0' || *ep != '\0') { // NaN
487 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
488 return default_value;
490 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
491 (lval > INT_MAX || lval < INT_MIN)) {
492 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
493 return default_value;
498 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
499 if (!strcmp(str, "middle")) {
500 return (max - self)/2;
502 return parse_integer(str, default_value, max);
506 /* char *lines[INITIAL_ITEMS] = {0}; */
507 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
508 readlines(&lines, INITIAL_ITEMS);
510 setlocale(LC_ALL, getenv("LANG"));
512 enum state status = LOOPING;
514 // where the monitor start (used only with xinerama)
518 // width and height of the window
522 // position on the screen
526 char *fontname = strdup("fixed");
527 check_allocation(fontname);
530 char *text = malloc(textlen * sizeof(char));
531 check_allocation(text);
533 struct completions *cs = filter(text, lines);
534 bool nothing_selected = true;
536 // start talking to xorg
537 Display *d = XOpenDisplay(nil);
539 fprintf(stderr, "Could not open display!\n");
540 return EX_UNAVAILABLE;
544 // XXX: is getting the default root window dimension correct?
545 XWindowAttributes xwa;
546 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
547 int d_width = xwa.width;
548 int d_height = xwa.height;
551 // TODO: this bit still needs to be improved
552 if (XineramaIsActive(d)) {
554 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
556 for (int i = 0; i < monitors; ++i) {
557 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
558 offset_x = info[x].x_org;
559 offset_y = info[y].y_org;
560 d_width = info[i].width;
561 d_height = info[i].height;
568 /* fprintf(stderr, "offset_x:\t%d\n" */
569 /* "offset_y:\t%d\n" */
570 /* "d_width:\t%d\n" */
571 /* "d_height:\t%d\n" */
572 /* , offset_x, offset_y, d_width, d_height); */
574 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
577 compl_highlighted_fg, compl_highlighted_bg;
579 bool horizontal_layout = true;
583 char *xrm = XResourceManagerString(d);
584 XrmDatabase xdb = nil;
586 xdb = XrmGetStringDatabase(xrm);
590 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
591 fontname = strdup(value.addr);
592 check_allocation(fontname);
595 fprintf(stderr, "no font defined, using %s\n", fontname);
597 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
598 char *v = strdup(value.addr);
600 horizontal_layout = !strcmp(v, "horizontal");
604 fprintf(stderr, "no layout defined, using horizontal\n");
606 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
607 width = parse_integer(value.addr, width, d_width);
609 fprintf(stderr, "no width defined, using %d\n", width);
611 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
612 height = parse_integer(value.addr, height, d_height);
614 fprintf(stderr, "no height defined, using %d\n", height);
616 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
617 x = parse_int_with_middle(value.addr, x, d_width, width);
619 fprintf(stderr, "no x defined, using %d\n", width);
621 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
622 y = parse_int_with_middle(value.addr, y, d_height, height);
624 fprintf(stderr, "no y defined, using %d\n", height);
627 // TODO: tmp needs to be free'd after every allocation?
630 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
631 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
633 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
635 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
636 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
638 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
641 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
642 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
644 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
646 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
647 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
649 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
651 // completion highlighted
652 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
653 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
655 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
657 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
658 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
660 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
663 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
664 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
665 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
666 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
667 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
668 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
672 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
673 /* if (font == nil) { */
674 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
675 /* font = XLoadQueryFont(d, "fixed"); */
678 char **missing_charset_list;
679 int missing_charset_count;
680 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
682 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
683 return EX_UNAVAILABLE;
687 XSetWindowAttributes attr;
689 Window w = XCreateWindow(d, // display
690 DefaultRootWindow(d), // parent
691 x + offset_x, y + offset_y, // x y
692 width, height, // w h
694 DefaultDepth(d, DefaultScreen(d)), // depth
695 InputOutput, // class
696 DefaultVisual(d, DefaultScreen(d)), // visual
700 set_win_atoms_hints(d, w, width, height);
702 // we want some events
703 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeyReleaseMask | KeymapStateMask);
705 // make the window appear on the screen
708 // wait for the MapNotify event (i.e. the event "window rendered")
712 if (e.type == MapNotify)
716 // get the *real* width & height after the window was rendered
717 get_wh(d, &w, &width, &height);
722 // Create some graphics contexts
724 /* values.font = font->fid; */
726 struct rendering r = {
729 .prompt = XCreateGC(d, w, 0, &values),
730 .prompt_bg = XCreateGC(d, w, 0, &values),
731 .completion = XCreateGC(d, w, 0, &values),
732 .completion_bg = XCreateGC(d, w, 0, &values),
733 .completion_highlighted = XCreateGC(d, w, 0, &values),
734 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
735 /* .prompt = XCreateGC(d, w, GCFont, &values), */
736 /* .prompt_bg = XCreateGC(d, w, GCFont, &values), */
737 /* .completion = XCreateGC(d, w, GCFont, &values), */
738 /* .completion_bg = XCreateGC(d, w, GCFont, &values), */
739 /* .completion_highlighted = XCreateGC(d, w, GCFont, &values), */
740 /* .completion_highlighted_bg = XCreateGC(d, w, GCFont, &values), */
744 .horizontal_layout = horizontal_layout
747 // load the colors in our GCs
748 XSetForeground(d, r.prompt, p_fg.pixel);
749 XSetForeground(d, r.prompt_bg, p_bg.pixel);
750 XSetForeground(d, r.completion, compl_fg.pixel);
751 XSetForeground(d, r.completion_bg, compl_bg.pixel);
752 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
753 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
755 // open the X input method
756 XIM xim = XOpenIM(d, xdb, resname, resclass);
757 check_allocation(xim);
759 XIMStyles *xis = nil;
760 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
761 fprintf(stderr, "Input Styles could not be retrieved\n");
762 return EX_UNAVAILABLE;
765 XIMStyle bestMatchStyle = 0;
766 for (int i = 0; i < xis->count_styles; ++i) {
767 XIMStyle ts = xis->supported_styles[i];
768 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
775 if (!bestMatchStyle) {
776 fprintf(stderr, "No matching input style could be determined\n");
779 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
780 check_allocation(xic);
782 // draw the window for the first time
786 while (status == LOOPING) {
790 if (XFilterEvent(&e, w))
795 XRefreshKeyboardMapping(&e.xmapping);
798 case KeyRelease: break; // ignore this
801 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
803 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
804 bool shift = (ev->state & ShiftMask);
805 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
806 : compl_select_next(cs, nothing_selected);
808 nothing_selected = false;
810 text = strdup(n->completion);
812 fprintf(stderr, "Memory allocation error!\n");
816 textlen = strlen(text);
822 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
823 nothing_selected = true;
825 update_completions(cs, text, lines);
830 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
835 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
840 // try to read what the user pressed
843 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
845 if (s == XBufferOverflow) {
846 // should not happen since there are no utf-8 characters
847 // larger than 24bits, but is something to be aware of when
848 // used to directly write to a string buffer
849 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
852 char *str = (char*)&symbol;
854 if (ev->state & ControlMask) {
855 // check for some key bindings
856 if (!strcmp(str, "")) { // C-u
857 nothing_selected = true;
858 for (int i = 0; i < textlen; ++i)
860 update_completions(cs, text, lines);
862 if (!strcmp(str, "")) { // C-h
863 nothing_selected = true;
865 update_completions(cs, text, lines);
867 if (!strcmp(str, "")) { // C-w
868 nothing_selected = true;
870 // `textlen` is the length of the allocated string, not the
871 // length of the ACTUAL string
872 int p = strlen(text) - 1;
873 if (p >= 0) { // delete the current char
877 while (p >= 0 && isalnum(text[p])) {
881 // erase also trailing white space
882 while (p >= 0 && isspace(text[p])) {
886 update_completions(cs, text, lines);
888 if (!strcmp(str, "\r")) { // C-m
895 int str_len = strlen(str);
896 for (int i = 0; i < str_len; ++i) {
897 textlen = pushc(&text, textlen, str[i]);
899 fprintf(stderr, "Memory allocation error\n");
903 nothing_selected = true;
904 update_completions(cs, text, lines);
912 fprintf(stderr, "Unknown event %d\n", e.type);
919 printf("%s\n", text);
926 /* XDestroyWindow(d, w); */
929 return status == OK ? 0 : 1;