Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020, 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <ctype.h> /* isalnum */
18 #include <err.h>
19 #include <errno.h>
20 #include <limits.h>
21 #include <locale.h> /* setlocale */
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h> /* strdup, strlen */
26 #include <sysexits.h>
27 #include <unistd.h>
29 #include <X11/Xcms.h>
30 #include <X11/Xlib.h>
31 #include <X11/Xresource.h>
32 #include <X11/Xutil.h>
33 #include <X11/keysym.h>
34 #include <X11/Xft/Xft.h>
36 #include <X11/extensions/Xinerama.h>
38 #define RESNAME "MyMenu"
39 #define RESCLASS "mymenu"
41 #define SYM_BUF_SIZE 4
43 #define DEFFONT "monospace"
45 #define ARGS "Aahmve:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:d:G:g:I:i:J:j:"
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define EXPANDBITS(x) (((x & 0xf0) * 0x100) | (x & 0x0f) * 0x10)
52 #define INNER_HEIGHT(r) (r->height - r->borders[0] - r->borders[2])
53 #define INNER_WIDTH(r) (r->width - r->borders[1] - r->borders[3])
55 /* The states of the event loop */
56 enum state { LOOPING, OK_LOOP, OK, ERR };
58 /*
59 * For the drawing-related function. The text to be rendere could be
60 * the prompt, a completion or a highlighted completion
61 */
62 enum obj_type { PROMPT, COMPL, COMPL_HIGH };
64 /* These are the possible action to be performed after user input. */
65 enum action {
66 NO_OP,
67 EXIT,
68 CONFIRM,
69 CONFIRM_CONTINUE,
70 NEXT_COMPL,
71 PREV_COMPL,
72 DEL_CHAR,
73 DEL_WORD,
74 DEL_LINE,
75 ADD_CHAR,
76 TOGGLE_FIRST_SELECTED,
77 SCROLL_DOWN,
78 SCROLL_UP,
79 };
81 /* A big set of values that needs to be carried around for drawing. A
82 * big struct to rule them all */
83 struct rendering {
84 Display *d; /* Connection to xorg */
85 Window w;
86 XIM xim;
87 int width;
88 int height;
89 int p_padding[4];
90 int c_padding[4];
91 int ch_padding[4];
92 int x_zero; /* the "zero" on the x axis (may not be exactly 0 'cause
93 the borders) */
94 int y_zero; /* like x_zero but for the y axis */
96 int offset; /* scroll offset */
98 short free_text;
99 short first_selected;
100 short multiple_select;
102 /* four border width */
103 int borders[4];
104 int p_borders[4];
105 int c_borders[4];
106 int ch_borders[4];
108 short horizontal_layout;
110 /* prompt */
111 char *ps1;
112 int ps1len;
113 int ps1w; /* ps1 width */
114 int ps1h; /* ps1 height */
116 int text_height; /* cache for the vertical layout */
118 XIC xic;
120 /* colors */
121 GC fgs[4];
122 GC bgs[4];
123 GC borders_bg[4];
124 GC p_borders_bg[4];
125 GC c_borders_bg[4];
126 GC ch_borders_bg[4];
127 XftFont *font;
128 XftDraw *xftdraw;
129 XftColor xft_colors[3];
130 };
132 struct completion {
133 char *completion;
134 char *rcompletion;
136 /*
137 * The X (or Y, depending on the layour) at which the item is
138 * rendered
139 */
140 int offset;
141 };
143 /* Wrap the linked list of completions */
144 struct completions {
145 struct completion *completions;
146 ssize_t selected;
147 size_t length;
148 };
150 /* idea stolen from lemonbar; ty lemonboy */
151 typedef union {
152 struct {
153 uint8_t b;
154 uint8_t g;
155 uint8_t r;
156 uint8_t a;
157 } rgba;
158 uint32_t v;
159 } rgba_t;
161 /* Return a newly allocated (and empty) completion list */
162 struct completions *
163 compls_new(size_t length)
165 struct completions *cs = malloc(sizeof(struct completions));
167 if (cs == NULL)
168 return cs;
170 cs->completions = calloc(length, sizeof(struct completion));
171 if (cs->completions == NULL) {
172 free(cs);
173 return NULL;
176 cs->selected = -1;
177 cs->length = length;
178 return cs;
181 /* Delete the wrapper and the whole list */
182 void
183 compls_delete(struct completions *cs)
185 if (cs == NULL)
186 return;
188 free(cs->completions);
189 free(cs);
192 /*
193 * Create a completion list from a text and the list of possible
194 * completions (null terminated). Expects a non-null `cs'. `lines' and
195 * `vlines' should have the same length OR `vlines' is NULL.
196 */
197 void
198 filter(struct completions *cs, char *text, char **lines, char **vlines)
200 size_t index = 0;
201 size_t matching = 0;
202 char *l;
204 if (vlines == NULL)
205 vlines = lines;
207 while (1) {
208 if (lines[index] == NULL)
209 break;
211 l = vlines[index] != NULL ? vlines[index] : lines[index];
213 if (strcasestr(l, text) != NULL) {
214 struct completion *c = &cs->completions[matching];
215 c->completion = l;
216 c->rcompletion = lines[index];
217 matching++;
220 index++;
222 cs->length = matching;
223 cs->selected = -1;
226 /* Update the given completion */
227 void
228 update_completions(struct completions *cs, char *text, char **lines,
229 char **vlines, short first_selected)
231 filter(cs, text, lines, vlines);
232 if (first_selected && cs->length > 0)
233 cs->selected = 0;
236 /*
237 * Select the next or previous selection and update some state. `text'
238 * will be updated with the text of the completion and `textlen' with
239 * the new length. If the memory cannot be allocated `status' will be
240 * set to `ERR'.
241 */
242 void
243 complete(struct completions *cs, short first_selected, short p,
244 char **text, int *textlen, enum state *status)
246 struct completion *n;
247 int index;
249 if (cs == NULL || cs->length == 0)
250 return;
252 /*
253 * If the first is always selected and the first entry is
254 * different from the text, expand the text and return
255 */
256 if (first_selected &&
257 cs->selected == 0 &&
258 strcmp(cs->completions->completion, *text) != 0 &&
259 !p) {
260 free(*text);
261 *text = strdup(cs->completions->completion);
262 if (text == NULL) {
263 *status = ERR;
264 return;
266 *textlen = strlen(*text);
267 return;
270 index = cs->selected;
272 if (index == -1 && p)
273 index = 0;
274 index = cs->selected = (cs->length + (p ? index - 1 : index + 1))
275 % cs->length;
277 n = &cs->completions[cs->selected];
279 free(*text);
280 *text = strdup(n->completion);
281 if (text == NULL) {
282 fprintf(stderr, "Memory allocation error!\n");
283 *status = ERR;
284 return;
286 *textlen = strlen(*text);
289 /* Push the character c at the end of the string pointed by p */
290 int
291 pushc(char **p, int maxlen, char c)
293 int len;
295 len = strnlen(*p, maxlen);
296 if (!(len < maxlen - 2)) {
297 char *newptr;
299 maxlen += maxlen >> 1;
300 newptr = realloc(*p, maxlen);
301 if (newptr == NULL) /* bad */
302 return -1;
303 *p = newptr;
306 (*p)[len] = c;
307 (*p)[len + 1] = '\0';
308 return maxlen;
311 /*
312 * Remove the last rune from the *UTF-8* string! This is different
313 * from just setting the last byte to 0 (in some cases ofc). Return a
314 * pointer (e) to the last nonzero char. If e < p then p is empty!
315 */
316 char *
317 popc(char *p)
319 int len = strlen(p);
320 char *e;
322 if (len == 0)
323 return p;
325 e = p + len - 1;
327 do {
328 char c = *e;
330 *e = '\0';
331 e -= 1;
333 /*
334 * If c is a starting byte (11......) or is under
335 * U+007F we're done.
336 */
337 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
338 break;
339 } while (e >= p);
341 return e;
344 /* Remove the last word plus trailing white spaces from the given string */
345 void
346 popw(char *w)
348 int len;
349 short in_word = 1;
351 if ((len = strlen(w)) == 0)
352 return;
354 while (1) {
355 char *e = popc(w);
357 if (e < w)
358 return;
360 if (in_word && isspace(*e))
361 in_word = 0;
363 if (!in_word && !isspace(*e))
364 return;
368 /*
369 * If the string is surrounded by quates (`"') remove them and replace
370 * every `\"' in the string with a single double-quote.
371 */
372 char *
373 normalize_str(const char *str)
375 int len, p;
376 char *s;
378 if ((len = strlen(str)) == 0)
379 return NULL;
381 if ((s = calloc(len, sizeof(char))) == NULL)
382 err(1, "calloc");
383 p = 0;
385 while (*str) {
386 char c = *str;
388 if (*str == '\\') {
389 if (*(str + 1)) {
390 s[p] = *(str + 1);
391 p++;
392 str += 2; /* skip this and the next char */
393 continue;
394 } else
395 break;
397 if (c == '"') {
398 str++; /* skip only this char */
399 continue;
401 s[p] = c;
402 p++;
403 str++;
406 return s;
409 char **
410 readlines(size_t *lineslen)
412 size_t len = 0, cap = 0;
413 size_t linesize = 0;
414 ssize_t linelen;
415 char *line = NULL, **lines = NULL;
417 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
418 if (linelen != 0 && line[linelen-1] == '\n')
419 line[linelen-1] = '\0';
421 if (len == cap) {
422 size_t newcap;
423 void *t;
425 newcap = MAX(cap * 1.5, 32);
426 t = recallocarray(lines, cap, newcap, sizeof(char *));
427 if (t == NULL)
428 err(1, "recallocarray");
429 cap = newcap;
430 lines = t;
433 if ((lines[len++] = strdup(line)) == NULL)
434 err(1, "strdup");
437 if (ferror(stdin))
438 err(1, "getline");
439 free(line);
441 *lineslen = len;
442 return lines;
445 /*
446 * Compute the dimensions of the string str once rendered.
447 * It'll return the width and set ret_width and ret_height if not NULL
448 */
449 int
450 text_extents(char *str, int len, struct rendering *r, int *ret_width,
451 int *ret_height)
453 int height, width;
454 XGlyphInfo gi;
455 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
456 height = r->font->ascent - r->font->descent;
457 width = gi.width - gi.x;
459 if (ret_width != NULL)
460 *ret_width = width;
461 if (ret_height != NULL)
462 *ret_height = height;
463 return width;
466 void
467 draw_string(char *str, int len, int x, int y, struct rendering *r,
468 enum obj_type tt)
470 XftColor xftcolor;
471 if (tt == PROMPT)
472 xftcolor = r->xft_colors[0];
473 if (tt == COMPL)
474 xftcolor = r->xft_colors[1];
475 if (tt == COMPL_HIGH)
476 xftcolor = r->xft_colors[2];
478 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
481 /* Duplicate the string and substitute every space with a 'n` */
482 char *
483 strdupn(char *str)
485 char *t, *dup;
487 if (str == NULL || *str == '\0')
488 return NULL;
490 if ((dup = strdup(str)) == NULL)
491 return NULL;
493 for (t = dup; *t; ++t) {
494 if (*t == ' ')
495 *t = 'n';
498 return dup;
501 int
502 draw_v_box(struct rendering *r, int y, char *prefix, int prefix_width,
503 enum obj_type t, char *text)
505 GC *border_color, bg;
506 int *padding, *borders;
507 int ret = 0, inner_width, inner_height, x;
509 switch (t) {
510 case PROMPT:
511 border_color = r->p_borders_bg;
512 padding = r->p_padding;
513 borders = r->p_borders;
514 bg = r->bgs[0];
515 break;
516 case COMPL:
517 border_color = r->c_borders_bg;
518 padding = r->c_padding;
519 borders = r->c_borders;
520 bg = r->bgs[1];
521 break;
522 case COMPL_HIGH:
523 border_color = r->ch_borders_bg;
524 padding = r->ch_padding;
525 borders = r->ch_borders;
526 bg = r->bgs[2];
527 break;
530 ret = borders[0] + padding[0] + r->text_height + padding[2] + borders[2];
532 inner_width = INNER_WIDTH(r) - borders[1] - borders[3];
533 inner_height = padding[0] + r->text_height + padding[2];
535 /* Border top */
536 XFillRectangle(r->d, r->w, border_color[0], r->x_zero, y, r->width,
537 borders[0]);
539 /* Border right */
540 XFillRectangle(r->d, r->w, border_color[1],
541 r->x_zero + INNER_WIDTH(r) - borders[1], y, borders[1], ret);
543 /* Border bottom */
544 XFillRectangle(r->d, r->w, border_color[2], r->x_zero,
545 y + borders[0] + padding[0] + r->text_height + padding[2],
546 r->width, borders[2]);
548 /* Border left */
549 XFillRectangle(r->d, r->w, border_color[3], r->x_zero, y, borders[3],
550 ret);
552 /* bg */
553 x = r->x_zero + borders[3];
554 y += borders[0];
555 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
557 /* content */
558 y += padding[0] + r->text_height;
559 x += padding[3];
560 if (prefix != NULL) {
561 draw_string(prefix, strlen(prefix), x, y, r, t);
562 x += prefix_width;
564 draw_string(text, strlen(text), x, y, r, t);
566 return ret;
569 int
570 draw_h_box(struct rendering *r, int x, char *prefix, int prefix_width,
571 enum obj_type t, char *text)
573 GC *border_color, bg;
574 int *padding, *borders;
575 int ret = 0, inner_width, inner_height, y, text_width;
577 switch (t) {
578 case PROMPT:
579 border_color = r->p_borders_bg;
580 padding = r->p_padding;
581 borders = r->p_borders;
582 bg = r->bgs[0];
583 break;
584 case COMPL:
585 border_color = r->c_borders_bg;
586 padding = r->c_padding;
587 borders = r->c_borders;
588 bg = r->bgs[1];
589 break;
590 case COMPL_HIGH:
591 border_color = r->ch_borders_bg;
592 padding = r->ch_padding;
593 borders = r->ch_borders;
594 bg = r->bgs[2];
595 break;
598 if (padding[0] < 0 || padding[2] < 0) {
599 padding[0] = INNER_HEIGHT(r) - borders[0] - borders[2]
600 - r->text_height;
601 padding[0] /= 2;
603 padding[2] = padding[0];
606 /* If they are still lesser than 0, set 'em to 0 */
607 if (padding[0] < 0 || padding[2] < 0)
608 padding[0] = padding[2] = 0;
610 /* Get the text width */
611 text_extents(text, strlen(text), r, &text_width, NULL);
612 if (prefix != NULL)
613 text_width += prefix_width;
615 ret = borders[3] + padding[3] + text_width + padding[1] + borders[1];
617 inner_width = padding[3] + text_width + padding[1];
618 inner_height = INNER_HEIGHT(r) - borders[0] - borders[2];
620 /* Border top */
621 XFillRectangle(r->d, r->w, border_color[0], x, r->y_zero, ret,
622 borders[0]);
624 /* Border right */
625 XFillRectangle(r->d, r->w, border_color[1],
626 x + borders[3] + inner_width, r->y_zero, borders[1],
627 INNER_HEIGHT(r));
629 /* Border bottom */
630 XFillRectangle(r->d, r->w, border_color[2], x,
631 r->y_zero + INNER_HEIGHT(r) - borders[2], ret,
632 borders[2]);
634 /* Border left */
635 XFillRectangle(r->d, r->w, border_color[3], x, r->y_zero, borders[3],
636 INNER_HEIGHT(r));
638 /* bg */
639 x += borders[3];
640 y = r->y_zero + borders[0];
641 XFillRectangle(r->d, r->w, bg, x, y, inner_width, inner_height);
643 /* content */
644 y += padding[0] + r->text_height;
645 x += padding[3];
646 if (prefix != NULL) {
647 draw_string(prefix, strlen(prefix), x, y, r, t);
648 x += prefix_width;
650 draw_string(text, strlen(text), x, y, r, t);
652 return ret;
655 /*
656 * ,-----------------------------------------------------------------,
657 * | 20 char text | completion | completion | completion | compl |
658 * `-----------------------------------------------------------------'
659 */
660 void
661 draw_horizontally(struct rendering *r, char *text, struct completions *cs)
663 size_t i;
664 int x = r->x_zero;
666 /* Draw the prompt */
667 x += draw_h_box(r, x, r->ps1, r->ps1w, PROMPT, text);
669 for (i = r->offset; i < cs->length; ++i) {
670 enum obj_type t;
672 if (cs->selected == (ssize_t)i)
673 t = COMPL_HIGH;
674 else
675 t = COMPL;
677 cs->completions[i].offset = x;
679 x += draw_h_box(r, x, NULL, 0, t,
680 cs->completions[i].completion);
682 if (x > INNER_WIDTH(r))
683 break;
686 for (i += 1; i < cs->length; ++i)
687 cs->completions[i].offset = -1;
690 /*
691 * ,-----------------------------------------------------------------,
692 * | prompt |
693 * |-----------------------------------------------------------------|
694 * | completion |
695 * |-----------------------------------------------------------------|
696 * | completion |
697 * `-----------------------------------------------------------------'
698 */
699 void
700 draw_vertically(struct rendering *r, char *text, struct completions *cs)
702 size_t i;
703 int y = r->y_zero;
705 y += draw_v_box(r, y, r->ps1, r->ps1w, PROMPT, text);
707 for (i = r->offset; i < cs->length; ++i) {
708 enum obj_type t;
710 if (cs->selected == (ssize_t)i)
711 t = COMPL_HIGH;
712 else
713 t = COMPL;
715 cs->completions[i].offset = y;
717 y += draw_v_box(r, y, NULL, 0, t,
718 cs->completions[i].completion);
720 if (y > INNER_HEIGHT(r))
721 break;
724 for (i += 1; i < cs->length; ++i)
725 cs->completions[i].offset = -1;
728 void
729 draw(struct rendering *r, char *text, struct completions *cs)
731 /* Draw the background */
732 XFillRectangle(r->d, r->w, r->bgs[1], r->x_zero, r->y_zero,
733 INNER_WIDTH(r), INNER_HEIGHT(r));
735 /* Draw the contents */
736 if (r->horizontal_layout)
737 draw_horizontally(r, text, cs);
738 else
739 draw_vertically(r, text, cs);
741 /* Draw the borders */
742 if (r->borders[0] != 0)
743 XFillRectangle(r->d, r->w, r->borders_bg[0], 0, 0, r->width,
744 r->borders[0]);
746 if (r->borders[1] != 0)
747 XFillRectangle(r->d, r->w, r->borders_bg[1],
748 r->width - r->borders[1], 0, r->borders[1],
749 r->height);
751 if (r->borders[2] != 0)
752 XFillRectangle(r->d, r->w, r->borders_bg[2], 0,
753 r->height - r->borders[2], r->width, r->borders[2]);
755 if (r->borders[3] != 0)
756 XFillRectangle(r->d, r->w, r->borders_bg[3], 0, 0,
757 r->borders[3], r->height);
759 /* render! */
760 XFlush(r->d);
763 /* Set some WM stuff */
764 void
765 set_win_atoms_hints(Display *d, Window w, int width, int height)
767 Atom type;
768 XClassHint *class_hint;
769 XSizeHints *size_hint;
771 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", 0);
772 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_WINDOW_TYPE", 0),
773 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
774 (unsigned char *)&type, 1);
776 /* some window managers honor this properties */
777 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", 0);
778 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
779 XInternAtom(d, "ATOM", 0), 32, PropModeReplace,
780 (unsigned char *)&type, 1);
782 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", 0);
783 XChangeProperty(d, w, XInternAtom(d, "_NET_WM_STATE", 0),
784 XInternAtom(d, "ATOM", 0), 32, PropModeAppend,
785 (unsigned char *)&type, 1);
787 /* Setting window hints */
788 class_hint = XAllocClassHint();
789 if (class_hint == NULL) {
790 fprintf(stderr, "Could not allocate memory for class hint\n");
791 exit(EX_UNAVAILABLE);
794 class_hint->res_name = RESNAME;
795 class_hint->res_class = RESCLASS;
796 XSetClassHint(d, w, class_hint);
797 XFree(class_hint);
799 size_hint = XAllocSizeHints();
800 if (size_hint == NULL) {
801 fprintf(stderr, "Could not allocate memory for size hint\n");
802 exit(EX_UNAVAILABLE);
805 size_hint->flags = PMinSize | PBaseSize;
806 size_hint->min_width = width;
807 size_hint->base_width = width;
808 size_hint->min_height = height;
809 size_hint->base_height = height;
811 XFlush(d);
814 /* Get the width and height of the window `w' */
815 void
816 get_wh(Display *d, Window *w, int *width, int *height)
818 XWindowAttributes win_attr;
820 XGetWindowAttributes(d, *w, &win_attr);
821 *height = win_attr.height;
822 *width = win_attr.width;
825 /* find the current xinerama monitor if possible */
826 void
827 findmonitor(Display *d, int *x, int *y, int *width, int *height)
829 XineramaScreenInfo *info;
830 Window rr;
831 Window root;
832 int screens, monitors, i;
833 int rootx, rooty, winx, winy;
834 unsigned int mask;
835 short res;
837 if (!XineramaIsActive(d))
838 return;
840 screens = XScreenCount(d);
841 for (i = 0; i < screens; ++i) {
842 root = XRootWindow(d, i);
843 res = XQueryPointer(d, root, &rr, &rr, &rootx, &rooty, &winx,
844 &winy, &mask);
845 if (res)
846 break;
849 if (!res)
850 return;
852 /* Now find in which monitor the mice is */
853 info = XineramaQueryScreens(d, &monitors);
854 if (info == NULL)
855 return;
857 for (i = 0; i < monitors; ++i) {
858 if (info[i].x_org <= rootx &&
859 rootx <= (info[i].x_org + info[i].width) &&
860 info[i].y_org <= rooty &&
861 rooty <= (info[i].y_org + info[i].height)) {
862 *x = info[i].x_org;
863 *y = info[i].y_org;
864 *width = info[i].width;
865 *height = info[i].height;
866 break;
870 XFree(info);
873 int
874 grabfocus(Display *d, Window w)
876 int i;
877 for (i = 0; i < 100; ++i) {
878 Window focuswin;
879 int revert_to_win;
881 XGetInputFocus(d, &focuswin, &revert_to_win);
883 if (focuswin == w)
884 return 1;
886 XSetInputFocus(d, w, RevertToParent, CurrentTime);
887 usleep(1000);
889 return 0;
892 /*
893 * I know this may seem a little hackish BUT is the only way I managed
894 * to actually grab that goddam keyboard. Only one call to
895 * XGrabKeyboard does not always end up with the keyboard grabbed!
896 */
897 int
898 take_keyboard(Display *d, Window w)
900 int i;
901 for (i = 0; i < 100; i++) {
902 if (XGrabKeyboard(d, w, 1, GrabModeAsync, GrabModeAsync,
903 CurrentTime) == GrabSuccess)
904 return 1;
905 usleep(1000);
907 fprintf(stderr, "Cannot grab keyboard\n");
908 return 0;
911 unsigned long
912 parse_color(const char *str, const char *def)
914 size_t len;
915 rgba_t tmp;
916 char *ep;
918 if (str == NULL)
919 goto err;
921 len = strlen(str);
923 /* +1 for the # ath the start */
924 if (*str != '#' || len > 9 || len < 4)
925 goto err;
926 ++str; /* skip the # */
928 errno = 0;
929 tmp = (rgba_t)(uint32_t)strtoul(str, &ep, 16);
931 if (errno)
932 goto err;
934 switch (len - 1) {
935 case 3:
936 /* expand #rgb -> #rrggbb */
937 tmp.v = (tmp.v & 0xf00) * 0x1100 | (tmp.v & 0x0f0) * 0x0110
938 | (tmp.v & 0x00f) * 0x0011;
939 case 6:
940 /* assume 0xff opacity */
941 tmp.rgba.a = 0xff;
942 break;
943 } /* colors in #aarrggbb need no adjustments */
945 /* premultiply the alpha */
946 if (tmp.rgba.a) {
947 tmp.rgba.r = (tmp.rgba.r * tmp.rgba.a) / 255;
948 tmp.rgba.g = (tmp.rgba.g * tmp.rgba.a) / 255;
949 tmp.rgba.b = (tmp.rgba.b * tmp.rgba.a) / 255;
950 return tmp.v;
953 return 0U;
955 err:
956 fprintf(stderr, "Invalid color: \"%s\".\n", str);
957 if (def != NULL)
958 return parse_color(def, NULL);
959 else
960 return 0U;
963 /*
964 * Given a string try to parse it as a number or return `def'.
965 */
966 int
967 parse_integer(const char *str, int def)
969 const char *errstr;
970 int i;
972 i = strtonum(str, INT_MIN, INT_MAX, &errstr);
973 if (errstr != NULL) {
974 warnx("'%s' is %s; using %d as default", str, errstr, def);
975 return def;
978 return i;
981 /*
982 * Like parse_integer but recognize the percentages (i.e. strings
983 * ending with `%')
984 */
985 int
986 parse_int_with_percentage(const char *str, int default_value, int max)
988 int len = strlen(str);
990 if (len > 0 && str[len - 1] == '%') {
991 int val;
992 char *cpy;
994 if ((cpy = strdup(str)) == NULL)
995 err(1, "strdup");
997 cpy[len - 1] = '\0';
998 val = parse_integer(cpy, default_value);
999 free(cpy);
1000 return val * max / 100;
1003 return parse_integer(str, default_value);
1006 void
1007 get_mouse_coords(Display *d, int *x, int *y)
1009 Window w, root;
1010 int i;
1011 unsigned int u;
1013 *x = *y = 0;
1014 root = DefaultRootWindow(d);
1016 if (!XQueryPointer(d, root, &root, &w, x, y, &i, &i, &u)) {
1017 for (i = 0; i < ScreenCount(d); ++i) {
1018 if (root == RootWindow(d, i))
1019 break;
1025 * Like parse_int_with_percentage but understands some special values:
1026 * - middle that is (max-self)/2
1027 * - center = middle
1028 * - start that is 0
1029 * - end that is (max-self)
1030 * - mx x coordinate of the mouse
1031 * - my y coordinate of the mouse
1033 int
1034 parse_int_with_pos(Display *d, const char *str, int default_value, int max,
1035 int self)
1037 if (!strcmp(str, "start"))
1038 return 0;
1039 if (!strcmp(str, "middle") || !strcmp(str, "center"))
1040 return (max - self) / 2;
1041 if (!strcmp(str, "end"))
1042 return max - self;
1043 if (!strcmp(str, "mx") || !strcmp(str, "my")) {
1044 int x, y;
1046 get_mouse_coords(d, &x, &y);
1047 if (!strcmp(str, "mx"))
1048 return x - 1;
1049 else
1050 return y - 1;
1052 return parse_int_with_percentage(str, default_value, max);
1055 /* Parse a string like a CSS value. */
1056 /* TODO: harden a bit this function */
1057 char **
1058 parse_csslike(const char *str)
1060 int i, j;
1061 char *s, *token, **ret;
1062 short any_null;
1064 s = strdup(str);
1065 if (s == NULL)
1066 return NULL;
1068 ret = malloc(4 * sizeof(char *));
1069 if (ret == NULL) {
1070 free(s);
1071 return NULL;
1074 for (i = 0; (token = strsep(&s, " ")) != NULL && i < 4; ++i)
1075 ret[i] = strdup(token);
1077 if (i == 1)
1078 for (j = 1; j < 4; j++)
1079 ret[j] = strdup(ret[0]);
1081 if (i == 2) {
1082 ret[2] = strdup(ret[0]);
1083 ret[3] = strdup(ret[1]);
1086 if (i == 3)
1087 ret[3] = strdup(ret[1]);
1090 * before we didn't check for the return type of strdup, here
1091 * we will
1094 any_null = 0;
1095 for (i = 0; i < 4; ++i)
1096 any_null = ret[i] == NULL || any_null;
1098 if (any_null)
1099 for (i = 0; i < 4; ++i)
1100 if (ret[i] != NULL)
1101 free(ret[i]);
1103 if (i == 0 || any_null) {
1104 free(s);
1105 free(ret);
1106 return NULL;
1109 return ret;
1113 * Given an event, try to understand what the users wants. If the
1114 * return value is ADD_CHAR then `input' is a pointer to a string that
1115 * will need to be free'ed later.
1117 enum action
1118 parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input)
1120 char str[SYM_BUF_SIZE] = { 0 };
1121 Status s;
1123 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
1124 return DEL_CHAR;
1126 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
1127 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
1129 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
1130 return CONFIRM;
1132 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
1133 return EXIT;
1135 /* Try to read what key was pressed */
1136 s = 0;
1137 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
1138 if (s == XBufferOverflow) {
1139 fprintf(stderr,
1140 "Buffer overflow when trying to create keyboard "
1141 "symbol map.\n");
1142 return EXIT;
1145 if (ev->state & ControlMask) {
1146 if (!strcmp(str, "")) /* C-u */
1147 return DEL_LINE;
1148 if (!strcmp(str, "")) /* C-w */
1149 return DEL_WORD;
1150 if (!strcmp(str, "")) /* C-h */
1151 return DEL_CHAR;
1152 if (!strcmp(str, "\r")) /* C-m */
1153 return CONFIRM_CONTINUE;
1154 if (!strcmp(str, "")) /* C-p */
1155 return PREV_COMPL;
1156 if (!strcmp(str, "")) /* C-n */
1157 return NEXT_COMPL;
1158 if (!strcmp(str, "")) /* C-c */
1159 return EXIT;
1160 if (!strcmp(str, "\t")) /* C-i */
1161 return TOGGLE_FIRST_SELECTED;
1164 *input = strdup(str);
1165 if (*input == NULL) {
1166 fprintf(stderr, "Error while allocating memory for key.\n");
1167 return EXIT;
1170 return ADD_CHAR;
1173 void
1174 confirm(enum state *status, struct rendering *r, struct completions *cs,
1175 char **text, int *textlen)
1177 if ((cs->selected != -1) || (cs->length > 0 && r->first_selected)) {
1178 /* if there is something selected expand it and return */
1179 int index = cs->selected == -1 ? 0 : cs->selected;
1180 struct completion *c = cs->completions;
1181 char *t;
1183 while (1) {
1184 if (index == 0)
1185 break;
1186 c++;
1187 index--;
1190 t = c->rcompletion;
1191 free(*text);
1192 *text = strdup(t);
1194 if (*text == NULL) {
1195 fprintf(stderr, "Memory allocation error\n");
1196 *status = ERR;
1199 *textlen = strlen(*text);
1200 return;
1203 if (!r->free_text) /* cannot accept arbitrary text */
1204 *status = LOOPING;
1208 * cs: completion list
1209 * offset: the offset of the click
1210 * first: the first (rendered) item
1211 * def: the default action
1213 enum action
1214 select_clicked(struct completions *cs, size_t offset, size_t first,
1215 enum action def)
1217 ssize_t selected = first;
1218 int set = 0;
1220 if (cs->length == 0)
1221 return NO_OP;
1223 if (offset < cs->completions[selected].offset)
1224 return EXIT;
1226 /* skip the first entry */
1227 for (selected += 1; selected < cs->length; ++selected) {
1228 if (cs->completions[selected].offset == -1)
1229 break;
1231 if (offset < cs->completions[selected].offset) {
1232 cs->selected = selected - 1;
1233 set = 1;
1234 break;
1238 if (!set)
1239 cs->selected = selected - 1;
1241 return def;
1244 enum action
1245 handle_mouse(struct rendering *r, struct completions *cs,
1246 XButtonPressedEvent *e)
1248 size_t off;
1250 if (r->horizontal_layout)
1251 off = e->x;
1252 else
1253 off = e->y;
1255 switch (e->button) {
1256 case Button1:
1257 return select_clicked(cs, off, r->offset, CONFIRM);
1259 case Button3:
1260 return select_clicked(cs, off, r->offset, CONFIRM_CONTINUE);
1262 case Button4:
1263 return SCROLL_UP;
1265 case Button5:
1266 return SCROLL_DOWN;
1269 return NO_OP;
1272 /* event loop */
1273 enum state
1274 loop(struct rendering *r, char **text, int *textlen, struct completions *cs,
1275 char **lines, char **vlines)
1277 enum state status = LOOPING;
1279 while (status == LOOPING) {
1280 XEvent e;
1281 XNextEvent(r->d, &e);
1283 if (XFilterEvent(&e, r->w))
1284 continue;
1286 switch (e.type) {
1287 case KeymapNotify:
1288 XRefreshKeyboardMapping(&e.xmapping);
1289 break;
1291 case FocusIn:
1292 /* Re-grab focus */
1293 if (e.xfocus.window != r->w)
1294 grabfocus(r->d, r->w);
1295 break;
1297 case VisibilityNotify:
1298 if (e.xvisibility.state != VisibilityUnobscured)
1299 XRaiseWindow(r->d, r->w);
1300 break;
1302 case MapNotify:
1303 get_wh(r->d, &r->w, &r->width, &r->height);
1304 draw(r, *text, cs);
1305 break;
1307 case KeyPress:
1308 case ButtonPress: {
1309 enum action a;
1310 char *input = NULL;
1312 if (e.type == KeyPress)
1313 a = parse_event(r->d, (XKeyPressedEvent *)&e,
1314 r->xic, &input);
1315 else
1316 a = handle_mouse(r, cs,
1317 (XButtonPressedEvent *)&e);
1319 switch (a) {
1320 case NO_OP:
1321 break;
1323 case EXIT:
1324 status = ERR;
1325 break;
1327 case CONFIRM: {
1328 status = OK;
1329 confirm(&status, r, cs, text, textlen);
1330 break;
1333 case CONFIRM_CONTINUE: {
1334 status = OK_LOOP;
1335 confirm(&status, r, cs, text, textlen);
1336 break;
1339 case PREV_COMPL: {
1340 complete(cs, r->first_selected, 1, text,
1341 textlen, &status);
1342 r->offset = cs->selected;
1343 break;
1346 case NEXT_COMPL: {
1347 complete(cs, r->first_selected, 0, text,
1348 textlen, &status);
1349 r->offset = cs->selected;
1350 break;
1353 case DEL_CHAR:
1354 popc(*text);
1355 update_completions(cs, *text, lines, vlines,
1356 r->first_selected);
1357 r->offset = 0;
1358 break;
1360 case DEL_WORD: {
1361 popw(*text);
1362 update_completions(cs, *text, lines, vlines,
1363 r->first_selected);
1364 break;
1367 case DEL_LINE: {
1368 int i;
1369 for (i = 0; i < *textlen; ++i)
1370 (*text)[i] = 0;
1371 update_completions(cs, *text, lines, vlines,
1372 r->first_selected);
1373 r->offset = 0;
1374 break;
1377 case ADD_CHAR: {
1378 int str_len, i;
1380 str_len = strlen(input);
1383 * sometimes a strange key is pressed
1384 * i.e. ctrl alone), so input will be
1385 * empty. Don't need to update
1386 * completion in that case
1388 if (str_len == 0)
1389 break;
1391 for (i = 0; i < str_len; ++i) {
1392 *textlen = pushc(text, *textlen,
1393 input[i]);
1394 if (*textlen == -1) {
1395 fprintf(stderr,
1396 "Memory allocation "
1397 "error\n");
1398 status = ERR;
1399 break;
1403 if (status != ERR) {
1404 update_completions(cs, *text, lines,
1405 vlines, r->first_selected);
1406 free(input);
1409 r->offset = 0;
1410 break;
1413 case TOGGLE_FIRST_SELECTED:
1414 r->first_selected = !r->first_selected;
1415 if (r->first_selected && cs->selected < 0)
1416 cs->selected = 0;
1417 if (!r->first_selected && cs->selected == 0)
1418 cs->selected = -1;
1419 break;
1421 case SCROLL_DOWN:
1422 r->offset = MIN(r->offset + 1, cs->length - 1);
1423 break;
1425 case SCROLL_UP:
1426 r->offset = MAX((ssize_t)r->offset - 1, 0);
1427 break;
1432 draw(r, *text, cs);
1435 return status;
1438 int
1439 load_font(struct rendering *r, const char *fontname)
1441 r->font = XftFontOpenName(r->d, DefaultScreen(r->d), fontname);
1442 return 0;
1445 void
1446 xim_init(struct rendering *r, XrmDatabase *xdb)
1448 XIMStyle best_match_style;
1449 XIMStyles *xis;
1450 int i;
1452 /* Open the X input method */
1453 if ((r->xim = XOpenIM(r->d, *xdb, RESNAME, RESCLASS)) == NULL)
1454 err(1, "XOpenIM");
1456 if (XGetIMValues(r->xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1457 fprintf(stderr, "Input Styles could not be retrieved\n");
1458 exit(EX_UNAVAILABLE);
1461 best_match_style = 0;
1462 for (i = 0; i < xis->count_styles; ++i) {
1463 XIMStyle ts = xis->supported_styles[i];
1464 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1465 best_match_style = ts;
1466 break;
1469 XFree(xis);
1471 if (!best_match_style)
1472 fprintf(stderr,
1473 "No matching input style could be determined\n");
1475 r->xic = XCreateIC(r->xim, XNInputStyle, best_match_style,
1476 XNClientWindow, r->w, XNFocusWindow, r->w, NULL);
1477 if (r->xic == NULL)
1478 err(1, "XCreateIC");
1481 void
1482 create_window(struct rendering *r, Window parent_window, Colormap cmap,
1483 XVisualInfo vinfo, int x, int y, int ox, int oy,
1484 unsigned long background_pixel)
1486 XSetWindowAttributes attr;
1487 unsigned long vmask;
1489 /* Create the window */
1490 attr.colormap = cmap;
1491 attr.override_redirect = 1;
1492 attr.border_pixel = 0;
1493 attr.background_pixel = background_pixel;
1494 attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask
1495 | KeymapStateMask | ButtonPress | VisibilityChangeMask;
1497 vmask = CWBorderPixel | CWBackPixel | CWColormap | CWEventMask |
1498 CWOverrideRedirect;
1500 r->w = XCreateWindow(r->d, parent_window, x + ox, y + oy, r->width, r->height, 0,
1501 vinfo.depth, InputOutput, vinfo.visual, vmask, &attr);
1504 void
1505 ps1extents(struct rendering *r)
1507 char *dup;
1508 dup = strdupn(r->ps1);
1509 text_extents(dup == NULL ? r->ps1 : dup, r->ps1len, r, &r->ps1w, &r->ps1h);
1510 free(dup);
1513 void
1514 usage(char *prgname)
1516 fprintf(stderr,
1517 "%s [-Aahmv] [-B colors] [-b size] [-C color] [-c color]\n"
1518 " [-d separator] [-e window] [-f font] [-G color] [-g "
1519 "size]\n"
1520 " [-H height] [-I color] [-i size] [-J color] [-j "
1521 "size] [-l layout]\n"
1522 " [-P padding] [-p prompt] [-S color] [-s color] [-T "
1523 "color]\n"
1524 " [-t color] [-W width] [-x coord] [-y coord]\n",
1525 prgname);
1528 int
1529 main(int argc, char **argv)
1531 struct completions *cs;
1532 struct rendering r;
1533 XVisualInfo vinfo;
1534 Colormap cmap;
1535 size_t nlines, i;
1536 Window parent_window;
1537 XrmDatabase xdb;
1538 unsigned long fgs[3], bgs[3]; /* prompt, compl, compl_highlighted */
1539 unsigned long borders_bg[4], p_borders_bg[4], c_borders_bg[4],
1540 ch_borders_bg[4]; /* N E S W */
1541 enum state status;
1542 int ch;
1543 int offset_x, offset_y, x, y;
1544 int textlen, d_width, d_height;
1545 short embed;
1546 char *sep, *parent_window_id;
1547 char **lines, **vlines;
1548 char *fontname, *text, *xrm;
1550 sep = NULL;
1551 parent_window_id = NULL;
1553 r.first_selected = 0;
1554 r.free_text = 1;
1555 r.multiple_select = 0;
1556 r.offset = 0;
1558 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1559 switch (ch) {
1560 case 'h': /* help */
1561 usage(*argv);
1562 return 0;
1563 case 'v': /* version */
1564 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
1565 return 0;
1566 case 'e': /* embed */
1567 if ((parent_window_id = strdup(optarg)) == NULL)
1568 err(1, "strdup");
1569 break;
1570 case 'd':
1571 if ((sep = strdup(optarg)) == NULL)
1572 err(1, "strdup");
1573 break;
1574 case 'A':
1575 r.free_text = 0;
1576 break;
1577 case 'm':
1578 r.multiple_select = 1;
1579 break;
1580 default:
1581 break;
1585 lines = readlines(&nlines);
1587 vlines = NULL;
1588 if (sep != NULL) {
1589 int l;
1590 l = strlen(sep);
1591 if ((vlines = calloc(nlines, sizeof(char *))) == NULL)
1592 err(1, "calloc");
1594 for (i = 0; i < nlines; i++) {
1595 char *t;
1596 t = strstr(lines[i], sep);
1597 if (t == NULL)
1598 vlines[i] = lines[i];
1599 else
1600 vlines[i] = t + l;
1604 setlocale(LC_ALL, getenv("LANG"));
1606 status = LOOPING;
1608 /* where the monitor start (used only with xinerama) */
1609 offset_x = offset_y = 0;
1611 /* default width and height */
1612 r.width = 400;
1613 r.height = 20;
1615 /* default position on the screen */
1616 x = y = 0;
1618 for (i = 0; i < 4; ++i) {
1619 /* default paddings */
1620 r.p_padding[i] = 10;
1621 r.c_padding[i] = 10;
1622 r.ch_padding[i] = 10;
1624 /* default borders */
1625 r.borders[i] = 0;
1626 r.p_borders[i] = 0;
1627 r.c_borders[i] = 0;
1628 r.ch_borders[i] = 0;
1632 * The prompt. We duplicate the string so later is easy to
1633 * free (in the case it's been overwritten by the user)
1635 if ((r.ps1 = strdup("$ ")) == NULL)
1636 err(1, "strdup");
1638 /* same for the font name */
1639 if ((fontname = strdup(DEFFONT)) == NULL)
1640 err(1, "strdup");
1642 textlen = 10;
1643 if ((text = malloc(textlen * sizeof(char))) == NULL)
1644 err(1, "malloc");
1646 /* struct completions *cs = filter(text, lines); */
1647 if ((cs = compls_new(nlines)) == NULL)
1648 err(1, "compls_new");
1650 /* start talking to xorg */
1651 r.d = XOpenDisplay(NULL);
1652 if (r.d == NULL) {
1653 fprintf(stderr, "Could not open display!\n");
1654 return EX_UNAVAILABLE;
1657 embed = 1;
1658 if (!(parent_window_id && (parent_window = strtol(parent_window_id, NULL, 0)))) {
1659 parent_window = DefaultRootWindow(r.d);
1660 embed = 0;
1663 /* get display size */
1664 get_wh(r.d, &parent_window, &d_width, &d_height);
1666 if (!embed)
1667 findmonitor(r.d, &offset_x, &offset_y, &d_width, &d_height);
1669 XMatchVisualInfo(r.d, DefaultScreen(r.d), 32, TrueColor, &vinfo);
1670 cmap = XCreateColormap(r.d, XDefaultRootWindow(r.d), vinfo.visual,
1671 AllocNone);
1673 fgs[0] = fgs[1] = parse_color("#fff", NULL);
1674 fgs[2] = parse_color("#000", NULL);
1676 bgs[0] = bgs[1] = parse_color("#000", NULL);
1677 bgs[2] = parse_color("#fff", NULL);
1679 borders_bg[0] = borders_bg[1] = borders_bg[2] = borders_bg[3] =
1680 parse_color("#000", NULL);
1682 p_borders_bg[0] = p_borders_bg[1] = p_borders_bg[2] = p_borders_bg[3]
1683 = parse_color("#000", NULL);
1684 c_borders_bg[0] = c_borders_bg[1] = c_borders_bg[2] = c_borders_bg[3]
1685 = parse_color("#000", NULL);
1686 ch_borders_bg[0] = ch_borders_bg[1] = ch_borders_bg[2] = ch_borders_bg[3]
1687 = parse_color("#000", NULL);
1689 r.horizontal_layout = 1;
1691 /* Read the resources */
1692 XrmInitialize();
1693 xrm = XResourceManagerString(r.d);
1694 xdb = NULL;
1695 if (xrm != NULL) {
1696 XrmValue value;
1697 char *datatype[20];
1699 xdb = XrmGetStringDatabase(xrm);
1701 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value)) {
1702 free(fontname);
1703 if ((fontname = strdup(value.addr)) == NULL)
1704 err(1, "strdup");
1705 } else {
1706 fprintf(stderr, "no font defined, using %s\n", fontname);
1709 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value))
1710 r.horizontal_layout = !strcmp(value.addr, "horizontal");
1711 else
1712 fprintf(stderr, "no layout defined, using horizontal\n");
1714 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value)) {
1715 free(r.ps1);
1716 r.ps1 = normalize_str(value.addr);
1717 } else {
1718 fprintf(stderr,
1719 "no prompt defined, using \"%s\" as "
1720 "default\n",
1721 r.ps1);
1724 if (XrmGetResource(xdb, "MyMenu.prompt.border.size", "*", datatype, &value)) {
1725 char **sizes;
1726 sizes = parse_csslike(value.addr);
1727 if (sizes != NULL)
1728 for (i = 0; i < 4; ++i)
1729 r.p_borders[i] = parse_integer(sizes[i], 0);
1730 else
1731 fprintf(stderr,
1732 "error while parsing "
1733 "MyMenu.prompt.border.size");
1736 if (XrmGetResource(xdb, "MyMenu.prompt.border.color", "*", datatype, &value)) {
1737 char **colors;
1738 colors = parse_csslike(value.addr);
1739 if (colors != NULL)
1740 for (i = 0; i < 4; ++i)
1741 p_borders_bg[i] = parse_color(colors[i], "#000");
1742 else
1743 fprintf(stderr,
1744 "error while parsing "
1745 "MyMenu.prompt.border.color");
1748 if (XrmGetResource(xdb, "MyMenu.prompt.padding", "*", datatype, &value)) {
1749 char **colors;
1750 colors = parse_csslike(value.addr);
1751 if (colors != NULL)
1752 for (i = 0; i < 4; ++i)
1753 r.p_padding[i] = parse_integer(colors[i], 0);
1754 else
1755 fprintf(stderr,
1756 "error while parsing "
1757 "MyMenu.prompt.padding");
1760 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value))
1761 r.width = parse_int_with_percentage(value.addr, r.width, d_width);
1762 else
1763 fprintf(stderr, "no width defined, using %d\n", r.width);
1765 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value))
1766 r.height = parse_int_with_percentage(value.addr, r.height, d_height);
1767 else
1768 fprintf(stderr, "no height defined, using %d\n", r.height);
1770 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value))
1771 x = parse_int_with_pos(r.d, value.addr, x, d_width, r.width);
1773 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value))
1774 y = parse_int_with_pos(r.d, value.addr, y, d_height, r.height);
1776 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value)) {
1777 char **borders;
1778 borders = parse_csslike(value.addr);
1779 if (borders != NULL)
1780 for (i = 0; i < 4; ++i)
1781 r.borders[i] = parse_int_with_percentage(
1782 borders[i], 0, (i % 2) == 0 ? d_height : d_width);
1783 else
1784 fprintf(stderr,
1785 "error while parsing "
1786 "MyMenu.border.size\n");
1789 /* Prompt */
1790 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value))
1791 fgs[0] = parse_color(value.addr, "#fff");
1793 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value))
1794 bgs[0] = parse_color(value.addr, "#000");
1796 /* Completions */
1797 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value))
1798 fgs[1] = parse_color(value.addr, "#fff");
1800 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value))
1801 bgs[1] = parse_color(value.addr, "#000");
1803 if (XrmGetResource(xdb, "MyMenu.completion.padding", "*", datatype, &value)) {
1804 char **paddings;
1805 paddings = parse_csslike(value.addr);
1806 if (paddings != NULL)
1807 for (i = 0; i < 4; ++i)
1808 r.c_padding[i] = parse_integer(paddings[i], 0);
1809 else
1810 fprintf(stderr,
1811 "Error while parsing "
1812 "MyMenu.completion.padding");
1815 if (XrmGetResource(xdb, "MyMenu.completion.border.size", "*", datatype, &value)) {
1816 char **sizes;
1817 sizes = parse_csslike(value.addr);
1818 if (sizes != NULL)
1819 for (i = 0; i < 4; ++i)
1820 r.c_borders[i] = parse_integer(sizes[i], 0);
1821 else
1822 fprintf(stderr,
1823 "Error while parsing "
1824 "MyMenu.completion.border.size");
1827 if (XrmGetResource(xdb, "MyMenu.completion.border.color", "*", datatype, &value)) {
1828 char **sizes;
1829 sizes = parse_csslike(value.addr);
1830 if (sizes != NULL)
1831 for (i = 0; i < 4; ++i)
1832 c_borders_bg[i] = parse_color(sizes[i], "#000");
1833 else
1834 fprintf(stderr,
1835 "Error while parsing "
1836 "MyMenu.completion.border.color");
1839 /* Completion Highlighted */
1840 if (XrmGetResource(
1841 xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value))
1842 fgs[2] = parse_color(value.addr, "#000");
1844 if (XrmGetResource(
1845 xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value))
1846 bgs[2] = parse_color(value.addr, "#fff");
1848 if (XrmGetResource(
1849 xdb, "MyMenu.completion_highlighted.padding", "*", datatype, &value)) {
1850 char **paddings;
1851 paddings = parse_csslike(value.addr);
1852 if (paddings != NULL)
1853 for (i = 0; i < 4; ++i)
1854 r.ch_padding[i] = parse_integer(paddings[i], 0);
1855 else
1856 fprintf(stderr,
1857 "Error while parsing "
1858 "MyMenu.completion_highlighted."
1859 "padding");
1862 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.size", "*", datatype,
1863 &value)) {
1864 char **sizes;
1865 sizes = parse_csslike(value.addr);
1866 if (sizes != NULL)
1867 for (i = 0; i < 4; ++i)
1868 r.ch_borders[i] = parse_integer(sizes[i], 0);
1869 else
1870 fprintf(stderr,
1871 "Error while parsing "
1872 "MyMenu.completion_highlighted."
1873 "border.size");
1876 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.border.color", "*", datatype,
1877 &value)) {
1878 char **colors;
1879 colors = parse_csslike(value.addr);
1880 if (colors != NULL)
1881 for (i = 0; i < 4; ++i)
1882 ch_borders_bg[i] = parse_color(colors[i], "#000");
1883 else
1884 fprintf(stderr,
1885 "Error while parsing "
1886 "MyMenu.completion_highlighted."
1887 "border.color");
1890 /* Border */
1891 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value)) {
1892 char **colors;
1893 colors = parse_csslike(value.addr);
1894 if (colors != NULL)
1895 for (i = 0; i < 4; ++i)
1896 borders_bg[i] = parse_color(colors[i], "#000");
1897 else
1898 fprintf(stderr,
1899 "error while parsing "
1900 "MyMenu.border.color\n");
1904 /* Second round of args parsing */
1905 optind = 0; /* reset the option index */
1906 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1907 switch (ch) {
1908 case 'a':
1909 r.first_selected = 1;
1910 break;
1911 case 'A':
1912 /* free_text -- already catched */
1913 case 'd':
1914 /* separator -- this case was already catched */
1915 case 'e':
1916 /* embedding mymenu this case was already catched. */
1917 case 'm':
1918 /* multiple selection this case was already catched.
1920 break;
1921 case 'p': {
1922 char *newprompt;
1923 newprompt = strdup(optarg);
1924 if (newprompt != NULL) {
1925 free(r.ps1);
1926 r.ps1 = newprompt;
1928 break;
1930 case 'x':
1931 x = parse_int_with_pos(r.d, optarg, x, d_width, r.width);
1932 break;
1933 case 'y':
1934 y = parse_int_with_pos(r.d, optarg, y, d_height, r.height);
1935 break;
1936 case 'P': {
1937 char **paddings;
1938 if ((paddings = parse_csslike(optarg)) != NULL)
1939 for (i = 0; i < 4; ++i)
1940 r.p_padding[i] = parse_integer(paddings[i], 0);
1941 break;
1943 case 'G': {
1944 char **colors;
1945 if ((colors = parse_csslike(optarg)) != NULL)
1946 for (i = 0; i < 4; ++i)
1947 p_borders_bg[i] = parse_color(colors[i], "#000");
1948 break;
1950 case 'g': {
1951 char **sizes;
1952 if ((sizes = parse_csslike(optarg)) != NULL)
1953 for (i = 0; i < 4; ++i)
1954 r.p_borders[i] = parse_integer(sizes[i], 0);
1955 break;
1957 case 'I': {
1958 char **colors;
1959 if ((colors = parse_csslike(optarg)) != NULL)
1960 for (i = 0; i < 4; ++i)
1961 c_borders_bg[i] = parse_color(colors[i], "#000");
1962 break;
1964 case 'i': {
1965 char **sizes;
1966 if ((sizes = parse_csslike(optarg)) != NULL)
1967 for (i = 0; i < 4; ++i)
1968 r.c_borders[i] = parse_integer(sizes[i], 0);
1969 break;
1971 case 'J': {
1972 char **colors;
1973 if ((colors = parse_csslike(optarg)) != NULL)
1974 for (i = 0; i < 4; ++i)
1975 ch_borders_bg[i] = parse_color(colors[i], "#000");
1976 break;
1978 case 'j': {
1979 char **sizes;
1980 if ((sizes = parse_csslike(optarg)) != NULL)
1981 for (i = 0; i < 4; ++i)
1982 r.ch_borders[i] = parse_integer(sizes[i], 0);
1983 break;
1985 case 'l':
1986 r.horizontal_layout = !strcmp(optarg, "horizontal");
1987 break;
1988 case 'f': {
1989 char *newfont;
1990 if ((newfont = strdup(optarg)) != NULL) {
1991 free(fontname);
1992 fontname = newfont;
1994 break;
1996 case 'W':
1997 r.width = parse_int_with_percentage(optarg, r.width, d_width);
1998 break;
1999 case 'H':
2000 r.height = parse_int_with_percentage(optarg, r.height, d_height);
2001 break;
2002 case 'b': {
2003 char **borders;
2004 if ((borders = parse_csslike(optarg)) != NULL) {
2005 for (i = 0; i < 4; ++i)
2006 r.borders[i] = parse_integer(borders[i], 0);
2007 } else
2008 fprintf(stderr, "Error parsing b option\n");
2009 break;
2011 case 'B': {
2012 char **colors;
2013 if ((colors = parse_csslike(optarg)) != NULL) {
2014 for (i = 0; i < 4; ++i)
2015 borders_bg[i] = parse_color(colors[i], "#000");
2016 } else
2017 fprintf(stderr, "error while parsing B option\n");
2018 break;
2020 case 't':
2021 fgs[0] = parse_color(optarg, NULL);
2022 break;
2023 case 'T':
2024 bgs[0] = parse_color(optarg, NULL);
2025 break;
2026 case 'c':
2027 fgs[1] = parse_color(optarg, NULL);
2028 break;
2029 case 'C':
2030 bgs[1] = parse_color(optarg, NULL);
2031 break;
2032 case 's':
2033 fgs[2] = parse_color(optarg, NULL);
2034 break;
2035 case 'S':
2036 bgs[2] = parse_color(optarg, NULL);
2037 break;
2038 default:
2039 fprintf(stderr, "Unrecognized option %c\n", ch);
2040 status = ERR;
2041 break;
2045 if (r.height < 0 || r.width < 0 || x < 0 || y < 0) {
2046 fprintf(stderr, "height, width, x or y are lesser than 0.");
2047 status = ERR;
2050 /* since only now we know if the first should be selected,
2051 * update the completion here */
2052 update_completions(cs, text, lines, vlines, r.first_selected);
2054 /* update the prompt lenght, only now we surely know the length of it
2056 r.ps1len = strlen(r.ps1);
2058 /* Create the window */
2059 create_window(&r, parent_window, cmap, vinfo, x, y, offset_x, offset_y, bgs[1]);
2060 set_win_atoms_hints(r.d, r.w, r.width, r.height);
2061 XMapRaised(r.d, r.w);
2063 /* If embed, listen for other events as well */
2064 if (embed) {
2065 Window *children, parent, root;
2066 unsigned int children_no;
2068 XSelectInput(r.d, parent_window, FocusChangeMask);
2069 if (XQueryTree(r.d, parent_window, &root, &parent, &children, &children_no)
2070 && children) {
2071 for (i = 0; i < children_no && children[i] != r.w; ++i)
2072 XSelectInput(r.d, children[i], FocusChangeMask);
2073 XFree(children);
2075 grabfocus(r.d, r.w);
2078 take_keyboard(r.d, r.w);
2080 r.x_zero = r.borders[3];
2081 r.y_zero = r.borders[0];
2084 XGCValues values;
2086 for (i = 0; i < 3; ++i) {
2087 r.fgs[i] = XCreateGC(r.d, r.w, 0, &values);
2088 r.bgs[i] = XCreateGC(r.d, r.w, 0, &values);
2091 for (i = 0; i < 4; ++i) {
2092 r.borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2093 r.p_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2094 r.c_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2095 r.ch_borders_bg[i] = XCreateGC(r.d, r.w, 0, &values);
2099 /* Load the colors in our GCs */
2100 for (i = 0; i < 3; ++i) {
2101 XSetForeground(r.d, r.fgs[i], fgs[i]);
2102 XSetForeground(r.d, r.bgs[i], bgs[i]);
2105 for (i = 0; i < 4; ++i) {
2106 XSetForeground(r.d, r.borders_bg[i], borders_bg[i]);
2107 XSetForeground(r.d, r.p_borders_bg[i], p_borders_bg[i]);
2108 XSetForeground(r.d, r.c_borders_bg[i], c_borders_bg[i]);
2109 XSetForeground(r.d, r.ch_borders_bg[i], ch_borders_bg[i]);
2112 if (load_font(&r, fontname) == -1)
2113 status = ERR;
2115 r.xftdraw = XftDrawCreate(r.d, r.w, vinfo.visual, cmap);
2117 for (i = 0; i < 3; ++i) {
2118 rgba_t c;
2119 XRenderColor xrcolor;
2121 c = *(rgba_t *)&fgs[i];
2122 xrcolor.red = EXPANDBITS(c.rgba.r);
2123 xrcolor.green = EXPANDBITS(c.rgba.g);
2124 xrcolor.blue = EXPANDBITS(c.rgba.b);
2125 xrcolor.alpha = EXPANDBITS(c.rgba.a);
2126 XftColorAllocValue(r.d, vinfo.visual, cmap, &xrcolor, &r.xft_colors[i]);
2129 /* compute prompt dimensions */
2130 ps1extents(&r);
2132 xim_init(&r, &xdb);
2134 #ifdef __OpenBSD__
2135 if (pledge("stdio", "") == -1)
2136 err(1, "pledge");
2137 #endif
2139 /* Cache text height */
2140 text_extents("fyjpgl", 6, &r, NULL, &r.text_height);
2142 /* Draw the window for the first time */
2143 draw(&r, text, cs);
2145 /* Main loop */
2146 while (status == LOOPING || status == OK_LOOP) {
2147 status = loop(&r, &text, &textlen, cs, lines, vlines);
2149 if (status != ERR)
2150 printf("%s\n", text);
2152 if (!r.multiple_select && status == OK_LOOP)
2153 status = OK;
2156 XUngrabKeyboard(r.d, CurrentTime);
2158 for (i = 0; i < 3; ++i)
2159 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2161 for (i = 0; i < 3; ++i) {
2162 XFreeGC(r.d, r.fgs[i]);
2163 XFreeGC(r.d, r.bgs[i]);
2166 for (i = 0; i < 4; ++i) {
2167 XFreeGC(r.d, r.borders_bg[i]);
2168 XFreeGC(r.d, r.p_borders_bg[i]);
2169 XFreeGC(r.d, r.c_borders_bg[i]);
2170 XFreeGC(r.d, r.ch_borders_bg[i]);
2173 XDestroyIC(r.xic);
2174 XCloseIM(r.xim);
2176 for (i = 0; i < 3; ++i)
2177 XftColorFree(r.d, vinfo.visual, cmap, &r.xft_colors[i]);
2178 XftFontClose(r.d, r.font);
2179 XftDrawDestroy(r.xftdraw);
2181 free(r.ps1);
2182 free(fontname);
2183 free(text);
2185 free(lines);
2186 free(vlines);
2187 compls_delete(cs);
2189 XFreeColormap(r.d, cmap);
2191 XDestroyWindow(r.d, r.w);
2192 XCloseDisplay(r.d);
2194 return status != OK;