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 /* fallthrough */
941 case 6:
942 /* assume 0xff opacity */
943 tmp.rgba.a = 0xff;
944 break;
945 } /* colors in #aarrggbb need no adjustments */
947 /* premultiply the alpha */
948 if (tmp.rgba.a) {
949 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
950 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
951 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
952 return tmp.v;
955 return 0U;
957 err:
958 fprintf(stderr, "Invalid color: \"%s\".\n", str);
959 if (def != NULL)
960 return parse_color(def, NULL);
961 else
962 return 0U;
965 /*
966 * Given a string try to parse it as a number or return `def'.
967 */
968 static int
969 parse_integer(const char *str, int def)
971 const char *errstr;
972 int i;
974 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
975 if (errstr != NULL) {
976 warnx("'%s' is %s; using %d as default", str, errstr, def);
977 return def;
980 return i;
983 /*
984 * Like parse_integer but recognize the percentages (i.e. strings
985 * ending with `%')
986 */
987 static int
988 parse_int_with_percentage(const char *str, int default_value, int max)
990 int len = strlen(str);
992 if (len > 0 && str[len - 1] == '%') {
993 int val;
994 char *cpy;
996 if ((cpy = strdup(str)) == NULL)
997 err(1, "strdup");
999 cpy[len - 1] = '\0';
1000 val = parse_integer(cpy, default_value);
1001 free(cpy);
1002 return val * max / 100;
1005 return parse_integer(str, default_value);
1008 static void
1009 get_mouse_coords(Display *d, int *x, int *y)
1011 Window w, root;
1012 int i;
1013 unsigned int u;
1015 *x = *y = 0;
1016 root = DefaultRootWindow(d);
1018 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1019 for (i = 0; i < ScreenCount(d); ++i) {
1020 if (root == RootWindow(d, i))
1021 break;
1027 * Like parse_int_with_percentage but understands some special values:
1028 * - middle that is (max-self)/2
1029 * - center = middle
1030 * - start that is 0
1031 * - end that is (max-self)
1032 * - mx x coordinate of the mouse
1033 * - my y coordinate of the mouse
1035 static int
1036 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1037 int self)
1039 if (!strcmp(str, "start"))
1040 return 0;
1041 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1042 return (max - self) / 2;
1043 if (!strcmp(str, "end"))
1044 return max - self;
1045 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1046 int x, y;
1048 get_mouse_coords(d, &x, &y);
1049 if (!strcmp(str, "mx"))
1050 return x - 1;
1051 else
1052 return y - 1;
1054 return parse_int_with_percentage(str, default_value, max);
1057 /* Parse a string like a CSS value. */
1058 /* TODO: harden a bit this function */
1059 static int
1060 parse_csslike(const char *str, char **ret)
1062 int i, j;
1063 char *s, *token;
1064 short any_null;
1066 memset(ret, 0, 4 * sizeof(*ret));
1068 s = strdup(str);
1069 if (s == NULL)
1070 return -1;
1072 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1073 ret[i] = strdup(token);
1075 if (i == 1)
1076 for (j = 1; j < 4; j++)
1077 ret[j] = strdup(ret[0]);
1079 if (i == 2) {
1080 ret[2] = strdup(ret[0]);
1081 ret[3] = strdup(ret[1]);
1084 if (i == 3)
1085 ret[3] = strdup(ret[1]);
1088 * before we didn't check for the return type of strdup, here
1089 * we will
1092 any_null = 0;
1093 for (i = 0; i < 4; ++i)
1094 any_null = ret[i] == NULL || any_null;
1096 if (any_null)
1097 for (i = 0; i < 4; ++i)
1098 free(ret[i]);
1100 if (i == 0 || any_null) {
1101 free(s);
1102 return -1;
1105 return 1;
1109 * Given an event, try to understand what the users wants. If the
1110 * return value is ADD_CHAR then `input' is a pointer to a string that
1111 * will need to be free'ed later.
1113 static enum action
1114 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1116 char str[SYM_BUF_SIZE] = { 0 };
1117 Status s;
1119 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1120 return DEL_CHAR;
1122 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1123 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1125 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1126 return CONFIRM;
1128 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1129 return EXIT;
1131 /* Try to read what key was pressed */
1132 s = 0;
1133 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1134 if (s == XBufferOverflow) {
1135 fprintf(stderr,
1136 "Buffer overflow when trying to create keyboard "
1137 "symbol map.\n");
1138 return EXIT;
1141 if (ev->state & ControlMask) {
1142 if (!strcmp(str, "")) /* C-u */
1143 return DEL_LINE;
1144 if (!strcmp(str, "")) /* C-w */
1145 return DEL_WORD;
1146 if (!strcmp(str, "")) /* C-h */
1147 return DEL_CHAR;
1148 if (!strcmp(str, "\r")) /* C-m */
1149 return CONFIRM_CONTINUE;
1150 if (!strcmp(str, "")) /* C-p */
1151 return PREV_COMPL;
1152 if (!strcmp(str, "")) /* C-n */
1153 return NEXT_COMPL;
1154 if (!strcmp(str, "")) /* C-c */
1155 return EXIT;
1156 if (!strcmp(str, "\t")) /* C-i */
1157 return TOGGLE_FIRST_SELECTED;
1160 *input = strdup(str);
1161 if (*input == NULL) {
1162 fprintf(stderr, "Error while allocating memory for key.\n");
1163 return EXIT;
1166 return ADD_CHAR;
1169 static void
1170 confirm(enum state *status, struct rendering *r, struct completions *cs,
1171 char **text, int *textlen)
1173 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1174 /* if there is something selected expand it and return */
1175 int index = cs->selected == -1 ? 0 : cs->selected;
1176 struct completion *c = cs->completions;
1177 char *t;
1179 while (1) {
1180 if (index == 0)
1181 break;
1182 c++;
1183 index--;
1186 t = c->rcompletion;
1187 free(*text);
1188 *text = strdup(t);
1190 if (*text == NULL) {
1191 fprintf(stderr, "Memory allocation error\n");
1192 *status = ERR;
1195 *textlen = strlen(*text);
1196 return;
1199 if (!r->free_text) /* cannot accept arbitrary text */
1200 *status = LOOPING;
1204 * cs: completion list
1205 * offset: the offset of the click
1206 * first: the first (rendered) item
1207 * def: the default action
1209 static enum action
1210 select_clicked(struct completions *cs, ssize_t offset, size_t first,
1211 enum action def)
1213 ssize_t selected = first;
1214 int set = 0;
1216 if (cs->length == 0)
1217 return NO_OP;
1219 if (offset < cs->completions[selected].offset)
1220 return EXIT;
1222 /* skip the first entry */
1223 for (selected += 1; selected < (ssize_t)cs->length; ++selected) {
1224 if (cs->completions[selected].offset == -1)
1225 break;
1227 if (offset < cs->completions[selected].offset) {
1228 cs->selected = selected - 1;
1229 set = 1;
1230 break;
1234 if (!set)
1235 cs->selected = selected - 1;
1237 return def;
1240 static enum action
1241 handle_mouse(struct rendering *r, struct completions *cs,
1242 XButtonPressedEvent *e)
1244 size_t off;
1246 if (r->horizontal_layout)
1247 off = e->x;
1248 else
1249 off = e->y;
1251 switch (e->button) {
1252 case Button1:
1253 return select_clicked(cs, off, r->offset, CONFIRM);
1255 case Button3:
1256 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1258 case Button4:
1259 return SCROLL_UP;
1261 case Button5:
1262 return SCROLL_DOWN;
1265 return NO_OP;
1268 /* event loop */
1269 static enum state
1270 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1271 char **lines, char **vlines)
1273 enum action a;
1274 char *input = NULL;
1275 enum state status = LOOPING;
1276 int i;
1278 while (status == LOOPING) {
1279 XEvent e;
1280 XNextEvent(r->d, &e);
1282 if (XFilterEvent(&e, r->w))
1283 continue;
1285 switch (e.type) {
1286 case KeymapNotify:
1287 XRefreshKeyboardMapping(&e.xmapping);
1288 break;
1290 case FocusIn:
1291 /* Re-grab focus */
1292 if (e.xfocus.window != r->w)
1293 grabfocus(r->d, r->w);
1294 break;
1296 case VisibilityNotify:
1297 if (e.xvisibility.state != VisibilityUnobscured)
1298 XRaiseWindow(r->d, r->w);
1299 break;
1301 case MapNotify:
1302 get_wh(r->d, &r->w, &r->width, &r->height);
1303 draw(r, *text, cs);
1304 break;
1306 case KeyPress:
1307 case ButtonPress:
1308 if (e.type == KeyPress)
1309 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1310 r->xic, &input);
1311 else
1312 a = handle_mouse(r, cs,
1313 (XButtonPressedEvent *)&e);
1315 switch (a) {
1316 case NO_OP:
1317 break;
1319 case EXIT:
1320 status = ERR;
1321 break;
1323 case CONFIRM:
1324 status = OK;
1325 confirm(&status, r, cs, text, textlen);
1326 break;
1328 case CONFIRM_CONTINUE:
1329 status = OK_LOOP;
1330 confirm(&status, r, cs, text, textlen);
1331 break;
1333 case PREV_COMPL:
1334 complete(cs, r->first_selected, 1, text,
1335 textlen, &status);
1336 r->offset = cs->selected;
1337 break;
1339 case NEXT_COMPL:
1340 complete(cs, r->first_selected, 0, text,
1341 textlen, &status);
1342 r->offset = cs->selected;
1343 break;
1345 case DEL_CHAR:
1346 popc(*text);
1347 update_completions(cs, *text, lines, vlines,
1348 r->first_selected);
1349 r->offset = 0;
1350 break;
1352 case DEL_WORD:
1353 popw(*text);
1354 update_completions(cs, *text, lines, vlines,
1355 r->first_selected);
1356 break;
1358 case DEL_LINE:
1359 for (i = 0; i < *textlen; ++i)
1360 (*text)[i] = 0;
1361 update_completions(cs, *text, lines, vlines,
1362 r->first_selected);
1363 r->offset = 0;
1364 break;
1366 case ADD_CHAR:
1368 * sometimes a strange key is pressed
1369 * i.e. ctrl alone), so input will be
1370 * empty. Don't need to update
1371 * completion in that case
1373 if (*input == '\0')
1374 break;
1376 for (i = 0; input[i] != '\0'; ++i) {
1377 *textlen = pushc(text, *textlen,
1378 input[i]);
1379 if (*textlen == -1) {
1380 fprintf(stderr,
1381 "Memory allocation "
1382 "error\n");
1383 status = ERR;
1384 break;
1388 if (status != ERR) {
1389 update_completions(cs, *text, lines,
1390 vlines, r->first_selected);
1391 free(input);
1394 r->offset = 0;
1395 break;
1397 case TOGGLE_FIRST_SELECTED:
1398 r->first_selected = !r->first_selected;
1399 if (r->first_selected && cs->selected < 0)
1400 cs->selected = 0;
1401 if (!r->first_selected && cs->selected == 0)
1402 cs->selected = -1;
1403 break;
1405 case SCROLL_DOWN:
1406 r->offset = MIN(r->offset + 1, cs->length - 1);
1407 break;
1409 case SCROLL_UP:
1410 r->offset = MAX((ssize_t)r->offset - 1, 0);
1411 break;
1415 draw(r, *text, cs);
1418 return status;
1421 static int
1422 load_font(struct rendering *r, const char *fontname)
1424 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1425 return 0;
1428 static void
1429 xim_init(struct rendering *r, XrmDatabase *xdb)
1431 XIMStyle best_match_style;
1432 XIMStyles *xis;
1433 int i;
1435 /* Open the X input method */
1436 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1437 err(1, "XOpenIM");
1439 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1440 fprintf(stderr, "Input Styles could not be retrieved\n");
1441 exit(EX_UNAVAILABLE);
1444 best_match_style = 0;
1445 for (i = 0; i < xis->count_styles; ++i) {
1446 XIMStyle ts = xis->supported_styles[i];
1447 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1448 best_match_style = ts;
1449 break;
1452 XFree(xis);
1454 if (!best_match_style)
1455 fprintf(stderr,
1456 "No matching input style could be determined\n");
1458 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1459 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1460 if (r->xic == NULL)
1461 err(1, "XCreateIC");
1464 static void
1465 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1466 XVisualInfo vinfo, int x, int y, int ox, int oy,
1467 unsigned long background_pixel)
1469 XSetWindowAttributes attr;
1470 unsigned long vmask;
1472 /* Create the window */
1473 attr.colormap = cmap;
1474 attr.override_redirect = 1;
1475 attr.border_pixel = 0;
1476 attr.background_pixel = background_pixel;
1477 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1478 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1480 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1481 CWOverrideRedirect;
1483 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1484 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1487 static void
1488 ps1extents(struct rendering *r)
1490 char *dup;
1491 dup = strdupn(r->ps1);
1492 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1493 free(dup);
1496 static void
1497 usage(char *prgname)
1499 fprintf(stderr,
1500 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1501 " [-d separator] [-e window] [-f font] [-G color] [-g "
1502 "size]\n"
1503 " [-H height] [-I color] [-i size] [-J color] [-j "
1504 "size] [-l layout]\n"
1505 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1506 "color]\n"
1507 " [-t color] [-W width] [-x coord] [-y coord]\n",
1508 prgname);
1511 int
1512 main(int argc, char **argv)
1514 struct completions *cs;
1515 struct rendering r;
1516 XVisualInfo vinfo;
1517 Colormap cmap;
1518 size_t nlines, i;
1519 Window parent_window;
1520 XrmDatabase xdb;
1521 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1522 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1523 ch_borders_bg[4]; /* N E S W */
1524 enum state status = LOOPING;
1525 int ch;
1526 int offset_x = 0, offset_y = 0;
1527 int x = 0, y = 0;
1528 int textlen, d_width, d_height;
1529 short embed;
1530 const char *sep = NULL;
1531 const char *parent_window_id = NULL;
1532 char *tmp[4];
1533 char **lines, **vlines;
1534 char *fontname, *text, *xrm;
1536 setlocale(LC_ALL, getenv("LANG"));
1538 for (i = 0; i < 4; ++i) {
1539 /* default paddings */
1540 r.p_padding[i] = 10;
1541 r.c_padding[i] = 10;
1542 r.ch_padding[i] = 10;
1544 /* default borders */
1545 r.borders[i] = 0;
1546 r.p_borders[i] = 0;
1547 r.c_borders[i] = 0;
1548 r.ch_borders[i] = 0;
1551 r.first_selected = 0;
1552 r.free_text = 1;
1553 r.multiple_select = 0;
1554 r.offset = 0;
1556 /* default width and height */
1557 r.width = 400;
1558 r.height = 20;
1561 * The prompt. We duplicate the string so later is easy to
1562 * free (in the case it's been overwritten by the user)
1564 if ((r.ps1 = strdup("$ ")) == NULL)
1565 err(1, "strdup");
1567 /* same for the font name */
1568 if ((fontname = strdup(DEFFONT)) == NULL)
1569 err(1, "strdup");
1571 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1572 switch (ch) {
1573 case 'h': /* help */
1574 usage(*argv);
1575 return 0;
1576 case 'v': /* version */
1577 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1578 return 0;
1579 case 'e': /* embed */
1580 if ((parent_window_id = strdup(optarg)) == NULL)
1581 err(1, "strdup");
1582 break;
1583 case 'd':
1584 if ((sep = strdup(optarg)) == NULL)
1585 err(1, "strdup");
1586 break;
1587 case 'A':
1588 r.free_text = 0;
1589 break;
1590 case 'm':
1591 r.multiple_select = 1;
1592 break;
1593 default:
1594 break;
1598 lines = readlines(&nlines);
1600 vlines = NULL;
1601 if (sep != NULL) {
1602 int l;
1603 l = strlen(sep);
1604 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1605 err(1, "calloc");
1607 for (i = 0; i < nlines; i++) {
1608 char *t;
1609 t = strstr(lines[i], sep);
1610 if (t == NULL)
1611 vlines[i] = lines[i];
1612 else
1613 vlines[i] = t + l;
1617 textlen = 10;
1618 if ((text = malloc(textlen * sizeof(char))) == NULL)
1619 err(1, "malloc");
1621 /* struct completions *cs = filter(text, lines); */
1622 if ((cs = compls_new(nlines)) == NULL)
1623 err(1, "compls_new");
1625 /* start talking to xorg */
1626 r.d = XOpenDisplay(NULL);
1627 if (r.d == NULL) {
1628 fprintf(stderr, "Could not open display!\n");
1629 return EX_UNAVAILABLE;
1632 embed = 1;
1633 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1634 parent_window = DefaultRootWindow(r.d);
1635 embed = 0;
1638 /* get display size */
1639 get_wh(r.d, &parent_window, &d_width, &d_height);
1641 if (!embed)
1642 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1644 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1645 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1646 AllocNone);
1648 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1649 fgs[2] = parse_color("#000", NULL);
1651 bgs[0] = bgs[1] = parse_color("#000", NULL);
1652 bgs[2] = parse_color("#fff", NULL);
1654 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1655 parse_color("#000", NULL);
1657 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1658 = parse_color("#000", NULL);
1659 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1660 = parse_color("#000", NULL);
1661 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1662 = parse_color("#000", NULL);
1664 r.horizontal_layout = 1;
1666 /* Read the resources */
1667 XrmInitialize();
1668 xrm = XResourceManagerString(r.d);
1669 xdb = NULL;
1670 if (xrm != NULL) {
1671 XrmValue value;
1672 char *datatype[20];
1674 xdb = XrmGetStringDatabase(xrm);
1676 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1677 free(fontname);
1678 if ((fontname = strdup(value.addr)) == NULL)
1679 err(1, "strdup");
1680 } else {
1681 fprintf(stderr, "no font defined, using %s\n", fontname);
1684 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1685 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1686 else
1687 fprintf(stderr, "no layout defined, using horizontal\n");
1689 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1690 free(r.ps1);
1691 r.ps1 = normalize_str(value.addr);
1692 } else {
1693 fprintf(stderr,
1694 "no prompt defined, using \"%s\" as "
1695 "default\n",
1696 r.ps1);
1699 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1700 if (parse_csslike(value.addr, tmp) == -1)
1701 err(1, "parse_csslike");
1702 for (i = 0; i < 4; ++i) {
1703 r.p_borders[i] = parse_integer(tmp[i], 0);
1704 free(tmp[i]);
1708 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1709 if (parse_csslike(value.addr, tmp) == -1)
1710 err(1, "parse_csslike");
1712 for (i = 0; i < 4; ++i) {
1713 p_borders_bg[i] = parse_color(tmp[i], "#000");
1714 free(tmp[i]);
1718 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1719 if (parse_csslike(value.addr, tmp) == -1)
1720 err(1, "parse_csslike");
1722 for (i = 0; i < 4; ++i) {
1723 r.p_padding[i] = parse_integer(tmp[i], 0);
1724 free(tmp[i]);
1728 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1729 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1730 else
1731 fprintf(stderr, "no width defined, using %d\n", r.width);
1733 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1734 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1735 else
1736 fprintf(stderr, "no height defined, using %d\n", r.height);
1738 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1739 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1741 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1742 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1744 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1745 if (parse_csslike(value.addr, tmp) == -1)
1746 err(1, "parse_csslike");
1748 for (i = 0; i < 4; ++i) {
1749 r.borders[i] = parse_int_with_percentage(tmp[i], 0,
1750 (i % 2) == 0 ? d_height : d_width);
1751 free(tmp[i]);
1755 /* Prompt */
1756 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1757 fgs[0] = parse_color(value.addr, "#fff");
1759 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1760 bgs[0] = parse_color(value.addr, "#000");
1762 /* Completions */
1763 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1764 fgs[1] = parse_color(value.addr, "#fff");
1766 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1767 bgs[1] = parse_color(value.addr, "#000");
1769 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1770 if (parse_csslike(value.addr, tmp) == -1)
1771 err(1, "parse_csslike");
1773 for (i = 0; i < 4; ++i) {
1774 r.c_padding[i] = parse_integer(tmp[i], 0);
1775 free(tmp[i]);
1779 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1780 if (parse_csslike(value.addr, tmp) == -1)
1781 err(1, "parse_csslike");
1783 for (i = 0; i < 4; ++i) {
1784 r.c_borders[i] = parse_integer(tmp[i], 0);
1785 free(tmp[i]);
1789 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1790 if (parse_csslike(value.addr, tmp) == -1)
1791 err(1, "parse_csslike");
1793 for (i = 0; i < 4; ++i) {
1794 c_borders_bg[i] = parse_color(tmp[i], "#000");
1795 free(tmp[i]);
1799 /* Completion Highlighted */
1800 if (XrmGetResource(
1801 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1802 fgs[2] = parse_color(value.addr, "#000");
1804 if (XrmGetResource(
1805 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1806 bgs[2] = parse_color(value.addr, "#fff");
1808 if (XrmGetResource(
1809 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1810 if (parse_csslike(value.addr, tmp) == -1)
1811 err(1, "parse_csslike");
1813 for (i = 0; i < 4; ++i) {
1814 r.ch_padding[i] = parse_integer(tmp[i], 0);
1815 free(tmp[i]);
1819 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1820 &value)) {
1821 if (parse_csslike(value.addr, tmp) == -1)
1822 err(1, "parse_csslike");
1824 for (i = 0; i < 4; ++i) {
1825 r.ch_borders[i] = parse_integer(tmp[i], 0);
1826 free(tmp[i]);
1830 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1831 &value)) {
1832 if (parse_csslike(value.addr, tmp) == -1)
1833 err(1, "parse_csslike");
1835 for (i = 0; i < 4; ++i) {
1836 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1837 free(tmp[i]);
1841 /* Border */
1842 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1843 if (parse_csslike(value.addr, tmp) == -1)
1844 err(1, "parse_csslike");
1846 for (i = 0; i < 4; ++i) {
1847 borders_bg[i] = parse_color(tmp[i], "#000");
1848 free(tmp[i]);
1853 /* Second round of args parsing */
1854 optind = 0; /* reset the option index */
1855 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1856 switch (ch) {
1857 case 'a':
1858 r.first_selected = 1;
1859 break;
1860 case 'A':
1861 /* free_text -- already catched */
1862 case 'd':
1863 /* separator -- this case was already catched */
1864 case 'e':
1865 /* embedding mymenu this case was already catched. */
1866 case 'm':
1867 /* multiple selection this case was already catched.
1869 break;
1870 case 'p': {
1871 char *newprompt;
1872 newprompt = strdup(optarg);
1873 if (newprompt != NULL) {
1874 free(r.ps1);
1875 r.ps1 = newprompt;
1877 break;
1879 case 'x':
1880 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1881 break;
1882 case 'y':
1883 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1884 break;
1885 case 'P':
1886 if (parse_csslike(optarg, tmp) == -1)
1887 err(1, "parse_csslike");
1888 for (i = 0; i < 4; ++i)
1889 r.p_padding[i] = parse_integer(tmp[i], 0);
1890 break;
1891 case 'G':
1892 if (parse_csslike(optarg, tmp) == -1)
1893 err(1, "parse_csslike");
1894 for (i = 0; i < 4; ++i)
1895 p_borders_bg[i] = parse_color(tmp[i], "#000");
1896 break;
1897 case 'g':
1898 if (parse_csslike(optarg, tmp) == -1)
1899 err(1, "parse_csslike");
1900 for (i = 0; i < 4; ++i)
1901 r.p_borders[i] = parse_integer(tmp[i], 0);
1902 break;
1903 case 'I':
1904 if (parse_csslike(optarg, tmp) == -1)
1905 err(1, "parse_csslike");
1906 for (i = 0; i < 4; ++i)
1907 c_borders_bg[i] = parse_color(tmp[i], "#000");
1908 break;
1909 case 'i':
1910 if (parse_csslike(optarg, tmp) == -1)
1911 err(1, "parse_csslike");
1912 for (i = 0; i < 4; ++i)
1913 r.c_borders[i] = parse_integer(tmp[i], 0);
1914 break;
1915 case 'J':
1916 if (parse_csslike(optarg, tmp) == -1)
1917 err(1, "parse_csslike");
1918 for (i = 0; i < 4; ++i)
1919 ch_borders_bg[i] = parse_color(tmp[i], "#000");
1920 break;
1921 case 'j':
1922 if (parse_csslike(optarg, tmp) == -1)
1923 err(1, "parse_csslike");
1924 for (i = 0; i < 4; ++i)
1925 r.ch_borders[i] = parse_integer(tmp[i], 0);
1926 break;
1927 case 'l':
1928 r.horizontal_layout = !strcmp(optarg, "horizontal");
1929 break;
1930 case 'f': {
1931 char *newfont;
1932 if ((newfont = strdup(optarg)) != NULL) {
1933 free(fontname);
1934 fontname = newfont;
1936 break;
1938 case 'W':
1939 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1940 break;
1941 case 'H':
1942 r.height = parse_int_with_percentage(optarg, r.height, d_height);
1943 break;
1944 case 'b':
1945 if (parse_csslike(optarg, tmp) == -1)
1946 err(1, "parse_csslike");
1947 for (i = 0; i < 4; ++i)
1948 r.borders[i] = parse_integer(tmp[i], 0);
1949 break;
1950 case 'B':
1951 if (parse_csslike(optarg, tmp) == -1)
1952 err(1, "parse_csslike");
1953 for (i = 0; i < 4; ++i)
1954 borders_bg[i] = parse_color(tmp[i], "#000");
1955 break;
1956 case 't':
1957 fgs[0] = parse_color(optarg, NULL);
1958 break;
1959 case 'T':
1960 bgs[0] = parse_color(optarg, NULL);
1961 break;
1962 case 'c':
1963 fgs[1] = parse_color(optarg, NULL);
1964 break;
1965 case 'C':
1966 bgs[1] = parse_color(optarg, NULL);
1967 break;
1968 case 's':
1969 fgs[2] = parse_color(optarg, NULL);
1970 break;
1971 case 'S':
1972 bgs[2] = parse_color(optarg, NULL);
1973 break;
1974 default:
1975 fprintf(stderr, "Unrecognized option %c\n", ch);
1976 status = ERR;
1977 break;
1981 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
1982 fprintf(stderr, "height, width, x or y are lesser than 0.");
1983 status = ERR;
1986 /* since only now we know if the first should be selected,
1987 * update the completion here */
1988 update_completions(cs, text, lines, vlines, r.first_selected);
1990 /* update the prompt lenght, only now we surely know the length of it
1992 r.ps1len = strlen(r.ps1);
1994 /* Create the window */
1995 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
1996 set_win_atoms_hints(r.d, r.w, r.width, r.height);
1997 XMapRaised(r.d, r.w);
1999 /* If embed, listen for other events as well */
2000 if (embed) {
2001 Window *children, parent, root;
2002 unsigned int children_no;
2004 XSelectInput(r.d, parent_window, FocusChangeMask);
2005 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2006 && children) {
2007 for (i = 0; i < children_no && children[i] != r.w; ++i)
2008 XSelectInput(r.d, children[i], FocusChangeMask);
2009 XFree(children);
2011 grabfocus(r.d, r.w);
2014 take_keyboard(r.d, r.w);
2016 r.x_zero = r.borders[3];
2017 r.y_zero = r.borders[0];
2020 XGCValues values;
2022 for (i = 0; i < 3; ++i) {
2023 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2024 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2027 for (i = 0; i < 4; ++i) {
2028 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2029 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2030 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2031 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2035 /* Load the colors in our GCs */
2036 for (i = 0; i < 3; ++i) {
2037 XSetForeground(r.d, r.fgs[i], fgs[i]);
2038 XSetForeground(r.d, r.bgs[i], bgs[i]);
2041 for (i = 0; i < 4; ++i) {
2042 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2043 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2044 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2045 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2048 if (load_font(&r, fontname) == -1)
2049 status = ERR;
2051 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2053 for (i = 0; i < 3; ++i) {
2054 rgba_t c;
2055 XRenderColor xrcolor;
2057 c = *(rgba_t *)&fgs[i];
2058 xrcolor.red = EXPANDBITS(c.rgba.r);
2059 xrcolor.green = EXPANDBITS(c.rgba.g);
2060 xrcolor.blue = EXPANDBITS(c.rgba.b);
2061 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2062 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2065 /* compute prompt dimensions */
2066 ps1extents(&r);
2068 xim_init(&r, &xdb);
2070 #ifdef __OpenBSD__
2071 if (pledge("stdio", "") == -1)
2072 err(1, "pledge");
2073 #endif
2075 /* Cache text height */
2076 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2078 /* Draw the window for the first time */
2079 draw(&r, text, cs);
2081 /* Main loop */
2082 while (status == LOOPING || status == OK_LOOP) {
2083 status = loop(&r, &text, &textlen, cs, lines, vlines);
2085 if (status != ERR)
2086 printf("%s\n", text);
2088 if (!r.multiple_select && status == OK_LOOP)
2089 status = OK;
2092 XUngrabKeyboard(r.d, CurrentTime);
2094 for (i = 0; i < 3; ++i)
2095 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2097 for (i = 0; i < 3; ++i) {
2098 XFreeGC(r.d, r.fgs[i]);
2099 XFreeGC(r.d, r.bgs[i]);
2102 for (i = 0; i < 4; ++i) {
2103 XFreeGC(r.d, r.borders_bg[i]);
2104 XFreeGC(r.d, r.p_borders_bg[i]);
2105 XFreeGC(r.d, r.c_borders_bg[i]);
2106 XFreeGC(r.d, r.ch_borders_bg[i]);
2109 XDestroyIC(r.xic);
2110 XCloseIM(r.xim);
2112 for (i = 0; i < 3; ++i)
2113 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2114 XftFontClose(r.d, r.font);
2115 XftDrawDestroy(r.xftdraw);
2117 free(r.ps1);
2118 free(fontname);
2119 free(text);
2121 free(lines);
2122 free(vlines);
2123 compls_delete(cs);
2125 XFreeColormap(r.d, cmap);
2127 XDestroyWindow(r.d, r.w);
2128 XCloseDisplay(r.d);
2130 return status != OK;