in reply to Realtime update of a textbuffer from STDOUT/STDERR in Gtk2
is an often used code line that forces the gtk2 event loop to do one loop, and update everything.$buffer->set_text($sysbuffer); Gtk2->main_iteration while Gtk2->events_pending;
Here is a pretty good complete scrolled textview example to help you out. (A commented out IO::Pipe method works too)
#!/usr/bin/perl -w use strict; use Glib qw(TRUE FALSE); use Gtk2 -init; use Gtk2::Helper; #use IO::Pipe; #open a pipe to a command #my $fh = new IO::Pipe; #$fh->reader("top -b"); #$fh->reader("counter1.pl"); #open(FH, "counter1.pl |") or die "$!\n"; open(FH, "top -b |") or die "$!\n"; #add a watch to this file handle my $helper_tag = Gtk2::Helper->add_watch(fileno FH, 'in',sub{ &watch_callback('FH'); }); #standard window creation, placement, and signal connecting my $window = Gtk2::Window->new('toplevel'); $window->signal_connect('delete_event' => sub { exit;}); $window->set_border_width(5); $window->set_position('center_always'); my $hbox = Gtk2::HBox->new(); $hbox->set( "border_width" => 0 ); $window->add($hbox); my $scroll = Gtk2::ScrolledWindow->new; $scroll->set_size_request(600,600); my $textview = Gtk2::TextView->new; my $buffer = $textview->get_buffer; create_tags($buffer); $scroll->add($textview); $hbox->pack_start($scroll,1, 1, 1 ); # expand?, fill?, padding; $window->show_all(); #our main event-loop Gtk2->main; sub watch_callback { my ($fh) = @_; my $line; #read 1000 caracters of the buffer #$fh->sysread($line,1000); sysread(FH,$line,1000); #remove the newline # print $line; chomp $line; if($line){ $buffer->insert_with_tags_by_name($buffer->get_end_iter, $l +ine,'blue'); }else{ Gtk2::Helper->remove_watch($helper_tag); } #absolutely need the main iteration here, or you #won't get the end iter correctly Gtk2->main_iteration while Gtk2->events_pending; $textview->scroll_to_iter($buffer->get_end_iter,0,0,0,0); # my $end_mark = $buffer->create_mark( 'end', $buffer->get_end_ +iter, FALSE ); # $textview->scroll_to_mark( $end_mark, 0.0, FALSE, 0.0, 1.0 ); #important so we can loop again return 1; } ###########################################3 sub create_tags{ my $buffer = shift; $buffer->create_tag('blue', foreground => 'blue', ); $buffer->create_tag('col', foreground => 'green', ); } ######################################### __END__
|
|---|