The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Tickit::Widget - abstract base class for on-screen widgets

DESCRIPTION

This class acts as an abstract base class for on-screen widget objects. It provides the lower-level machinery required by most or all widget types.

Objects cannot be directly constructed in this class. Instead, a subclass of this class which provides a suitable implementation of the render_to_rb and other provided methods is derived. Instances in that class are then constructed.

See the EXAMPLES section below.

The core Tickit distribution only contains a couple of simple widget classes. Many more widget types are available on CPAN. Almost certainly for any widget-based program you will want to at least install the Tickit::Widgets distribution, which provides many of the basic UI types of widget.

STYLE

The following style tags are used on all widget classes that use Style:

:focus

Set when this widget has the input focus

The following style actions are used:

focus_next_before (<Tab>)
focus_next_after (<S-Tab>)

Requests the focus move to the next or previous focusable widget in display order.

CONSTRUCTOR

new

$widget = Tickit::Widget->new( %args );

Constructs a new Tickit::Widget object. Must be called on a subclass that implements the required methods; see the SUBCLASS METHODS section below.

Any pen attributes present in %args will be used to set the default values on the widget's pen object, other than the following:

class => STRING
classes => ARRAY of STRING

If present, gives the Tickit::Style class name or names applied to this widget.

style => HASH

If present, gives a set of "direct applied" style to the Widget. This is treated as an extra set of style definitions that apply more directly than any of the style classes or the default definitions.

The hash should contain style keys, optionally suffixed by style tags, giving values.

style => {
  'fg'        => 3,
  'fg:active' => 5,
}

METHODS

style_classes

@classes = $widget->style_classes;

Returns a list of the style class names this Widget has.

set_style_tag

$widget->set_style_tag( $tag, $value );

Sets the (boolean) state of the named style tag. After calling this method, the get_style_* methods may return different results. No resizing or redrawing is necessarily performed; but the widget can use style_reshape_keys, style_reshape_textwidth_keys or style_redraw_keys to declare which style keys should cause automatic reshaping or redrawing. In addition it can override the on_style_changed_values method to inspect the changes and decide for itself.

get_style_values

@values = $widget->get_style_values( @keys );

$value = $widget->get_style_values( $key );

Returns a list of values for the given keys of the currently-applied style. For more detail see the Tickit::Style documentation. Returns just one value in scalar context.

get_style_pen

$pen = $widget->get_style_pen( $prefix );

A shortcut to calling get_style_values to collect up the pen attributes, and form a Tickit::Pen::Immutable object from them. If $prefix is supplied, it will be prefixed on the pen attribute names with an underscore (which would be read from the stylesheet file as a hyphen). Note that the returned pen instance is immutable, and may be cached.

get_style_text

$text = $widget->get_style_text;

A shortcut to calling get_style_values for a single key called "text".

set_style

$widget->set_style( %defs );

Changes the widget's direct-applied style.

%defs should contain style keys optionally suffixed with tags in the same form as that given to the style key to the constructor. Defined values will add to or replace values already stored by the widget. Keys mapping to undef are deleted from the stored style.

Note that changing the direct applied style is moderately costly because it must invalidate all of the cached style values and pens that depend on the changed keys. For normal runtime changes of style, consider using a tag if possible, because style caching takes tags into account, and simply changing applied style tags does not invalidate the caches.

set_window

$widget->set_window( $window );

Sets the Tickit::Window for the widget to draw on. Setting undef removes the window.

If a window is associated to the widget, that window's pen is set to the current widget pen. The widget is then drawn to the window by calling the render_to_rb method. If a window is removed (by setting undef) then no cleanup of the window is performed; the new owner of the window is expected to do this.

This method may invoke the window_gained and window_lost methods.

window

$window = $widget->window;

Returns the current window of the widget, if one has been set using set_window.

set_parent

$widget->set_parent( $parent );

Sets the parent widget; pass undef to remove the parent.

$parent, if defined, must be a subclass of Tickit::ContainerWidget.

parent

$parent = $widget->parent;

Returns the current container widget

resized

$widget->resized;

Provided for subclasses to call when their size requirements have or may have changed. Re-calculates the size requirements by calling lines and cols again, then calls set_requested_size.

set_requested_size

$widget->set_requested_size( $lines, $cols );

Provided for subclasses to call when their size requirements have or may have changed. Informs the parent that the widget requires a differently-sized window if the dimensions are now different to last time.

requested_size

( $lines, $cols ) = $widget->requested_size;

Returns the requested size of the widget; its preferred dimensions. This method calls lines and cols and caches the result until the next call to resized. Container widgets should use this method in preference to calling lines and cols directly.

requested_lines

$lines = $widget->requested_lines;

requested_cols

$cols  = $widget->requested_cols;

Returns one or other of the requested dimensions. Shortcuts for calling requested_size. These are temporary convenience methods to assist container widgets during the transition to the new sizing model.

redraw

$widget->redraw;

Clears the widget's window then invokes the render method. This should completely redraw the widget.

This redraw doesn't happen immediately. The widget is marked as needing to redraw, and its parent is marked that it has a child needing redraw, recursively to the root widget. These will then be flushed out down the widget tree using an Tickit later call. This allows other widgets to register a requirement to redraw, and have them all flushed in a fairly efficient manner.

pen

$pen = $widget->pen;

Returns the widget's Tickit::Pen.

take_focus

$widget->take_focus;

Calls take_focus on the Widget's underlying Window, if present, or stores that the window should take focus when one is eventually set by set_window.

May only be called on Widget subclasses that override CAN_FOCUS to return a true value.

SUBCLASS METHODS

Because this is an abstract class, the constructor must be called on a subclass which implements the following methods.

render_to_rb

$widget->render_to_rb( $renderbuffer, $rect )

Called to redraw the widget's content to the given Tickit::RenderBuffer.

Will be passed the clipping rectangle region to be rendered as a Tickit::Rect. the method does not have to render any content outside of this region.

reshape

$widget->reshape;

Optional. Called after the window geometry is changed. Useful to distribute window change sizes to contained child widgets.

lines

$lines = $widget->lines;

cols

$cols = $widget->cols;

Called to enquire on the requested window for this widget. It is possible that the actual allocated window may be larger, or smaller than this amount.

window_gained

$widget->window_gained( $window );

Optional. Called by set_window when a window has been set for this widget.

window_lost

$widget->window_lost( $window );

Optional. Called by set_window when undef has been set as the window for this widget. The old window object is passed in.

on_key

$handled = $widget->on_key( $ev );

Optional. If provided, this method will be set as the on_key callback for any window set on the widget. By providing this method a subclass can implement widgets that respond to user input. It receives the same event arguments structure as the underlying window on_key event.

on_mouse

$handled = $widget->on_mouse( $ev );

Optional. If provided, this method will be set as the on_mouse callback for any window set on the widget. By providing this method a subclass can implement widgets that respond to user input. If receives the same event arguments structure as the underlying window on_mouse event.

on_style_changed_values

$widget->on_style_changed_values( %values );

Optional. If provided, this method will be called by set_style_tag to inform the widget which style keys may have changed values, as a result of the tag change. The style values are passed in ARRAY references of two elements, containing the old and new values.

The %values hash may contain false positives in some cases, if the old and the new value are actually the same, but it still appears from the style definitions that certain keys are changed.

Most of the time this method may not be necessary as the style_reshape_keys style_reshape_textwidth_keys, and style_redraw_keys declarations should suffice for most purposes.

CAN_FOCUS

$widget->CAN_FOCUS;

Optional, normally false. If this constant method returns a true value, the widget is allowed to take focus using the take_focus method. It will also take focus automatically if it receives a mouse button 1 press event.

KEYPRESSES_FROM_STYLE

$widget->KEYPRESSES_FROM_STYLE;

Optional, normally false. If this constant method returns a true value, the widget will use style information to invoke named methods on keypresses. When the window's on_key event is invoked, the widget will first attempt to look up a style key with the name of the pressed key, including its modifier key prefixes, surrounded by <angle brackets>. If this gives the name of a, method prefixed by key_ then that method is invoked as a special-purpose on_key handler. If this does not exist, or does not return true, then the widget's regular on_key handler is invoked, if present.

As a special case, space is given the key name <Space> instead of being notated by a literal space character in brackets, for neatness of the style information.

UTILITY FUNCTIONS

The following functions (not methods) are not exported by this package, but intended to be called by widget subclasses fully-qualified.

split_widget_opts

( $widget, %opts ) = split_widget_opts( $arg );

If $arg is an object reference derived from Tickit::Widget, return it directly with no extra options.

If $arg is a reference to an unblessed hash, return the widget value from it (which must exist), followed by any other keys and values in no particular order.

This function is intended for methods that add an entire collection of child widgets in a single call (for example Tickit::Widget::LinearBox's add_children) where the caller wants to override options on specific ones.

EXAMPLES

A Trivial "Hello, World" Widget

The following is about the smallest possible Tickit::Widget implementation, containing the bare minimum of functionality. It displays the fixed string "Hello, world" at the top left corner of its window.

package HelloWorldWidget;
use base 'Tickit::Widget';

sub lines {  1 }
sub cols  { 12 }

sub render_to_rb
{
   my $self = shift;
   my ( $rb, $rect ) = @_;

   $rb->eraserect( $rect );

   $rb->text_at( 0, 0, "Hello, world" );
}

1;

The lines and cols methods tell the container of the widget what its minimum size requirements are, and the render_to_rb method actually draws it to the render buffer.

A slight improvement on this would be to obtain the size of the window, and position the text in the centre rather than the top left corner.

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"
   );
}

Reacting To User Input

If a widget subclass provides an 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 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 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 Tickit object to handle them instead.

Similarly, by providing an 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 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 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 @points array, for the render method to use.

AUTHOR

Paul Evans <leonerd@leonerd.org.uk>