12 #include <X11/Xutil.h>
14 #include <X11/Xatom.h>
16 #define PROGNAME "xitems"
19 /* usage -- print usage information and die. */
24 "usage: " PROGNAME " [-font font] [-bg colour] [-fg colour]\n"
25 " [-sbg colour] [-sfg colour] [-bc colour] [-bw width]\n"
26 " [-hp padding] [-vp padding] [-x x] [-y y]\n");
30 /* die -- print formatted string, and exit with the status eval. */
32 die(int eval, const char *fmt, ...)
34 fputs(PROGNAME ": ", stderr);
38 vfprintf(stderr, fmt, argp);
45 /* warn -- print formatted string to stderr. */
47 warn(const char *fmt, ...)
49 fputs(PROGNAME ": ", stderr);
53 vfprintf(stderr, fmt, argp);
64 /* doubly-linked cyclic list */
69 KeySym ks[MAXKS]; /* array of associated keysyms */
70 size_t len; /* length of string */
71 size_t nks; /* number of associated keysyms */
72 bool dirty; /* should be redrawn */
75 static struct item *first = NULL; /* first member of the list */
76 static struct item *selected = NULL;
78 /* command-line options and X resources */
79 static char *o_font = NULL;
80 static char *o_bg = NULL, *o_fg = NULL, *o_sbg = NULL, *o_sfg = NULL,
82 static int o_x = -1, o_y = -1;
84 static int o_hp = -1, o_vp = -1;
87 static Display *dpy = NULL;
90 static GC gc_sel, gc_norm;
91 static Pixmap pm_sel, pm_norm; /* background pixmaps */
92 static XFontStruct *font;
93 static int height, width; /* height and width of one item */
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;
131 if (it == selected) {
139 XCopyArea(dpy, pm, win, gc, 0, 0, width, height, 0, y);
140 XDrawString(dpy, win, gc, o_hp, y + o_vp+font->ascent,
148 } while (it != first);
151 /* succeed -- exit successfully. If print is true, also print selected item. */
155 if (print && selected)
160 /* scroll -- select the previous, or next item, depending on dir. */
162 scroll(enum direction dir)
165 selected->dirty = true;
166 selected = (dir == DIR_UP) ? selected->prev : selected->next;
168 selected = (dir == DIR_UP) ? first->prev : first;
169 selected->dirty = true;
173 * keyselectd -- compare ks with keysyms stored in the items list, and mark
174 * the first match as selected. Return true on match, and false otherwise.
179 struct item *it = first;
182 XConvertCase(ks, &k, &dummy);
186 for (i = 0; i < it->nks; ++i)
187 if (it->ks[i] == k) {
188 selected->dirty = true;
190 selected->dirty = true;
194 } while (it != first);
199 /* proc -- body of the main event-reading loop. */
208 static bool inwin = false;
210 XNextEvent(dpy, &ev);
217 selpos(ev.xbutton.y);
226 if (ev.xbutton.button == Button4) {
229 } else if (ev.xbutton.button == Button5) {
239 XLookupString(&ke, dummy, 0, &ks, NULL);
241 if (ke.state & ControlMask) {
263 } else if (keyselect(ks))
291 /* grabptr -- try to grab pointer for a second */
295 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
298 for (i = 0; i < 1000; ++i) {
299 if (XGrabPointer(dpy, RootWindow(dpy, screen), True,
300 ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None,
301 CurrentTime) == GrabSuccess)
303 nanosleep(&ts, NULL);
305 die(1, "couldn't grab pointer");
308 /* grabkb -- try to grab keyboard for a second */
312 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
315 for (i = 0; i < 1000; ++i) {
316 if (XGrabKeyboard(dpy, RootWindow(dpy, screen), True,
317 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
319 nanosleep(&ts, NULL);
321 die(1, "couldn't grab keyboard");
324 /* setfocus -- try setting focus to the menu for a second */
328 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
332 for (i = 0; i < 1000; ++i) {
333 XGetInputFocus(dpy, &focuswin, &dummy);
336 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
337 nanosleep(&ts, NULL);
339 die(1, "couldn't grab keyboard");
343 * setupx -- create and map a window for n items; assign values to the X
352 XClassHint ch = {PROGNAME, PROGNAME};
353 XSetWindowAttributes swa = {
354 .override_redirect = True,
356 .event_mask = ExposureMask | StructureNotifyMask |
357 KeyPressMask | ButtonPressMask | ButtonReleaseMask |
358 PointerMotionMask | LeaveWindowMask | EnterWindowMask,
361 if (!(font = XLoadQueryFont(dpy, o_font)))
362 die(1, "couldn't load font");
363 height = font->ascent + font->descent + o_vp;
368 if ((w = XTextWidth(font, it->s, it->len) + o_hp*2) > width)
371 } while (it != first);
373 if (o_x + width > DisplayWidth(dpy, screen))
374 o_x = DisplayWidth(dpy, screen) - width;
375 if (o_y + height*n > DisplayHeight(dpy, screen))
376 o_y = DisplayHeight(dpy, screen) - height*n;
378 XAllocNamedColor(dpy, DefaultColormap(dpy, screen), o_bc, &col, &dummy);
379 swa.border_pixel = col.pixel;
380 XAllocNamedColor(dpy, DefaultColormap(dpy, screen), o_bg, &col, &dummy);
381 swa.background_pixel = col.pixel;
383 win = XCreateWindow(dpy, RootWindow(dpy, screen), o_x, o_y,
384 width, n*height, o_bw, CopyFromParent, CopyFromParent,
385 CopyFromParent, CWOverrideRedirect | CWBackPixel | CWBorderPixel |
386 CWEventMask | CWSaveUnder, &swa);
387 XSetClassHint(dpy, win, &ch);
390 * Foreground here means the colour with which to draw the background
391 * pixmap, i.e. the actual background colour.
393 gcv.foreground = col.pixel;
394 gc_norm = XCreateGC(dpy, win, GCForeground, &gcv);
395 XAllocNamedColor(dpy, DefaultColormap(dpy, screen), o_sbg, &col,
397 gcv.foreground = col.pixel;
398 gc_sel = XCreateGC(dpy, win, GCForeground, &gcv);
400 pm_sel = XCreatePixmap(dpy, win, width, height,
401 DefaultDepth(dpy, screen));
402 pm_norm = XCreatePixmap(dpy, win, width, height,
403 DefaultDepth(dpy, screen));
404 XFillRectangle(dpy, pm_sel, gc_sel, 0, 0, width, height);
405 XFillRectangle(dpy, pm_norm, gc_norm, 0, 0, width, height);
408 * Since the background pixmaps are already created, the GCs can be
411 XAllocNamedColor(dpy, DefaultColormap(dpy, screen), o_fg, &col,
413 XSetForeground(dpy, gc_norm, col.pixel);
414 XAllocNamedColor(dpy, DefaultColormap(dpy, screen), o_sfg, &col,
416 XSetForeground(dpy, gc_sel, col.pixel);
421 XMapRaised(dpy, win);
427 * Create a new struct item, and insert it a after the it item. The rest of the
428 * arguments are values that the new item receives. On success return pointer
429 * to the new item. Return NULL otherwise.
432 insitem(struct item *it, char *s) {
436 if (!(new = calloc(1, sizeof *new)))
440 new->next = it->next;
441 it->next->prev = new;
444 new->prev = new->next = new;
448 for (p = s; ; p = end) {
455 if (!(n = strcspn(p, " \t"))) {
456 p += strspn(p, " \t");
464 if ((ks = XStringToKeysym(p)) == NoSymbol)
465 warn("no such keysym: %s\n", p);
466 else if (new->nks >= MAXKS)
467 warn("too many keysyms (%s)\n", p);
470 XConvertCase(ks, &k, &dummy);
471 new->ks[new->nks++] = k;
477 new->len = strlen(p);
484 * mkitems -- create a list of items from stdin, and return pointer to the
485 * new list's first element. If np is not NULL, set its value to the number of
486 * elements in the list. Return NULL on error.
491 struct item *last = NULL;
497 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
499 if (line[linelen-1] == '\n')
500 line[--linelen] = '\0';
501 if (!(it = insitem(last, line)))
502 die(1, "couldn't insert new item");
511 return last ? last->next : NULL;
515 * {s,i}default -- return the {char *,int} value of the X default, or def
519 sdefault(const char *opt, const char *def)
521 char *val = XGetDefault(dpy, PROGNAME, opt);
522 return val ? val : (char *)def;
526 idefault(const char *opt, int def)
528 char *val = XGetDefault(dpy, PROGNAME, opt);
529 return val ? atoi(val) : def;
532 /* nextarg -- safely skip the current command-line option */
534 nextarg(int *argcp, char **argvp[])
542 * {s,i}arg -- return the {char *,int} argument of the current command-line
546 sarg(int *argcp, char **argvp[])
548 nextarg(argcp, argvp);
553 iarg(int *argcp, char **argvp[])
555 nextarg(argcp, argvp);
556 return atoi(**argvp);
560 * xitems -- pop-up menu for X, constructed from stdin, and printing user choice
564 main(int argc, char *argv[])
568 for (--argc, ++argv; argc > 0; --argc, ++argv)
569 if (argv[0][0] == '-')
570 switch (argv[0][1]) {
572 switch (argv[0][2]) {
574 o_bc = sarg(&argc, &argv);
577 o_bg = sarg(&argc, &argv);
580 o_bw = iarg(&argc, &argv);
588 switch (argv[0][2]) {
590 o_fg = sarg(&argc, &argv);
592 case 'o': /* -font */
593 o_font = sarg(&argc, &argv);
601 o_hp = iarg(&argc, &argv);
604 switch (argv[0][2]) {
606 o_sbg = sarg(&argc, &argv);
609 o_sfg = sarg(&argc, &argv);
617 o_vp = iarg(&argc, &argv);
620 o_x = iarg(&argc, &argv);
623 o_y = iarg(&argc, &argv);
630 if (!(dpy = XOpenDisplay(NULL)))
631 die(1, "couldn't open display");
632 screen = DefaultScreen(dpy);
635 o_bg = sdefault("background", "white");
637 o_fg = sdefault("foreground", "black");
639 o_font = sdefault("font", "fixed");
641 o_sbg = sdefault("selectedBackground", "black");
643 o_sfg = sdefault("selectedForeground", "white");
645 o_bc = sdefault("borderColour", "black");
647 o_bw = idefault("borderWidth", 1);
649 o_hp = idefault("horizontalPadding", 2);
651 o_vp = idefault("verticalPadding", 1);
653 if (o_x == -1 || o_y == -1) {
659 xp = (o_x == -1) ? &o_x : &i;
660 yp = (o_y == -1) ? &o_y : &i;
662 XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, xp, yp, &i,
666 if (!(first = selected = mkitems(&n))) {
668 die(1, "coulnd't create items list");