
#include "nawm.h"


static Window getwbnrec (name, parent, levels, atom)
     char *name;
     Window parent;
     int levels;
     Atom atom;
{
  Window *children;
  unsigned int numchildren, n;
  Window rootret;
  Window parentret;
  Window retval = (Window) NULL;
  Atom type;
  int format;
  unsigned long items;
  unsigned char *prop, *c;
  unsigned long left;

  levels--;
  XQueryTree (dpy, parent, &rootret, &parentret, &children, &numchildren);
  if(numchildren && !children) return NULL; /* XXX [danw:19960217.1958EST] */
  for (n = 0; n < numchildren; n++) { 
    XGetWindowProperty(dpy, children[n], atom, 0, 1000, False,
		       AnyPropertyType, &type, &format, &items, &left, &prop);
    if (items) {
      c = prop;
#ifdef QUERY_TEST
      printf ("found %s (items %d, type %d, format %d, left %d)\n", prop, items, type, format, left);
#endif
      while (c < prop + items) {
	if (!strcmp(name, (char *) c)) {
	  XFree((char *) prop);
	  retval = children[n];
	  free ((char *) children);
	  return retval;
	}
#if defined(vax) || defined(AOS)
	c = (unsigned char *) index((char *) c, 0) + 1;
#else
	c = (unsigned char *) strchr((char *) c, 0) + 1;
#endif /* Vax or RT */
#ifdef QUERY_TEST
	if (c < prop + items) {
	  printf ("    also %s\n", c);
	}
#endif
      }
      XFree((char *) prop);
    }
    if (levels && (retval = getwbnrec (name, children[n], levels, atom))) {
      break;
    }
  }
  free ((char *) children);
  return retval;
}

Window getwindowbyname (name)
     char *name;
{
  Window w;
  
  if (w = getwbnrec (name, root, 2, XA_WM_NAME))
    return w;
  return getwbnrec (name, root, 2, XA_WM_CLASS);
}

#ifdef QUERY_TEST

Display *dpy;
int screen;
Window root;

main(argc, argv)
     char **argv;
{
  Window win;
  if (!(dpy = XOpenDisplay(NULL))) {
    printf ("can't open display\n");
    exit(1);
  }
  screen = DefaultScreen(dpy);
  root = RootWindow(dpy, screen);
  win = getwindowbyname(argv[1]);
  printf ("Found: %08x\n", win);
}

#endif
