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 "config.h"
19 #include <ctype.h> /* isalnum */
20 #include <err.h>
21 #include <errno.h>
22 #include <limits.h>
23 #include <locale.h> /* setlocale */
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h> /* strdup, strlen */
28 #include <sysexits.h>
29 #include <unistd.h>
31 #include <X11/Xcms.h>
32 #include <X11/Xlib.h>
33 #include <X11/Xresource.h>
34 #include <X11/Xutil.h>
35 #include <X11/keysym.h>
36 #include <X11/Xft/Xft.h>
38 #include <X11/extensions/Xinerama.h>
40 #define RESNAME "MyMenu"
41 #define RESCLASS "mymenu"
43 #define SYM_BUF_SIZE 4
45 #define DEFFONT "monospace"
47 #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:"
49 #define MIN(a, b) ((a) < (b) ? (a) : (b))
50 #define MAX(a, b) ((a) > (b) ? (a) : (b))
52 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
54 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
55 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
57 /* The states of the event loop */
58 enum state { LOOPING, OK_LOOP, OK, ERR };
60 /*
61 * For the drawing-related function. The text to be rendere could be
62 * the prompt, a completion or a highlighted completion
63 */
64 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
66 /* These are the possible action to be performed after user input. */
67 enum action {
68 NO_OP,
69 EXIT,
70 CONFIRM,
71 CONFIRM_CONTINUE,
72 NEXT_COMPL,
73 PREV_COMPL,
74 DEL_CHAR,
75 DEL_WORD,
76 DEL_LINE,
77 ADD_CHAR,
78 TOGGLE_FIRST_SELECTED,
79 SCROLL_DOWN,
80 SCROLL_UP,
81 };
83 /* A big set of values that needs to be carried around for drawing. A
84 * big struct to rule them all */
85 struct rendering {
86 Display *d; /* Connection to xorg */
87 Window w;
88 XIM xim;
89 int width;
90 int height;
91 int p_padding[4];
92 int c_padding[4];
93 int ch_padding[4];
94 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
95 the borders) */
96 int y_zero; /* like x_zero but for the y axis */
98 size_t offset; /* scroll offset */
100 short free_text;
101 short first_selected;
102 short multiple_select;
104 /* four border width */
105 int borders[4];
106 int p_borders[4];
107 int c_borders[4];
108 int ch_borders[4];
110 short horizontal_layout;
112 /* prompt */
113 char *ps1;
114 int ps1len;
115 int ps1w; /* ps1 width */
116 int ps1h; /* ps1 height */
118 int text_height; /* cache for the vertical layout */
120 XIC xic;
122 /* colors */
123 GC fgs[4];
124 GC bgs[4];
125 GC borders_bg[4];
126 GC p_borders_bg[4];
127 GC c_borders_bg[4];
128 GC ch_borders_bg[4];
129 XftFont *font;
130 XftDraw *xftdraw;
131 XftColor xft_colors[3];
132 };
134 struct completion {
135 char *completion;
136 char *rcompletion;
138 /*
139 * The X (or Y, depending on the layour) at which the item is
140 * rendered
141 */
142 ssize_t offset;
143 };
145 /* Wrap the linked list of completions */
146 struct completions {
147 struct completion *completions;
148 ssize_t selected;
149 size_t length;
150 };
152 /* idea stolen from lemonbar; ty lemonboy */
153 typedef union {
154 struct {
155 uint8_t b;
156 uint8_t g;
157 uint8_t r;
158 uint8_t a;
159 } rgba;
160 uint32_t v;
161 } rgba_t;
163 /* Return a newly allocated (and empty) completion list */
164 static struct completions *
165 compls_new(size_t length)
167 struct completions *cs = malloc(sizeof(struct completions));
169 if (cs == NULL)
170 return cs;
172 cs->completions = calloc(length, sizeof(struct completion));
173 if (cs->completions == NULL) {
174 free(cs);
175 return NULL;
178 cs->selected = -1;
179 cs->length = length;
180 return cs;
183 /* Delete the wrapper and the whole list */
184 static void
185 compls_delete(struct completions *cs)
187 if (cs == NULL)
188 return;
190 free(cs->completions);
191 free(cs);
194 /*
195 * Create a completion list from a text and the list of possible
196 * completions (null terminated). Expects a non-null `cs'. `lines' and
197 * `vlines' should have the same length OR `vlines' is NULL.
198 */
199 static void
200 filter(struct completions *cs, char *text, char **lines, char **vlines)
202 size_t index = 0;
203 size_t matching = 0;
204 char *l;
206 if (vlines == NULL)
207 vlines = lines;
209 while (1) {
210 if (lines[index] == NULL)
211 break;
213 l = vlines[index] != NULL ? vlines[index] : lines[index];
215 if (strcasestr(l, text) != NULL) {
216 struct completion *c = &cs->completions[matching];
217 c->completion = l;
218 c->rcompletion = lines[index];
219 matching++;
222 index++;
224 cs->length = matching;
225 cs->selected = -1;
228 /* Update the given completion */
229 static void
230 update_completions(struct completions *cs, char *text, char **lines,
231 char **vlines, short first_selected)
233 filter(cs, text, lines, vlines);
234 if (first_selected && cs->length > 0)
235 cs->selected = 0;
238 /*
239 * Select the next or previous selection and update some state. `text'
240 * will be updated with the text of the completion and `textlen' with
241 * the new length. If the memory cannot be allocated `status' will be
242 * set to `ERR'.
243 */
244 static void
245 complete(struct completions *cs, short first_selected, short p,
246 char **text, int *textlen, enum state *status)
248 struct completion *n;
249 int index;
251 if (cs == NULL || cs->length == 0)
252 return;
254 /*
255 * If the first is always selected and the first entry is
256 * different from the text, expand the text and return
257 */
258 if (first_selected &&
259 cs->selected == 0 &&
260 strcmp(cs->completions->completion, *text) != 0 &&
261 !p) {
262 free(*text);
263 *text = strdup(cs->completions->completion);
264 if (text == NULL) {
265 *status = ERR;
266 return;
268 *textlen = strlen(*text);
269 return;
272 index = cs->selected;
274 if (index == -1 && p)
275 index = 0;
276 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
277 % cs->length;
279 n = &cs->completions[cs->selected];
281 free(*text);
282 *text = strdup(n->completion);
283 if (text == NULL) {
284 fprintf(stderr, "Memory allocation error!\n");
285 *status = ERR;
286 return;
288 *textlen = strlen(*text);
291 /* Push the character c at the end of the string pointed by p */
292 static int
293 pushc(char **p, int maxlen, char c)
295 int len;
297 len = strnlen(*p, maxlen);
298 if (!(len < maxlen - 2)) {
299 char *newptr;
301 maxlen += maxlen >> 1;
302 newptr = realloc(*p, maxlen);
303 if (newptr == NULL) /* bad */
304 return -1;
305 *p = newptr;
308 (*p)[len] = c;
309 (*p)[len + 1] = '\0';
310 return maxlen;
313 /*
314 * Remove the last rune from the *UTF-8* string! This is different
315 * from just setting the last byte to 0 (in some cases ofc). Return a
316 * pointer (e) to the last nonzero char. If e < p then p is empty!
317 */
318 static char *
319 popc(char *p)
321 int len = strlen(p);
322 char *e;
324 if (len == 0)
325 return p;
327 e = p + len - 1;
329 do {
330 char c = *e;
332 *e = '\0';
333 e -= 1;
335 /*
336 * If c is a starting byte (11......) or is under
337 * U+007F we're done.
338 */
339 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
340 break;
341 } while (e >= p);
343 return e;
346 /* Remove the last word plus trailing white spaces from the given string */
347 static void
348 popw(char *w)
350 short in_word = 1;
352 if (*w == '\0')
353 return;
355 while (1) {
356 char *e = popc(w);
358 if (e < w)
359 return;
361 if (in_word && isspace(*e))
362 in_word = 0;
364 if (!in_word && !isspace(*e))
365 return;
369 /*
370 * If the string is surrounded by quates (`"') remove them and replace
371 * every `\"' in the string with a single double-quote.
372 */
373 static char *
374 normalize_str(const char *str)
376 int len, p;
377 char *s;
379 if ((len = strlen(str)) == 0)
380 return NULL;
382 if ((s = calloc(len, sizeof(char))) == NULL)
383 err(1, "calloc");
384 p = 0;
386 while (*str) {
387 char c = *str;
389 if (*str == '\\') {
390 if (*(str + 1)) {
391 s[p] = *(str + 1);
392 p++;
393 str += 2; /* skip this and the next char */
394 continue;
395 } else
396 break;
398 if (c == '"') {
399 str++; /* skip only this char */
400 continue;
402 s[p] = c;
403 p++;
404 str++;
407 return s;
410 static char **
411 readlines(size_t *lineslen)
413 size_t len = 0, cap = 0;
414 size_t linesize = 0;
415 ssize_t linelen;
416 char *line = NULL, **lines = NULL;
418 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
419 if (linelen != 0 && line[linelen-1] == '\n')
420 line[linelen-1] = '\0';
422 if (len == cap) {
423 size_t newcap;
424 void *t;
426 newcap = MAX(cap * 1.5, 32);
427 t = recallocarray(lines, cap, newcap, sizeof(char *));
428 if (t == NULL)
429 err(1, "recallocarray");
430 cap = newcap;
431 lines = t;
434 if ((lines[len++] = strdup(line)) == NULL)
435 err(1, "strdup");
438 if (ferror(stdin))
439 err(1, "getline");
440 free(line);
442 *lineslen = len;
443 return lines;
446 /*
447 * Compute the dimensions of the string str once rendered.
448 * It'll return the width and set ret_width and ret_height if not NULL
449 */
450 static int
451 text_extents(char *str, int len, struct rendering *r, int *ret_width,
452 int *ret_height)
454 int height, width;
455 XGlyphInfo gi;
456 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
457 height = r->font->ascent - r->font->descent;
458 width = gi.width - gi.x;
460 if (ret_width != NULL)
461 *ret_width = width;
462 if (ret_height != NULL)
463 *ret_height = height;
464 return width;
467 static void
468 draw_string(char *str, int len, int x, int y, struct rendering *r,
469 enum obj_type tt)
471 XftColor xftcolor;
472 if (tt == PROMPT)
473 xftcolor = r->xft_colors[0];
474 if (tt == COMPL)
475 xftcolor = r->xft_colors[1];
476 if (tt == COMPL_HIGH)
477 xftcolor = r->xft_colors[2];
479 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
482 /* Duplicate the string and substitute every space with a 'n` */
483 static char *
484 strdupn(char *str)
486 char *t, *dup;
488 if (str == NULL || *str == '\0')
489 return NULL;
491 if ((dup = strdup(str)) == NULL)
492 return NULL;
494 for (t = dup; *t; ++t) {
495 if (*t == ' ')
496 *t = 'n';
499 return dup;
502 static int
503 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
504 enum obj_type t, char *text)
506 GC *border_color, bg;
507 int *padding, *borders;
508 int ret = 0, inner_width, inner_height, x;
510 switch (t) {
511 case PROMPT:
512 border_color = r->p_borders_bg;
513 padding = r->p_padding;
514 borders = r->p_borders;
515 bg = r->bgs[0];
516 break;
517 case COMPL:
518 border_color = r->c_borders_bg;
519 padding = r->c_padding;
520 borders = r->c_borders;
521 bg = r->bgs[1];
522 break;
523 case COMPL_HIGH:
524 border_color = r->ch_borders_bg;
525 padding = r->ch_padding;
526 borders = r->ch_borders;
527 bg = r->bgs[2];
528 break;
531 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
533 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
534 inner_height = padding[0] + r->text_height + padding[2];
536 /* Border top */
537 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
538 borders[0]);
540 /* Border right */
541 XFillRectangle(r->d, r->w, border_color[1],
542 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
544 /* Border bottom */
545 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
546 y + borders[0] + padding[0] + r->text_height + padding[2],
547 r->width, borders[2]);
549 /* Border left */
550 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
551 ret);
553 /* bg */
554 x = r->x_zero + borders[3];
555 y += borders[0];
556 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
558 /* content */
559 y += padding[0] + r->text_height;
560 x += padding[3];
561 if (prefix != NULL) {
562 draw_string(prefix, strlen(prefix), x, y, r, t);
563 x += prefix_width;
565 draw_string(text, strlen(text), x, y, r, t);
567 return ret;
570 static int
571 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
572 enum obj_type t, char *text)
574 GC *border_color, bg;
575 int *padding, *borders;
576 int ret = 0, inner_width, inner_height, y, text_width;
578 switch (t) {
579 case PROMPT:
580 border_color = r->p_borders_bg;
581 padding = r->p_padding;
582 borders = r->p_borders;
583 bg = r->bgs[0];
584 break;
585 case COMPL:
586 border_color = r->c_borders_bg;
587 padding = r->c_padding;
588 borders = r->c_borders;
589 bg = r->bgs[1];
590 break;
591 case COMPL_HIGH:
592 border_color = r->ch_borders_bg;
593 padding = r->ch_padding;
594 borders = r->ch_borders;
595 bg = r->bgs[2];
596 break;
599 if (padding[0] < 0 || padding[2] < 0) {
600 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
601 - r->text_height;
602 padding[0] /= 2;
604 padding[2] = padding[0];
607 /* If they are still lesser than 0, set 'em to 0 */
608 if (padding[0] < 0 || padding[2] < 0)
609 padding[0] = padding[2] = 0;
611 /* Get the text width */
612 text_extents(text, strlen(text), r, &text_width, NULL);
613 if (prefix != NULL)
614 text_width += prefix_width;
616 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
618 inner_width = padding[3] + text_width + padding[1];
619 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
621 /* Border top */
622 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
623 borders[0]);
625 /* Border right */
626 XFillRectangle(r->d, r->w, border_color[1],
627 x + borders[3] + inner_width, r->y_zero, borders[1],
628 INNER_HEIGHT(r));
630 /* Border bottom */
631 XFillRectangle(r->d, r->w, border_color[2], x,
632 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
633 borders[2]);
635 /* Border left */
636 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
637 INNER_HEIGHT(r));
639 /* bg */
640 x += borders[3];
641 y = r->y_zero + borders[0];
642 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
644 /* content */
645 y += padding[0] + r->text_height;
646 x += padding[3];
647 if (prefix != NULL) {
648 draw_string(prefix, strlen(prefix), x, y, r, t);
649 x += prefix_width;
651 draw_string(text, strlen(text), x, y, r, t);
653 return ret;
656 /*
657 * ,-----------------------------------------------------------------,
658 * | 20 char text | completion | completion | completion | compl |
659 * `-----------------------------------------------------------------'
660 */
661 static void
662 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
664 size_t i;
665 int x = r->x_zero;
667 /* Draw the prompt */
668 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
670 for (i = r->offset; i < cs->length; ++i) {
671 enum obj_type t;
673 if (cs->selected == (ssize_t)i)
674 t = COMPL_HIGH;
675 else
676 t = COMPL;
678 cs->completions[i].offset = x;
680 x += draw_h_box(r, x, NULL, 0, t,
681 cs->completions[i].completion);
683 if (x > INNER_WIDTH(r))
684 break;
687 for (i += 1; i < cs->length; ++i)
688 cs->completions[i].offset = -1;
691 /*
692 * ,-----------------------------------------------------------------,
693 * | prompt |
694 * |-----------------------------------------------------------------|
695 * | completion |
696 * |-----------------------------------------------------------------|
697 * | completion |
698 * `-----------------------------------------------------------------'
699 */
700 static void
701 draw_vertically(struct rendering *r, char *text, struct completions *cs)
703 size_t i;
704 int y = r->y_zero;
706 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
708 for (i = r->offset; i < cs->length; ++i) {
709 enum obj_type t;
711 if (cs->selected == (ssize_t)i)
712 t = COMPL_HIGH;
713 else
714 t = COMPL;
716 cs->completions[i].offset = y;
718 y += draw_v_box(r, y, NULL, 0, t,
719 cs->completions[i].completion);
721 if (y > INNER_HEIGHT(r))
722 break;
725 for (i += 1; i < cs->length; ++i)
726 cs->completions[i].offset = -1;
729 static void
730 draw(struct rendering *r, char *text, struct completions *cs)
732 /* Draw the background */
733 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
734 INNER_WIDTH(r), INNER_HEIGHT(r));
736 /* Draw the contents */
737 if (r->horizontal_layout)
738 draw_horizontally(r, text, cs);
739 else
740 draw_vertically(r, text, cs);
742 /* Draw the borders */
743 if (r->borders[0] != 0)
744 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
745 r->borders[0]);
747 if (r->borders[1] != 0)
748 XFillRectangle(r->d, r->w, r->borders_bg[1],
749 r->width - r->borders[1], 0, r->borders[1],
750 r->height);
752 if (r->borders[2] != 0)
753 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
754 r->height - r->borders[2], r->width, r->borders[2]);
756 if (r->borders[3] != 0)
757 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
758 r->borders[3], r->height);
760 /* render! */
761 XFlush(r->d);
764 /* Set some WM stuff */
765 static void
766 set_win_atoms_hints(Display *d, Window w, int width, int height)
768 Atom type;
769 XClassHint *class_hint;
770 XSizeHints *size_hint;
772 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
773 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
774 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
775 (unsigned char *)&type, 1);
777 /* some window managers honor this properties */
778 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
779 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
780 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
781 (unsigned char *)&type, 1);
783 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
784 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
785 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
786 (unsigned char *)&type, 1);
788 /* Setting window hints */
789 class_hint = XAllocClassHint();
790 if (class_hint == NULL) {
791 fprintf(stderr, "Could not allocate memory for class hint\n");
792 exit(EX_UNAVAILABLE);
795 class_hint->res_name = RESNAME;
796 class_hint->res_class = RESCLASS;
797 XSetClassHint(d, w, class_hint);
798 XFree(class_hint);
800 size_hint = XAllocSizeHints();
801 if (size_hint == NULL) {
802 fprintf(stderr, "Could not allocate memory for size hint\n");
803 exit(EX_UNAVAILABLE);
806 size_hint->flags = PMinSize | PBaseSize;
807 size_hint->min_width = width;
808 size_hint->base_width = width;
809 size_hint->min_height = height;
810 size_hint->base_height = height;
812 XFlush(d);
815 /* Get the width and height of the window `w' */
816 static void
817 get_wh(Display *d, Window *w, int *width, int *height)
819 XWindowAttributes win_attr;
821 XGetWindowAttributes(d, *w, &win_attr);
822 *height = win_attr.height;
823 *width = win_attr.width;
826 /* find the current xinerama monitor if possible */
827 static void
828 findmonitor(Display *d, int *x, int *y, int *width, int *height)
830 XineramaScreenInfo *info;
831 Window rr;
832 Window root;
833 int screens, monitors, i;
834 int rootx, rooty, winx, winy;
835 unsigned int mask;
836 short res;
838 if (!XineramaIsActive(d))
839 return;
841 screens = XScreenCount(d);
842 for (i = 0; i < screens; ++i) {
843 root = XRootWindow(d, i);
844 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
845 &winy, &mask);
846 if (res)
847 break;
850 if (!res)
851 return;
853 /* Now find in which monitor the mice is */
854 info = XineramaQueryScreens(d, &monitors);
855 if (info == NULL)
856 return;
858 for (i = 0; i < monitors; ++i) {
859 if (info[i].x_org <= rootx &&
860 rootx <= (info[i].x_org + info[i].width) &&
861 info[i].y_org <= rooty &&
862 rooty <= (info[i].y_org + info[i].height)) {
863 *x = info[i].x_org;
864 *y = info[i].y_org;
865 *width = info[i].width;
866 *height = info[i].height;
867 break;
871 XFree(info);
874 static int
875 grabfocus(Display *d, Window w)
877 int i;
878 for (i = 0; i < 100; ++i) {
879 Window focuswin;
880 int revert_to_win;
882 XGetInputFocus(d, &focuswin, &revert_to_win);
884 if (focuswin == w)
885 return 1;
887 XSetInputFocus(d, w, RevertToParent, CurrentTime);
888 usleep(1000);
890 return 0;
893 /*
894 * I know this may seem a little hackish BUT is the only way I managed
895 * to actually grab that goddam keyboard. Only one call to
896 * XGrabKeyboard does not always end up with the keyboard grabbed!
897 */
898 static int
899 take_keyboard(Display *d, Window w)
901 int i;
902 for (i = 0; i < 100; i++) {
903 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
904 CurrentTime) == GrabSuccess)
905 return 1;
906 usleep(1000);
908 fprintf(stderr, "Cannot grab keyboard\n");
909 return 0;
912 static unsigned long
913 parse_color(const char *str, const char *def)
915 size_t len;
916 rgba_t tmp;
917 char *ep;
919 if (str == NULL)
920 goto err;
922 len = strlen(str);
924 /* +1 for the # ath the start */
925 if (*str != '#' || len > 9 || len < 4)
926 goto err;
927 ++str; /* skip the # */
929 errno = 0;
930 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
932 if (errno)
933 goto err;
935 switch (len - 1) {
936 case 3:
937 /* expand #rgb -> #rrggbb */
938 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
939 | (tmp.v & 0x00f) * 0x0011;
940 case 6:
941 /* assume 0xff opacity */
942 tmp.rgba.a = 0xff;
943 break;
944 } /* colors in #aarrggbb need no adjustments */
946 /* premultiply the alpha */
947 if (tmp.rgba.a) {
948 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
949 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
950 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
951 return tmp.v;
954 return 0U;
956 err:
957 fprintf(stderr, "Invalid color: \"%s\".\n", str);
958 if (def != NULL)
959 return parse_color(def, NULL);
960 else
961 return 0U;
964 /*
965 * Given a string try to parse it as a number or return `def'.
966 */
967 static int
968 parse_integer(const char *str, int def)
970 const char *errstr;
971 int i;
973 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
974 if (errstr != NULL) {
975 warnx("'%s' is %s; using %d as default", str, errstr, def);
976 return def;
979 return i;
982 /*
983 * Like parse_integer but recognize the percentages (i.e. strings
984 * ending with `%')
985 */
986 static int
987 parse_int_with_percentage(const char *str, int default_value, int max)
989 int len = strlen(str);
991 if (len > 0 && str[len - 1] == '%') {
992 int val;
993 char *cpy;
995 if ((cpy = strdup(str)) == NULL)
996 err(1, "strdup");
998 cpy[len - 1] = '\0';
999 val = parse_integer(cpy, default_value);
1000 free(cpy);
1001 return val * max / 100;
1004 return parse_integer(str, default_value);
1007 static void
1008 get_mouse_coords(Display *d, int *x, int *y)
1010 Window w, root;
1011 int i;
1012 unsigned int u;
1014 *x = *y = 0;
1015 root = DefaultRootWindow(d);
1017 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1018 for (i = 0; i < ScreenCount(d); ++i) {
1019 if (root == RootWindow(d, i))
1020 break;
1026 * Like parse_int_with_percentage but understands some special values:
1027 * - middle that is (max-self)/2
1028 * - center = middle
1029 * - start that is 0
1030 * - end that is (max-self)
1031 * - mx x coordinate of the mouse
1032 * - my y coordinate of the mouse
1034 static int
1035 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1036 int self)
1038 if (!strcmp(str, "start"))
1039 return 0;
1040 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1041 return (max - self) / 2;
1042 if (!strcmp(str, "end"))
1043 return max - self;
1044 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1045 int x, y;
1047 get_mouse_coords(d, &x, &y);
1048 if (!strcmp(str, "mx"))
1049 return x - 1;
1050 else
1051 return y - 1;
1053 return parse_int_with_percentage(str, default_value, max);
1056 /* Parse a string like a CSS value. */
1057 /* TODO: harden a bit this function */
1058 static int
1059 parse_csslike(const char *str, char **ret)
1061 int i, j;
1062 char *s, *token;
1063 short any_null;
1065 memset(ret, 0, 4 * sizeof(*ret));
1067 s = strdup(str);
1068 if (s == NULL)
1069 return -1;
1071 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1072 ret[i] = strdup(token);
1074 if (i == 1)
1075 for (j = 1; j < 4; j++)
1076 ret[j] = strdup(ret[0]);
1078 if (i == 2) {
1079 ret[2] = strdup(ret[0]);
1080 ret[3] = strdup(ret[1]);
1083 if (i == 3)
1084 ret[3] = strdup(ret[1]);
1087 * before we didn't check for the return type of strdup, here
1088 * we will
1091 any_null = 0;
1092 for (i = 0; i < 4; ++i)
1093 any_null = ret[i] == NULL || any_null;
1095 if (any_null)
1096 for (i = 0; i < 4; ++i)
1097 free(ret[i]);
1099 if (i == 0 || any_null) {
1100 free(s);
1101 return -1;
1104 return 1;
1108 * Given an event, try to understand what the users wants. If the
1109 * return value is ADD_CHAR then `input' is a pointer to a string that
1110 * will need to be free'ed later.
1112 static enum action
1113 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1115 char str[SYM_BUF_SIZE] = { 0 };
1116 Status s;
1118 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1119 return DEL_CHAR;
1121 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1122 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1124 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1125 return CONFIRM;
1127 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1128 return EXIT;
1130 /* Try to read what key was pressed */
1131 s = 0;
1132 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1133 if (s == XBufferOverflow) {
1134 fprintf(stderr,
1135 "Buffer overflow when trying to create keyboard "
1136 "symbol map.\n");
1137 return EXIT;
1140 if (ev->state & ControlMask) {
1141 if (!strcmp(str, "")) /* C-u */
1142 return DEL_LINE;
1143 if (!strcmp(str, "")) /* C-w */
1144 return DEL_WORD;
1145 if (!strcmp(str, "")) /* C-h */
1146 return DEL_CHAR;
1147 if (!strcmp(str, "\r")) /* C-m */
1148 return CONFIRM_CONTINUE;
1149 if (!strcmp(str, "")) /* C-p */
1150 return PREV_COMPL;
1151 if (!strcmp(str, "")) /* C-n */
1152 return NEXT_COMPL;
1153 if (!strcmp(str, "")) /* C-c */
1154 return EXIT;
1155 if (!strcmp(str, "\t")) /* C-i */
1156 return TOGGLE_FIRST_SELECTED;
1159 *input = strdup(str);
1160 if (*input == NULL) {
1161 fprintf(stderr, "Error while allocating memory for key.\n");
1162 return EXIT;
1165 return ADD_CHAR;
1168 static void
1169 confirm(enum state *status, struct rendering *r, struct completions *cs,
1170 char **text, int *textlen)
1172 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1173 /* if there is something selected expand it and return */
1174 int index = cs->selected == -1 ? 0 : cs->selected;
1175 struct completion *c = cs->completions;
1176 char *t;
1178 while (1) {
1179 if (index == 0)
1180 break;
1181 c++;
1182 index--;
1185 t = c->rcompletion;
1186 free(*text);
1187 *text = strdup(t);
1189 if (*text == NULL) {
1190 fprintf(stderr, "Memory allocation error\n");
1191 *status = ERR;
1194 *textlen = strlen(*text);
1195 return;
1198 if (!r->free_text) /* cannot accept arbitrary text */
1199 *status = LOOPING;
1203 * cs: completion list
1204 * offset: the offset of the click
1205 * first: the first (rendered) item
1206 * def: the default action
1208 static enum action
1209 select_clicked(struct completions *cs, ssize_t offset, size_t first,
1210 enum action def)
1212 ssize_t selected = first;
1213 int set = 0;
1215 if (cs->length == 0)
1216 return NO_OP;
1218 if (offset < cs->completions[selected].offset)
1219 return EXIT;
1221 /* skip the first entry */
1222 for (selected += 1; selected < (ssize_t)cs->length; ++selected) {
1223 if (cs->completions[selected].offset == -1)
1224 break;
1226 if (offset < cs->completions[selected].offset) {
1227 cs->selected = selected - 1;
1228 set = 1;
1229 break;
1233 if (!set)
1234 cs->selected = selected - 1;
1236 return def;
1239 static enum action
1240 handle_mouse(struct rendering *r, struct completions *cs,
1241 XButtonPressedEvent *e)
1243 size_t off;
1245 if (r->horizontal_layout)
1246 off = e->x;
1247 else
1248 off = e->y;
1250 switch (e->button) {
1251 case Button1:
1252 return select_clicked(cs, off, r->offset, CONFIRM);
1254 case Button3:
1255 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1257 case Button4:
1258 return SCROLL_UP;
1260 case Button5:
1261 return SCROLL_DOWN;
1264 return NO_OP;
1267 /* event loop */
1268 static enum state
1269 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1270 char **lines, char **vlines)
1272 enum action a;
1273 char *input = NULL;
1274 enum state status = LOOPING;
1275 int i;
1277 while (status == LOOPING) {
1278 XEvent e;
1279 XNextEvent(r->d, &e);
1281 if (XFilterEvent(&e, r->w))
1282 continue;
1284 switch (e.type) {
1285 case KeymapNotify:
1286 XRefreshKeyboardMapping(&e.xmapping);
1287 break;
1289 case FocusIn:
1290 /* Re-grab focus */
1291 if (e.xfocus.window != r->w)
1292 grabfocus(r->d, r->w);
1293 break;
1295 case VisibilityNotify:
1296 if (e.xvisibility.state != VisibilityUnobscured)
1297 XRaiseWindow(r->d, r->w);
1298 break;
1300 case MapNotify:
1301 get_wh(r->d, &r->w, &r->width, &r->height);
1302 draw(r, *text, cs);
1303 break;
1305 case KeyPress:
1306 case ButtonPress:
1307 if (e.type == KeyPress)
1308 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1309 r->xic, &input);
1310 else
1311 a = handle_mouse(r, cs,
1312 (XButtonPressedEvent *)&e);
1314 switch (a) {
1315 case NO_OP:
1316 break;
1318 case EXIT:
1319 status = ERR;
1320 break;
1322 case CONFIRM:
1323 status = OK;
1324 confirm(&status, r, cs, text, textlen);
1325 break;
1327 case CONFIRM_CONTINUE:
1328 status = OK_LOOP;
1329 confirm(&status, r, cs, text, textlen);
1330 break;
1332 case PREV_COMPL:
1333 complete(cs, r->first_selected, 1, text,
1334 textlen, &status);
1335 r->offset = cs->selected;
1336 break;
1338 case NEXT_COMPL:
1339 complete(cs, r->first_selected, 0, text,
1340 textlen, &status);
1341 r->offset = cs->selected;
1342 break;
1344 case DEL_CHAR:
1345 popc(*text);
1346 update_completions(cs, *text, lines, vlines,
1347 r->first_selected);
1348 r->offset = 0;
1349 break;
1351 case DEL_WORD:
1352 popw(*text);
1353 update_completions(cs, *text, lines, vlines,
1354 r->first_selected);
1355 break;
1357 case DEL_LINE:
1358 for (i = 0; i < *textlen; ++i)
1359 (*text)[i] = 0;
1360 update_completions(cs, *text, lines, vlines,
1361 r->first_selected);
1362 r->offset = 0;
1363 break;
1365 case ADD_CHAR:
1367 * sometimes a strange key is pressed
1368 * i.e. ctrl alone), so input will be
1369 * empty. Don't need to update
1370 * completion in that case
1372 if (*input == '\0')
1373 break;
1375 for (i = 0; input[i] != '\0'; ++i) {
1376 *textlen = pushc(text, *textlen,
1377 input[i]);
1378 if (*textlen == -1) {
1379 fprintf(stderr,
1380 "Memory allocation "
1381 "error\n");
1382 status = ERR;
1383 break;
1387 if (status != ERR) {
1388 update_completions(cs, *text, lines,
1389 vlines, r->first_selected);
1390 free(input);
1393 r->offset = 0;
1394 break;
1396 case TOGGLE_FIRST_SELECTED:
1397 r->first_selected = !r->first_selected;
1398 if (r->first_selected && cs->selected < 0)
1399 cs->selected = 0;
1400 if (!r->first_selected && cs->selected == 0)
1401 cs->selected = -1;
1402 break;
1404 case SCROLL_DOWN:
1405 r->offset = MIN(r->offset + 1, cs->length - 1);
1406 break;
1408 case SCROLL_UP:
1409 r->offset = MAX((ssize_t)r->offset - 1, 0);
1410 break;
1414 draw(r, *text, cs);
1417 return status;
1420 static int
1421 load_font(struct rendering *r, const char *fontname)
1423 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1424 return 0;
1427 static void
1428 xim_init(struct rendering *r, XrmDatabase *xdb)
1430 XIMStyle best_match_style;
1431 XIMStyles *xis;
1432 int i;
1434 /* Open the X input method */
1435 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1436 err(1, "XOpenIM");
1438 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1439 fprintf(stderr, "Input Styles could not be retrieved\n");
1440 exit(EX_UNAVAILABLE);
1443 best_match_style = 0;
1444 for (i = 0; i < xis->count_styles; ++i) {
1445 XIMStyle ts = xis->supported_styles[i];
1446 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1447 best_match_style = ts;
1448 break;
1451 XFree(xis);
1453 if (!best_match_style)
1454 fprintf(stderr,
1455 "No matching input style could be determined\n");
1457 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1458 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1459 if (r->xic == NULL)
1460 err(1, "XCreateIC");
1463 static void
1464 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1465 XVisualInfo vinfo, int x, int y, int ox, int oy,
1466 unsigned long background_pixel)
1468 XSetWindowAttributes attr;
1469 unsigned long vmask;
1471 /* Create the window */
1472 attr.colormap = cmap;
1473 attr.override_redirect = 1;
1474 attr.border_pixel = 0;
1475 attr.background_pixel = background_pixel;
1476 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1477 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1479 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1480 CWOverrideRedirect;
1482 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1483 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1486 static void
1487 ps1extents(struct rendering *r)
1489 char *dup;
1490 dup = strdupn(r->ps1);
1491 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1492 free(dup);
1495 static void
1496 usage(char *prgname)
1498 fprintf(stderr,
1499 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1500 " [-d separator] [-e window] [-f font] [-G color] [-g "
1501 "size]\n"
1502 " [-H height] [-I color] [-i size] [-J color] [-j "
1503 "size] [-l layout]\n"
1504 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1505 "color]\n"
1506 " [-t color] [-W width] [-x coord] [-y coord]\n",
1507 prgname);
1510 int
1511 main(int argc, char **argv)
1513 struct completions *cs;
1514 struct rendering r;
1515 XVisualInfo vinfo;
1516 Colormap cmap;
1517 size_t nlines, i;
1518 Window parent_window;
1519 XrmDatabase xdb;
1520 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1521 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1522 ch_borders_bg[4]; /* N E S W */
1523 enum state status = LOOPING;
1524 int ch;
1525 int offset_x = 0, offset_y = 0;
1526 int x = 0, y = 0;
1527 int textlen, d_width, d_height;
1528 short embed;
1529 const char *sep = NULL;
1530 const char *parent_window_id = NULL;
1531 char *tmp[4];
1532 char **lines, **vlines;
1533 char *fontname, *text, *xrm;
1535 setlocale(LC_ALL, getenv("LANG"));
1537 for (i = 0; i < 4; ++i) {
1538 /* default paddings */
1539 r.p_padding[i] = 10;
1540 r.c_padding[i] = 10;
1541 r.ch_padding[i] = 10;
1543 /* default borders */
1544 r.borders[i] = 0;
1545 r.p_borders[i] = 0;
1546 r.c_borders[i] = 0;
1547 r.ch_borders[i] = 0;
1550 r.first_selected = 0;
1551 r.free_text = 1;
1552 r.multiple_select = 0;
1553 r.offset = 0;
1555 /* default width and height */
1556 r.width = 400;
1557 r.height = 20;
1560 * The prompt. We duplicate the string so later is easy to
1561 * free (in the case it's been overwritten by the user)
1563 if ((r.ps1 = strdup("$ ")) == NULL)
1564 err(1, "strdup");
1566 /* same for the font name */
1567 if ((fontname = strdup(DEFFONT)) == NULL)
1568 err(1, "strdup");
1570 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1571 switch (ch) {
1572 case 'h': /* help */
1573 usage(*argv);
1574 return 0;
1575 case 'v': /* version */
1576 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1577 return 0;
1578 case 'e': /* embed */
1579 if ((parent_window_id = strdup(optarg)) == NULL)
1580 err(1, "strdup");
1581 break;
1582 case 'd':
1583 if ((sep = strdup(optarg)) == NULL)
1584 err(1, "strdup");
1585 break;
1586 case 'A':
1587 r.free_text = 0;
1588 break;
1589 case 'm':
1590 r.multiple_select = 1;
1591 break;
1592 default:
1593 break;
1597 lines = readlines(&nlines);
1599 vlines = NULL;
1600 if (sep != NULL) {
1601 int l;
1602 l = strlen(sep);
1603 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1604 err(1, "calloc");
1606 for (i = 0; i < nlines; i++) {
1607 char *t;
1608 t = strstr(lines[i], sep);
1609 if (t == NULL)
1610 vlines[i] = lines[i];
1611 else
1612 vlines[i] = t + l;
1616 textlen = 10;
1617 if ((text = malloc(textlen * sizeof(char))) == NULL)
1618 err(1, "malloc");
1620 /* struct completions *cs = filter(text, lines); */
1621 if ((cs = compls_new(nlines)) == NULL)
1622 err(1, "compls_new");
1624 /* start talking to xorg */
1625 r.d = XOpenDisplay(NULL);
1626 if (r.d == NULL) {
1627 fprintf(stderr, "Could not open display!\n");
1628 return EX_UNAVAILABLE;
1631 embed = 1;
1632 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1633 parent_window = DefaultRootWindow(r.d);
1634 embed = 0;
1637 /* get display size */
1638 get_wh(r.d, &parent_window, &d_width, &d_height);
1640 if (!embed)
1641 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1643 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1644 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1645 AllocNone);
1647 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1648 fgs[2] = parse_color("#000", NULL);
1650 bgs[0] = bgs[1] = parse_color("#000", NULL);
1651 bgs[2] = parse_color("#fff", NULL);
1653 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1654 parse_color("#000", NULL);
1656 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1657 = parse_color("#000", NULL);
1658 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1659 = parse_color("#000", NULL);
1660 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1661 = parse_color("#000", NULL);
1663 r.horizontal_layout = 1;
1665 /* Read the resources */
1666 XrmInitialize();
1667 xrm = XResourceManagerString(r.d);
1668 xdb = NULL;
1669 if (xrm != NULL) {
1670 XrmValue value;
1671 char *datatype[20];
1673 xdb = XrmGetStringDatabase(xrm);
1675 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1676 free(fontname);
1677 if ((fontname = strdup(value.addr)) == NULL)
1678 err(1, "strdup");
1679 } else {
1680 fprintf(stderr, "no font defined, using %s\n", fontname);
1683 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1684 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1685 else
1686 fprintf(stderr, "no layout defined, using horizontal\n");
1688 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1689 free(r.ps1);
1690 r.ps1 = normalize_str(value.addr);
1691 } else {
1692 fprintf(stderr,
1693 "no prompt defined, using \"%s\" as "
1694 "default\n",
1695 r.ps1);
1698 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1699 if (parse_csslike(value.addr, tmp) == -1)
1700 err(1, "parse_csslike");
1701 for (i = 0; i < 4; ++i) {
1702 r.p_borders[i] = parse_integer(tmp[i], 0);
1703 free(tmp[i]);
1707 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1708 if (parse_csslike(value.addr, tmp) == -1)
1709 err(1, "parse_csslike");
1711 for (i = 0; i < 4; ++i) {
1712 p_borders_bg[i] = parse_color(tmp[i], "#000");
1713 free(tmp[i]);
1717 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1718 if (parse_csslike(value.addr, tmp) == -1)
1719 err(1, "parse_csslike");
1721 for (i = 0; i < 4; ++i) {
1722 r.p_padding[i] = parse_integer(tmp[i], 0);
1723 free(tmp[i]);
1727 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1728 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1729 else
1730 fprintf(stderr, "no width defined, using %d\n", r.width);
1732 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1733 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1734 else
1735 fprintf(stderr, "no height defined, using %d\n", r.height);
1737 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1738 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1740 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1741 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1743 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1744 if (parse_csslike(value.addr, tmp) == -1)
1745 err(1, "parse_csslike");
1747 for (i = 0; i < 4; ++i) {
1748 r.borders[i] = parse_int_with_percentage(tmp[i], 0,
1749 (i % 2) == 0 ? d_height : d_width);
1750 free(tmp[i]);
1754 /* Prompt */
1755 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1756 fgs[0] = parse_color(value.addr, "#fff");
1758 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1759 bgs[0] = parse_color(value.addr, "#000");
1761 /* Completions */
1762 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1763 fgs[1] = parse_color(value.addr, "#fff");
1765 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1766 bgs[1] = parse_color(value.addr, "#000");
1768 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1769 if (parse_csslike(value.addr, tmp) == -1)
1770 err(1, "parse_csslike");
1772 for (i = 0; i < 4; ++i) {
1773 r.c_padding[i] = parse_integer(tmp[i], 0);
1774 free(tmp[i]);
1778 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1779 if (parse_csslike(value.addr, tmp) == -1)
1780 err(1, "parse_csslike");
1782 for (i = 0; i < 4; ++i) {
1783 r.c_borders[i] = parse_integer(tmp[i], 0);
1784 free(tmp[i]);
1788 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1789 if (parse_csslike(value.addr, tmp) == -1)
1790 err(1, "parse_csslike");
1792 for (i = 0; i < 4; ++i) {
1793 c_borders_bg[i] = parse_color(tmp[i], "#000");
1794 free(tmp[i]);
1798 /* Completion Highlighted */
1799 if (XrmGetResource(
1800 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1801 fgs[2] = parse_color(value.addr, "#000");
1803 if (XrmGetResource(
1804 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1805 bgs[2] = parse_color(value.addr, "#fff");
1807 if (XrmGetResource(
1808 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1809 if (parse_csslike(value.addr, tmp) == -1)
1810 err(1, "parse_csslike");
1812 for (i = 0; i < 4; ++i) {
1813 r.ch_padding[i] = parse_integer(tmp[i], 0);
1814 free(tmp[i]);
1818 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1819 &value)) {
1820 if (parse_csslike(value.addr, tmp) == -1)
1821 err(1, "parse_csslike");
1823 for (i = 0; i < 4; ++i) {
1824 r.ch_borders[i] = parse_integer(tmp[i], 0);
1825 free(tmp[i]);
1829 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1830 &value)) {
1831 if (parse_csslike(value.addr, tmp) == -1)
1832 err(1, "parse_csslike");
1834 for (i = 0; i < 4; ++i) {
1835 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1836 free(tmp[i]);
1840 /* Border */
1841 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1842 if (parse_csslike(value.addr, tmp) == -1)
1843 err(1, "parse_csslike");
1845 for (i = 0; i < 4; ++i) {
1846 borders_bg[i] = parse_color(tmp[i], "#000");
1847 free(tmp[i]);
1852 /* Second round of args parsing */
1853 optind = 0; /* reset the option index */
1854 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1855 switch (ch) {
1856 case 'a':
1857 r.first_selected = 1;
1858 break;
1859 case 'A':
1860 /* free_text -- already catched */
1861 case 'd':
1862 /* separator -- this case was already catched */
1863 case 'e':
1864 /* embedding mymenu this case was already catched. */
1865 case 'm':
1866 /* multiple selection this case was already catched.
1868 break;
1869 case 'p': {
1870 char *newprompt;
1871 newprompt = strdup(optarg);
1872 if (newprompt != NULL) {
1873 free(r.ps1);
1874 r.ps1 = newprompt;
1876 break;
1878 case 'x':
1879 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1880 break;
1881 case 'y':
1882 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1883 break;
1884 case 'P':
1885 if (parse_csslike(optarg, tmp) == -1)
1886 err(1, "parse_csslike");
1887 for (i = 0; i < 4; ++i)
1888 r.p_padding[i] = parse_integer(tmp[i], 0);
1889 break;
1890 case 'G':
1891 if (parse_csslike(optarg, tmp) == -1)
1892 err(1, "parse_csslike");
1893 for (i = 0; i < 4; ++i)
1894 p_borders_bg[i] = parse_color(tmp[i], "#000");
1895 break;
1896 case 'g':
1897 if (parse_csslike(optarg, tmp) == -1)
1898 err(1, "parse_csslike");
1899 for (i = 0; i < 4; ++i)
1900 r.p_borders[i] = parse_integer(tmp[i], 0);
1901 break;
1902 case 'I':
1903 if (parse_csslike(optarg, tmp) == -1)
1904 err(1, "parse_csslike");
1905 for (i = 0; i < 4; ++i)
1906 c_borders_bg[i] = parse_color(tmp[i], "#000");
1907 break;
1908 case 'i':
1909 if (parse_csslike(optarg, tmp) == -1)
1910 err(1, "parse_csslike");
1911 for (i = 0; i < 4; ++i)
1912 r.c_borders[i] = parse_integer(tmp[i], 0);
1913 break;
1914 case 'J':
1915 if (parse_csslike(optarg, tmp) == -1)
1916 err(1, "parse_csslike");
1917 for (i = 0; i < 4; ++i)
1918 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1919 break;
1920 case 'j':
1921 if (parse_csslike(optarg, tmp) == -1)
1922 err(1, "parse_csslike");
1923 for (i = 0; i < 4; ++i)
1924 r.ch_borders[i] = parse_integer(tmp[i], 0);
1925 break;
1926 case 'l':
1927 r.horizontal_layout = !strcmp(optarg, "horizontal");
1928 break;
1929 case 'f': {
1930 char *newfont;
1931 if ((newfont = strdup(optarg)) != NULL) {
1932 free(fontname);
1933 fontname = newfont;
1935 break;
1937 case 'W':
1938 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1939 break;
1940 case 'H':
1941 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1942 break;
1943 case 'b':
1944 if (parse_csslike(optarg, tmp) == -1)
1945 err(1, "parse_csslike");
1946 for (i = 0; i < 4; ++i)
1947 r.borders[i] = parse_integer(tmp[i], 0);
1948 break;
1949 case 'B':
1950 if (parse_csslike(optarg, tmp) == -1)
1951 err(1, "parse_csslike");
1952 for (i = 0; i < 4; ++i)
1953 borders_bg[i] = parse_color(tmp[i], "#000");
1954 break;
1955 case 't':
1956 fgs[0] = parse_color(optarg, NULL);
1957 break;
1958 case 'T':
1959 bgs[0] = parse_color(optarg, NULL);
1960 break;
1961 case 'c':
1962 fgs[1] = parse_color(optarg, NULL);
1963 break;
1964 case 'C':
1965 bgs[1] = parse_color(optarg, NULL);
1966 break;
1967 case 's':
1968 fgs[2] = parse_color(optarg, NULL);
1969 break;
1970 case 'S':
1971 bgs[2] = parse_color(optarg, NULL);
1972 break;
1973 default:
1974 fprintf(stderr, "Unrecognized option %c\n", ch);
1975 status = ERR;
1976 break;
1980 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1981 fprintf(stderr, "height, width, x or y are lesser than 0.");
1982 status = ERR;
1985 /* since only now we know if the first should be selected,
1986 * update the completion here */
1987 update_completions(cs, text, lines, vlines, r.first_selected);
1989 /* update the prompt lenght, only now we surely know the length of it
1991 r.ps1len = strlen(r.ps1);
1993 /* Create the window */
1994 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1995 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1996 XMapRaised(r.d, r.w);
1998 /* If embed, listen for other events as well */
1999 if (embed) {
2000 Window *children, parent, root;
2001 unsigned int children_no;
2003 XSelectInput(r.d, parent_window, FocusChangeMask);
2004 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2005 && children) {
2006 for (i = 0; i < children_no && children[i] != r.w; ++i)
2007 XSelectInput(r.d, children[i], FocusChangeMask);
2008 XFree(children);
2010 grabfocus(r.d, r.w);
2013 take_keyboard(r.d, r.w);
2015 r.x_zero = r.borders[3];
2016 r.y_zero = r.borders[0];
2019 XGCValues values;
2021 for (i = 0; i < 3; ++i) {
2022 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2023 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2026 for (i = 0; i < 4; ++i) {
2027 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2028 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2029 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2030 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2034 /* Load the colors in our GCs */
2035 for (i = 0; i < 3; ++i) {
2036 XSetForeground(r.d, r.fgs[i], fgs[i]);
2037 XSetForeground(r.d, r.bgs[i], bgs[i]);
2040 for (i = 0; i < 4; ++i) {
2041 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2042 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2043 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2044 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2047 if (load_font(&r, fontname) == -1)
2048 status = ERR;
2050 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2052 for (i = 0; i < 3; ++i) {
2053 rgba_t c;
2054 XRenderColor xrcolor;
2056 c = *(rgba_t *)&fgs[i];
2057 xrcolor.red = EXPANDBITS(c.rgba.r);
2058 xrcolor.green = EXPANDBITS(c.rgba.g);
2059 xrcolor.blue = EXPANDBITS(c.rgba.b);
2060 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2061 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2064 /* compute prompt dimensions */
2065 ps1extents(&r);
2067 xim_init(&r, &xdb);
2069 #ifdef __OpenBSD__
2070 if (pledge("stdio", "") == -1)
2071 err(1, "pledge");
2072 #endif
2074 /* Cache text height */
2075 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2077 /* Draw the window for the first time */
2078 draw(&r, text, cs);
2080 /* Main loop */
2081 while (status == LOOPING || status == OK_LOOP) {
2082 status = loop(&r, &text, &textlen, cs, lines, vlines);
2084 if (status != ERR)
2085 printf("%s\n", text);
2087 if (!r.multiple_select && status == OK_LOOP)
2088 status = OK;
2091 XUngrabKeyboard(r.d, CurrentTime);
2093 for (i = 0; i < 3; ++i)
2094 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2096 for (i = 0; i < 3; ++i) {
2097 XFreeGC(r.d, r.fgs[i]);
2098 XFreeGC(r.d, r.bgs[i]);
2101 for (i = 0; i < 4; ++i) {
2102 XFreeGC(r.d, r.borders_bg[i]);
2103 XFreeGC(r.d, r.p_borders_bg[i]);
2104 XFreeGC(r.d, r.c_borders_bg[i]);
2105 XFreeGC(r.d, r.ch_borders_bg[i]);
2108 XDestroyIC(r.xic);
2109 XCloseIM(r.xim);
2111 for (i = 0; i < 3; ++i)
2112 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2113 XftFontClose(r.d, r.font);
2114 XftDrawDestroy(r.xftdraw);
2116 free(r.ps1);
2117 free(fontname);
2118 free(text);
2120 free(lines);
2121 free(vlines);
2122 compls_delete(cs);
2124 XFreeColormap(r.d, cmap);
2126 XDestroyWindow(r.d, r.w);
2127 XCloseDisplay(r.d);
2129 return status != OK;