Re: Tk and LWP?



On Sat, 5 May 2007 07:18:24 +0200, "Petr Vileta" <stoupa@xxxxxxxxxxxxx>
wrote:

I made some Tk application where I download something from web. I use
LWP::UserAgent for this but the problem is then when I download a huge file
the Tk application look like "freezed". Is impossible to click on Stop
button or manupulate with any other interactive widgets. Is here some way?

Yeah, you are the guy stuck with version 800 of Tk arn't you? :-)

I would say use a thread, but with Perl5.6.1 you may have problems.

So here is the basic thing to do, how you work it into your script
is up to you. LWP supports a progress callback( shown below ),
so put a $mw->update in the callback.
Here is a similar idea, but I upload instead:
http://perlmonks.org?node_id=436810

But if you really want a smooth gui, put the lwp stuff in a thread.
I have an example for that, but you need perl 5.8.5+ for good results,
but you may luck out.


# how to use a simple callback with LWP

#!/usr/bin/perl -w
use strict;
use LWP::UserAgent;

# don't buffer the prints to make the status update
$| = 1;

my $ua = LWP::UserAgent->new();
my $received_size = 0;
my $url = 'http://zentara.net/zentara1.avi';
print "Fetching $url\n";

my $filename = substr( $url, rindex( $url, "/" ) + 1 );
#print "$filename\n";
open( IN, ">$filename" ) or die $!;


my $request_time = time;
my $last_update = 0;
my $response = $ua->get($url,
':content_cb' => \&callback,
':read_size_hint' => 8192,
);
print "\n";

close IN;


sub callback {
my ($data, $response, $protocol) = @_;

my $total_size = $response->header('Content-Length') || 0;
$received_size += length $data;

print IN $data;

####################################################
$mw->update;
####################################################
my $time_now = time;

# this to make the status only update once per second.
return unless $time_now > $last_update or $received_size ==
$total_size;
$last_update = $time_now;



print "\rReceived $received_size bytes";
printf " (%i%%)", (100/$total_size)*$received_size if $total_size;
printf " %6.1f/bps", $received_size/(($time_now-$request_time)||1)
if $received_size;
}
__END__


zentara




--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html
.