require Tk;
require "scrolledlistbox.pl";

package Pad;
sub new {
    local($frame) = Frame::new(shift);
    local($sl) = Scrolledlistbox::new($frame, "-setgrid" => 1,
                                      "-relief" => "ridge");
    local($e) = Entry::new($frame, "-relief" => "sunken");
    local($pad);
    Tk::tkpack($sl, "-fill" => "both", "-expand" => "y");
    Tk::tkpack($e, "-fill" => "x");
    $pad = bless({Default => $frame, Listbox => $sl, Entry => $e,
                  Focus => $e, "string" => ""});
    $e->configure("-textvariable" => $pad->{"string"});
    Tk::tkbind($e, "<Return>", "process", $pad);
    return $pad;
}

sub append {
    local($w) = shift;
    local($l) = $w->{Listbox};
    local($ywindow, $ytop, $ysize);
    foreach (@_) {
        $l->insert("end", $_);
    }
    $ysize = $l->size();
    $ywindow = $l->configure("-geometry");
    $ywindow =~ /x(\d*)$/;
    $ytop = $ysize - $1;
    $ytop = 0 if $ytop < 0;
    $l->yview($ytop);
}

sub cut {
    local($w, $remains) = @_;
    local($max) = $w->size();
    local($todel);
    $todel = $w->{Listbox}->size() - $remains - 1;
    $w->{Listbox}->tkdelete(0, $todel) if $todel >= 0;
}

sub handler {
    local($w, $subref) = @_;
    $w->{"handler"} = $subref;
}

sub process {
    local($w) = shift; 
    local($subref) = $w->{"handler"};
    &$subref($w->{"string"});
    $w->{"string"} = "";
}

sub focus {
    local($w) = shift;
    Tk::focus $w->{Entry};
}

1;
