Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020, 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <ctype.h> /* isalnum */
18 #include <err.h>
19 #include <errno.h>
20 #include <limits.h>
21 #include <locale.h> /* setlocale */
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h> /* strdup, strlen */
26 #include <sysexits.h>
27 #include <unistd.h>
29 #include <X11/Xcms.h>
30 #include <X11/Xlib.h>
31 #include <X11/Xresource.h>
32 #include <X11/Xutil.h>
33 #include <X11/keysym.h>
34 #include <X11/Xft/Xft.h>
36 #include <X11/extensions/Xinerama.h>
38 #define RESNAME "MyMenu"
39 #define RESCLASS "mymenu"
41 #define SYM_BUF_SIZE 4
43 #define DEFFONT "monospace"
45 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
52 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
53 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
55 /* The states of the event loop */
56 enum state { LOOPING, OK_LOOP, OK, ERR };
58 /*
59 * For the drawing-related function. The text to be rendere could be
60 * the prompt, a completion or a highlighted completion
61 */
62 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
64 /* These are the possible action to be performed after user input. */
65 enum action {
66 NO_OP,
67 EXIT,
68 CONFIRM,
69 CONFIRM_CONTINUE,
70 NEXT_COMPL,
71 PREV_COMPL,
72 DEL_CHAR,
73 DEL_WORD,
74 DEL_LINE,
75 ADD_CHAR,
76 TOGGLE_FIRST_SELECTED,
77 SCROLL_DOWN,
78 SCROLL_UP,
79 };
81 /* A big set of values that needs to be carried around for drawing. A
82 * big struct to rule them all */
83 struct rendering {
84 Display *d; /* Connection to xorg */
85 Window w;
86 XIM xim;
87 int width;
88 int height;
89 int p_padding[4];
90 int c_padding[4];
91 int ch_padding[4];
92 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
93 the borders) */
94 int y_zero; /* like x_zero but for the y axis */
96 int offset; /* scroll offset */
98 short free_text;
99 short first_selected;
100 short multiple_select;
102 /* four border width */
103 int borders[4];
104 int p_borders[4];
105 int c_borders[4];
106 int ch_borders[4];
108 short horizontal_layout;
110 /* prompt */
111 char *ps1;
112 int ps1len;
113 int ps1w; /* ps1 width */
114 int ps1h; /* ps1 height */
116 int text_height; /* cache for the vertical layout */
118 XIC xic;
120 /* colors */
121 GC fgs[4];
122 GC bgs[4];
123 GC borders_bg[4];
124 GC p_borders_bg[4];
125 GC c_borders_bg[4];
126 GC ch_borders_bg[4];
127 XftFont *font;
128 XftDraw *xftdraw;
129 XftColor xft_colors[3];
130 };
132 struct completion {
133 char *completion;
134 char *rcompletion;
136 /*
137 * The X (or Y, depending on the layour) at which the item is
138 * rendered
139 */
140 int offset;
141 };
143 /* Wrap the linked list of completions */
144 struct completions {
145 struct completion *completions;
146 ssize_t selected;
147 size_t length;
148 };
150 /* idea stolen from lemonbar; ty lemonboy */
151 typedef union {
152 struct {
153 uint8_t b;
154 uint8_t g;
155 uint8_t r;
156 uint8_t a;
157 } rgba;
158 uint32_t v;
159 } rgba_t;
161 extern char *optarg;
162 extern int optind;
164 /* Return a newly allocated (and empty) completion list */
165 struct completions *
166 compls_new(size_t length)
168 struct completions *cs = malloc(sizeof(struct completions));
170 if (cs == NULL)
171 return cs;
173 cs->completions = calloc(length, sizeof(struct completion));
174 if (cs->completions == NULL) {
175 free(cs);
176 return NULL;
179 cs->selected = -1;
180 cs->length = length;
181 return cs;
184 /* Delete the wrapper and the whole list */
185 void
186 compls_delete(struct completions *cs)
188 if (cs == NULL)
189 return;
191 free(cs->completions);
192 free(cs);
195 /*
196 * Create a completion list from a text and the list of possible
197 * completions (null terminated). Expects a non-null `cs'. `lines' and
198 * `vlines' should have the same length OR `vlines' is NULL.
199 */
200 void
201 filter(struct completions *cs, char *text, char **lines, char **vlines)
203 size_t index = 0;
204 size_t matching = 0;
205 char *l;
207 if (vlines == NULL)
208 vlines = lines;
210 while (1) {
211 if (lines[index] == NULL)
212 break;
214 l = vlines[index] != NULL ? vlines[index] : lines[index];
216 if (strcasestr(l, text) != NULL) {
217 struct completion *c = &cs->completions[matching];
218 c->completion = l;
219 c->rcompletion = lines[index];
220 matching++;
223 index++;
225 cs->length = matching;
226 cs->selected = -1;
229 /* Update the given completion */
230 void
231 update_completions(struct completions *cs, char *text, char **lines,
232 char **vlines, short first_selected)
234 filter(cs, text, lines, vlines);
235 if (first_selected && cs->length > 0)
236 cs->selected = 0;
239 /*
240 * Select the next or previous selection and update some state. `text'
241 * will be updated with the text of the completion and `textlen' with
242 * the new length. If the memory cannot be allocated `status' will be
243 * set to `ERR'.
244 */
245 void
246 complete(struct completions *cs, short first_selected, short p,
247 char **text, int *textlen, enum state *status)
249 struct completion *n;
250 int index;
252 if (cs == NULL || cs->length == 0)
253 return;
255 /*
256 * If the first is always selected and the first entry is
257 * different from the text, expand the text and return
258 */
259 if (first_selected &&
260 cs->selected == 0 &&
261 strcmp(cs->completions->completion, *text) != 0 &&
262 !p) {
263 free(*text);
264 *text = strdup(cs->completions->completion);
265 if (text == NULL) {
266 *status = ERR;
267 return;
269 *textlen = strlen(*text);
270 return;
273 index = cs->selected;
275 if (index == -1 && p)
276 index = 0;
277 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
278 % cs->length;
280 n = &cs->completions[cs->selected];
282 free(*text);
283 *text = strdup(n->completion);
284 if (text == NULL) {
285 fprintf(stderr, "Memory allocation error!\n");
286 *status = ERR;
287 return;
289 *textlen = strlen(*text);
292 /* Push the character c at the end of the string pointed by p */
293 int
294 pushc(char **p, int maxlen, char c)
296 int len;
298 len = strnlen(*p, maxlen);
299 if (!(len < maxlen - 2)) {
300 char *newptr;
302 maxlen += maxlen >> 1;
303 newptr = realloc(*p, maxlen);
304 if (newptr == NULL) /* bad */
305 return -1;
306 *p = newptr;
309 (*p)[len] = c;
310 (*p)[len + 1] = '\0';
311 return maxlen;
314 /*
315 * Remove the last rune from the *UTF-8* string! This is different
316 * from just setting the last byte to 0 (in some cases ofc). Return a
317 * pointer (e) to the last nonzero char. If e < p then p is empty!
318 */
319 char *
320 popc(char *p)
322 int len = strlen(p);
323 char *e;
325 if (len == 0)
326 return p;
328 e = p + len - 1;
330 do {
331 char c = *e;
333 *e = '\0';
334 e -= 1;
336 /*
337 * If c is a starting byte (11......) or is under
338 * U+007F we're done.
339 */
340 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
341 break;
342 } while (e >= p);
344 return e;
347 /* Remove the last word plus trailing white spaces from the given string */
348 void
349 popw(char *w)
351 int len;
352 short in_word = 1;
354 if ((len = strlen(w)) == 0)
355 return;
357 while (1) {
358 char *e = popc(w);
360 if (e < w)
361 return;
363 if (in_word && isspace(*e))
364 in_word = 0;
366 if (!in_word && !isspace(*e))
367 return;
371 /*
372 * If the string is surrounded by quates (`"') remove them and replace
373 * every `\"' in the string with a single double-quote.
374 */
375 char *
376 normalize_str(const char *str)
378 int len, p;
379 char *s;
381 if ((len = strlen(str)) == 0)
382 return NULL;
384 if ((s = calloc(len, sizeof(char))) == NULL)
385 err(1, "calloc");
386 p = 0;
388 while (*str) {
389 char c = *str;
391 if (*str == '\\') {
392 if (*(str + 1)) {
393 s[p] = *(str + 1);
394 p++;
395 str += 2; /* skip this and the next char */
396 continue;
397 } else
398 break;
400 if (c == '"') {
401 str++; /* skip only this char */
402 continue;
404 s[p] = c;
405 p++;
406 str++;
409 return s;
412 char **
413 readlines(size_t *lineslen)
415 size_t len = 0, cap = 0;
416 size_t linesize = 0;
417 ssize_t linelen;
418 char *line = NULL, **lines = NULL;
420 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
421 if (linelen != 0 && line[linelen-1] == '\n')
422 line[linelen-1] = '\0';
424 if (len == cap) {
425 size_t newcap;
426 void *t;
428 newcap = MAX(cap * 1.5, 32);
429 t = recallocarray(lines, cap, newcap, sizeof(char *));
430 if (t == NULL)
431 err(1, "recallocarray");
432 cap = newcap;
433 lines = t;
436 if ((lines[len++] = strdup(line)) == NULL)
437 err(1, "strdup");
440 if (ferror(stdin))
441 err(1, "getline");
442 free(line);
444 *lineslen = len;
445 return lines;
448 /*
449 * Compute the dimensions of the string str once rendered.
450 * It'll return the width and set ret_width and ret_height if not NULL
451 */
452 int
453 text_extents(char *str, int len, struct rendering *r, int *ret_width,
454 int *ret_height)
456 int height, width;
457 XGlyphInfo gi;
458 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
459 height = r->font->ascent - r->font->descent;
460 width = gi.width - gi.x;
462 if (ret_width != NULL)
463 *ret_width = width;
464 if (ret_height != NULL)
465 *ret_height = height;
466 return width;
469 void
470 draw_string(char *str, int len, int x, int y, struct rendering *r,
471 enum obj_type tt)
473 XftColor xftcolor;
474 if (tt == PROMPT)
475 xftcolor = r->xft_colors[0];
476 if (tt == COMPL)
477 xftcolor = r->xft_colors[1];
478 if (tt == COMPL_HIGH)
479 xftcolor = r->xft_colors[2];
481 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
484 /* Duplicate the string and substitute every space with a 'n` */
485 char *
486 strdupn(char *str)
488 char *t, *dup;
490 if (str == NULL || *str == '\0')
491 return NULL;
493 if ((dup = strdup(str)) == NULL)
494 return NULL;
496 for (t = dup; *t; ++t) {
497 if (*t == ' ')
498 *t = 'n';
501 return dup;
504 int
505 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
506 enum obj_type t, char *text)
508 GC *border_color, bg;
509 int *padding, *borders;
510 int ret = 0, inner_width, inner_height, x;
512 switch (t) {
513 case PROMPT:
514 border_color = r->p_borders_bg;
515 padding = r->p_padding;
516 borders = r->p_borders;
517 bg = r->bgs[0];
518 break;
519 case COMPL:
520 border_color = r->c_borders_bg;
521 padding = r->c_padding;
522 borders = r->c_borders;
523 bg = r->bgs[1];
524 break;
525 case COMPL_HIGH:
526 border_color = r->ch_borders_bg;
527 padding = r->ch_padding;
528 borders = r->ch_borders;
529 bg = r->bgs[2];
530 break;
533 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
535 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
536 inner_height = padding[0] + r->text_height + padding[2];
538 /* Border top */
539 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
540 borders[0]);
542 /* Border right */
543 XFillRectangle(r->d, r->w, border_color[1],
544 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
546 /* Border bottom */
547 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
548 y + borders[0] + padding[0] + r->text_height + padding[2],
549 r->width, borders[2]);
551 /* Border left */
552 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
553 ret);
555 /* bg */
556 x = r->x_zero + borders[3];
557 y += borders[0];
558 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
560 /* content */
561 y += padding[0] + r->text_height;
562 x += padding[3];
563 if (prefix != NULL) {
564 draw_string(prefix, strlen(prefix), x, y, r, t);
565 x += prefix_width;
567 draw_string(text, strlen(text), x, y, r, t);
569 return ret;
572 int
573 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
574 enum obj_type t, char *text)
576 GC *border_color, bg;
577 int *padding, *borders;
578 int ret = 0, inner_width, inner_height, y, text_width;
580 switch (t) {
581 case PROMPT:
582 border_color = r->p_borders_bg;
583 padding = r->p_padding;
584 borders = r->p_borders;
585 bg = r->bgs[0];
586 break;
587 case COMPL:
588 border_color = r->c_borders_bg;
589 padding = r->c_padding;
590 borders = r->c_borders;
591 bg = r->bgs[1];
592 break;
593 case COMPL_HIGH:
594 border_color = r->ch_borders_bg;
595 padding = r->ch_padding;
596 borders = r->ch_borders;
597 bg = r->bgs[2];
598 break;
601 if (padding[0] < 0 || padding[2] < 0) {
602 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
603 - r->text_height;
604 padding[0] /= 2;
606 padding[2] = padding[0];
609 /* If they are still lesser than 0, set 'em to 0 */
610 if (padding[0] < 0 || padding[2] < 0)
611 padding[0] = padding[2] = 0;
613 /* Get the text width */
614 text_extents(text, strlen(text), r, &text_width, NULL);
615 if (prefix != NULL)
616 text_width += prefix_width;
618 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
620 inner_width = padding[3] + text_width + padding[1];
621 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
623 /* Border top */
624 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
625 borders[0]);
627 /* Border right */
628 XFillRectangle(r->d, r->w, border_color[1],
629 x + borders[3] + inner_width, r->y_zero, borders[1],
630 INNER_HEIGHT(r));
632 /* Border bottom */
633 XFillRectangle(r->d, r->w, border_color[2], x,
634 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
635 borders[2]);
637 /* Border left */
638 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
639 INNER_HEIGHT(r));
641 /* bg */
642 x += borders[3];
643 y = r->y_zero + borders[0];
644 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
646 /* content */
647 y += padding[0] + r->text_height;
648 x += padding[3];
649 if (prefix != NULL) {
650 draw_string(prefix, strlen(prefix), x, y, r, t);
651 x += prefix_width;
653 draw_string(text, strlen(text), x, y, r, t);
655 return ret;
658 /*
659 * ,-----------------------------------------------------------------,
660 * | 20 char text | completion | completion | completion | compl |
661 * `-----------------------------------------------------------------'
662 */
663 void
664 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
666 size_t i;
667 int x = r->x_zero;
669 /* Draw the prompt */
670 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
672 for (i = r->offset; i < cs->length; ++i) {
673 enum obj_type t;
675 if (cs->selected == (ssize_t)i)
676 t = COMPL_HIGH;
677 else
678 t = COMPL;
680 cs->completions[i].offset = x;
682 x += draw_h_box(r, x, NULL, 0, t,
683 cs->completions[i].completion);
685 if (x > INNER_WIDTH(r))
686 break;
689 for (i += 1; i < cs->length; ++i)
690 cs->completions[i].offset = -1;
693 /*
694 * ,-----------------------------------------------------------------,
695 * | prompt |
696 * |-----------------------------------------------------------------|
697 * | completion |
698 * |-----------------------------------------------------------------|
699 * | completion |
700 * `-----------------------------------------------------------------'
701 */
702 void
703 draw_vertically(struct rendering *r, char *text, struct completions *cs)
705 size_t i;
706 int y = r->y_zero;
708 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
710 for (i = r->offset; i < cs->length; ++i) {
711 enum obj_type t;
713 if (cs->selected == (ssize_t)i)
714 t = COMPL_HIGH;
715 else
716 t = COMPL;
718 cs->completions[i].offset = y;
720 y += draw_v_box(r, y, NULL, 0, t,
721 cs->completions[i].completion);
723 if (y > INNER_HEIGHT(r))
724 break;
727 for (i += 1; i < cs->length; ++i)
728 cs->completions[i].offset = -1;
731 void
732 draw(struct rendering *r, char *text, struct completions *cs)
734 /* Draw the background */
735 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
736 INNER_WIDTH(r), INNER_HEIGHT(r));
738 /* Draw the contents */
739 if (r->horizontal_layout)
740 draw_horizontally(r, text, cs);
741 else
742 draw_vertically(r, text, cs);
744 /* Draw the borders */
745 if (r->borders[0] != 0)
746 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
747 r->borders[0]);
749 if (r->borders[1] != 0)
750 XFillRectangle(r->d, r->w, r->borders_bg[1],
751 r->width - r->borders[1], 0, r->borders[1],
752 r->height);
754 if (r->borders[2] != 0)
755 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
756 r->height - r->borders[2], r->width, r->borders[2]);
758 if (r->borders[3] != 0)
759 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
760 r->borders[3], r->height);
762 /* render! */
763 XFlush(r->d);
766 /* Set some WM stuff */
767 void
768 set_win_atoms_hints(Display *d, Window w, int width, int height)
770 Atom type;
771 XClassHint *class_hint;
772 XSizeHints *size_hint;
774 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
775 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
776 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
777 (unsigned char *)&type, 1);
779 /* some window managers honor this properties */
780 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
781 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
782 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
783 (unsigned char *)&type, 1);
785 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
786 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
787 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
788 (unsigned char *)&type, 1);
790 /* Setting window hints */
791 class_hint = XAllocClassHint();
792 if (class_hint == NULL) {
793 fprintf(stderr, "Could not allocate memory for class hint\n");
794 exit(EX_UNAVAILABLE);
797 class_hint->res_name = RESNAME;
798 class_hint->res_class = RESCLASS;
799 XSetClassHint(d, w, class_hint);
800 XFree(class_hint);
802 size_hint = XAllocSizeHints();
803 if (size_hint == NULL) {
804 fprintf(stderr, "Could not allocate memory for size hint\n");
805 exit(EX_UNAVAILABLE);
808 size_hint->flags = PMinSize | PBaseSize;
809 size_hint->min_width = width;
810 size_hint->base_width = width;
811 size_hint->min_height = height;
812 size_hint->base_height = height;
814 XFlush(d);
817 /* Get the width and height of the window `w' */
818 void
819 get_wh(Display *d, Window *w, int *width, int *height)
821 XWindowAttributes win_attr;
823 XGetWindowAttributes(d, *w, &win_attr);
824 *height = win_attr.height;
825 *width = win_attr.width;
828 /* find the current xinerama monitor if possible */
829 void
830 findmonitor(Display *d, int *x, int *y, int *width, int *height)
832 XineramaScreenInfo *info;
833 Window rr;
834 Window root;
835 int screens, monitors, i;
836 int rootx, rooty, winx, winy;
837 unsigned int mask;
838 short res;
840 if (!XineramaIsActive(d))
841 return;
843 screens = XScreenCount(d);
844 for (i = 0; i < screens; ++i) {
845 root = XRootWindow(d, i);
846 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
847 &winy, &mask);
848 if (res)
849 break;
852 if (!res)
853 return;
855 /* Now find in which monitor the mice is */
856 info = XineramaQueryScreens(d, &monitors);
857 if (info == NULL)
858 return;
860 for (i = 0; i < monitors; ++i) {
861 if (info[i].x_org <= rootx &&
862 rootx <= (info[i].x_org + info[i].width) &&
863 info[i].y_org <= rooty &&
864 rooty <= (info[i].y_org + info[i].height)) {
865 *x = info[i].x_org;
866 *y = info[i].y_org;
867 *width = info[i].width;
868 *height = info[i].height;
869 break;
873 XFree(info);
876 int
877 grabfocus(Display *d, Window w)
879 int i;
880 for (i = 0; i < 100; ++i) {
881 Window focuswin;
882 int revert_to_win;
884 XGetInputFocus(d, &focuswin, &revert_to_win);
886 if (focuswin == w)
887 return 1;
889 XSetInputFocus(d, w, RevertToParent, CurrentTime);
890 usleep(1000);
892 return 0;
895 /*
896 * I know this may seem a little hackish BUT is the only way I managed
897 * to actually grab that goddam keyboard. Only one call to
898 * XGrabKeyboard does not always end up with the keyboard grabbed!
899 */
900 int
901 take_keyboard(Display *d, Window w)
903 int i;
904 for (i = 0; i < 100; i++) {
905 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
906 CurrentTime) == GrabSuccess)
907 return 1;
908 usleep(1000);
910 fprintf(stderr, "Cannot grab keyboard\n");
911 return 0;
914 unsigned long
915 parse_color(const char *str, const char *def)
917 size_t len;
918 rgba_t tmp;
919 char *ep;
921 if (str == NULL)
922 goto invc;
924 len = strlen(str);
926 /* +1 for the # ath the start */
927 if (*str != '#' || len > 9 || len < 4)
928 goto invc;
929 ++str; /* skip the # */
931 errno = 0;
932 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
934 if (errno)
935 goto invc;
937 switch (len - 1) {
938 case 3:
939 /* expand #rgb -> #rrggbb */
940 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
941 | (tmp.v & 0x00f) * 0x0011;
942 case 6:
943 /* assume 0xff opacity */
944 tmp.rgba.a = 0xff;
945 break;
946 } /* colors in #aarrggbb need no adjustments */
948 /* premultiply the alpha */
949 if (tmp.rgba.a) {
950 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
951 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
952 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
953 return tmp.v;
956 return 0U;
958 invc:
959 fprintf(stderr, "Invalid color: \"%s\".\n", str);
960 if (def != NULL)
961 return parse_color(def, NULL);
962 else
963 return 0U;
966 /*
967 * Given a string try to parse it as a number or return `def'.
968 */
969 int
970 parse_integer(const char *str, int def)
972 const char *errstr;
973 int i;
975 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
976 if (errstr != NULL) {
977 warnx("'%s' is %s; using %d as default", str, errstr, def);
978 return def;
981 return i;
984 /*
985 * Like parse_integer but recognize the percentages (i.e. strings
986 * ending with `%')
987 */
988 int
989 parse_int_with_percentage(const char *str, int default_value, int max)
991 int len = strlen(str);
993 if (len > 0 && str[len - 1] == '%') {
994 int val;
995 char *cpy;
997 if ((cpy = strdup(str)) == NULL)
998 err(1, "strdup");
1000 cpy[len - 1] = '\0';
1001 val = parse_integer(cpy, default_value);
1002 free(cpy);
1003 return val * max / 100;
1006 return parse_integer(str, default_value);
1009 void
1010 get_mouse_coords(Display *d, int *x, int *y)
1012 Window w, root;
1013 int i;
1014 unsigned int u;
1016 *x = *y = 0;
1017 root = DefaultRootWindow(d);
1019 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1020 for (i = 0; i < ScreenCount(d); ++i) {
1021 if (root == RootWindow(d, i))
1022 break;
1028 * Like parse_int_with_percentage but understands some special values:
1029 * - middle that is (max-self)/2
1030 * - center = middle
1031 * - start that is 0
1032 * - end that is (max-self)
1033 * - mx x coordinate of the mouse
1034 * - my y coordinate of the mouse
1036 int
1037 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1038 int self)
1040 if (!strcmp(str, "start"))
1041 return 0;
1042 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1043 return (max - self) / 2;
1044 if (!strcmp(str, "end"))
1045 return max - self;
1046 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1047 int x, y;
1049 get_mouse_coords(d, &x, &y);
1050 if (!strcmp(str, "mx"))
1051 return x - 1;
1052 else
1053 return y - 1;
1055 return parse_int_with_percentage(str, default_value, max);
1058 /* Parse a string like a CSS value. */
1059 /* TODO: harden a bit this function */
1060 char **
1061 parse_csslike(const char *str)
1063 int i, j;
1064 char *s, *token, **ret;
1065 short any_null;
1067 s = strdup(str);
1068 if (s == NULL)
1069 return NULL;
1071 ret = malloc(4 * sizeof(char *));
1072 if (ret == NULL) {
1073 free(s);
1074 return NULL;
1077 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1078 ret[i] = strdup(token);
1080 if (i == 1)
1081 for (j = 1; j < 4; j++)
1082 ret[j] = strdup(ret[0]);
1084 if (i == 2) {
1085 ret[2] = strdup(ret[0]);
1086 ret[3] = strdup(ret[1]);
1089 if (i == 3)
1090 ret[3] = strdup(ret[1]);
1093 * before we didn't check for the return type of strdup, here
1094 * we will
1097 any_null = 0;
1098 for (i = 0; i < 4; ++i)
1099 any_null = ret[i] == NULL || any_null;
1101 if (any_null)
1102 for (i = 0; i < 4; ++i)
1103 if (ret[i] != NULL)
1104 free(ret[i]);
1106 if (i == 0 || any_null) {
1107 free(s);
1108 free(ret);
1109 return NULL;
1112 return ret;
1116 * Given an event, try to understand what the users wants. If the
1117 * return value is ADD_CHAR then `input' is a pointer to a string that
1118 * will need to be free'ed later.
1120 enum action
1121 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1123 char str[SYM_BUF_SIZE] = { 0 };
1124 Status s;
1126 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1127 return DEL_CHAR;
1129 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1130 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1132 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1133 return CONFIRM;
1135 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1136 return EXIT;
1138 /* Try to read what key was pressed */
1139 s = 0;
1140 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1141 if (s == XBufferOverflow) {
1142 fprintf(stderr,
1143 "Buffer overflow when trying to create keyboard "
1144 "symbol map.\n");
1145 return EXIT;
1148 if (ev->state & ControlMask) {
1149 if (!strcmp(str, "")) /* C-u */
1150 return DEL_LINE;
1151 if (!strcmp(str, "")) /* C-w */
1152 return DEL_WORD;
1153 if (!strcmp(str, "")) /* C-h */
1154 return DEL_CHAR;
1155 if (!strcmp(str, "\r")) /* C-m */
1156 return CONFIRM_CONTINUE;
1157 if (!strcmp(str, "")) /* C-p */
1158 return PREV_COMPL;
1159 if (!strcmp(str, "")) /* C-n */
1160 return NEXT_COMPL;
1161 if (!strcmp(str, "")) /* C-c */
1162 return EXIT;
1163 if (!strcmp(str, "\t")) /* C-i */
1164 return TOGGLE_FIRST_SELECTED;
1167 *input = strdup(str);
1168 if (*input == NULL) {
1169 fprintf(stderr, "Error while allocating memory for key.\n");
1170 return EXIT;
1173 return ADD_CHAR;
1176 void
1177 confirm(enum state *status, struct rendering *r, struct completions *cs,
1178 char **text, int *textlen)
1180 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1181 /* if there is something selected expand it and return */
1182 int index = cs->selected == -1 ? 0 : cs->selected;
1183 struct completion *c = cs->completions;
1184 char *t;
1186 while (1) {
1187 if (index == 0)
1188 break;
1189 c++;
1190 index--;
1193 t = c->rcompletion;
1194 free(*text);
1195 *text = strdup(t);
1197 if (*text == NULL) {
1198 fprintf(stderr, "Memory allocation error\n");
1199 *status = ERR;
1202 *textlen = strlen(*text);
1203 return;
1206 if (!r->free_text) /* cannot accept arbitrary text */
1207 *status = LOOPING;
1211 * cs: completion list
1212 * offset: the offset of the click
1213 * first: the first (rendered) item
1214 * def: the default action
1216 enum action
1217 select_clicked(struct completions *cs, size_t offset, size_t first,
1218 enum action def)
1220 ssize_t selected = first;
1221 int set = 0;
1223 if (cs->length == 0)
1224 return NO_OP;
1226 if (offset < cs->completions[selected].offset)
1227 return EXIT;
1229 /* skip the first entry */
1230 for (selected += 1; selected < cs->length; ++selected) {
1231 if (cs->completions[selected].offset == -1)
1232 break;
1234 if (offset < cs->completions[selected].offset) {
1235 cs->selected = selected - 1;
1236 set = 1;
1237 break;
1241 if (!set)
1242 cs->selected = selected - 1;
1244 return def;
1247 enum action
1248 handle_mouse(struct rendering *r, struct completions *cs,
1249 XButtonPressedEvent *e)
1251 size_t off;
1253 if (r->horizontal_layout)
1254 off = e->x;
1255 else
1256 off = e->y;
1258 switch (e->button) {
1259 case Button1:
1260 return select_clicked(cs, off, r->offset, CONFIRM);
1262 case Button3:
1263 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1265 case Button4:
1266 return SCROLL_UP;
1268 case Button5:
1269 return SCROLL_DOWN;
1272 return NO_OP;
1275 /* event loop */
1276 enum state
1277 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1278 char **lines, char **vlines)
1280 enum state status = LOOPING;
1282 while (status == LOOPING) {
1283 XEvent e;
1284 XNextEvent(r->d, &e);
1286 if (XFilterEvent(&e, r->w))
1287 continue;
1289 switch (e.type) {
1290 case KeymapNotify:
1291 XRefreshKeyboardMapping(&e.xmapping);
1292 break;
1294 case FocusIn:
1295 /* Re-grab focus */
1296 if (e.xfocus.window != r->w)
1297 grabfocus(r->d, r->w);
1298 break;
1300 case VisibilityNotify:
1301 if (e.xvisibility.state != VisibilityUnobscured)
1302 XRaiseWindow(r->d, r->w);
1303 break;
1305 case MapNotify:
1306 get_wh(r->d, &r->w, &r->width, &r->height);
1307 draw(r, *text, cs);
1308 break;
1310 case KeyPress:
1311 case ButtonPress: {
1312 enum action a;
1313 char *input = NULL;
1315 if (e.type == KeyPress)
1316 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1317 r->xic, &input);
1318 else
1319 a = handle_mouse(r, cs,
1320 (XButtonPressedEvent *)&e);
1322 switch (a) {
1323 case NO_OP:
1324 break;
1326 case EXIT:
1327 status = ERR;
1328 break;
1330 case CONFIRM: {
1331 status = OK;
1332 confirm(&status, r, cs, text, textlen);
1333 break;
1336 case CONFIRM_CONTINUE: {
1337 status = OK_LOOP;
1338 confirm(&status, r, cs, text, textlen);
1339 break;
1342 case PREV_COMPL: {
1343 complete(cs, r->first_selected, 1, text,
1344 textlen, &status);
1345 r->offset = cs->selected;
1346 break;
1349 case NEXT_COMPL: {
1350 complete(cs, r->first_selected, 0, text,
1351 textlen, &status);
1352 r->offset = cs->selected;
1353 break;
1356 case DEL_CHAR:
1357 popc(*text);
1358 update_completions(cs, *text, lines, vlines,
1359 r->first_selected);
1360 r->offset = 0;
1361 break;
1363 case DEL_WORD: {
1364 popw(*text);
1365 update_completions(cs, *text, lines, vlines,
1366 r->first_selected);
1367 break;
1370 case DEL_LINE: {
1371 int i;
1372 for (i = 0; i < *textlen; ++i)
1373 *(*text + i) = 0;
1374 update_completions(cs, *text, lines, vlines,
1375 r->first_selected);
1376 r->offset = 0;
1377 break;
1380 case ADD_CHAR: {
1381 int str_len, i;
1383 str_len = strlen(input);
1386 * sometimes a strange key is pressed
1387 * i.e. ctrl alone), so input will be
1388 * empty. Don't need to update
1389 * completion in that case
1391 if (str_len == 0)
1392 break;
1394 for (i = 0; i < str_len; ++i) {
1395 *textlen = pushc(text, *textlen,
1396 input[i]);
1397 if (*textlen == -1) {
1398 fprintf(stderr,
1399 "Memory allocation "
1400 "error\n");
1401 status = ERR;
1402 break;
1406 if (status != ERR) {
1407 update_completions(cs, *text, lines,
1408 vlines, r->first_selected);
1409 free(input);
1412 r->offset = 0;
1413 break;
1416 case TOGGLE_FIRST_SELECTED:
1417 r->first_selected = !r->first_selected;
1418 if (r->first_selected && cs->selected < 0)
1419 cs->selected = 0;
1420 if (!r->first_selected && cs->selected == 0)
1421 cs->selected = -1;
1422 break;
1424 case SCROLL_DOWN:
1425 r->offset = MIN(r->offset + 1, cs->length - 1);
1426 break;
1428 case SCROLL_UP:
1429 r->offset = MAX((ssize_t)r->offset - 1, 0);
1430 break;
1435 draw(r, *text, cs);
1438 return status;
1441 int
1442 load_font(struct rendering *r, const char *fontname)
1444 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1445 return 0;
1448 void
1449 xim_init(struct rendering *r, XrmDatabase *xdb)
1451 XIMStyle best_match_style;
1452 XIMStyles *xis;
1453 int i;
1455 /* Open the X input method */
1456 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1457 err(1, "XOpenIM");
1459 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1460 fprintf(stderr, "Input Styles could not be retrieved\n");
1461 exit(EX_UNAVAILABLE);
1464 best_match_style = 0;
1465 for (i = 0; i < xis->count_styles; ++i) {
1466 XIMStyle ts = xis->supported_styles[i];
1467 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1468 best_match_style = ts;
1469 break;
1472 XFree(xis);
1474 if (!best_match_style)
1475 fprintf(stderr,
1476 "No matching input style could be determined\n");
1478 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1479 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1480 if (r->xic == NULL)
1481 err(1, "XCreateIC");
1484 void
1485 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1486 XVisualInfo vinfo, int x, int y, int ox, int oy,
1487 unsigned long background_pixel)
1489 XSetWindowAttributes attr;
1490 unsigned long vmask;
1492 /* Create the window */
1493 attr.colormap = cmap;
1494 attr.override_redirect = 1;
1495 attr.border_pixel = 0;
1496 attr.background_pixel = background_pixel;
1497 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1498 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1500 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1501 CWOverrideRedirect;
1503 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1504 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1507 void
1508 ps1extents(struct rendering *r)
1510 char *dup;
1511 dup = strdupn(r->ps1);
1512 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1513 free(dup);
1516 void
1517 usage(char *prgname)
1519 fprintf(stderr,
1520 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1521 " [-d separator] [-e window] [-f font] [-G color] [-g "
1522 "size]\n"
1523 " [-H height] [-I color] [-i size] [-J color] [-j "
1524 "size] [-l layout]\n"
1525 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1526 "color]\n"
1527 " [-t color] [-W width] [-x coord] [-y coord]\n",
1528 prgname);
1531 int
1532 main(int argc, char **argv)
1534 struct completions *cs;
1535 struct rendering r;
1536 XVisualInfo vinfo;
1537 Colormap cmap;
1538 size_t nlines, i;
1539 Window parent_window;
1540 XrmDatabase xdb;
1541 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1542 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1543 ch_borders_bg[4]; /* N E S W */
1544 enum state status;
1545 int ch;
1546 int offset_x, offset_y, x, y;
1547 int textlen, d_width, d_height;
1548 short embed;
1549 char *sep, *parent_window_id;
1550 char **lines, **vlines;
1551 char *fontname, *text, *xrm;
1553 sep = NULL;
1554 parent_window_id = NULL;
1556 r.first_selected = 0;
1557 r.free_text = 1;
1558 r.multiple_select = 0;
1559 r.offset = 0;
1561 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1562 switch (ch) {
1563 case 'h': /* help */
1564 usage(*argv);
1565 return 0;
1566 case 'v': /* version */
1567 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1568 return 0;
1569 case 'e': /* embed */
1570 if ((parent_window_id = strdup(optarg)) == NULL)
1571 err(1, "strdup");
1572 break;
1573 case 'd':
1574 if ((sep = strdup(optarg)) == NULL)
1575 err(1, "strdup");
1576 break;
1577 case 'A':
1578 r.free_text = 0;
1579 break;
1580 case 'm':
1581 r.multiple_select = 1;
1582 break;
1583 default:
1584 break;
1588 lines = readlines(&nlines);
1590 vlines = NULL;
1591 if (sep != NULL) {
1592 int l;
1593 l = strlen(sep);
1594 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1595 err(1, "calloc");
1597 for (i = 0; i < nlines; i++) {
1598 char *t;
1599 t = strstr(lines[i], sep);
1600 if (t == NULL)
1601 vlines[i] = lines[i];
1602 else
1603 vlines[i] = t + l;
1607 setlocale(LC_ALL, getenv("LANG"));
1609 status = LOOPING;
1611 /* where the monitor start (used only with xinerama) */
1612 offset_x = offset_y = 0;
1614 /* default width and height */
1615 r.width = 400;
1616 r.height = 20;
1618 /* default position on the screen */
1619 x = y = 0;
1621 for (i = 0; i < 4; ++i) {
1622 /* default paddings */
1623 r.p_padding[i] = 10;
1624 r.c_padding[i] = 10;
1625 r.ch_padding[i] = 10;
1627 /* default borders */
1628 r.borders[i] = 0;
1629 r.p_borders[i] = 0;
1630 r.c_borders[i] = 0;
1631 r.ch_borders[i] = 0;
1635 * The prompt. We duplicate the string so later is easy to
1636 * free (in the case it's been overwritten by the user)
1638 if ((r.ps1 = strdup("$ ")) == NULL)
1639 err(1, "strdup");
1641 /* same for the font name */
1642 if ((fontname = strdup(DEFFONT)) == NULL)
1643 err(1, "strdup");
1645 textlen = 10;
1646 if ((text = malloc(textlen * sizeof(char))) == NULL)
1647 err(1, "malloc");
1649 /* struct completions *cs = filter(text, lines); */
1650 if ((cs = compls_new(nlines)) == NULL)
1651 err(1, "compls_new");
1653 /* start talking to xorg */
1654 r.d = XOpenDisplay(NULL);
1655 if (r.d == NULL) {
1656 fprintf(stderr, "Could not open display!\n");
1657 return EX_UNAVAILABLE;
1660 embed = 1;
1661 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1662 parent_window = DefaultRootWindow(r.d);
1663 embed = 0;
1666 /* get display size */
1667 get_wh(r.d, &parent_window, &d_width, &d_height);
1669 if (!embed)
1670 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1672 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1673 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1674 AllocNone);
1676 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1677 fgs[2] = parse_color("#000", NULL);
1679 bgs[0] = bgs[1] = parse_color("#000", NULL);
1680 bgs[2] = parse_color("#fff", NULL);
1682 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1683 parse_color("#000", NULL);
1685 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1686 = parse_color("#000", NULL);
1687 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1688 = parse_color("#000", NULL);
1689 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1690 = parse_color("#000", NULL);
1692 r.horizontal_layout = 1;
1694 /* Read the resources */
1695 XrmInitialize();
1696 xrm = XResourceManagerString(r.d);
1697 xdb = NULL;
1698 if (xrm != NULL) {
1699 XrmValue value;
1700 char *datatype[20];
1702 xdb = XrmGetStringDatabase(xrm);
1704 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1705 free(fontname);
1706 if ((fontname = strdup(value.addr)) == NULL)
1707 err(1, "strdup");
1708 } else {
1709 fprintf(stderr, "no font defined, using %s\n", fontname);
1712 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1713 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1714 else
1715 fprintf(stderr, "no layout defined, using horizontal\n");
1717 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1718 free(r.ps1);
1719 r.ps1 = normalize_str(value.addr);
1720 } else {
1721 fprintf(stderr,
1722 "no prompt defined, using \"%s\" as "
1723 "default\n",
1724 r.ps1);
1727 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1728 char **sizes;
1729 sizes = parse_csslike(value.addr);
1730 if (sizes != NULL)
1731 for (i = 0; i < 4; ++i)
1732 r.p_borders[i] = parse_integer(sizes[i], 0);
1733 else
1734 fprintf(stderr,
1735 "error while parsing "
1736 "MyMenu.prompt.border.size");
1739 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1740 char **colors;
1741 colors = parse_csslike(value.addr);
1742 if (colors != NULL)
1743 for (i = 0; i < 4; ++i)
1744 p_borders_bg[i] = parse_color(colors[i], "#000");
1745 else
1746 fprintf(stderr,
1747 "error while parsing "
1748 "MyMenu.prompt.border.color");
1751 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1752 char **colors;
1753 colors = parse_csslike(value.addr);
1754 if (colors != NULL)
1755 for (i = 0; i < 4; ++i)
1756 r.p_padding[i] = parse_integer(colors[i], 0);
1757 else
1758 fprintf(stderr,
1759 "error while parsing "
1760 "MyMenu.prompt.padding");
1763 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1764 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1765 else
1766 fprintf(stderr, "no width defined, using %d\n", r.width);
1768 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1769 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1770 else
1771 fprintf(stderr, "no height defined, using %d\n", r.height);
1773 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1774 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1776 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1777 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1779 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1780 char **borders;
1781 borders = parse_csslike(value.addr);
1782 if (borders != NULL)
1783 for (i = 0; i < 4; ++i)
1784 r.borders[i] = parse_int_with_percentage(
1785 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1786 else
1787 fprintf(stderr,
1788 "error while parsing "
1789 "MyMenu.border.size\n");
1792 /* Prompt */
1793 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1794 fgs[0] = parse_color(value.addr, "#fff");
1796 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1797 bgs[0] = parse_color(value.addr, "#000");
1799 /* Completions */
1800 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1801 fgs[1] = parse_color(value.addr, "#fff");
1803 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1804 bgs[1] = parse_color(value.addr, "#000");
1806 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1807 char **paddings;
1808 paddings = parse_csslike(value.addr);
1809 if (paddings != NULL)
1810 for (i = 0; i < 4; ++i)
1811 r.c_padding[i] = parse_integer(paddings[i], 0);
1812 else
1813 fprintf(stderr,
1814 "Error while parsing "
1815 "MyMenu.completion.padding");
1818 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1819 char **sizes;
1820 sizes = parse_csslike(value.addr);
1821 if (sizes != NULL)
1822 for (i = 0; i < 4; ++i)
1823 r.c_borders[i] = parse_integer(sizes[i], 0);
1824 else
1825 fprintf(stderr,
1826 "Error while parsing "
1827 "MyMenu.completion.border.size");
1830 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1831 char **sizes;
1832 sizes = parse_csslike(value.addr);
1833 if (sizes != NULL)
1834 for (i = 0; i < 4; ++i)
1835 c_borders_bg[i] = parse_color(sizes[i], "#000");
1836 else
1837 fprintf(stderr,
1838 "Error while parsing "
1839 "MyMenu.completion.border.color");
1842 /* Completion Highlighted */
1843 if (XrmGetResource(
1844 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1845 fgs[2] = parse_color(value.addr, "#000");
1847 if (XrmGetResource(
1848 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1849 bgs[2] = parse_color(value.addr, "#fff");
1851 if (XrmGetResource(
1852 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1853 char **paddings;
1854 paddings = parse_csslike(value.addr);
1855 if (paddings != NULL)
1856 for (i = 0; i < 4; ++i)
1857 r.ch_padding[i] = parse_integer(paddings[i], 0);
1858 else
1859 fprintf(stderr,
1860 "Error while parsing "
1861 "MyMenu.completion_highlighted."
1862 "padding");
1865 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1866 &value)) {
1867 char **sizes;
1868 sizes = parse_csslike(value.addr);
1869 if (sizes != NULL)
1870 for (i = 0; i < 4; ++i)
1871 r.ch_borders[i] = parse_integer(sizes[i], 0);
1872 else
1873 fprintf(stderr,
1874 "Error while parsing "
1875 "MyMenu.completion_highlighted."
1876 "border.size");
1879 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1880 &value)) {
1881 char **colors;
1882 colors = parse_csslike(value.addr);
1883 if (colors != NULL)
1884 for (i = 0; i < 4; ++i)
1885 ch_borders_bg[i] = parse_color(colors[i], "#000");
1886 else
1887 fprintf(stderr,
1888 "Error while parsing "
1889 "MyMenu.completion_highlighted."
1890 "border.color");
1893 /* Border */
1894 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1895 char **colors;
1896 colors = parse_csslike(value.addr);
1897 if (colors != NULL)
1898 for (i = 0; i < 4; ++i)
1899 borders_bg[i] = parse_color(colors[i], "#000");
1900 else
1901 fprintf(stderr,
1902 "error while parsing "
1903 "MyMenu.border.color\n");
1907 /* Second round of args parsing */
1908 optind = 0; /* reset the option index */
1909 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1910 switch (ch) {
1911 case 'a':
1912 r.first_selected = 1;
1913 break;
1914 case 'A':
1915 /* free_text -- already catched */
1916 case 'd':
1917 /* separator -- this case was already catched */
1918 case 'e':
1919 /* embedding mymenu this case was already catched. */
1920 case 'm':
1921 /* multiple selection this case was already catched.
1923 break;
1924 case 'p': {
1925 char *newprompt;
1926 newprompt = strdup(optarg);
1927 if (newprompt != NULL) {
1928 free(r.ps1);
1929 r.ps1 = newprompt;
1931 break;
1933 case 'x':
1934 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1935 break;
1936 case 'y':
1937 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1938 break;
1939 case 'P': {
1940 char **paddings;
1941 if ((paddings = parse_csslike(optarg)) != NULL)
1942 for (i = 0; i < 4; ++i)
1943 r.p_padding[i] = parse_integer(paddings[i], 0);
1944 break;
1946 case 'G': {
1947 char **colors;
1948 if ((colors = parse_csslike(optarg)) != NULL)
1949 for (i = 0; i < 4; ++i)
1950 p_borders_bg[i] = parse_color(colors[i], "#000");
1951 break;
1953 case 'g': {
1954 char **sizes;
1955 if ((sizes = parse_csslike(optarg)) != NULL)
1956 for (i = 0; i < 4; ++i)
1957 r.p_borders[i] = parse_integer(sizes[i], 0);
1958 break;
1960 case 'I': {
1961 char **colors;
1962 if ((colors = parse_csslike(optarg)) != NULL)
1963 for (i = 0; i < 4; ++i)
1964 c_borders_bg[i] = parse_color(colors[i], "#000");
1965 break;
1967 case 'i': {
1968 char **sizes;
1969 if ((sizes = parse_csslike(optarg)) != NULL)
1970 for (i = 0; i < 4; ++i)
1971 r.c_borders[i] = parse_integer(sizes[i], 0);
1972 break;
1974 case 'J': {
1975 char **colors;
1976 if ((colors = parse_csslike(optarg)) != NULL)
1977 for (i = 0; i < 4; ++i)
1978 ch_borders_bg[i] = parse_color(colors[i], "#000");
1979 break;
1981 case 'j': {
1982 char **sizes;
1983 if ((sizes = parse_csslike(optarg)) != NULL)
1984 for (i = 0; i < 4; ++i)
1985 r.ch_borders[i] = parse_integer(sizes[i], 0);
1986 break;
1988 case 'l':
1989 r.horizontal_layout = !strcmp(optarg, "horizontal");
1990 break;
1991 case 'f': {
1992 char *newfont;
1993 if ((newfont = strdup(optarg)) != NULL) {
1994 free(fontname);
1995 fontname = newfont;
1997 break;
1999 case 'W':
2000 r.width = parse_int_with_percentage(optarg, r.width, d_width);
2001 break;
2002 case 'H':
2003 r.height = parse_int_with_percentage(optarg, r.height, d_height);
2004 break;
2005 case 'b': {
2006 char **borders;
2007 if ((borders = parse_csslike(optarg)) != NULL) {
2008 for (i = 0; i < 4; ++i)
2009 r.borders[i] = parse_integer(borders[i], 0);
2010 } else
2011 fprintf(stderr, "Error parsing b option\n");
2012 break;
2014 case 'B': {
2015 char **colors;
2016 if ((colors = parse_csslike(optarg)) != NULL) {
2017 for (i = 0; i < 4; ++i)
2018 borders_bg[i] = parse_color(colors[i], "#000");
2019 } else
2020 fprintf(stderr, "error while parsing B option\n");
2021 break;
2023 case 't':
2024 fgs[0] = parse_color(optarg, NULL);
2025 break;
2026 case 'T':
2027 bgs[0] = parse_color(optarg, NULL);
2028 break;
2029 case 'c':
2030 fgs[1] = parse_color(optarg, NULL);
2031 break;
2032 case 'C':
2033 bgs[1] = parse_color(optarg, NULL);
2034 break;
2035 case 's':
2036 fgs[2] = parse_color(optarg, NULL);
2037 break;
2038 case 'S':
2039 bgs[2] = parse_color(optarg, NULL);
2040 break;
2041 default:
2042 fprintf(stderr, "Unrecognized option %c\n", ch);
2043 status = ERR;
2044 break;
2048 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2049 fprintf(stderr, "height, width, x or y are lesser than 0.");
2050 status = ERR;
2053 /* since only now we know if the first should be selected,
2054 * update the completion here */
2055 update_completions(cs, text, lines, vlines, r.first_selected);
2057 /* update the prompt lenght, only now we surely know the length of it
2059 r.ps1len = strlen(r.ps1);
2061 /* Create the window */
2062 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2063 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2064 XMapRaised(r.d, r.w);
2066 /* If embed, listen for other events as well */
2067 if (embed) {
2068 Window *children, parent, root;
2069 unsigned int children_no;
2071 XSelectInput(r.d, parent_window, FocusChangeMask);
2072 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2073 && children) {
2074 for (i = 0; i < children_no && children[i] != r.w; ++i)
2075 XSelectInput(r.d, children[i], FocusChangeMask);
2076 XFree(children);
2078 grabfocus(r.d, r.w);
2081 take_keyboard(r.d, r.w);
2083 r.x_zero = r.borders[3];
2084 r.y_zero = r.borders[0];
2087 XGCValues values;
2089 for (i = 0; i < 3; ++i) {
2090 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2091 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2094 for (i = 0; i < 4; ++i) {
2095 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2096 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2097 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2098 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2102 /* Load the colors in our GCs */
2103 for (i = 0; i < 3; ++i) {
2104 XSetForeground(r.d, r.fgs[i], fgs[i]);
2105 XSetForeground(r.d, r.bgs[i], bgs[i]);
2108 for (i = 0; i < 4; ++i) {
2109 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2110 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2111 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2112 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2115 if (load_font(&r, fontname) == -1)
2116 status = ERR;
2118 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2120 for (i = 0; i < 3; ++i) {
2121 rgba_t c;
2122 XRenderColor xrcolor;
2124 c = *(rgba_t *)&fgs[i];
2125 xrcolor.red = EXPANDBITS(c.rgba.r);
2126 xrcolor.green = EXPANDBITS(c.rgba.g);
2127 xrcolor.blue = EXPANDBITS(c.rgba.b);
2128 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2129 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2132 /* compute prompt dimensions */
2133 ps1extents(&r);
2135 xim_init(&r, &xdb);
2137 #ifdef __OpenBSD__
2138 if (pledge("stdio", "") == -1)
2139 err(1, "pledge");
2140 #endif
2142 /* Cache text height */
2143 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2145 /* Draw the window for the first time */
2146 draw(&r, text, cs);
2148 /* Main loop */
2149 while (status == LOOPING || status == OK_LOOP) {
2150 status = loop(&r, &text, &textlen, cs, lines, vlines);
2152 if (status != ERR)
2153 printf("%s\n", text);
2155 if (!r.multiple_select && status == OK_LOOP)
2156 status = OK;
2159 XUngrabKeyboard(r.d, CurrentTime);
2161 for (i = 0; i < 3; ++i)
2162 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2164 for (i = 0; i < 3; ++i) {
2165 XFreeGC(r.d, r.fgs[i]);
2166 XFreeGC(r.d, r.bgs[i]);
2169 for (i = 0; i < 4; ++i) {
2170 XFreeGC(r.d, r.borders_bg[i]);
2171 XFreeGC(r.d, r.p_borders_bg[i]);
2172 XFreeGC(r.d, r.c_borders_bg[i]);
2173 XFreeGC(r.d, r.ch_borders_bg[i]);
2176 XDestroyIC(r.xic);
2177 XCloseIM(r.xim);
2179 for (i = 0; i < 3; ++i)
2180 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2181 XftFontClose(r.d, r.font);
2182 XftDrawDestroy(r.xftdraw);
2184 free(r.ps1);
2185 free(fontname);
2186 free(text);
2188 free(lines);
2189 free(vlines);
2190 compls_delete(cs);
2192 XFreeColormap(r.d, cmap);
2194 XDestroyWindow(r.d, r.w);
2195 XCloseDisplay(r.d);
2197 return status != OK;