Alt-Tickit-Widgets-ObjectPad
view release on metacpan or search on metacpan
lib/Tickit/Widget.pm view on Meta::CPAN
sub render_to_rb
{
my $self = shift;
my ( $rb, $rect ) = @_;
my $win = $self->window;
$rb->eraserect( $rect );
$rb->text_at( $win->lines - 1 ) / 2, ( $win->cols - 12 ) / 2,
"Hello, world"
);
}
=head2 Reacting To User Input
If a widget subclass provides an C<on_key> method, then this will receive
keypress events if the widget's window has the focus. This example uses it to
change the pen foreground colour.
package ColourWidget;
use base 'Tickit::Widget';
my $text = "Press 0 to 7 to change the colour of this text";
sub lines { 1 }
sub cols { length $text }
sub render_to_rb
{
my $self = shift;
my ( $rb, $rect ) = @_;
my $win = $self->window;
$rb->eraserect( $rect );
$rb->text_at( $win->lines - 1 ) / 2, ( $win->cols - 12 ) / 2,
"Hello, world"
);
$win->focus( 0, 0 );
}
sub on_key
{
my $self = shift;
my ( $args ) = @_;
if( $args->type eq "text" and $args->str =~ m/[0-7]/ ) {
$self->set_style( fg => $args->str );
return 1;
}
return 0;
}
1;
The C<render_to_rb> method sets the focus at the window's top left corner to
ensure that the window always has focus, so the widget will receive keypress
events. (A real widget implementation would likely pick a more sensible place
to put the cursor).
The C<on_key> method then gets invoked for keypresses. It returns a true value
to indicate the keys it handles, returning false for the others, to allow
parent widgets or the main C<Tickit> object to handle them instead.
Similarly, by providing an C<on_mouse> method, the widget subclass will
receive mouse events within the window of the widget. This example saves a
list of the last 10 mouse clicks and renders them with an C<X>.
package ClickerWidget;
use base 'Tickit::Widget';
# In a real Widget this would be stored in an attribute of $self
my @points;
sub lines { 1 }
sub cols { 1 }
sub render_to_rb
{
my $self = shift;
my ( $rb, $rect ) = @_;
$rb->eraserect( $rect );
foreach my $point ( @points ) {
$rb->text_at( $point->[0], $point->[1], "X" );
}
}
sub on_mouse
{
my $self = shift;
my ( $args ) = @_;
return unless $args->type eq "press" and $args->button == 1;
push @points, [ $args->line, $args->col ];
shift @points while @points > 10;
$self->redraw;
}
1;
This time there is no need to set the window focus, because mouse events do
not need to follow the window that's in focus; they always affect the window
at the location of the mouse cursor.
The C<on_mouse> method then gets invoked whenever a mouse event happens within
the window occupied by the widget. In this particular case, the method filters
only for pressing button 1. It then stores the position of the mouse click in
the C<@points> array, for the C<render> method to use.
=cut
=head1 AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
=cut
0x55AA;
( run in 0.645 second using v1.01-cache-2.11-cpan-39bf76dae61 )