Events from files (was Known issues about SpinButtons?)



Hi Chris,

A rule of thumb in any event driven program is that you should
never have to give up the main loop and do polling. It is only
in very rare circumstance that you need to resort to such things.
Instead you have to add to the event loop information that tells
it to call your callback once there is something to read on 
a file handle.

This is explained in Gtk2::Helper . Here is my interpretation of
it:

    #!/usr/bin/perl -w
    ######################################################################
    #  Example of howto use the Gtk2::Helper functions to get input from
    #  a file descriptor.
    ######################################################################
    
    use Gtk2 '-init';
    use Gtk2::Helper;
    use strict;
    
    my $buffer;
    sub create_widgets {
        my $wm = Gtk2::Window->new;
        my $vbox = Gtk2::VBox->new;
        my $sw = Gtk2::ScrolledWindow->new(undef, undef);
        my $tw = Gtk2::TextView->new();
        $buffer= $tw->get_buffer();
        $wm->set_default_size(400,300);
        $sw->add($tw);
        $sw->set_policy('automatic','automatic');
        $vbox->pack_start($sw,1,1,0);
    
        my $button = Gtk2::Button->new("Quit");
        $vbox->pack_start($button,0,0,0);
        $button->signal_connect(clicked=> sub { exit });
        $wm->add($vbox);
    
        $wm->show_all();
    }
    
    create_widgets();
    
    open(IN, q^perl -e '$|++; for($i=0;$i<10;$i++) { $sum+= $i; print "Line $i: sum = $sum\n"; sleep 1;}'|^)
       or die "Failed running perl subprocess\n";
    
    my $tag;
    $tag = Gtk2::Helper->add_watch ( fileno(IN), 'in', sub {
        if (eof(IN)) {
        Gtk2::Helper->remove_watch ($tag);
        close(IN);
        }
        else {
        my $line = <IN>;
        $buffer->insert($buffer->get_end_iter,
                        $line);
        }
        
        return 1;
    });
    
    Gtk2->main;
    
The main lines are the 

   open(IN, "...|")
   
and

   $tag = Gtk2::Helper->add_watch(fh,'in', sub {...} ) lines. 
   
Helper->add_watch call tells gtk to call the anonymous sunroutine when
there is something to read on the filehandle. 

Hope this helps.

Regards,
--
                                                        ___   ___
                                                      /  o  \   o \
Dov Grobgeld                                         ( o  o  ) o   |
The Weizmann Institute of Science, Israel             \  o  /o  o /
"Where the tree of wisdom carries oranges"              | |   | |
                                                       _| |_ _| |_




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]