#!/usr/bin/perl
#
# xrandr Test suite
#
# Do a set of xrandr calls and verify that the screen setup is as expected
# after each call.
#
$xrandr="xrandr";
$xrandr=$ENV{XRANDR} if defined $ENV{XRANDR};
$version="0.1";
$inbetween="";
print "\n***** xrandr test suite V$version *****\n\n";
# Known issues and their fixes
%fixes=(
 s2 => "xrandr: 307f3686",
 s4 => "xserver: f7dd0c72",
 s11 => "xrandr: f7aaf894",
 s18 => "issue known, but not fixed yet"
);
# Get output configuration
@outputs=();
%mode_name=();
%out_modes=();
%modes=();
open P, "$xrandr --verbose|" or die "$xrandr";
while (
) {
  if (/^\S/) {
    $o=""; $m=""; $x="";
  }
  if (/^(\S+)\s(connected|unknown connection)\s/) {
    $o=$1;
    push @outputs, $o         if $2 eq "connected";
    push @outputs_unknown, $o if $2 eq "unknown connection";
    $out_modes{$o}=[];
  } elsif (/^\s+(\d+x\d+)\s+\((0x[0-9a-f]+)\)/) {
    my $m=$1;
    my $x=$2;
    while (
) {
      if (/^\s+(\d+x\d+)\s+\((0x[0-9a-f]+)\)/) {
        print "WARNING: Ignoring incomplete mode $x:$m on $o\n";
        $m=$1, $x=$2;
      } elsif (/^\s+v:.*?([0-9.]+)Hz\s*$/) {
        if (defined $mode_name{$x} && $mode_name{$x} ne "$m\@$1") {
	  print "WARNING: Ignoring mode $x:$m\@$1 because $x:$mode_name{$x} already exists\n";
	  last;
	}
	if (defined $modes{"$o:$x"}) {
	  print "WARNING: Ignoring duplicate mode $x on $o\n";
	  last;
	}
	$mode_name{$x}="$m\@$1";
	push @{$out_modes{$o}}, $x;
	$modes{"$o:$x"}=$x;
	$modes{"$o:$m\@$1"}=$x;
	$modes{"$o:$m"}=$x;
        last;
      }
    }
  }
}
close P;
@outputs=(@outputs,@outputs_unknown) if @outputs < 2;
# preamble
if ($ARGV[0] eq "-w") {
  print "Waiting for keypress after each test for manual verification.\n\n";
  $inbetween='print "    Press  to continue...\n"; $_=';
} elsif ($ARGV[0] ne "") {
  print "Preparing for test # $ARGV[0]\n\n";
  $prepare = $ARGV[0];
}
print "Detected connected outputs and available modes:\n\n";
for $o (@outputs) {
  print "$o:";
  my $i=0;
  for $x (@{$out_modes{$o}}) {
    print "\n" if $i++ % 3 == 0;
    print "  $x:$mode_name{$x}";
  }
  print "\n";
}
print "\n";
if (@outputs < 2) {
  print "Found less than two connected outputs. No tests available for that.\n";
  exit 1;
}
if (@outputs > 2) {
  print "Note: No tests for more than two connected outputs available yet.\n";
  print "Using the first two outputs.\n\n";
}
$a=$outputs[0];
$b=$outputs[1];
# For each resolution only a single refresh rate should be used in order to
# reduce ambiguities. For that we need to find unused modes. The %used hash is
# used to track used ones. All references point to .
#