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;
88 static Display *dpy = NULL;
91 static int height, width; /* height and width of one item */
93 static XftColor c_fg, c_sfg, c_sbg;
95 /* selpos -- mark the item at position y (from top) as selected. */
99 struct item *unselected = selected;
107 for (selected = first; selected != first->prev;
108 selected = selected->next) {
109 if (y >= top && y < top+height)
115 if (unselected != selected)
116 unselected->dirty = selected->dirty = true;
119 /* redraw -- redraw the entire window */
123 struct item *it = first;
126 static XftDraw *d = NULL;
128 if (!d && !(d = XftDrawCreate(dpy, win, DefaultVisual(dpy, screen),
129 DefaultColormap(dpy, screen))))
130 die(1, "couldn't create XftDraw");
136 XClearArea(dpy, win, 0, y, width, height, False);
138 if (it == selected) {
140 XftDrawRect(d, &c_sbg, 0, y, width, height);
144 XftDrawStringUtf8(d, xftc, font,
145 o_hp, y + o_vp+font->ascent,
146 (FcChar8 *)it->s, it->len);
153 } while (it != first);
156 /* succeed -- exit successfully. If print is true, also print selected item. */
160 if (print && selected)
165 /* scroll -- select the previous, or next item, depending on dir. */
167 scroll(enum direction dir)
170 selected->dirty = true;
171 selected = (dir == DIR_UP) ? selected->prev : selected->next;
173 selected = (dir == DIR_UP) ? first->prev : first;
174 selected->dirty = true;
178 * keyselectd -- compare ks with keysyms stored in the items list, and mark
179 * the first match as selected. Return true on match, and false otherwise.
184 struct item *it = first;
187 XConvertCase(ks, &k, &dummy);
191 for (i = 0; i < it->nks; ++i)
192 if (it->ks[i] == k) {
193 selected->dirty = true;
195 selected->dirty = true;
199 } while (it != first);
204 /* proc -- body of the main event-reading loop. */
213 static bool inwin = false;
215 XNextEvent(dpy, &ev);
222 selpos(ev.xbutton.y);
231 if (ev.xbutton.button == Button4) {
234 } else if (ev.xbutton.button == Button5) {
244 XLookupString(&ke, dummy, 0, &ks, NULL);
246 if (ke.state & ControlMask) {
268 } else if (keyselect(ks))
296 /* grabptr -- try to grab pointer for a second */
300 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
303 for (i = 0; i < 1000; ++i) {
304 if (XGrabPointer(dpy, RootWindow(dpy, screen), True,
305 ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None,
306 CurrentTime) == GrabSuccess)
308 nanosleep(&ts, NULL);
310 die(1, "couldn't grab pointer");
313 /* grabkb -- try to grab keyboard for a second */
317 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
320 for (i = 0; i < 1000; ++i) {
321 if (XGrabKeyboard(dpy, RootWindow(dpy, screen), True,
322 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
324 nanosleep(&ts, NULL);
326 die(1, "couldn't grab keyboard");
329 /* setfocus -- try setting focus to the menu for a second */
333 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
337 for (i = 0; i < 1000; ++i) {
338 XGetInputFocus(dpy, &focuswin, &dummy);
341 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
342 nanosleep(&ts, NULL);
344 die(1, "couldn't grab keyboard");
347 /* alloccol_xft -- safely allocate new Xft colour c from string s. */
349 alloccol_xft(char *s, XftColor *c)
351 if (!(XftColorAllocName(dpy, DefaultVisual(dpy, screen),
352 DefaultColormap(dpy, screen), s, c)))
353 die(1, "couldn't allocate Xft colour %s\n", s);
356 /* alloccol -- safely allocate new colour c from string s. */
358 alloccol(char *s, XColor *c)
361 if (!(XAllocNamedColor(dpy, DefaultColormap(dpy, screen), s, c, &dummy)))
362 die(1, "couldn't allocate colour %s\n", s);
366 * setupx -- create and map a window for n items; assign values to the X
374 XClassHint ch = {PROGNAME, PROGNAME};
375 XSetWindowAttributes swa = {
376 .override_redirect = True,
378 .event_mask = ExposureMask | StructureNotifyMask |
379 KeyPressMask | ButtonPressMask | ButtonReleaseMask |
380 PointerMotionMask | LeaveWindowMask | EnterWindowMask,
383 if (!(font = XftFontOpenName(dpy, screen, o_font)))
384 die(1, "couldn't load font");
385 height = font->height + o_vp;
390 XftTextExtentsUtf8(dpy, font, (FcChar8 *)it->s, it->len, &gi);
391 if (gi.xOff + o_hp*2 > width)
392 width = gi.xOff + o_hp*2;
394 } while (it != first);
396 if (o_x + width > DisplayWidth(dpy, screen))
397 o_x = DisplayWidth(dpy, screen) - width;
398 if (o_y + height*n > DisplayHeight(dpy, screen))
399 o_y = DisplayHeight(dpy, screen) - height*n;
401 alloccol(o_bc, &col);
402 swa.border_pixel = col.pixel;
403 alloccol(o_bg, &col);
404 swa.background_pixel = col.pixel;
406 win = XCreateWindow(dpy, RootWindow(dpy, screen), o_x, o_y,
407 width, n*height, o_bw, CopyFromParent, CopyFromParent,
408 CopyFromParent, CWOverrideRedirect | CWBackPixel | CWBorderPixel |
409 CWEventMask | CWSaveUnder, &swa);
410 XSetClassHint(dpy, win, &ch);
412 alloccol_xft(o_fg, &c_fg);
413 alloccol_xft(o_sfg, &c_sfg);
414 alloccol_xft(o_sbg, &c_sbg);
419 XMapRaised(dpy, win);
425 * Create a new struct item, and insert it a after the it item. The rest of the
426 * arguments are values that the new item receives. On success return pointer
427 * to the new item. Return NULL otherwise.
430 insitem(struct item *it, char *s) {
434 if (!(new = calloc(1, sizeof *new)))
438 new->next = it->next;
439 it->next->prev = new;
442 new->prev = new->next = new;
446 for (p = s; ; p = end) {
453 if (!(n = strcspn(p, " \t"))) {
454 p += strspn(p, " \t");
462 if ((ks = XStringToKeysym(p)) == NoSymbol)
463 warn("no such keysym: %s\n", p);
464 else if (new->nks >= MAXKS)
465 warn("too many keysyms (%s)\n", p);
468 XConvertCase(ks, &k, &dummy);
469 new->ks[new->nks++] = k;
475 new->len = strlen(p);
482 * mkitems -- create a list of items from stdin, and return pointer to the
483 * new list's first element. If np is not NULL, set its value to the number of
484 * elements in the list. Return NULL on error.
489 struct item *last = NULL;
495 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
497 if (line[linelen-1] == '\n')
498 line[--linelen] = '\0';
499 if (!(it = insitem(last, line)))
500 die(1, "couldn't insert new item");
509 return last ? last->next : NULL;
513 * {s,i}default -- return the {char *,int} value of the X default, or def
517 sdefault(const char *opt, const char *def)
519 char *val = XGetDefault(dpy, PROGNAME, opt);
520 return val ? val : (char *)def;
524 idefault(const char *opt, int def)
526 char *val = XGetDefault(dpy, PROGNAME, opt);
527 return val ? atoi(val) : def;
530 /* nextarg -- safely skip the current command-line option */
532 nextarg(int *argcp, char **argvp[])
540 * {s,i}arg -- return the {char *,int} argument of the current command-line
544 sarg(int *argcp, char **argvp[])
546 nextarg(argcp, argvp);
551 iarg(int *argcp, char **argvp[])
553 nextarg(argcp, argvp);
554 return atoi(**argvp);
558 * xitems -- pop-up menu for X, constructed from stdin, and printing user choice
562 main(int argc, char *argv[])
566 for (--argc, ++argv; argc > 0; --argc, ++argv)
567 if (argv[0][0] == '-')
568 switch (argv[0][1]) {
570 switch (argv[0][2]) {
572 o_bc = sarg(&argc, &argv);
575 o_bg = sarg(&argc, &argv);
578 o_bw = iarg(&argc, &argv);
586 switch (argv[0][2]) {
588 o_fg = sarg(&argc, &argv);
590 case 'o': /* -font */
591 o_font = sarg(&argc, &argv);
599 o_hp = iarg(&argc, &argv);
602 switch (argv[0][2]) {
604 o_sbg = sarg(&argc, &argv);
607 o_sfg = sarg(&argc, &argv);
615 o_vp = iarg(&argc, &argv);
618 o_x = iarg(&argc, &argv);
621 o_y = iarg(&argc, &argv);
628 if (!(dpy = XOpenDisplay(NULL)))
629 die(1, "couldn't open display");
630 screen = DefaultScreen(dpy);
633 o_bg = sdefault("background", "white");
635 o_fg = sdefault("foreground", "black");
637 o_font = sdefault("font", "DejaVu Sans Mono-10");
639 o_sbg = sdefault("selectedBackground", "black");
641 o_sfg = sdefault("selectedForeground", "white");
643 o_bc = sdefault("borderColour", "black");
645 o_bw = idefault("borderWidth", 1);
647 o_hp = idefault("horizontalPadding", 2);
649 o_vp = idefault("verticalPadding", 1);
651 if (o_x == -1 || o_y == -1) {
657 xp = (o_x == -1) ? &o_x : &i;
658 yp = (o_y == -1) ? &o_y : &i;
660 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, xp, yp, &i,
664 if (!(first = selected = mkitems(&n))) {
666 die(1, "coulnd't create items list");