lsw

lists window titles of X clients to stdout
git clone git://git.suckless.org/lsw
Log | Files | Refs | README | LICENSE

lsw.c (1481B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include <X11/Xlib.h>
      6 #include <X11/Xutil.h>
      7 
      8 static const char *getname(Window);
      9 static void lsw(Window);
     10 
     11 static Atom netwmname;
     12 static Display *dpy;
     13 
     14 int
     15 main(int argc, char *argv[]) {
     16 	int i;
     17 
     18 	if(!(dpy = XOpenDisplay(NULL))) {
     19 		fprintf(stderr, "%s: cannot open display\n", argv[0]);
     20 		exit(EXIT_FAILURE);
     21 	}
     22 	netwmname = XInternAtom(dpy, "_NET_WM_NAME", False);
     23 
     24 	if(argc < 2)
     25 		lsw(DefaultRootWindow(dpy));
     26 	else for(i = 1; i < argc; i++)
     27 		lsw(strtol(argv[i], NULL, 0));
     28 
     29 	XCloseDisplay(dpy);
     30 	return EXIT_SUCCESS;
     31 }
     32 
     33 void
     34 lsw(Window win) {
     35 	unsigned int n;
     36 	Window *wins, *w, dw;
     37 	XWindowAttributes wa;
     38 
     39 	if(!XQueryTree(dpy, win, &dw, &dw, &wins, &n))
     40 		return;
     41 	for(w = &wins[n-1]; w >= &wins[0]; w--)
     42 		if(XGetWindowAttributes(dpy, *w, &wa)
     43 		&& !wa.override_redirect && wa.map_state == IsViewable)
     44 			printf("0x%07lx %s\n", *w, getname(*w));
     45 	XFree(wins);
     46 }
     47 
     48 const char *
     49 getname(Window win) {
     50 	static char buf[BUFSIZ];
     51 	char **list;
     52 	int n;
     53 	XTextProperty prop;
     54 
     55 	if(!XGetTextProperty(dpy, win, &prop, netwmname) || prop.nitems == 0)
     56 		if(!XGetWMName(dpy, win, &prop) || prop.nitems == 0)
     57 			return "";
     58 	if(!XmbTextPropertyToTextList(dpy, &prop, &list, &n) && n > 0) {
     59 		strncpy(buf, list[0], sizeof buf);
     60 		XFreeStringList(list);
     61 	} else
     62 		strncpy(buf, (char *)prop.value, sizeof buf);
     63 	XFree(prop.value);
     64 	buf[sizeof buf - 1] = '\0';
     65 	return buf;
     66 }