Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020, 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <ctype.h> /* isalnum */
18 #include <err.h>
19 #include <errno.h>
20 #include <limits.h>
21 #include <locale.h> /* setlocale */
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h> /* strdup, strlen */
26 #include <sysexits.h>
27 #include <unistd.h>
29 #include <X11/Xcms.h>
30 #include <X11/Xlib.h>
31 #include <X11/Xresource.h>
32 #include <X11/Xutil.h>
33 #include <X11/keysym.h>
34 #include <X11/Xft/Xft.h>
36 #include <X11/extensions/Xinerama.h>
38 #define RESNAME "MyMenu"
39 #define RESCLASS "mymenu"
41 #define SYM_BUF_SIZE 4
43 #define DEFFONT "monospace"
45 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
52 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
53 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
55 /* The states of the event loop */
56 enum state { LOOPING, OK_LOOP, OK, ERR };
58 /*
59 * For the drawing-related function. The text to be rendere could be
60 * the prompt, a completion or a highlighted completion
61 */
62 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
64 /* These are the possible action to be performed after user input. */
65 enum action {
66 NO_OP,
67 EXIT,
68 CONFIRM,
69 CONFIRM_CONTINUE,
70 NEXT_COMPL,
71 PREV_COMPL,
72 DEL_CHAR,
73 DEL_WORD,
74 DEL_LINE,
75 ADD_CHAR,
76 TOGGLE_FIRST_SELECTED,
77 SCROLL_DOWN,
78 SCROLL_UP,
79 };
81 /* A big set of values that needs to be carried around for drawing. A
82 * big struct to rule them all */
83 struct rendering {
84 Display *d; /* Connection to xorg */
85 Window w;
86 XIM xim;
87 int width;
88 int height;
89 int p_padding[4];
90 int c_padding[4];
91 int ch_padding[4];
92 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
93 the borders) */
94 int y_zero; /* like x_zero but for the y axis */
96 int offset; /* scroll offset */
98 short free_text;
99 short first_selected;
100 short multiple_select;
102 /* four border width */
103 int borders[4];
104 int p_borders[4];
105 int c_borders[4];
106 int ch_borders[4];
108 short horizontal_layout;
110 /* prompt */
111 char *ps1;
112 int ps1len;
113 int ps1w; /* ps1 width */
114 int ps1h; /* ps1 height */
116 int text_height; /* cache for the vertical layout */
118 XIC xic;
120 /* colors */
121 GC fgs[4];
122 GC bgs[4];
123 GC borders_bg[4];
124 GC p_borders_bg[4];
125 GC c_borders_bg[4];
126 GC ch_borders_bg[4];
127 XftFont *font;
128 XftDraw *xftdraw;
129 XftColor xft_colors[3];
130 };
132 struct completion {
133 char *completion;
134 char *rcompletion;
136 /*
137 * The X (or Y, depending on the layour) at which the item is
138 * rendered
139 */
140 int offset;
141 };
143 /* Wrap the linked list of completions */
144 struct completions {
145 struct completion *completions;
146 ssize_t selected;
147 size_t length;
148 };
150 /* idea stolen from lemonbar; ty lemonboy */
151 typedef union {
152 struct {
153 uint8_t b;
154 uint8_t g;
155 uint8_t r;
156 uint8_t a;
157 } rgba;
158 uint32_t v;
159 } rgba_t;
161 /* Return a newly allocated (and empty) completion list */
162 struct completions *
163 compls_new(size_t length)
165 struct completions *cs = malloc(sizeof(struct completions));
167 if (cs == NULL)
168 return cs;
170 cs->completions = calloc(length, sizeof(struct completion));
171 if (cs->completions == NULL) {
172 free(cs);
173 return NULL;
176 cs->selected = -1;
177 cs->length = length;
178 return cs;
181 /* Delete the wrapper and the whole list */
182 void
183 compls_delete(struct completions *cs)
185 if (cs == NULL)
186 return;
188 free(cs->completions);
189 free(cs);
192 /*
193 * Create a completion list from a text and the list of possible
194 * completions (null terminated). Expects a non-null `cs'. `lines' and
195 * `vlines' should have the same length OR `vlines' is NULL.
196 */
197 void
198 filter(struct completions *cs, char *text, char **lines, char **vlines)
200 size_t index = 0;
201 size_t matching = 0;
202 char *l;
204 if (vlines == NULL)
205 vlines = lines;
207 while (1) {
208 if (lines[index] == NULL)
209 break;
211 l = vlines[index] != NULL ? vlines[index] : lines[index];
213 if (strcasestr(l, text) != NULL) {
214 struct completion *c = &cs->completions[matching];
215 c->completion = l;
216 c->rcompletion = lines[index];
217 matching++;
220 index++;
222 cs->length = matching;
223 cs->selected = -1;
226 /* Update the given completion */
227 void
228 update_completions(struct completions *cs, char *text, char **lines,
229 char **vlines, short first_selected)
231 filter(cs, text, lines, vlines);
232 if (first_selected && cs->length > 0)
233 cs->selected = 0;
236 /*
237 * Select the next or previous selection and update some state. `text'
238 * will be updated with the text of the completion and `textlen' with
239 * the new length. If the memory cannot be allocated `status' will be
240 * set to `ERR'.
241 */
242 void
243 complete(struct completions *cs, short first_selected, short p,
244 char **text, int *textlen, enum state *status)
246 struct completion *n;
247 int index;
249 if (cs == NULL || cs->length == 0)
250 return;
252 /*
253 * If the first is always selected and the first entry is
254 * different from the text, expand the text and return
255 */
256 if (first_selected &&
257 cs->selected == 0 &&
258 strcmp(cs->completions->completion, *text) != 0 &&
259 !p) {
260 free(*text);
261 *text = strdup(cs->completions->completion);
262 if (text == NULL) {
263 *status = ERR;
264 return;
266 *textlen = strlen(*text);
267 return;
270 index = cs->selected;
272 if (index == -1 && p)
273 index = 0;
274 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
275 % cs->length;
277 n = &cs->completions[cs->selected];
279 free(*text);
280 *text = strdup(n->completion);
281 if (text == NULL) {
282 fprintf(stderr, "Memory allocation error!\n");
283 *status = ERR;
284 return;
286 *textlen = strlen(*text);
289 /* Push the character c at the end of the string pointed by p */
290 int
291 pushc(char **p, int maxlen, char c)
293 int len;
295 len = strnlen(*p, maxlen);
296 if (!(len < maxlen - 2)) {
297 char *newptr;
299 maxlen += maxlen >> 1;
300 newptr = realloc(*p, maxlen);
301 if (newptr == NULL) /* bad */
302 return -1;
303 *p = newptr;
306 (*p)[len] = c;
307 (*p)[len + 1] = '\0';
308 return maxlen;
311 /*
312 * Remove the last rune from the *UTF-8* string! This is different
313 * from just setting the last byte to 0 (in some cases ofc). Return a
314 * pointer (e) to the last nonzero char. If e < p then p is empty!
315 */
316 char *
317 popc(char *p)
319 int len = strlen(p);
320 char *e;
322 if (len == 0)
323 return p;
325 e = p + len - 1;
327 do {
328 char c = *e;
330 *e = '\0';
331 e -= 1;
333 /*
334 * If c is a starting byte (11......) or is under
335 * U+007F we're done.
336 */
337 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
338 break;
339 } while (e >= p);
341 return e;
344 /* Remove the last word plus trailing white spaces from the given string */
345 void
346 popw(char *w)
348 short in_word = 1;
350 if (*w == '\0')
351 return;
353 while (1) {
354 char *e = popc(w);
356 if (e < w)
357 return;
359 if (in_word && isspace(*e))
360 in_word = 0;
362 if (!in_word && !isspace(*e))
363 return;
367 /*
368 * If the string is surrounded by quates (`"') remove them and replace
369 * every `\"' in the string with a single double-quote.
370 */
371 char *
372 normalize_str(const char *str)
374 int len, p;
375 char *s;
377 if ((len = strlen(str)) == 0)
378 return NULL;
380 if ((s = calloc(len, sizeof(char))) == NULL)
381 err(1, "calloc");
382 p = 0;
384 while (*str) {
385 char c = *str;
387 if (*str == '\\') {
388 if (*(str + 1)) {
389 s[p] = *(str + 1);
390 p++;
391 str += 2; /* skip this and the next char */
392 continue;
393 } else
394 break;
396 if (c == '"') {
397 str++; /* skip only this char */
398 continue;
400 s[p] = c;
401 p++;
402 str++;
405 return s;
408 char **
409 readlines(size_t *lineslen)
411 size_t len = 0, cap = 0;
412 size_t linesize = 0;
413 ssize_t linelen;
414 char *line = NULL, **lines = NULL;
416 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
417 if (linelen != 0 && line[linelen-1] == '\n')
418 line[linelen-1] = '\0';
420 if (len == cap) {
421 size_t newcap;
422 void *t;
424 newcap = MAX(cap * 1.5, 32);
425 t = recallocarray(lines, cap, newcap, sizeof(char *));
426 if (t == NULL)
427 err(1, "recallocarray");
428 cap = newcap;
429 lines = t;
432 if ((lines[len++] = strdup(line)) == NULL)
433 err(1, "strdup");
436 if (ferror(stdin))
437 err(1, "getline");
438 free(line);
440 *lineslen = len;
441 return lines;
444 /*
445 * Compute the dimensions of the string str once rendered.
446 * It'll return the width and set ret_width and ret_height if not NULL
447 */
448 int
449 text_extents(char *str, int len, struct rendering *r, int *ret_width,
450 int *ret_height)
452 int height, width;
453 XGlyphInfo gi;
454 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
455 height = r->font->ascent - r->font->descent;
456 width = gi.width - gi.x;
458 if (ret_width != NULL)
459 *ret_width = width;
460 if (ret_height != NULL)
461 *ret_height = height;
462 return width;
465 void
466 draw_string(char *str, int len, int x, int y, struct rendering *r,
467 enum obj_type tt)
469 XftColor xftcolor;
470 if (tt == PROMPT)
471 xftcolor = r->xft_colors[0];
472 if (tt == COMPL)
473 xftcolor = r->xft_colors[1];
474 if (tt == COMPL_HIGH)
475 xftcolor = r->xft_colors[2];
477 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
480 /* Duplicate the string and substitute every space with a 'n` */
481 char *
482 strdupn(char *str)
484 char *t, *dup;
486 if (str == NULL || *str == '\0')
487 return NULL;
489 if ((dup = strdup(str)) == NULL)
490 return NULL;
492 for (t = dup; *t; ++t) {
493 if (*t == ' ')
494 *t = 'n';
497 return dup;
500 int
501 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
502 enum obj_type t, char *text)
504 GC *border_color, bg;
505 int *padding, *borders;
506 int ret = 0, inner_width, inner_height, x;
508 switch (t) {
509 case PROMPT:
510 border_color = r->p_borders_bg;
511 padding = r->p_padding;
512 borders = r->p_borders;
513 bg = r->bgs[0];
514 break;
515 case COMPL:
516 border_color = r->c_borders_bg;
517 padding = r->c_padding;
518 borders = r->c_borders;
519 bg = r->bgs[1];
520 break;
521 case COMPL_HIGH:
522 border_color = r->ch_borders_bg;
523 padding = r->ch_padding;
524 borders = r->ch_borders;
525 bg = r->bgs[2];
526 break;
529 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
531 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
532 inner_height = padding[0] + r->text_height + padding[2];
534 /* Border top */
535 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
536 borders[0]);
538 /* Border right */
539 XFillRectangle(r->d, r->w, border_color[1],
540 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
542 /* Border bottom */
543 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
544 y + borders[0] + padding[0] + r->text_height + padding[2],
545 r->width, borders[2]);
547 /* Border left */
548 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
549 ret);
551 /* bg */
552 x = r->x_zero + borders[3];
553 y += borders[0];
554 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
556 /* content */
557 y += padding[0] + r->text_height;
558 x += padding[3];
559 if (prefix != NULL) {
560 draw_string(prefix, strlen(prefix), x, y, r, t);
561 x += prefix_width;
563 draw_string(text, strlen(text), x, y, r, t);
565 return ret;
568 int
569 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
570 enum obj_type t, char *text)
572 GC *border_color, bg;
573 int *padding, *borders;
574 int ret = 0, inner_width, inner_height, y, text_width;
576 switch (t) {
577 case PROMPT:
578 border_color = r->p_borders_bg;
579 padding = r->p_padding;
580 borders = r->p_borders;
581 bg = r->bgs[0];
582 break;
583 case COMPL:
584 border_color = r->c_borders_bg;
585 padding = r->c_padding;
586 borders = r->c_borders;
587 bg = r->bgs[1];
588 break;
589 case COMPL_HIGH:
590 border_color = r->ch_borders_bg;
591 padding = r->ch_padding;
592 borders = r->ch_borders;
593 bg = r->bgs[2];
594 break;
597 if (padding[0] < 0 || padding[2] < 0) {
598 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
599 - r->text_height;
600 padding[0] /= 2;
602 padding[2] = padding[0];
605 /* If they are still lesser than 0, set 'em to 0 */
606 if (padding[0] < 0 || padding[2] < 0)
607 padding[0] = padding[2] = 0;
609 /* Get the text width */
610 text_extents(text, strlen(text), r, &text_width, NULL);
611 if (prefix != NULL)
612 text_width += prefix_width;
614 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
616 inner_width = padding[3] + text_width + padding[1];
617 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
619 /* Border top */
620 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
621 borders[0]);
623 /* Border right */
624 XFillRectangle(r->d, r->w, border_color[1],
625 x + borders[3] + inner_width, r->y_zero, borders[1],
626 INNER_HEIGHT(r));
628 /* Border bottom */
629 XFillRectangle(r->d, r->w, border_color[2], x,
630 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
631 borders[2]);
633 /* Border left */
634 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
635 INNER_HEIGHT(r));
637 /* bg */
638 x += borders[3];
639 y = r->y_zero + borders[0];
640 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
642 /* content */
643 y += padding[0] + r->text_height;
644 x += padding[3];
645 if (prefix != NULL) {
646 draw_string(prefix, strlen(prefix), x, y, r, t);
647 x += prefix_width;
649 draw_string(text, strlen(text), x, y, r, t);
651 return ret;
654 /*
655 * ,-----------------------------------------------------------------,
656 * | 20 char text | completion | completion | completion | compl |
657 * `-----------------------------------------------------------------'
658 */
659 void
660 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
662 size_t i;
663 int x = r->x_zero;
665 /* Draw the prompt */
666 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
668 for (i = r->offset; i < cs->length; ++i) {
669 enum obj_type t;
671 if (cs->selected == (ssize_t)i)
672 t = COMPL_HIGH;
673 else
674 t = COMPL;
676 cs->completions[i].offset = x;
678 x += draw_h_box(r, x, NULL, 0, t,
679 cs->completions[i].completion);
681 if (x > INNER_WIDTH(r))
682 break;
685 for (i += 1; i < cs->length; ++i)
686 cs->completions[i].offset = -1;
689 /*
690 * ,-----------------------------------------------------------------,
691 * | prompt |
692 * |-----------------------------------------------------------------|
693 * | completion |
694 * |-----------------------------------------------------------------|
695 * | completion |
696 * `-----------------------------------------------------------------'
697 */
698 void
699 draw_vertically(struct rendering *r, char *text, struct completions *cs)
701 size_t i;
702 int y = r->y_zero;
704 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
706 for (i = r->offset; i < cs->length; ++i) {
707 enum obj_type t;
709 if (cs->selected == (ssize_t)i)
710 t = COMPL_HIGH;
711 else
712 t = COMPL;
714 cs->completions[i].offset = y;
716 y += draw_v_box(r, y, NULL, 0, t,
717 cs->completions[i].completion);
719 if (y > INNER_HEIGHT(r))
720 break;
723 for (i += 1; i < cs->length; ++i)
724 cs->completions[i].offset = -1;
727 void
728 draw(struct rendering *r, char *text, struct completions *cs)
730 /* Draw the background */
731 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
732 INNER_WIDTH(r), INNER_HEIGHT(r));
734 /* Draw the contents */
735 if (r->horizontal_layout)
736 draw_horizontally(r, text, cs);
737 else
738 draw_vertically(r, text, cs);
740 /* Draw the borders */
741 if (r->borders[0] != 0)
742 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
743 r->borders[0]);
745 if (r->borders[1] != 0)
746 XFillRectangle(r->d, r->w, r->borders_bg[1],
747 r->width - r->borders[1], 0, r->borders[1],
748 r->height);
750 if (r->borders[2] != 0)
751 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
752 r->height - r->borders[2], r->width, r->borders[2]);
754 if (r->borders[3] != 0)
755 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
756 r->borders[3], r->height);
758 /* render! */
759 XFlush(r->d);
762 /* Set some WM stuff */
763 void
764 set_win_atoms_hints(Display *d, Window w, int width, int height)
766 Atom type;
767 XClassHint *class_hint;
768 XSizeHints *size_hint;
770 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
771 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
772 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
773 (unsigned char *)&type, 1);
775 /* some window managers honor this properties */
776 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
777 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
778 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
779 (unsigned char *)&type, 1);
781 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
782 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
783 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
784 (unsigned char *)&type, 1);
786 /* Setting window hints */
787 class_hint = XAllocClassHint();
788 if (class_hint == NULL) {
789 fprintf(stderr, "Could not allocate memory for class hint\n");
790 exit(EX_UNAVAILABLE);
793 class_hint->res_name = RESNAME;
794 class_hint->res_class = RESCLASS;
795 XSetClassHint(d, w, class_hint);
796 XFree(class_hint);
798 size_hint = XAllocSizeHints();
799 if (size_hint == NULL) {
800 fprintf(stderr, "Could not allocate memory for size hint\n");
801 exit(EX_UNAVAILABLE);
804 size_hint->flags = PMinSize | PBaseSize;
805 size_hint->min_width = width;
806 size_hint->base_width = width;
807 size_hint->min_height = height;
808 size_hint->base_height = height;
810 XFlush(d);
813 /* Get the width and height of the window `w' */
814 void
815 get_wh(Display *d, Window *w, int *width, int *height)
817 XWindowAttributes win_attr;
819 XGetWindowAttributes(d, *w, &win_attr);
820 *height = win_attr.height;
821 *width = win_attr.width;
824 /* find the current xinerama monitor if possible */
825 void
826 findmonitor(Display *d, int *x, int *y, int *width, int *height)
828 XineramaScreenInfo *info;
829 Window rr;
830 Window root;
831 int screens, monitors, i;
832 int rootx, rooty, winx, winy;
833 unsigned int mask;
834 short res;
836 if (!XineramaIsActive(d))
837 return;
839 screens = XScreenCount(d);
840 for (i = 0; i < screens; ++i) {
841 root = XRootWindow(d, i);
842 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
843 &winy, &mask);
844 if (res)
845 break;
848 if (!res)
849 return;
851 /* Now find in which monitor the mice is */
852 info = XineramaQueryScreens(d, &monitors);
853 if (info == NULL)
854 return;
856 for (i = 0; i < monitors; ++i) {
857 if (info[i].x_org <= rootx &&
858 rootx <= (info[i].x_org + info[i].width) &&
859 info[i].y_org <= rooty &&
860 rooty <= (info[i].y_org + info[i].height)) {
861 *x = info[i].x_org;
862 *y = info[i].y_org;
863 *width = info[i].width;
864 *height = info[i].height;
865 break;
869 XFree(info);
872 int
873 grabfocus(Display *d, Window w)
875 int i;
876 for (i = 0; i < 100; ++i) {
877 Window focuswin;
878 int revert_to_win;
880 XGetInputFocus(d, &focuswin, &revert_to_win);
882 if (focuswin == w)
883 return 1;
885 XSetInputFocus(d, w, RevertToParent, CurrentTime);
886 usleep(1000);
888 return 0;
891 /*
892 * I know this may seem a little hackish BUT is the only way I managed
893 * to actually grab that goddam keyboard. Only one call to
894 * XGrabKeyboard does not always end up with the keyboard grabbed!
895 */
896 int
897 take_keyboard(Display *d, Window w)
899 int i;
900 for (i = 0; i < 100; i++) {
901 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
902 CurrentTime) == GrabSuccess)
903 return 1;
904 usleep(1000);
906 fprintf(stderr, "Cannot grab keyboard\n");
907 return 0;
910 unsigned long
911 parse_color(const char *str, const char *def)
913 size_t len;
914 rgba_t tmp;
915 char *ep;
917 if (str == NULL)
918 goto err;
920 len = strlen(str);
922 /* +1 for the # ath the start */
923 if (*str != '#' || len > 9 || len < 4)
924 goto err;
925 ++str; /* skip the # */
927 errno = 0;
928 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
930 if (errno)
931 goto err;
933 switch (len - 1) {
934 case 3:
935 /* expand #rgb -> #rrggbb */
936 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
937 | (tmp.v & 0x00f) * 0x0011;
938 case 6:
939 /* assume 0xff opacity */
940 tmp.rgba.a = 0xff;
941 break;
942 } /* colors in #aarrggbb need no adjustments */
944 /* premultiply the alpha */
945 if (tmp.rgba.a) {
946 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
947 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
948 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
949 return tmp.v;
952 return 0U;
954 err:
955 fprintf(stderr, "Invalid color: \"%s\".\n", str);
956 if (def != NULL)
957 return parse_color(def, NULL);
958 else
959 return 0U;
962 /*
963 * Given a string try to parse it as a number or return `def'.
964 */
965 int
966 parse_integer(const char *str, int def)
968 const char *errstr;
969 int i;
971 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
972 if (errstr != NULL) {
973 warnx("'%s' is %s; using %d as default", str, errstr, def);
974 return def;
977 return i;
980 /*
981 * Like parse_integer but recognize the percentages (i.e. strings
982 * ending with `%')
983 */
984 int
985 parse_int_with_percentage(const char *str, int default_value, int max)
987 int len = strlen(str);
989 if (len > 0 && str[len - 1] == '%') {
990 int val;
991 char *cpy;
993 if ((cpy = strdup(str)) == NULL)
994 err(1, "strdup");
996 cpy[len - 1] = '\0';
997 val = parse_integer(cpy, default_value);
998 free(cpy);
999 return val * max / 100;
1002 return parse_integer(str, default_value);
1005 void
1006 get_mouse_coords(Display *d, int *x, int *y)
1008 Window w, root;
1009 int i;
1010 unsigned int u;
1012 *x = *y = 0;
1013 root = DefaultRootWindow(d);
1015 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1016 for (i = 0; i < ScreenCount(d); ++i) {
1017 if (root == RootWindow(d, i))
1018 break;
1024 * Like parse_int_with_percentage but understands some special values:
1025 * - middle that is (max-self)/2
1026 * - center = middle
1027 * - start that is 0
1028 * - end that is (max-self)
1029 * - mx x coordinate of the mouse
1030 * - my y coordinate of the mouse
1032 int
1033 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1034 int self)
1036 if (!strcmp(str, "start"))
1037 return 0;
1038 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1039 return (max - self) / 2;
1040 if (!strcmp(str, "end"))
1041 return max - self;
1042 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1043 int x, y;
1045 get_mouse_coords(d, &x, &y);
1046 if (!strcmp(str, "mx"))
1047 return x - 1;
1048 else
1049 return y - 1;
1051 return parse_int_with_percentage(str, default_value, max);
1054 /* Parse a string like a CSS value. */
1055 /* TODO: harden a bit this function */
1056 int
1057 parse_csslike(const char *str, char **ret)
1059 int i, j;
1060 char *s, *token;
1061 short any_null;
1063 memset(ret, 0, 4 * sizeof(*ret));
1065 s = strdup(str);
1066 if (s == NULL)
1067 return -1;
1069 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1070 ret[i] = strdup(token);
1072 if (i == 1)
1073 for (j = 1; j < 4; j++)
1074 ret[j] = strdup(ret[0]);
1076 if (i == 2) {
1077 ret[2] = strdup(ret[0]);
1078 ret[3] = strdup(ret[1]);
1081 if (i == 3)
1082 ret[3] = strdup(ret[1]);
1085 * before we didn't check for the return type of strdup, here
1086 * we will
1089 any_null = 0;
1090 for (i = 0; i < 4; ++i)
1091 any_null = ret[i] == NULL || any_null;
1093 if (any_null)
1094 for (i = 0; i < 4; ++i)
1095 free(ret[i]);
1097 if (i == 0 || any_null) {
1098 free(s);
1099 return -1;
1102 return 1;
1106 * Given an event, try to understand what the users wants. If the
1107 * return value is ADD_CHAR then `input' is a pointer to a string that
1108 * will need to be free'ed later.
1110 enum action
1111 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1113 char str[SYM_BUF_SIZE] = { 0 };
1114 Status s;
1116 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1117 return DEL_CHAR;
1119 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1120 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1122 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1123 return CONFIRM;
1125 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1126 return EXIT;
1128 /* Try to read what key was pressed */
1129 s = 0;
1130 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1131 if (s == XBufferOverflow) {
1132 fprintf(stderr,
1133 "Buffer overflow when trying to create keyboard "
1134 "symbol map.\n");
1135 return EXIT;
1138 if (ev->state & ControlMask) {
1139 if (!strcmp(str, "")) /* C-u */
1140 return DEL_LINE;
1141 if (!strcmp(str, "")) /* C-w */
1142 return DEL_WORD;
1143 if (!strcmp(str, "")) /* C-h */
1144 return DEL_CHAR;
1145 if (!strcmp(str, "\r")) /* C-m */
1146 return CONFIRM_CONTINUE;
1147 if (!strcmp(str, "")) /* C-p */
1148 return PREV_COMPL;
1149 if (!strcmp(str, "")) /* C-n */
1150 return NEXT_COMPL;
1151 if (!strcmp(str, "")) /* C-c */
1152 return EXIT;
1153 if (!strcmp(str, "\t")) /* C-i */
1154 return TOGGLE_FIRST_SELECTED;
1157 *input = strdup(str);
1158 if (*input == NULL) {
1159 fprintf(stderr, "Error while allocating memory for key.\n");
1160 return EXIT;
1163 return ADD_CHAR;
1166 void
1167 confirm(enum state *status, struct rendering *r, struct completions *cs,
1168 char **text, int *textlen)
1170 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1171 /* if there is something selected expand it and return */
1172 int index = cs->selected == -1 ? 0 : cs->selected;
1173 struct completion *c = cs->completions;
1174 char *t;
1176 while (1) {
1177 if (index == 0)
1178 break;
1179 c++;
1180 index--;
1183 t = c->rcompletion;
1184 free(*text);
1185 *text = strdup(t);
1187 if (*text == NULL) {
1188 fprintf(stderr, "Memory allocation error\n");
1189 *status = ERR;
1192 *textlen = strlen(*text);
1193 return;
1196 if (!r->free_text) /* cannot accept arbitrary text */
1197 *status = LOOPING;
1201 * cs: completion list
1202 * offset: the offset of the click
1203 * first: the first (rendered) item
1204 * def: the default action
1206 enum action
1207 select_clicked(struct completions *cs, size_t offset, size_t first,
1208 enum action def)
1210 ssize_t selected = first;
1211 int set = 0;
1213 if (cs->length == 0)
1214 return NO_OP;
1216 if (offset < cs->completions[selected].offset)
1217 return EXIT;
1219 /* skip the first entry */
1220 for (selected += 1; selected < cs->length; ++selected) {
1221 if (cs->completions[selected].offset == -1)
1222 break;
1224 if (offset < cs->completions[selected].offset) {
1225 cs->selected = selected - 1;
1226 set = 1;
1227 break;
1231 if (!set)
1232 cs->selected = selected - 1;
1234 return def;
1237 enum action
1238 handle_mouse(struct rendering *r, struct completions *cs,
1239 XButtonPressedEvent *e)
1241 size_t off;
1243 if (r->horizontal_layout)
1244 off = e->x;
1245 else
1246 off = e->y;
1248 switch (e->button) {
1249 case Button1:
1250 return select_clicked(cs, off, r->offset, CONFIRM);
1252 case Button3:
1253 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1255 case Button4:
1256 return SCROLL_UP;
1258 case Button5:
1259 return SCROLL_DOWN;
1262 return NO_OP;
1265 /* event loop */
1266 enum state
1267 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1268 char **lines, char **vlines)
1270 enum action a;
1271 char *input = NULL;
1272 enum state status = LOOPING;
1273 int i;
1275 while (status == LOOPING) {
1276 XEvent e;
1277 XNextEvent(r->d, &e);
1279 if (XFilterEvent(&e, r->w))
1280 continue;
1282 switch (e.type) {
1283 case KeymapNotify:
1284 XRefreshKeyboardMapping(&e.xmapping);
1285 break;
1287 case FocusIn:
1288 /* Re-grab focus */
1289 if (e.xfocus.window != r->w)
1290 grabfocus(r->d, r->w);
1291 break;
1293 case VisibilityNotify:
1294 if (e.xvisibility.state != VisibilityUnobscured)
1295 XRaiseWindow(r->d, r->w);
1296 break;
1298 case MapNotify:
1299 get_wh(r->d, &r->w, &r->width, &r->height);
1300 draw(r, *text, cs);
1301 break;
1303 case KeyPress:
1304 case ButtonPress:
1305 if (e.type == KeyPress)
1306 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1307 r->xic, &input);
1308 else
1309 a = handle_mouse(r, cs,
1310 (XButtonPressedEvent *)&e);
1312 switch (a) {
1313 case NO_OP:
1314 break;
1316 case EXIT:
1317 status = ERR;
1318 break;
1320 case CONFIRM:
1321 status = OK;
1322 confirm(&status, r, cs, text, textlen);
1323 break;
1325 case CONFIRM_CONTINUE:
1326 status = OK_LOOP;
1327 confirm(&status, r, cs, text, textlen);
1328 break;
1330 case PREV_COMPL:
1331 complete(cs, r->first_selected, 1, text,
1332 textlen, &status);
1333 r->offset = cs->selected;
1334 break;
1336 case NEXT_COMPL:
1337 complete(cs, r->first_selected, 0, text,
1338 textlen, &status);
1339 r->offset = cs->selected;
1340 break;
1342 case DEL_CHAR:
1343 popc(*text);
1344 update_completions(cs, *text, lines, vlines,
1345 r->first_selected);
1346 r->offset = 0;
1347 break;
1349 case DEL_WORD:
1350 popw(*text);
1351 update_completions(cs, *text, lines, vlines,
1352 r->first_selected);
1353 break;
1355 case DEL_LINE:
1356 for (i = 0; i < *textlen; ++i)
1357 (*text)[i] = 0;
1358 update_completions(cs, *text, lines, vlines,
1359 r->first_selected);
1360 r->offset = 0;
1361 break;
1363 case ADD_CHAR:
1365 * sometimes a strange key is pressed
1366 * i.e. ctrl alone), so input will be
1367 * empty. Don't need to update
1368 * completion in that case
1370 if (*input == '\0')
1371 break;
1373 for (i = 0; input[i] != '\0'; ++i) {
1374 *textlen = pushc(text, *textlen,
1375 input[i]);
1376 if (*textlen == -1) {
1377 fprintf(stderr,
1378 "Memory allocation "
1379 "error\n");
1380 status = ERR;
1381 break;
1385 if (status != ERR) {
1386 update_completions(cs, *text, lines,
1387 vlines, r->first_selected);
1388 free(input);
1391 r->offset = 0;
1392 break;
1394 case TOGGLE_FIRST_SELECTED:
1395 r->first_selected = !r->first_selected;
1396 if (r->first_selected && cs->selected < 0)
1397 cs->selected = 0;
1398 if (!r->first_selected && cs->selected == 0)
1399 cs->selected = -1;
1400 break;
1402 case SCROLL_DOWN:
1403 r->offset = MIN(r->offset + 1, cs->length - 1);
1404 break;
1406 case SCROLL_UP:
1407 r->offset = MAX((ssize_t)r->offset - 1, 0);
1408 break;
1412 draw(r, *text, cs);
1415 return status;
1418 int
1419 load_font(struct rendering *r, const char *fontname)
1421 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1422 return 0;
1425 void
1426 xim_init(struct rendering *r, XrmDatabase *xdb)
1428 XIMStyle best_match_style;
1429 XIMStyles *xis;
1430 int i;
1432 /* Open the X input method */
1433 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1434 err(1, "XOpenIM");
1436 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1437 fprintf(stderr, "Input Styles could not be retrieved\n");
1438 exit(EX_UNAVAILABLE);
1441 best_match_style = 0;
1442 for (i = 0; i < xis->count_styles; ++i) {
1443 XIMStyle ts = xis->supported_styles[i];
1444 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1445 best_match_style = ts;
1446 break;
1449 XFree(xis);
1451 if (!best_match_style)
1452 fprintf(stderr,
1453 "No matching input style could be determined\n");
1455 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1456 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1457 if (r->xic == NULL)
1458 err(1, "XCreateIC");
1461 void
1462 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1463 XVisualInfo vinfo, int x, int y, int ox, int oy,
1464 unsigned long background_pixel)
1466 XSetWindowAttributes attr;
1467 unsigned long vmask;
1469 /* Create the window */
1470 attr.colormap = cmap;
1471 attr.override_redirect = 1;
1472 attr.border_pixel = 0;
1473 attr.background_pixel = background_pixel;
1474 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1475 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1477 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1478 CWOverrideRedirect;
1480 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1481 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1484 void
1485 ps1extents(struct rendering *r)
1487 char *dup;
1488 dup = strdupn(r->ps1);
1489 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1490 free(dup);
1493 void
1494 usage(char *prgname)
1496 fprintf(stderr,
1497 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1498 " [-d separator] [-e window] [-f font] [-G color] [-g "
1499 "size]\n"
1500 " [-H height] [-I color] [-i size] [-J color] [-j "
1501 "size] [-l layout]\n"
1502 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1503 "color]\n"
1504 " [-t color] [-W width] [-x coord] [-y coord]\n",
1505 prgname);
1508 int
1509 main(int argc, char **argv)
1511 struct completions *cs;
1512 struct rendering r;
1513 XVisualInfo vinfo;
1514 Colormap cmap;
1515 size_t nlines, i;
1516 Window parent_window;
1517 XrmDatabase xdb;
1518 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1519 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1520 ch_borders_bg[4]; /* N E S W */
1521 enum state status = LOOPING;
1522 int ch;
1523 int offset_x = 0, offset_y = 0;
1524 int x = 0, y = 0;
1525 int textlen, d_width, d_height;
1526 short embed;
1527 const char *sep = NULL;
1528 const char *parent_window_id = NULL;
1529 char *tmp[4];
1530 char **lines, **vlines;
1531 char *fontname, *text, *xrm;
1533 setlocale(LC_ALL, getenv("LANG"));
1535 for (i = 0; i < 4; ++i) {
1536 /* default paddings */
1537 r.p_padding[i] = 10;
1538 r.c_padding[i] = 10;
1539 r.ch_padding[i] = 10;
1541 /* default borders */
1542 r.borders[i] = 0;
1543 r.p_borders[i] = 0;
1544 r.c_borders[i] = 0;
1545 r.ch_borders[i] = 0;
1548 r.first_selected = 0;
1549 r.free_text = 1;
1550 r.multiple_select = 0;
1551 r.offset = 0;
1553 /* default width and height */
1554 r.width = 400;
1555 r.height = 20;
1558 * The prompt. We duplicate the string so later is easy to
1559 * free (in the case it's been overwritten by the user)
1561 if ((r.ps1 = strdup("$ ")) == NULL)
1562 err(1, "strdup");
1564 /* same for the font name */
1565 if ((fontname = strdup(DEFFONT)) == NULL)
1566 err(1, "strdup");
1568 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1569 switch (ch) {
1570 case 'h': /* help */
1571 usage(*argv);
1572 return 0;
1573 case 'v': /* version */
1574 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1575 return 0;
1576 case 'e': /* embed */
1577 if ((parent_window_id = strdup(optarg)) == NULL)
1578 err(1, "strdup");
1579 break;
1580 case 'd':
1581 if ((sep = strdup(optarg)) == NULL)
1582 err(1, "strdup");
1583 break;
1584 case 'A':
1585 r.free_text = 0;
1586 break;
1587 case 'm':
1588 r.multiple_select = 1;
1589 break;
1590 default:
1591 break;
1595 lines = readlines(&nlines);
1597 vlines = NULL;
1598 if (sep != NULL) {
1599 int l;
1600 l = strlen(sep);
1601 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1602 err(1, "calloc");
1604 for (i = 0; i < nlines; i++) {
1605 char *t;
1606 t = strstr(lines[i], sep);
1607 if (t == NULL)
1608 vlines[i] = lines[i];
1609 else
1610 vlines[i] = t + l;
1614 textlen = 10;
1615 if ((text = malloc(textlen * sizeof(char))) == NULL)
1616 err(1, "malloc");
1618 /* struct completions *cs = filter(text, lines); */
1619 if ((cs = compls_new(nlines)) == NULL)
1620 err(1, "compls_new");
1622 /* start talking to xorg */
1623 r.d = XOpenDisplay(NULL);
1624 if (r.d == NULL) {
1625 fprintf(stderr, "Could not open display!\n");
1626 return EX_UNAVAILABLE;
1629 embed = 1;
1630 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1631 parent_window = DefaultRootWindow(r.d);
1632 embed = 0;
1635 /* get display size */
1636 get_wh(r.d, &parent_window, &d_width, &d_height);
1638 if (!embed)
1639 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1641 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1642 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1643 AllocNone);
1645 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1646 fgs[2] = parse_color("#000", NULL);
1648 bgs[0] = bgs[1] = parse_color("#000", NULL);
1649 bgs[2] = parse_color("#fff", NULL);
1651 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1652 parse_color("#000", NULL);
1654 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1655 = parse_color("#000", NULL);
1656 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1657 = parse_color("#000", NULL);
1658 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1659 = parse_color("#000", NULL);
1661 r.horizontal_layout = 1;
1663 /* Read the resources */
1664 XrmInitialize();
1665 xrm = XResourceManagerString(r.d);
1666 xdb = NULL;
1667 if (xrm != NULL) {
1668 XrmValue value;
1669 char *datatype[20];
1671 xdb = XrmGetStringDatabase(xrm);
1673 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1674 free(fontname);
1675 if ((fontname = strdup(value.addr)) == NULL)
1676 err(1, "strdup");
1677 } else {
1678 fprintf(stderr, "no font defined, using %s\n", fontname);
1681 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1682 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1683 else
1684 fprintf(stderr, "no layout defined, using horizontal\n");
1686 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1687 free(r.ps1);
1688 r.ps1 = normalize_str(value.addr);
1689 } else {
1690 fprintf(stderr,
1691 "no prompt defined, using \"%s\" as "
1692 "default\n",
1693 r.ps1);
1696 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1697 if (parse_csslike(value.addr, tmp) == -1)
1698 err(1, "parse_csslike");
1699 for (i = 0; i < 4; ++i) {
1700 r.p_borders[i] = parse_integer(tmp[i], 0);
1701 free(tmp[i]);
1705 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1706 if (parse_csslike(value.addr, tmp) == -1)
1707 err(1, "parse_csslike");
1709 for (i = 0; i < 4; ++i) {
1710 p_borders_bg[i] = parse_color(tmp[i], "#000");
1711 free(tmp[i]);
1715 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1716 if (parse_csslike(value.addr, tmp) == -1)
1717 err(1, "parse_csslike");
1719 for (i = 0; i < 4; ++i) {
1720 r.p_padding[i] = parse_integer(tmp[i], 0);
1721 free(tmp[i]);
1725 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1726 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1727 else
1728 fprintf(stderr, "no width defined, using %d\n", r.width);
1730 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1731 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1732 else
1733 fprintf(stderr, "no height defined, using %d\n", r.height);
1735 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1736 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1738 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1739 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1741 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1742 if (parse_csslike(value.addr, tmp) == -1)
1743 err(1, "parse_csslike");
1745 for (i = 0; i < 4; ++i) {
1746 r.borders[i] = parse_int_with_percentage(tmp[i], 0,
1747 (i % 2) == 0 ? d_height : d_width);
1748 free(tmp[i]);
1752 /* Prompt */
1753 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1754 fgs[0] = parse_color(value.addr, "#fff");
1756 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1757 bgs[0] = parse_color(value.addr, "#000");
1759 /* Completions */
1760 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1761 fgs[1] = parse_color(value.addr, "#fff");
1763 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1764 bgs[1] = parse_color(value.addr, "#000");
1766 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1767 if (parse_csslike(value.addr, tmp) == -1)
1768 err(1, "parse_csslike");
1770 for (i = 0; i < 4; ++i) {
1771 r.c_padding[i] = parse_integer(tmp[i], 0);
1772 free(tmp[i]);
1776 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1777 if (parse_csslike(value.addr, tmp) == -1)
1778 err(1, "parse_csslike");
1780 for (i = 0; i < 4; ++i) {
1781 r.c_borders[i] = parse_integer(tmp[i], 0);
1782 free(tmp[i]);
1786 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1787 if (parse_csslike(value.addr, tmp) == -1)
1788 err(1, "parse_csslike");
1790 for (i = 0; i < 4; ++i) {
1791 c_borders_bg[i] = parse_color(tmp[i], "#000");
1792 free(tmp[i]);
1796 /* Completion Highlighted */
1797 if (XrmGetResource(
1798 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1799 fgs[2] = parse_color(value.addr, "#000");
1801 if (XrmGetResource(
1802 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1803 bgs[2] = parse_color(value.addr, "#fff");
1805 if (XrmGetResource(
1806 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1807 if (parse_csslike(value.addr, tmp) == -1)
1808 err(1, "parse_csslike");
1810 for (i = 0; i < 4; ++i) {
1811 r.ch_padding[i] = parse_integer(tmp[i], 0);
1812 free(tmp[i]);
1816 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1817 &value)) {
1818 if (parse_csslike(value.addr, tmp) == -1)
1819 err(1, "parse_csslike");
1821 for (i = 0; i < 4; ++i) {
1822 r.ch_borders[i] = parse_integer(tmp[i], 0);
1823 free(tmp[i]);
1827 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1828 &value)) {
1829 if (parse_csslike(value.addr, tmp) == -1)
1830 err(1, "parse_csslike");
1832 for (i = 0; i < 4; ++i) {
1833 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1834 free(tmp[i]);
1838 /* Border */
1839 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1840 if (parse_csslike(value.addr, tmp) == -1)
1841 err(1, "parse_csslike");
1843 for (i = 0; i < 4; ++i) {
1844 borders_bg[i] = parse_color(tmp[i], "#000");
1845 free(tmp[i]);
1850 /* Second round of args parsing */
1851 optind = 0; /* reset the option index */
1852 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1853 switch (ch) {
1854 case 'a':
1855 r.first_selected = 1;
1856 break;
1857 case 'A':
1858 /* free_text -- already catched */
1859 case 'd':
1860 /* separator -- this case was already catched */
1861 case 'e':
1862 /* embedding mymenu this case was already catched. */
1863 case 'm':
1864 /* multiple selection this case was already catched.
1866 break;
1867 case 'p': {
1868 char *newprompt;
1869 newprompt = strdup(optarg);
1870 if (newprompt != NULL) {
1871 free(r.ps1);
1872 r.ps1 = newprompt;
1874 break;
1876 case 'x':
1877 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1878 break;
1879 case 'y':
1880 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1881 break;
1882 case 'P':
1883 if (parse_csslike(optarg, tmp) == -1)
1884 err(1, "parse_csslike");
1885 for (i = 0; i < 4; ++i)
1886 r.p_padding[i] = parse_integer(tmp[i], 0);
1887 break;
1888 case 'G':
1889 if (parse_csslike(optarg, tmp) == -1)
1890 err(1, "parse_csslike");
1891 for (i = 0; i < 4; ++i)
1892 p_borders_bg[i] = parse_color(tmp[i], "#000");
1893 break;
1894 case 'g':
1895 if (parse_csslike(optarg, tmp) == -1)
1896 err(1, "parse_csslike");
1897 for (i = 0; i < 4; ++i)
1898 r.p_borders[i] = parse_integer(tmp[i], 0);
1899 break;
1900 case 'I':
1901 if (parse_csslike(optarg, tmp) == -1)
1902 err(1, "parse_csslike");
1903 for (i = 0; i < 4; ++i)
1904 c_borders_bg[i] = parse_color(tmp[i], "#000");
1905 break;
1906 case 'i':
1907 if (parse_csslike(optarg, tmp) == -1)
1908 err(1, "parse_csslike");
1909 for (i = 0; i < 4; ++i)
1910 r.c_borders[i] = parse_integer(tmp[i], 0);
1911 break;
1912 case 'J':
1913 if (parse_csslike(optarg, tmp) == -1)
1914 err(1, "parse_csslike");
1915 for (i = 0; i < 4; ++i)
1916 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1917 break;
1918 case 'j':
1919 if (parse_csslike(optarg, tmp) == -1)
1920 err(1, "parse_csslike");
1921 for (i = 0; i < 4; ++i)
1922 r.ch_borders[i] = parse_integer(tmp[i], 0);
1923 break;
1924 case 'l':
1925 r.horizontal_layout = !strcmp(optarg, "horizontal");
1926 break;
1927 case 'f': {
1928 char *newfont;
1929 if ((newfont = strdup(optarg)) != NULL) {
1930 free(fontname);
1931 fontname = newfont;
1933 break;
1935 case 'W':
1936 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1937 break;
1938 case 'H':
1939 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1940 break;
1941 case 'b':
1942 if (parse_csslike(optarg, tmp) == -1)
1943 err(1, "parse_csslike");
1944 for (i = 0; i < 4; ++i)
1945 r.borders[i] = parse_integer(tmp[i], 0);
1946 break;
1947 case 'B':
1948 if (parse_csslike(optarg, tmp) == -1)
1949 err(1, "parse_csslike");
1950 for (i = 0; i < 4; ++i)
1951 borders_bg[i] = parse_color(tmp[i], "#000");
1952 break;
1953 case 't':
1954 fgs[0] = parse_color(optarg, NULL);
1955 break;
1956 case 'T':
1957 bgs[0] = parse_color(optarg, NULL);
1958 break;
1959 case 'c':
1960 fgs[1] = parse_color(optarg, NULL);
1961 break;
1962 case 'C':
1963 bgs[1] = parse_color(optarg, NULL);
1964 break;
1965 case 's':
1966 fgs[2] = parse_color(optarg, NULL);
1967 break;
1968 case 'S':
1969 bgs[2] = parse_color(optarg, NULL);
1970 break;
1971 default:
1972 fprintf(stderr, "Unrecognized option %c\n", ch);
1973 status = ERR;
1974 break;
1978 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1979 fprintf(stderr, "height, width, x or y are lesser than 0.");
1980 status = ERR;
1983 /* since only now we know if the first should be selected,
1984 * update the completion here */
1985 update_completions(cs, text, lines, vlines, r.first_selected);
1987 /* update the prompt lenght, only now we surely know the length of it
1989 r.ps1len = strlen(r.ps1);
1991 /* Create the window */
1992 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1993 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1994 XMapRaised(r.d, r.w);
1996 /* If embed, listen for other events as well */
1997 if (embed) {
1998 Window *children, parent, root;
1999 unsigned int children_no;
2001 XSelectInput(r.d, parent_window, FocusChangeMask);
2002 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2003 && children) {
2004 for (i = 0; i < children_no && children[i] != r.w; ++i)
2005 XSelectInput(r.d, children[i], FocusChangeMask);
2006 XFree(children);
2008 grabfocus(r.d, r.w);
2011 take_keyboard(r.d, r.w);
2013 r.x_zero = r.borders[3];
2014 r.y_zero = r.borders[0];
2017 XGCValues values;
2019 for (i = 0; i < 3; ++i) {
2020 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2021 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2024 for (i = 0; i < 4; ++i) {
2025 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2026 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2027 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2028 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2032 /* Load the colors in our GCs */
2033 for (i = 0; i < 3; ++i) {
2034 XSetForeground(r.d, r.fgs[i], fgs[i]);
2035 XSetForeground(r.d, r.bgs[i], bgs[i]);
2038 for (i = 0; i < 4; ++i) {
2039 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2040 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2041 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2042 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2045 if (load_font(&r, fontname) == -1)
2046 status = ERR;
2048 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2050 for (i = 0; i < 3; ++i) {
2051 rgba_t c;
2052 XRenderColor xrcolor;
2054 c = *(rgba_t *)&fgs[i];
2055 xrcolor.red = EXPANDBITS(c.rgba.r);
2056 xrcolor.green = EXPANDBITS(c.rgba.g);
2057 xrcolor.blue = EXPANDBITS(c.rgba.b);
2058 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2059 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2062 /* compute prompt dimensions */
2063 ps1extents(&r);
2065 xim_init(&r, &xdb);
2067 #ifdef __OpenBSD__
2068 if (pledge("stdio", "") == -1)
2069 err(1, "pledge");
2070 #endif
2072 /* Cache text height */
2073 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2075 /* Draw the window for the first time */
2076 draw(&r, text, cs);
2078 /* Main loop */
2079 while (status == LOOPING || status == OK_LOOP) {
2080 status = loop(&r, &text, &textlen, cs, lines, vlines);
2082 if (status != ERR)
2083 printf("%s\n", text);
2085 if (!r.multiple_select && status == OK_LOOP)
2086 status = OK;
2089 XUngrabKeyboard(r.d, CurrentTime);
2091 for (i = 0; i < 3; ++i)
2092 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2094 for (i = 0; i < 3; ++i) {
2095 XFreeGC(r.d, r.fgs[i]);
2096 XFreeGC(r.d, r.bgs[i]);
2099 for (i = 0; i < 4; ++i) {
2100 XFreeGC(r.d, r.borders_bg[i]);
2101 XFreeGC(r.d, r.p_borders_bg[i]);
2102 XFreeGC(r.d, r.c_borders_bg[i]);
2103 XFreeGC(r.d, r.ch_borders_bg[i]);
2106 XDestroyIC(r.xic);
2107 XCloseIM(r.xim);
2109 for (i = 0; i < 3; ++i)
2110 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2111 XftFontClose(r.d, r.font);
2112 XftDrawDestroy(r.xftdraw);
2114 free(r.ps1);
2115 free(fontname);
2116 free(text);
2118 free(lines);
2119 free(vlines);
2120 compls_delete(cs);
2122 XFreeColormap(r.d, cmap);
2124 XDestroyWindow(r.d, r.w);
2125 XCloseDisplay(r.d);
2127 return status != OK;