package W3MImg;

use strict;
use IPC::Open2;
use Symbol;

sub new
{
    my ($class, $w3m) = @_;

    # Try to find w3mimgdisplay
    unless (-e $w3m)
    {
	foreach my $element (split /:/, $ENV{PATH})
	{
	    next unless -e "$element/w3m";

	    my $real = (readlink "$element/w3m") || "$element/w3m";
	    $real =~ s/bin.*/libexec\/w3m\/w3mimgdisplay/;
	    next unless -e $real;

	    $w3m = $real;
	    last;
	}

	die "Can't find w3mimgdisplay\n"
	    unless $w3m;
    }

    # Open up a socket
    my ($read, $write) = (gensym, gensym);
    open2($read, $write, $w3m);

    # Return
    bless { read => $read,
	    write => $write,
	    n => 0 }, $class;
}

sub draw
{
    my ($this, $path, $x, $y) = @_;
    my ($read, $write) = ($this->{read}, $this->{write});
    
    my ($width, $height) = $this->_size($path);

    my $n = ++$this->{n};
    print $write "0;$n;$x;$y;$width;$height;0;0;$width;$height;$path\n";

    $this->_sync;
}

sub _sync
{
    my ($this) = @_; 
    my ($read, $write) = ($this->{read}, $this->{write});
   
    print $write "3;\n4;\n";
}

sub _size
{ 
    my ($this, $path) = @_;
    my ($read, $write) = ($this->{read}, $this->{write});
    
    print $write "5;$path\n";
    chomp(my $line = <$read>);
    split / /, $line;
}

1;
