#!perl
#$xlib::debug = 1;
#$xlib::debugpkt = 1;

require "./xbase.pl";
# require "./xatomhash.pl";
$xopen = xlib::x_open_display($ENV{"DISPLAY"});

$fc = xlib::joincolor(65535,0,0);
$bc = xlib::joincolor(0,0,0);
$curs = xlib::x_createfontcursor($xopen, $XC::crosshair, $fc, $bc);

sub xx { 
#    $stat = xlib::xungrabpointer($xopen, 0); # time now
    $stat = xlib::xgrabpointer($xopen,
			       0,	# owner-events false
			       &xlib::defaultroot($xopen), # grabw
			       $X::defines{"ButtonPressMask"} | 
			       $X::defines{"ButtonReleaseMask"},
			       $X::defines{"GrabModeSync"},
			       $X::defines{"GrabModeAsync"},
			       &xlib::defaultroot($xopen),
			       # conf window none (vs root?)
			       $curs,	# cursor none
			       $X::defines{"CurrentTime"} # time now
			       ); 
#    print "grabstat: $stat\n";
    &xlib::xallowevents($xopen, 
			$X::defines{"SyncPointer"},
			$X::defines{"CurrentTime"});
}
xx();
$SIG{"ALRM"} = $SIG{"INT"} = sub {
    xlib::x_closedisplay($xopen);
    exit;
  };
alarm(30);
#print "waiting (30s)... $stat\n";
print "click on a window to toggle backing store...\n";
$xlib::handler{"ButtonRelease"} = 
$xlib::handler{"ButtonPress"} = sub {
    my $rep = xlib::xlibconvert("keyButtonPointer", $xopen->{"readqueue"});
#    xlib::debugxlib($rep);
#    printf "child: 0x%x\n", $xchild = $rep->{"child"};
    $xchild = $rep->{"child"};
};
$st = xlib::handle_event($xopen);
$ch1 = $xchild;
#print "event: $st, child $xchild\n";
xx();
$st = xlib::handle_event($xopen);
$ch2 = $xchild;
#print "event: $st, child $xchild\n";
# button press, button release, double check that they have the same child...
$stat = xlib::xungrabpointer($xopen, 0); # time now
if ($ch1 != $ch2) {
    die "different windows, aborting on user request";
}

sub query_eval {
    my ($d,$w,$sub)=@_;
    &$sub($d,$w);
    my @lf = &xlib::x_querytree($d, $w);
    shift @lf;			# lose the rep, we just want the kids
    my $i;
    for $i (@lf) {
	query_eval($d,$i,$sub);
    }
}
sub toggle_backingstore { # disp, win
    my ($d,$w) = @_;
    printf "toggling 0x%x (%d):", $w, $w;
    my $attrs = xlib::x_get_window_attributes($d,$w);
    if ($attrs->{"backingStore"} == $X::defines{"NotUseful"}) {
	print "setting to Always\n";
	$stat = xlib::x_change_window_attributes($d, $w,
					     $X::defines{"CWBackingStore"},
					     $X::defines{"Always"});
    } else {
	print "setting to NotUseful\n";
	$stat = xlib::x_change_window_attributes($d, $w,
					     $X::defines{"CWBackingStore"},
					     $X::defines{"NotUseful"});
    }
}
query_eval($xopen,$ch1,\&toggle_backingstore);
