12 #include <X11/Xutil.h>
14 #include <X11/Xatom.h>
15 #include <X11/Xft/Xft.h>
17 #define PROGNAME "xitems"
20 /* usage -- print usage information and die. */
25 "usage: " PROGNAME " [-font font] [-bg colour] [-fg colour]\n"
26 " [-sbg colour] [-sfg colour] [-bc colour] [-bw width]\n"
27 " [-hp padding] [-vp padding] [-x x] [-y y]\n");
31 /* die -- print formatted string, and exit with the status eval. */
33 die(int eval, const char *fmt, ...)
35 fputs(PROGNAME ": ", stderr);
39 vfprintf(stderr, fmt, argp);
46 /* warn -- print formatted string to stderr. */
48 warn(const char *fmt, ...)
50 fputs(PROGNAME ": ", stderr);
54 vfprintf(stderr, fmt, argp);
65 /* doubly-linked cyclic list */
70 KeySym ks[MAXKS]; /* array of associated keysyms */
71 size_t len; /* length of string */
72 size_t nks; /* number of associated keysyms */
73 bool dirty; /* should be redrawn */
76 static struct item *first = NULL; /* first member of the list */
77 static struct item *selected = NULL;
79 /* command-line options and X resources */
80 static char *o_font = NULL;
81 static char *o_bg = NULL, *o_fg = NULL, *o_sbg = NULL, *o_sfg = NULL,
83 static int o_x = -1, o_y = -1;
85 static int o_hp = -1, o_vp = -1;
94 static Display *dpy = NULL;
97 static int height, width; /* height and width of one item */
99 static XftColor c_fg, c_sfg, c_sbg;
100 static unsigned long pixels[PIXEL_N];
102 /* selpos -- mark the item at position y (from top) as selected. */
106 struct item *unselected = selected;
114 for (selected = first; selected != first->prev;
115 selected = selected->next) {
116 if (y >= top && y < top+height)
122 if (unselected != selected)
123 unselected->dirty = selected->dirty = true;
126 /* redraw -- redraw the entire window. */
130 struct item *it = first;
133 static XftDraw *d = NULL;
135 if (!d && !(d = XftDrawCreate(dpy, win, DefaultVisual(dpy, screen),
136 DefaultColormap(dpy, screen))))
137 die(1, "couldn't create XftDraw");
143 XClearArea(dpy, win, 0, y, width, height, False);
145 if (it == selected) {
147 XftDrawRect(d, &c_sbg, 0, y, width, height);
151 XftDrawStringUtf8(d, c, font,
152 o_hp, y + o_vp+font->ascent,
153 (FcChar8 *)it->s, it->len);
160 } while (it != first);
164 * freeitems -- recursively free the list of items. First call should be
168 freeitems(struct item *it)
172 else if (it == first)
179 /* cleanup -- free allocated resources. */
183 Colormap cmap = DefaultColormap(dpy, screen);
184 Visual *vis = DefaultVisual(dpy, screen);
188 XftFontClose(dpy, font);
190 XFreeColors(dpy, cmap, pixels, PIXEL_N, 0);
191 XftColorFree(dpy, vis, cmap, &c_fg);
192 XftColorFree(dpy, vis, cmap, &c_sbg);
193 XftColorFree(dpy, vis, cmap, &c_sfg);
195 XUngrabKeyboard(dpy, CurrentTime);
196 XUngrabPointer(dpy, CurrentTime);
201 /* succeed -- exit successfully. If print is true, also print selected item. */
205 if (print && selected)
211 /* scroll -- select the previous, or next item, depending on dir. */
213 scroll(enum direction dir)
216 selected->dirty = true;
217 selected = (dir == DIR_UP) ? selected->prev : selected->next;
219 selected = (dir == DIR_UP) ? first->prev : first;
220 selected->dirty = true;
224 * keyselectd -- compare ks with keysyms stored in the items list, and mark
225 * the first match as selected. Return true on match, and false otherwise.
230 struct item *it = first;
233 XConvertCase(ks, &k, &dummy);
237 for (i = 0; i < it->nks; ++i)
238 if (it->ks[i] == k) {
239 selected->dirty = true;
241 selected->dirty = true;
245 } while (it != first);
250 /* proc -- body of the main event-reading loop. */
259 static bool inwin = false;
261 XNextEvent(dpy, &ev);
268 selpos(ev.xbutton.y);
277 if (ev.xbutton.button == Button4) {
280 } else if (ev.xbutton.button == Button5) {
290 XLookupString(&ke, dummy, 0, &ks, NULL);
292 if (ke.state & ControlMask) {
314 } else if (keyselect(ks))
342 /* grabptr -- try to grab pointer for a second */
346 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
349 for (i = 0; i < 1000; ++i) {
350 if (XGrabPointer(dpy, RootWindow(dpy, screen), True,
351 ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None,
352 CurrentTime) == GrabSuccess)
354 nanosleep(&ts, NULL);
356 die(1, "couldn't grab pointer");
359 /* grabkb -- try to grab keyboard for a second */
363 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
366 for (i = 0; i < 1000; ++i) {
367 if (XGrabKeyboard(dpy, RootWindow(dpy, screen), True,
368 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
370 nanosleep(&ts, NULL);
372 die(1, "couldn't grab keyboard");
375 /* setfocus -- try setting focus to the menu for a second */
379 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
383 for (i = 0; i < 1000; ++i) {
384 XGetInputFocus(dpy, &focuswin, &dummy);
387 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
388 nanosleep(&ts, NULL);
390 die(1, "couldn't grab keyboard");
393 /* alloccol_xft -- safely allocate new Xft colour c from string s. */
395 alloccol_xft(char *s, XftColor *c)
397 if (!(XftColorAllocName(dpy, DefaultVisual(dpy, screen),
398 DefaultColormap(dpy, screen), s, c)))
399 die(1, "couldn't allocate Xft colour %s\n", s);
402 /* alloccol -- safely allocate new colour c from string s. */
404 alloccol(char *s, XColor *c)
407 if (!(XAllocNamedColor(dpy, DefaultColormap(dpy, screen), s, c, &dummy)))
408 die(1, "couldn't allocate colour %s\n", s);
412 * setupx -- create and map a window for n items; assign values to the X
420 XClassHint ch = {PROGNAME, PROGNAME};
421 XSetWindowAttributes swa = {
422 .override_redirect = True,
424 .event_mask = ExposureMask | StructureNotifyMask |
425 KeyPressMask | ButtonPressMask | ButtonReleaseMask |
426 PointerMotionMask | LeaveWindowMask | EnterWindowMask,
429 if (!(font = XftFontOpenName(dpy, screen, o_font)))
430 die(1, "couldn't load font");
431 height = font->height + o_vp;
436 XftTextExtentsUtf8(dpy, font, (FcChar8 *)it->s, it->len, &gi);
437 if (gi.xOff + o_hp*2 > width)
438 width = gi.xOff + o_hp*2;
440 } while (it != first);
442 if (o_x + width > DisplayWidth(dpy, screen))
443 o_x = DisplayWidth(dpy, screen) - width;
444 if (o_y + height*n > DisplayHeight(dpy, screen))
445 o_y = DisplayHeight(dpy, screen) - height*n;
447 alloccol(o_bg, &col);
448 pixels[PIXEL_BG] = swa.background_pixel = col.pixel;
449 alloccol(o_bc, &col);
450 pixels[PIXEL_BC] = swa.border_pixel = col.pixel;
452 win = XCreateWindow(dpy, RootWindow(dpy, screen), o_x, o_y,
453 width, n*height, o_bw, CopyFromParent, CopyFromParent,
454 CopyFromParent, CWOverrideRedirect | CWBackPixel | CWBorderPixel |
455 CWEventMask | CWSaveUnder, &swa);
456 XSetClassHint(dpy, win, &ch);
458 alloccol_xft(o_fg, &c_fg);
459 alloccol_xft(o_sfg, &c_sfg);
460 alloccol_xft(o_sbg, &c_sbg);
465 XMapRaised(dpy, win);
471 * Create a new struct item, and insert it a after the it item. The rest of the
472 * arguments are values that the new item receives. On success return pointer
473 * to the new item. Return NULL otherwise.
476 insitem(struct item *it, char *s) {
480 if (!(new = calloc(1, sizeof *new)))
484 new->next = it->next;
485 it->next->prev = new;
488 new->prev = new->next = new;
492 for (p = s; ; p = end) {
499 if (!(n = strcspn(p, " \t"))) {
500 p += strspn(p, " \t");
508 if ((ks = XStringToKeysym(p)) == NoSymbol)
509 warn("no such keysym: %s\n", p);
510 else if (new->nks >= MAXKS)
511 warn("too many keysyms (%s)\n", p);
514 XConvertCase(ks, &k, &dummy);
515 new->ks[new->nks++] = k;
521 new->len = strlen(p);
528 * mkitems -- create a list of items from stdin, and return pointer to the
529 * new list's first element. If np is not NULL, set its value to the number of
530 * elements in the list. Return NULL on error.
535 struct item *last = NULL;
541 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
543 if (line[linelen-1] == '\n')
544 line[--linelen] = '\0';
545 if (!(it = insitem(last, line)))
546 die(1, "couldn't insert new item");
555 return last ? last->next : NULL;
559 * {s,i}default -- return the {char *,int} value of the X default, or def
563 sdefault(const char *opt, const char *def)
565 char *val = XGetDefault(dpy, PROGNAME, opt);
566 return val ? val : (char *)def;
570 idefault(const char *opt, int def)
572 char *val = XGetDefault(dpy, PROGNAME, opt);
573 return val ? atoi(val) : def;
576 /* nextarg -- safely skip the current command-line option */
578 nextarg(int *argcp, char **argvp[])
586 * {s,i}arg -- return the {char *,int} argument of the current command-line
590 sarg(int *argcp, char **argvp[])
592 nextarg(argcp, argvp);
597 iarg(int *argcp, char **argvp[])
599 nextarg(argcp, argvp);
600 return atoi(**argvp);
604 * xitems -- pop-up menu for X, constructed from stdin, and printing user choice
608 main(int argc, char *argv[])
612 for (--argc, ++argv; argc > 0; --argc, ++argv)
613 if (argv[0][0] == '-')
614 switch (argv[0][1]) {
616 switch (argv[0][2]) {
618 o_bc = sarg(&argc, &argv);
621 o_bg = sarg(&argc, &argv);
624 o_bw = iarg(&argc, &argv);
632 switch (argv[0][2]) {
634 o_fg = sarg(&argc, &argv);
636 case 'o': /* -font */
637 o_font = sarg(&argc, &argv);
645 o_hp = iarg(&argc, &argv);
648 switch (argv[0][2]) {
650 o_sbg = sarg(&argc, &argv);
653 o_sfg = sarg(&argc, &argv);
661 o_vp = iarg(&argc, &argv);
664 o_x = iarg(&argc, &argv);
667 o_y = iarg(&argc, &argv);
674 if (!(dpy = XOpenDisplay(NULL)))
675 die(1, "couldn't open display");
676 screen = DefaultScreen(dpy);
679 o_bg = sdefault("background", "white");
681 o_fg = sdefault("foreground", "black");
683 o_font = sdefault("font", "DejaVu Sans Mono-10");
685 o_sbg = sdefault("selectedBackground", "black");
687 o_sfg = sdefault("selectedForeground", "white");
689 o_bc = sdefault("borderColour", "black");
691 o_bw = idefault("borderWidth", 1);
693 o_hp = idefault("horizontalPadding", 2);
695 o_vp = idefault("verticalPadding", 1);
697 if (o_x == -1 || o_y == -1) {
703 xp = (o_x == -1) ? &o_x : &i;
704 yp = (o_y == -1) ? &o_y : &i;
706 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, xp, yp, &i,
710 if (!(first = selected = mkitems(&n))) {
712 die(1, "coulnd't create items list");