Widget.pm

filter: Statementstmt 91.3% 21 / 23 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.5% 29 / 31 CC 1 SCAR 0.4
CC
1
Cov
91%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« WidgetRole/SingleChildContainer.pm ↑ Summary
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2009-2023 -- leonerd@leonerd.org.uk
5  
6 3 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Object::Pad 0.805;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 package Tickit::Widget 0.58;
11 class Tickit::Widget :repr(HASH);
12  
13 3 ▶use experimental 'postderef';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use Scalar::Util qw( blessed weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use List::Util 1.33 qw( all );
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 0 ▶use Tickit::Pen;
Subroutine BEGIN: called CC=1 SCAR=2.6
20 use Tickit::Style;
21 use Tickit::Utils qw( textwidth );
22 use Tickit::Window 0.57; # $win->bind_event
23 use Tickit::Event 0.66; # $info->type newapi
24  
25 use constant PEN_ATTR_MAP => { map { $_ => 1 } @Tickit::Pen::ALL_ATTRS };
26  
27 use constant KEYPRESSES_FROM_STYLE => 0;
28  
29 use constant CAN_FOCUS => 0;
30  
31 =head1 NAME
32  
33 C<Tickit::Widget> - abstract base class for on-screen widgets
34  
35 =head1 DESCRIPTION
36  
37 This class acts as an abstract base class for on-screen widget objects. It
38 provides the lower-level machinery required by most or all widget types.
39  
40 Objects cannot be directly constructed in this class. Instead, a subclass of
41 this class which provides a suitable implementation of the C<render_to_rb> and
42 other provided methods is derived. Instances in that class are then
43 constructed.
44  
45 See the C<EXAMPLES> section below.
46  
47 The core F<Tickit> distribution only contains a couple of simple widget
48 classes. Many more widget types are available on CPAN. Almost certainly for
49 any widget-based program you will want to at least install the
50 L<Tickit::Widgets> distribution, which provides many of the basic UI types of
51 widget.
52  
53 =head1 STYLE
54  
55 The following style tags are used on all widget classes that use Style:
56  
57 =over 4
58  
59 =item :focus
60  
61 Set when this widget has the input focus
62  
63 =back
64  
65 The following style actions are used:
66  
67 =over 4
68  
69 =item focus_next_before (<Tab>)
70  
71 =item focus_next_after (<S-Tab>)
72  
73 Requests the focus move to the next or previous focusable widget in display
74 order.
75  
76 =back
77  
78 =cut
79  
80 style_definition base =>
81 '<Tab>' => "focus_next_after",
82 '<S-Tab>' => "focus_next_before";
83  
84 =head1 CONSTRUCTOR
85  
86 =cut
87  
88 =head2 new
89  
90 $widget = Tickit::Widget->new( %args );
91  
92 Constructs a new C<Tickit::Widget> object. Must be called on a subclass that
93 implements the required methods; see the B<SUBCLASS METHODS> section below.
94  
95 Any pen attributes present in C<%args> will be used to set the default values
96 on the widget's pen object, other than the following:
97  
98 =over 8
99  
100 =item class => STRING
101  
102 =item classes => ARRAY of STRING
103  
104 If present, gives the C<Tickit::Style> class name or names applied to this
105 widget.
106  
107 =item style => HASH
108  
109 If present, gives a set of "direct applied" style to the Widget. This is
110 treated as an extra set of style definitions that apply more directly than any
111 of the style classes or the default definitions.
112  
113 The hash should contain style keys, optionally suffixed by style tags, giving
114 values.
115  
116 style => {
117 'fg' => 3,
118 'fg:active' => 5,
119 }
120  
121 =back
122  
123 =cut
124  
125 field @_style_classes;
126 field $_style_direct;
127 field %_style_tag;
128  
129 ADJUST
130 {
131 my $class = ref $self;
132 foreach my $method (qw( lines cols render_to_rb )) {
133 $class->can( $method ) or
134 croak "$class cannot ->$method - do you subclass and implement it?";
135 }
136 }
137  
138 ADJUST :params (
139 :$class = undef,
140 :$classes = [ $class ],
141 ) {
142 @_style_classes = $classes->@*;
143 }
144  
145 ADJUST :params (
146 :$style = undef,
147 %params
148 ) {
149 # Legacy direct-applied-style argument support
150 foreach my $attr ( @Tickit::Pen::ALL_ATTRS ) {
151 next unless defined( my $val = delete $params{$attr} );
152  
153 carp "Applying legacy direct pen attribute '$attr' for ${\ref $self}";
154 $style->{$attr} = $val;
155 }
156  
157 if( $style ) {
158 my $tagset = $_style_direct = Tickit::Style::_Tagset->new;
159 foreach my $key ( keys %$style ) {
160 $tagset->add( $key, $style->{$key} );
161 }
162 }
163  
164 $self->_update_pen( $self->get_style_pen );
165 }
166  
167 field $_parent :reader;
168 field $_window :reader;
169 field $_pen :reader;
170  
171 field $_focus_pending;
172  
173 field %_event_ids;
174  
175 =head1 METHODS
176  
177 =cut
178  
179 =head2 style_classes
180  
181 @classes = $widget->style_classes;
182  
183 Returns a list of the style class names this Widget has.
184  
185 =cut
186  
187 method style_classes
188 {
189 return @_style_classes;
190 }
191  
192 =head2 set_style_tag
193  
194 $widget->set_style_tag( $tag, $value );
195  
196 Sets the (boolean) state of the named style tag. After calling this method,
197 the C<get_style_*> methods may return different results. No resizing or
198 redrawing is necessarily performed; but the widget can use
199 C<style_reshape_keys>, C<style_reshape_textwidth_keys> or C<style_redraw_keys>
200 to declare which style keys should cause automatic reshaping or redrawing. In
201 addition it can override the C<on_style_changed_values> method to inspect the
202 changes and decide for itself.
203  
204 =cut
205  
206 # This is cached, so will need invalidating on style loads
207 my %KEYS_BY_TYPE_CLASS_TAG;
208 Tickit::Style::on_style_load( sub { undef %KEYS_BY_TYPE_CLASS_TAG } );
209  
210 method set_style_tag
211 {
212 my ( $tag, $value ) = @_;
213  
214 # Early-return on no change
215 return if !$_style_tag{$tag} == !$value;
216  
217 # Work out what style keys might depend on this tag
218 my %values;
219  
220 if( $_style_direct ) {
221 KEYSET: foreach my $keyset ( $_style_direct->keysets ) {
222 $keyset->tags->{$tag} or next KEYSET;
223  
224 $values{$_} ||= [] for keys $keyset->style->%*;
225 }
226 }
227  
228 my $type = $self->_widget_style_type;
229 foreach my $class ( $self->style_classes, undef ) {
230 my $keys = $KEYS_BY_TYPE_CLASS_TAG{$type}{$class//""}{$tag} ||= do {
231 my $tagset = Tickit::Style::_ref_tagset( $type, $class );
232  
233 my %keys;
234 KEYSET: foreach my $keyset ( $tagset->keysets ) {
235 $keyset->tags->{$tag} or next KEYSET;
236  
237 $keys{$_}++ for keys $keyset->style->%*;
238 }
239  
240 [ keys %keys ];
241 };
242  
243 $values{$_} ||= [] for @$keys;
244 }
245  
246 my @keys = keys %values;
247  
248 my @old_values = $self->get_style_values( @keys );
249 $values{$keys[$_]}[0] = $old_values[$_] for 0 .. $#keys;
250  
251 $_style_tag{$tag} = !!$value;
252  
253 $self->_style_changed_values( \%values );
254 }
255  
256 method _style_tags
257 {
258 return join "|", sort grep { $_style_tag{$_} } keys %_style_tag;
259 }
260  
261 =head2 get_style_values
262  
263 @values = $widget->get_style_values( @keys );
264  
265 $value = $widget->get_style_values( $key );
266  
267 Returns a list of values for the given keys of the currently-applied style.
268 For more detail see the L<Tickit::Style> documentation. Returns just one value
269 in scalar context.
270  
271 =cut
272  
273 field %_style_cache;
274  
275 method get_style_values
276 {
277 my @keys = @_;
278  
279 my $type = $self->_widget_style_type;
280  
281 my @set = ( 0 ) x @keys;
282 my @values = ( undef ) x @keys;
283  
284 my $cache = $_style_cache{$self->_style_tags} ||= {};
285  
286 foreach my $i ( 0 .. $#keys ) {
287 next unless exists $cache->{$keys[$i]};
288  
289 $set[$i] = 1;
290 $values[$i] = $cache->{$keys[$i]};
291 }
292  
293 my @classes = ( $self->style_classes, undef );
294 my $tagset = $_style_direct;
295  
296 while( !all { $_ } @set and @classes ) {
297 # First time around this uses the direct style, if set. Thereafter uses
298 # the style classes in order, finally the unclassed base.
299 defined $tagset or $tagset = Tickit::Style::_ref_tagset( $type, shift @classes );
300  
301 KEYSET: foreach my $keyset ( $tagset->keysets ) {
302 $_style_tag{$_} or next KEYSET for keys $keyset->tags->%*;
303  
304 my $style = $keyset->style;
305  
306 foreach ( 0 .. $#keys ) {
307 exists $style->{$keys[$_]} or next;
308 $set[$_] and next;
309  
310 $values[$_] = $style->{$keys[$_]};
311 $set[$_] = 1;
312 }
313 }
314  
315 undef $tagset;
316  
317 # After all the classes, try again with type as "*"
318 if( $type ne "*" and !@classes ) {
319 $type = "*";
320 @classes = ( $self->style_classes, undef );
321 }
322 }
323  
324 foreach my $i ( 0 .. $#keys ) {
325 next if exists $cache->{$keys[$i]};
326  
327 $cache->{$keys[$i]} = $values[$i];
328 }
329  
330 return @values if wantarray;
331 return $values[0];
332 }
333  
334 =head2 get_style_pen
335  
336 $pen = $widget->get_style_pen( $prefix );
337  
338 A shortcut to calling C<get_style_values> to collect up the pen attributes,
339 and form a L<Tickit::Pen::Immutable> object from them. If C<$prefix> is
340 supplied, it will be prefixed on the pen attribute names with an underscore
341 (which would be read from the stylesheet file as a hyphen). Note that the
342 returned pen instance is immutable, and may be cached.
343  
344 =cut
345  
346 field %_style_pen_cache;
347  
348 method get_style_pen
349 {
350 my $class = ref $self;
351 my ( $prefix ) = @_;
352  
353 return $_style_pen_cache{$self->_style_tags}{$prefix//""} ||= do {
354 my @keys = map { defined $prefix ? "${prefix}_$_" : $_ } @Tickit::Pen::ALL_ATTRS;
355  
356 my %attrs;
357 @attrs{@Tickit::Pen::ALL_ATTRS} = $self->get_style_values( @keys );
358  
359 Tickit::Pen::Immutable->new( %attrs );
360 };
361 }
362  
363 =head2 get_style_text
364  
365 $text = $widget->get_style_text;
366  
367 A shortcut to calling C<get_style_values> for a single key called C<"text">.
368  
369 =cut
370  
371 method get_style_text
372 {
373 my $class = ref $self;
374  
375 return $self->get_style_values( "text" ) // croak "$class style does not define text";
376 }
377  
378 =head2 set_style
379  
380 $widget->set_style( %defs );
381  
382 Changes the widget's direct-applied style.
383  
384 C<%defs> should contain style keys optionally suffixed with tags in the same
385 form as that given to the C<style> key to the constructor. Defined values will
386 add to or replace values already stored by the widget. Keys mapping to
387 C<undef> are deleted from the stored style.
388  
389 Note that changing the direct applied style is moderately costly because it
390 must invalidate all of the cached style values and pens that depend on the
391 changed keys. For normal runtime changes of style, consider using a tag if
392 possible, because style caching takes tags into account, and simply changing
393 applied style tags does not invalidate the caches.
394  
395 =cut
396  
397 method set_style
398 {
399 my %defs = @_;
400  
401 my $new = Tickit::Style::_Tagset->new;
402 $new->add( $_, $defs{$_} ) for keys %defs;
403  
404 my %values;
405 foreach my $keyset ( $new->keysets ) {
406 $values{$_} ||= [] for keys $keyset->style->%*;
407 }
408  
409 my @keys = keys %values;
410  
411 my @old_values = $self->get_style_values( @keys );
412 $values{$keys[$_]}[0] = $old_values[$_] for 0 .. $#keys;
413  
414 if( $_style_direct ) {
415 $_style_direct->merge( $new );
416 }
417 else {
418 $_style_direct = $new;
419 }
420  
421 $self->_style_changed_values( \%values, 1 );
422 }
423  
424 method _style_changed_values
425 {
426 my ( $values, $invalidate_caches ) = @_;
427  
428 my @keys = keys %$values;
429  
430 if( $invalidate_caches ) {
431 foreach my $keyset ( values %_style_cache ) {
432 delete $keyset->{$_} for @keys;
433 }
434 }
435  
436 my @new_values = $self->get_style_values( @keys );
437  
438 # Remove unchanged keys
439 foreach ( 0 .. $#keys ) {
440 my $key = $keys[$_];
441 my $old = $values->{$key}[0];
442 my $new = $new_values[$_];
443  
444 delete $values->{$key}, next if !defined $old and !defined $new;
445 delete $values->{$key}, next if defined $old and defined $new and $old eq $new;
446  
447 $values->{$key}[1] = $new;
448 }
449  
450 my %changed_pens;
451 foreach my $key ( @keys ) {
452 PEN_ATTR_MAP->{$key} and
453 $changed_pens{""}++;
454  
455 $key =~ m/^(.*)_([^_]+)$/ && PEN_ATTR_MAP->{$2} and
456 $changed_pens{$1}++;
457 }
458  
459 if( $invalidate_caches ) {
460 foreach my $penset ( values %_style_pen_cache ) {
461 delete $penset->{$_} for keys %changed_pens;
462 }
463 }
464  
465 if( $changed_pens{""} ) {
466 $self->_update_pen( $self->get_style_pen );
467 }
468  
469 my $reshape = 0;
470 my $redraw = 0;
471  
472 my $type = $self->_widget_style_type;
473 foreach ( Tickit::Style::_reshape_keys( $type ) ) {
474 next unless $values->{$_};
475  
476 $reshape = 1;
477 last;
478 }
479  
480 foreach ( Tickit::Style::_reshape_textwidth_keys( $type ) ) {
481 next unless $values->{$_};
482 next if textwidth( $values->{$_}[0] ) == textwidth( $values->{$_}[1] );
483  
484 $reshape = 1;
485 last;
486 }
487  
488 foreach ( Tickit::Style::_redraw_keys( $type ) ) {
489 next unless $values->{$_};
490  
491 $redraw = 1;
492 last;
493 }
494  
495 my $code = $self->can( "on_style_changed_values" );
496 $self->$code( %$values ) if $code;
497  
498 if( $reshape ) {
499 $self->reshape;
500 $self->redraw;
501 }
502 elsif( keys %changed_pens or $redraw ) {
503 $self->redraw;
504 }
505 }
506  
507 =head2 set_window
508  
509 $widget->set_window( $window );
510  
511 Sets the L<Tickit::Window> for the widget to draw on. Setting C<undef> removes
512 the window.
513  
514 If a window is associated to the widget, that window's pen is set to the
515 current widget pen. The widget is then drawn to the window by calling the
516 C<render_to_rb> method. If a window is removed (by setting C<undef>) then no
517 cleanup of the window is performed; the new owner of the window is expected to
518 do this.
519  
520 This method may invoke the C<window_gained> and C<window_lost> methods.
521  
522 =cut
523  
524 method set_window
525 {
526 my ( $window ) = @_;
527  
528 # Early out if no change
529 return if !$window and !$_window;
530 return if $window and $_window and $_window == $window;
531  
532 if( $_window and !$window ) {
533 $_window->set_pen( undef );
534 $self->window_lost( $_window );
535 }
536  
537 $_window = $window;
538  
539 if( $window ) {
540 $window->set_pen( $_pen );
541  
542 $self->window_gained( $_window );
543  
544 $window->take_focus, undef $_focus_pending if $_focus_pending;
545  
546 $self->reshape;
547  
548 $window->expose;
549 }
550 }
551  
552 method window_gained
553 {
554 my $window = $self->window;
555  
556 weaken $self;
557  
558 $_event_ids{geomchange} = $window->bind_event( geomchange => sub {
559 $self->reshape;
560 $self->redraw if !$self->parent;
561 } );
562  
563 $_event_ids{expose} = $window->bind_event( expose => sub {
564 my ( $win, undef, $info ) = @_;
565 $win->is_visible or return 1;
566  
567 $info->rb->setpen( $_pen );
568  
569 $self->render_to_rb( $info->rb, $info->rect );
570 return 1;
571 });
572  
573 $_event_ids{focus} = $window->bind_event( focus => sub {
574 my ( $win, undef, $info ) = @_;
575 $self->_on_win_focus( $win, $info->type, $info->win );
576 } ) if $self->can( "_widget_style_type" );
577  
578 if( $self->can( "on_key" ) or $self->KEYPRESSES_FROM_STYLE ) {
579 $_event_ids{key} = $window->bind_event( key => sub {
580 my ( $win, undef, $info ) = @_;
581  
582 {
583 # Space comes as " " but we'd prefer to use "Space" in styles
584 my $keystr = $info->str eq " " ? "Space" : $info->str;
585  
586 my $action;
587 $action = $self->get_style_values( "<$keystr>" ) if $self->KEYPRESSES_FROM_STYLE;
588  
589 last unless $action;
590  
591 my $code = $self->can( "key_$action" );
592 return 1 if $code and $code->( $self, $info );
593 }
594 my $code = $self->can( "on_key" );
595 return 1 if $code and $code->( $self, $info );
596 } );
597 }
598  
599 $_event_ids{mouse} = $window->bind_event( mouse => sub {
600 my ( $win, undef, $info ) = @_;
601 $self->take_focus if $self->CAN_FOCUS and $info->type eq "press" and $info->button == 1;
602 $self->on_mouse( $info ) if $self->can( "on_mouse" );
603 } );
604 }
605  
606 method _on_win_focus
607 {
608 my ( $win, $focus ) = @_;
609  
610 $self->set_style_tag( focus => $focus eq "in" );
611 }
612  
613 method key_focus_next_after
614 {
615 $self->parent and $self->parent->focus_next( after => $self );
616 return 1;
617 }
618  
619 method key_focus_next_before
620 {
621 $self->parent and $self->parent->focus_next( before => $self );
622 return 1;
623 }
624  
625 method window_lost
626 {
627 my $window = $self->window;
628  
629 $window->unbind_event_id( $_ ) for values %_event_ids;
630 }
631  
632 =head2 window
633  
634 $window = $widget->window;
635  
636 Returns the current window of the widget, if one has been set using
637 C<set_window>.
638  
639 =cut
640  
641 # generated
642  
643 =head2 set_parent
644  
645 $widget->set_parent( $parent );
646  
647 Sets the parent widget; pass C<undef> to remove the parent.
648  
649 C<$parent>, if defined, must be a subclass of L<Tickit::ContainerWidget>.
650  
651 =cut
652  
653 method set_parent
654 {
655 my ( $parent ) = @_;
656  
657 !$parent or $parent->isa( "Tickit::ContainerWidget" ) or croak "Parent must be a ContainerWidget";
658  
659 weaken( $_parent = $parent );
660 }
661  
662 =head2 parent
663  
664 $parent = $widget->parent;
665  
666 Returns the current container widget
667  
668 =cut
669  
670 # generated accessor
671  
672 =head2 resized
673  
674 $widget->resized;
675  
676 Provided for subclasses to call when their size requirements have or may have
677 changed. Re-calculates the size requirements by calling C<lines> and C<cols>
678 again, then calls C<set_requested_size>.
679  
680 =cut
681  
682 method resized
683 {
684 # 'scalar' just in case of odd behaviour in subclasses
685 $self->set_requested_size( scalar $self->lines, scalar $self->cols );
686 }
687  
688 =head2 set_requested_size
689  
690 $widget->set_requested_size( $lines, $cols );
691  
692 Provided for subclasses to call when their size requirements have or may have
693 changed. Informs the parent that the widget requires a differently-sized
694 window if the dimensions are now different to last time.
695  
696 =cut
697  
698 field $_req_lines;
699 field $_req_cols;
700  
701 method set_requested_size
702 {
703 my ( $new_lines, $new_cols ) = @_;
704  
705 return if defined $_req_lines and $_req_lines == $new_lines and
706 defined $_req_cols and $_req_cols == $new_cols;
707  
708 $_req_lines = $new_lines;
709 $_req_cols = $new_cols;
710  
711 if( $self->parent ) {
712 $self->parent->child_resized( $self );
713 }
714 else {
715 $self->reshape if $self->window;
716 $self->redraw;
717 }
718 }
719  
720 =head2 requested_size
721  
722 ( $lines, $cols ) = $widget->requested_size;
723  
724 Returns the requested size of the widget; its preferred dimensions. This
725 method calls C<lines> and C<cols> and caches the result until the next call to
726 C<resized>. Container widgets should use this method in preference to calling
727 C<lines> and C<cols> directly.
728  
729 =head2 requested_lines
730  
731 $lines = $widget->requested_lines;
732  
733 =head2 requested_cols
734  
735 $cols = $widget->requested_cols;
736  
737 Returns one or other of the requested dimensions. Shortcuts for calling
738 C<requested_size>. These are I<temporary> convenience methods to assist
739 container widgets during the transition to the new sizing model.
740  
741 =cut
742  
743 method requested_size
744 {
745 return ( $_req_lines //= $self->lines,
746 $_req_cols //= $self->cols );
747 }
748  
749 method requested_lines { ( $self->requested_size )[0] }
750 method requested_cols { ( $self->requested_size )[1] }
751  
752 =head2 redraw
753  
754 $widget->redraw;
755  
756 Clears the widget's window then invokes the C<render> method. This should
757 completely redraw the widget.
758  
759 This redraw doesn't happen immediately. The widget is marked as needing to
760 redraw, and its parent is marked that it has a child needing redraw,
761 recursively to the root widget. These will then be flushed out down the widget
762 tree using an C<Tickit> C<later> call. This allows other widgets to register a
763 requirement to redraw, and have them all flushed in a fairly efficient manner.
764  
765 =cut
766  
767 method redraw
768 {
769 $self->window or return;
770 $self->window->expose;
771 }
772  
773 =head2 pen
774  
775 $pen = $widget->pen;
776  
777 Returns the widget's L<Tickit::Pen>.
778  
779 =cut
780  
781 # generated accessor
782  
783 method _update_pen
784 {
785 my ( $newpen ) = @_;
786  
787 return if $_pen and $_pen == $newpen;
788  
789 $_pen = $newpen;
790  
791 if( $self->window ) {
792 $self->window->set_pen( $newpen );
793 $self->redraw;
794 }
795 }
796  
797 # Default empty implementation
798 method reshape { }
799  
800 =head2 take_focus
801  
802 $widget->take_focus;
803  
804 Calls C<take_focus> on the Widget's underlying Window, if present, or stores
805 that the window should take focus when one is eventually set by C<set_window>.
806  
807 May only be called on Widget subclasses that override C<CAN_FOCUS> to return a
808 true value.
809  
810 =cut
811  
812 method take_focus
813 {
814 croak ref($self) . " cannot ->take_focus" unless $self->CAN_FOCUS;
815  
816 if( my $win = $self->window ) {
817 $win->take_focus if $win->is_visible;
818 }
819 else {
820 $_focus_pending = 1;
821 }
822 }
823  
824 =head1 SUBCLASS METHODS
825  
826 Because this is an abstract class, the constructor must be called on a
827 subclass which implements the following methods.
828  
829 =head2 render_to_rb
830  
831 $widget->render_to_rb( $renderbuffer, $rect )
832  
833 Called to redraw the widget's content to the given L<Tickit::RenderBuffer>.
834  
835 Will be passed the clipping rectangle region to be rendered as a
836 L<Tickit::Rect>. the method does not have to render any content outside of
837 this region.
838  
839 =head2 reshape
840  
841 $widget->reshape;
842  
843 Optional. Called after the window geometry is changed. Useful to distribute
844 window change sizes to contained child widgets.
845  
846 =head2 lines
847  
848 $lines = $widget->lines;
849  
850 =head2 cols
851  
852 $cols = $widget->cols;
853  
854 Called to enquire on the requested window for this widget. It is possible that
855 the actual allocated window may be larger, or smaller than this amount.
856  
857 =head2 window_gained
858  
859 $widget->window_gained( $window );
860  
861 Optional. Called by C<set_window> when a window has been set for this widget.
862  
863 =head2 window_lost
864  
865 $widget->window_lost( $window );
866  
867 Optional. Called by C<set_window> when C<undef> has been set as the window for
868 this widget. The old window object is passed in.
869  
870 =head2 on_key
871  
872 $handled = $widget->on_key( $ev );
873  
874 Optional. If provided, this method will be set as the C<on_key> callback for
875 any window set on the widget. By providing this method a subclass can
876 implement widgets that respond to user input. It receives the same event
877 arguments structure as the underlying window C<on_key> event.
878  
879 =head2 on_mouse
880  
881 $handled = $widget->on_mouse( $ev );
882  
883 Optional. If provided, this method will be set as the C<on_mouse> callback for
884 any window set on the widget. By providing this method a subclass can
885 implement widgets that respond to user input. If receives the same event
886 arguments structure as the underlying window C<on_mouse> event.
887  
888 =head2 on_style_changed_values
889  
890 $widget->on_style_changed_values( %values );
891  
892 Optional. If provided, this method will be called by C<set_style_tag> to
893 inform the widget which style keys may have changed values, as a result of the
894 tag change. The style values are passed in ARRAY references of two elements,
895 containing the old and new values.
896  
897 The C<%values> hash may contain false positives in some cases, if the old and
898 the new value are actually the same, but it still appears from the style
899 definitions that certain keys are changed.
900  
901 Most of the time this method may not be necessary as the C<style_reshape_keys>
902 C<style_reshape_textwidth_keys>, and C<style_redraw_keys> declarations should
903 suffice for most purposes.
904  
905 =head2 CAN_FOCUS
906  
907 $widget->CAN_FOCUS;
908  
909 Optional, normally false. If this constant method returns a true value, the
910 widget is allowed to take focus using the C<take_focus> method. It will also
911 take focus automatically if it receives a mouse button 1 press event.
912  
913 =head2 KEYPRESSES_FROM_STYLE
914  
915 $widget->KEYPRESSES_FROM_STYLE;
916  
917 Optional, normally false. If this constant method returns a true value, the
918 widget will use style information to invoke named methods on keypresses. When
919 the window's C<on_key> event is invoked, the widget will first attempt to look
920 up a style key with the name of the pressed key, including its modifier key
921 prefixes, surrounded by C<< <angle brackets> >>. If this gives the name of a,
922 method prefixed by C<key_> then that method is invoked as a special-purpose
923 C<on_key> handler. If this does not exist, or does not return true, then the
924 widget's regular C<on_key> handler is invoked, if present.
925  
926 As a special case, space is given the key name C<< <Space> >> instead of being
927 notated by a literal space character in brackets, for neatness of the style
928 information.
929  
930 =cut
931  
932 =head1 UTILITY FUNCTIONS
933  
934 The following functions (not methods) are not exported by this package, but
935 intended to be called by widget subclasses fully-qualified.
936  
937 =cut
938  
939 =head2 split_widget_opts
940  
941 ( $widget, %opts ) = split_widget_opts( $arg );
942  
943 If C<$arg> is an object reference derived from C<Tickit::Widget>, return it
944 directly with no extra options.
945  
946 If C<$arg> is a reference to an unblessed hash, return the C<widget> value
947 from it (which must exist), followed by any other keys and values in no
948 particular order.
949  
950 This function is intended for methods that add an entire collection of child
951 widgets in a single call (for example L<Tickit::Widget::LinearBox>'s
952 C<add_children>) where the caller wants to override options on specific ones.
953  
954 =cut
955  
956 sub split_widget_opts
957 {
958 my ( $arg ) = @_;
959  
960 my $child;
961 my %opts;
962  
963 if( blessed $arg and $arg->isa( "Tickit::Widget" ) ) {
964 $child = $arg;
965 }
966 elsif( ref $arg eq "HASH" ) {
967 %opts = %$arg;
968 $child = delete $opts{child} or
969 croak "Expected to find a 'child' key";
970 }
971 else {
972 croak "Unsure what to do with argument $arg";
973 }
974  
975 return ( $child, %opts );
976 }
977  
978 =head1 EXAMPLES
979  
980 =head2 A Trivial "Hello, World" Widget
981  
982 The following is about the smallest possible C<Tickit::Widget> implementation,
983 containing the bare minimum of functionality. It displays the fixed string
984 "Hello, world" at the top left corner of its window.
985  
986 package HelloWorldWidget;
987 use base 'Tickit::Widget';
988  
989 sub lines { 1 }
990 sub cols { 12 }
991  
992 sub render_to_rb
993 {
994 my $self = shift;
995 my ( $rb, $rect ) = @_;
996  
997 $rb->eraserect( $rect );
998  
999 $rb->text_at( 0, 0, "Hello, world" );
1000 }
1001  
1002 1;
1003  
1004 The C<lines> and C<cols> methods tell the container of the widget what its
1005 minimum size requirements are, and the C<render_to_rb> method actually draws
1006 it to the render buffer.
1007  
1008 A slight improvement on this would be to obtain the size of the window, and
1009 position the text in the centre rather than the top left corner.
1010  
1011 sub render_to_rb
1012 {
1013 my $self = shift;
1014 my ( $rb, $rect ) = @_;
1015 my $win = $self->window;
1016  
1017 $rb->eraserect( $rect );
1018  
1019 $rb->text_at( $win->lines - 1 ) / 2, ( $win->cols - 12 ) / 2,
1020 "Hello, world"
1021 );
1022 }
1023  
1024 =head2 Reacting To User Input
1025  
1026 If a widget subclass provides an C<on_key> method, then this will receive
1027 keypress events if the widget's window has the focus. This example uses it to
1028 change the pen foreground colour.
1029  
1030 package ColourWidget;
1031 use base 'Tickit::Widget';
1032  
1033 my $text = "Press 0 to 7 to change the colour of this text";
1034  
1035 sub lines { 1 }
1036 sub cols { length $text }
1037  
1038 sub render_to_rb
1039 {
1040 my $self = shift;
1041 my ( $rb, $rect ) = @_;
1042 my $win = $self->window;
1043  
1044 $rb->eraserect( $rect );
1045  
1046 $rb->text_at( $win->lines - 1 ) / 2, ( $win->cols - 12 ) / 2,
1047 "Hello, world"
1048 );
1049  
1050 $win->focus( 0, 0 );
1051 }
1052  
1053 sub on_key
1054 {
1055 my $self = shift;
1056 my ( $args ) = @_;
1057  
1058 if( $args->type eq "text" and $args->str =~ m/[0-7]/ ) {
1059 $self->set_style( fg => $args->str );
1060 return 1;
1061 }
1062  
1063 return 0;
1064 }
1065  
1066 1;
1067  
1068 The C<render_to_rb> method sets the focus at the window's top left corner to
1069 ensure that the window always has focus, so the widget will receive keypress
1070 events. (A real widget implementation would likely pick a more sensible place
1071 to put the cursor).
1072  
1073 The C<on_key> method then gets invoked for keypresses. It returns a true value
1074 to indicate the keys it handles, returning false for the others, to allow
1075 parent widgets or the main C<Tickit> object to handle them instead.
1076  
1077 Similarly, by providing an C<on_mouse> method, the widget subclass will
1078 receive mouse events within the window of the widget. This example saves a
1079 list of the last 10 mouse clicks and renders them with an C<X>.
1080  
1081 package ClickerWidget;
1082 use base 'Tickit::Widget';
1083  
1084 # In a real Widget this would be stored in an attribute of $self
1085 my @points;
1086  
1087 sub lines { 1 }
1088 sub cols { 1 }
1089  
1090 sub render_to_rb
1091 {
1092 my $self = shift;
1093 my ( $rb, $rect ) = @_;
1094  
1095 $rb->eraserect( $rect );
1096  
1097 foreach my $point ( @points ) {
1098 $rb->text_at( $point->[0], $point->[1], "X" );
1099 }
1100 }
1101  
1102 sub on_mouse
1103 {
1104 my $self = shift;
1105 my ( $args ) = @_;
1106  
1107 return unless $args->type eq "press" and $args->button == 1;
1108  
1109 push @points, [ $args->line, $args->col ];
1110 shift @points while @points > 10;
1111 $self->redraw;
1112 }
1113  
1114 1;
1115  
1116 This time there is no need to set the window focus, because mouse events do
1117 not need to follow the window that's in focus; they always affect the window
1118 at the location of the mouse cursor.
1119  
1120 The C<on_mouse> method then gets invoked whenever a mouse event happens within
1121 the window occupied by the widget. In this particular case, the method filters
1122 only for pressing button 1. It then stores the position of the mouse click in
1123 the C<@points> array, for the C<render> method to use.
1124  
1125 =cut
1126  
1127 =head1 AUTHOR
1128  
1129 Paul Evans <leonerd@leonerd.org.uk>
1130  
1131 =cut
1132  
1133 0x55AA;
« WidgetRole/SingleChildContainer.pm ↑ Summary