#!perl

require "./xbase.pl";
require "./xatomhash.pl";
$xopen = &xlib::x_open_display($ENV{"DISPLAY"});
die $xlib::status if not defined $xopen;
tie %xatom, XATOM, $xopen;

# features:
#   list all (id, name) [done]
#   walk tree doing something
#   move, resize, map/unmap  (by id, by name?)
#   select window with click
sub getwinname {
    my ($d,$w) = @_;
#    $atom_wm_name = xlib::x_internatom($d,$X::defines{"xTrue"},"WM_NAME")
#	if ! defined($atom_wm_name);
#    die if $atom_wm_name == 0;
    my @x = xlib::x_getproperty($d,$X::defines{"xFalse"}, $w,$xatom{"WM_NAME"},
				$X::defines{"AnyPropertyType"}, 0,255);
    return $x[1];
}

sub list_all {
    my $d = shift;
    my $debug = shift;
    list_level($d, $xlib::root_window, $debug);
}

sub list_level {
    my $d = shift;
    my $w = shift;
    my $debug = shift;
    my @ret;
    my @lf = &xlib::x_querytree($d, $w, $xlib::root_window);
    shift @lf;			# lose the rep, we just want the kids
    for $i (@lf) {
	# need one level deeper...
	my $wn = getwinname($d, $i);
	if ($wn eq "") {
	    my @l2 = &xlib::x_querytree($d, $i);
	    shift @l2;		# lose the rep, we just want the kids
	    for $j (@l2) {
		my $wn = getwinname($d, $j);
		if ($wn ne "") {
		    printf "%x(%x): %s\n", $i, $j, $wn if $debug;
		    push(@ret, $i, $wn);
		    last;
		}
	    }
	} else {
	    printf "%x: %s\n", $i, $wn if $debug;
	    push(@ret, $i, $wn);
	}
    }
    for $i (@lf) {
	push(@ret, list_level($d, $i, $debug));
    }
    @ret;
}
@list = list_all($xopen,1);
print join(":",@list),"\n";

while(1) {
    my $wid = shift @list;
    my $wn = shift @list;

    if ($wn =~ /studentloan/) {
	print "changing $wn\n";
        xlib::x_changeproperty($xopen,$X::defines{"PropModeReplace"},$wid,
			       $xatom{"WM_NAME"},$xatom{"STRING"},8,"hello");
        xlib::x_changeproperty($xopen,$X::defines{"PropModeReplace"},$wid,
			       $xatom{"WM_ICON_NAME"},$xatom{"STRING"},
			       8,"hello icon");
    }
    last if scalar(@list) == 0;
}

xlib::handle_event($xopen);
