blib/lib/Term/Fabulous/Widget/DocumentView.pm untested

filter: Statementstmt 0.0% 0 / 520 Branchbran 0.0% 0 / 228 Conditioncond 0.0% 0 / 172 MC/DCmcdc 0.0% 0 / 104 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 1047 CC 2 SCAR 8.5
CC
2
Cov
0%
BUILDARGS
6.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.3
1 package Term::Fabulous::Widget::DocumentView;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 use Object::Pad 0.825;
9  
10 use Clay::UI::Role::Interaction::Focusable;
11 use Clay::UI::Role::Interaction::HasFocusOrder;
12 use Term::Fabulous::Widget::VirtualList;
13  
14 our $VERSION = '0.05';
15  
16 class Term::Fabulous::Widget::DocumentView
17 :isa(Term::Fabulous::Widget::VirtualList)
18 :does(Clay::UI::Role::Interaction::Focusable)
19 :does(Clay::UI::Role::Interaction::HasFocusOrder)
20 :strict(params)
21 {
22 use Clay::UI::Enum::Result;
23 use Clay::XS qw(sizing_grow CLAY_TOP_TO_BOTTOM);
24 use List::Util qw(any first max min);
25 use Scalar::Util qw(blessed refaddr weaken);
26 use Term::Fabulous::Check qw(describe non_negative_integer);
27 use Term::Fabulous::Document;
28 use Term::Fabulous::Document::Look;
29 use Term::Fabulous::Event::LinkActivate;
30 use Term::Fabulous::Event::ViewChange;
31 use Term::Fabulous::Scrolling qw(inner_rows reveal_rows scroll_by_key scroll_by_pages scroll_by_rows scrolled_percent);
32 use Term::Fabulous::Termbox qw(TF_KEY_MOUSE_WHEEL_LEFT TF_KEY_MOUSE_WHEEL_RIGHT);
33 use Term::Fabulous::Widget::Box;
34  
35 use constant {
36 CODE_STEP => 8, # columns the code moves per Left or Right
37 CODE_WHEEL_COLUMNS => 3, # and per notch of the horizontal wheel
38 REVEAL_FRAMES => 8, # frames a reveal may take until its line is in view
39 FOCUS_FRAMES => 4, # frames a widget far away may take to be built for the focus
40 QUOTE_COLUMNS => 2, # the bar of a quote and the space after it
41 };
42  
43 my $CONTINUE = Clay::UI::Enum::Result->CONTINUE;
44  
45 field $document :param = undef;
46 field $highlighter :param = undef;
47 field $indent :param = 2;
48  
49 # The slots built for items, by index: { slot => what the list shows,
50 # holder => the box the item is the child of, item, quotes => the
51 # boxes whose left border is a quote bar }.
52 field %slot_of;
53  
54 # How far the code blocks are scrolled sideways, together.
55 field $code_offset = 0;
56  
57 # The search: { query, matches => [ [ item index, widget, key, start,
58 # end, revision ] ], current, groups => { id => { widget, key,
59 # members } }, group_of => [ id per match ], painted => { refaddr =>
60 # widget } }; undef without one.
61 field $search;
62  
63 # The selected link: { index, text, link, revision }, or undef.
64 field $selected;
65  
66 # What the last ViewChange said; the line of an item being brought
67 # into view ({ index, widget, key, offset }) and the widget to focus
68 # once its item is built ({ widget }). The frame work that follows a
69 # request holds it; these weak copies only tell which request is the
70 # current one, so setting one to undef cancels it, and it is undef
71 # again once its frame work ended.
72 field $reported = '';
73 field $pending_reveal;
74 field $pending_focus;
75  
76 # The list's build, estimate and count are the document's: a
77 # placeholder satisfies VirtualList's constructor until ADJUST, where
78 # $self exists, installs the real ones.
79 sub BUILDARGS ( $class, %params ) {
80 foreach my $name (qw(build estimate count)) {
81 die "$class: $name cannot be given; the view builds its items from its document" if exists $params{$name};
82 }
83 return $class->SUPER::BUILDARGS( %params, build => sub ($index) { die "$class: the builder is installed in ADJUST" } );
84 }
85  
86 ADJUST {
87 $highlighter = _checked_highlighter( $self, $highlighter );
88 $indent = non_negative_integer( $self, indent => $indent );
89 $document = $self->_checked_document($document);
90 $document->_attach_view($self) if defined $document;
91  
92 weaken( my $weak_self = $self ); # for the build and estimate code, which the list keeps
93 $self->SUPER::build( sub ($index) { return $weak_self->_build_slot($index) } );
94 $self->SUPER::estimate( sub ( $index, $columns ) { return $weak_self->_item_rows( $index, $columns ) } );
95 $self->on( KeyPress => sub ( $self, $event ) { return $self->_key($event) }, owner => $self );
96 $self->on( Mouse => sub ( $self, $event ) { return $self->_wheel($event) }, owner => $self );
97 $self->on( LinkActivate => sub ( $self, $event ) { return $self->_link_clicked($event) }, owner => $self );
98 $self->on( OnFocus => sub ( $self, $event ) { $self->_focus_arrived( $event->target ); return $CONTINUE }, owner => $self );
99 $self->_show_document;
100 }
101  
102 method _checked_document ($value) {
103 return undef unless defined $value;
104 die ref($self) . ": document must be a Term::Fabulous::Document or undef, got " . describe($value) unless blessed $value && $value->isa('Term::Fabulous::Document');
105 return $value;
106 }
107  
108 sub _checked_highlighter ( $owner, $value ) {
109 die ref($owner) . ": highlighter must be a code reference or undef, got " . describe($value) if defined $value && ref $value ne 'CODE';
110 return $value;
111 }
112  
113 # The look of the document, in the theme the view draws with.
114 method document_look () {
115 return $self->_look_class->of($self);
116 }
117  
118 method _look_class () {
119 return defined $document ? $document->look : 'Term::Fabulous::Document::Look';
120 }
121  
122 # ---------------------------------------------------------------------
123 # Parameters
124 # ---------------------------------------------------------------------
125  
126 method document (@new) {
127 return $document unless @new;
128 my $new = $self->_checked_document( $new[0] );
129 $new->_attach_view($self) if defined $new;
130 $self->_forget_marks;
131 $document->_detach_view($self) if defined $document && !( defined $new && refaddr($new) == refaddr($document) );
132 $document = $new;
133 $self->_show_document;
134 return $document;
135 }
136  
137 method highlighter (@new) {
138 return $highlighter unless @new;
139 $highlighter = _checked_highlighter( $self, $new[0] );
140 $_->highlighter($highlighter) foreach $self->_document_code;
141 return $highlighter;
142 }
143  
144 method indent (@new) {
145 return $indent unless @new;
146 $indent = non_negative_integer( $self, indent => $new[0] );
147 $self->rebuild;
148 return $indent;
149 }
150  
151 # The list's own parameters are the document's business.
152 method build :override (@new) {
153 die ref($self) . ": build cannot be set; the view builds its items from its document" if @new;
154 return $self->SUPER::build;
155 }
156  
157 method estimate :override (@new) {
158 die ref($self) . ": estimate cannot be set; the view estimates its items from its document" if @new;
159 return $self->SUPER::estimate;
160 }
161  
162 method count :override (@new) {
163 die ref($self) . ": count cannot be set; it is the number of items of the document" if @new;
164 $self->_adopt_new_items;
165 return $self->SUPER::count;
166 }
167  
168 # Items added to the document since the view last looked join the
169 # list: before a frame, and before anything that needs their indexes.
170 method _adopt_new_items () {
171 return unless defined $document;
172 my $count = $document->count;
173 $self->SUPER::count($count) if $count != $self->SUPER::count;
174 return;
175 }
176  
177 # The items leave their slots, so that they can be shown again, in new
178 # slots or by another view.
179 method rebuild :override () {
180 foreach my $built ( values %slot_of ) {
181 my ( $item, $holder ) = @{$built}{qw(item holder)};
182 my $parent = $item->parent;
183 $holder->remove_child($item) if defined $parent && refaddr($parent) == refaddr($holder);
184 }
185 %slot_of = ();
186 return $self->SUPER::rebuild;
187 }
188  
189 # A new document starts at its top, with no marks, its code not
190 # scrolled sideways, and a ViewChange for its first frame.
191 method _show_document () {
192 ( $pending_reveal, $pending_focus ) = ();
193 ( $code_offset, $reported ) = ( 0, '' );
194 $self->rebuild;
195 $self->SUPER::count( defined $document ? $document->count : 0 );
196 foreach my $code ( $self->_document_code ) {
197 $code->highlighter($highlighter) if defined $highlighter;
198 $code->offset(0);
199 }
200 $self->scroll_to_item(0) if $self->SUPER::count;
201 return;
202 }
203  
204 method _document_code () {
205 return defined $document ? $document->code_blocks : ();
206 }
207  
208 # ---------------------------------------------------------------------
209 # The slots of the items
210 # ---------------------------------------------------------------------
211  
212 # Columns before an item: the view's indent, unless the item is flush,
213 # and its own.
214 method _left_of ($option) {
215 return ( $option->{flush} ? 0 : $indent ) + $option->{indent};
216 }
217  
218 # The item in a box that gives it its indent and the blank rows above
219 # it, inside a bar for each quote it is in. The blank rows stay inside
220 # the innermost bar, so the bars of one quote join.
221 method _build_slot ($index) {
222 my $item = $document->item($index);
223 my $option = $document->options_of($index);
224 my $holder = Term::Fabulous::Widget::Box->new(
225 layout => {
226 layout_direction => CLAY_TOP_TO_BOTTOM,
227 sizing => { width => sizing_grow() },
228 padding => { left => $self->_left_of($option), top => $index ? $option->{gap} : 0 },
229 }
230 );
231 $holder->add_child($item);
232 my ( $slot, @quotes ) = ($holder);
233 foreach ( 1 .. $option->{quote} ) {
234 my $quote = Term::Fabulous::Widget::Box->new(
235 bordered => { left => 1 },
236 layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow() }, padding => { left => QUOTE_COLUMNS - 1 } },
237 );
238 $quote->add_child($slot);
239 push @quotes, $quote;
240 $slot = $quote;
241 }
242 $slot_of{$index} = { slot => $slot, holder => $holder, item => $item, quotes => \@quotes };
243 $self->_color_quotes( $slot_of{$index} );
244 $self->_settle_code($index);
245 return $slot;
246 }
247  
248 # The code blocks of an item built after the document was shown take
249 # what the others got then: the view's highlighter, for a code block
250 # of the document, and the offset the code is scrolled to.
251 method _settle_code ($index) {
252 my $item = $slot_of{$index}{item};
253 $item->highlighter($highlighter) if defined $highlighter && any { refaddr($_) == refaddr($item) } $self->_document_code;
254 $_->offset($code_offset) foreach $self->_built_code($index);
255 return;
256 }
257  
258 method _color_quotes ($built) {
259 return unless @{ $built->{quotes} };
260 my $color = $self->document_look->style('quote')->{color};
261 $_->border_color($color) foreach @{ $built->{quotes} };
262 return;
263 }
264  
265 # The rows of an item before it was laid out: the blank rows above it,
266 # and what the item says it takes in the columns left for it (see
267 # Term::Fabulous::Widget::estimated_rows), or what the document says.
268 method _item_rows ( $index, $columns ) {
269 my $option = $document->options_of($index);
270 my $top = $index ? $option->{gap} : 0;
271 return $top + $option->{rows} if defined $option->{rows};
272 my $item = $document->item($index);
273 my $inner = max( 1, $columns - $self->_left_of($option) - QUOTE_COLUMNS * $option->{quote} );
274 return $top + ( $item->can('estimated_rows') ? $item->estimated_rows($inner) : 1 );
275 }
276  
277 # A theme switch recolors the quote bars; everything else draws with
278 # palette tokens and follows by itself. The ScrollBox pads its gutter
279 # for the border first.
280 method looks_changed :override (@names) {
281 $self->SUPER::looks_changed(@names);
282 $self->_color_quotes($_) foreach values %slot_of;
283 return;
284 }
285  
286 # The item a widget belongs to: its index, or undef for a widget that
287 # is in none (the view, its scrollbars).
288 method _item_index_of ($widget) {
289 return undef unless defined $document;
290 foreach my $node ( $widget, $widget->ancestors ) {
291 last if refaddr($node) == refaddr($self);
292 my $index = $document->index_of($node);
293 return $index if defined $index;
294 }
295 return undef;
296 }
297  
298 # ---------------------------------------------------------------------
299 # Scrolling
300 # ---------------------------------------------------------------------
301  
302 method scroll_lines ($lines) {
303 my $ui = $self->ui // return 0;
304 return scroll_by_rows( $ui, $self, $lines );
305 }
306  
307 # A page is the rows the content shows less one (see
308 # Term::Fabulous::Scrolling).
309 method scroll_pages ($pages) {
310 my $ui = $self->ui // return 0;
311 return scroll_by_pages( $ui, $self, $pages );
312 }
313  
314 method scroll_to_top () {
315 return 0 unless $self->count;
316 $self->scroll_to_item(0);
317 return 1;
318 }
319  
320 method scroll_to_bottom () {
321 my $count = $self->count or return 0;
322 $self->scroll_to_item( $count - 1 );
323 return 1;
324 }
325  
326 method show_item ($index) {
327 $self->_adopt_new_items;
328 $self->scroll_to_item($index);
329 return $self;
330 }
331  
332 method top_item () {
333 my $visible = $self->visible_items // return undef;
334 return $visible->{first};
335 }
336  
337 # Brings the line that holds a character of a text into view, with as
338 # little movement as possible. An item that is not laid out goes to
339 # the top first, and its line follows once it is. The list may move
340 # the item to the top once more in the next frame (it repeats
341 # scroll_to_item until it has measured the item), and a widget may
342 # build the text only in the next frame (a table turns to a page), so
343 # the reveal is checked again after each of a few frames, until the
344 # line is in view. A new reveal replaces one still waiting.
345 method _reveal ( $index, $widget, $key, $offset ) {
346 my $request = { index => $index, widget => $widget, key => $key, offset => $offset };
347 $pending_reveal = undef;
348 return 1 unless $self->_reveal_line_now($request);
349 weaken( $pending_reveal = $request );
350 $self->_follow_frames( 'reveal line', sub ($view) { return $view->_continue_reveal($request) }, REVEAL_FRAMES );
351 return 1;
352 }
353  
354 # True when the reveal is done: cancelled, replaced or in view.
355 method _continue_reveal ($request) {
356 return 1 unless _is_current( $pending_reveal, $request );
357 return $self->_reveal_line_now($request) ? 0 : 1;
358 }
359  
360 sub _is_current ( $pending, $request ) {
361 return defined $pending && refaddr($pending) == refaddr($request) ? 1 : 0;
362 }
363  
364 # One attempt: 1 when the view had to move or could not tell yet, 0
365 # when the line is in view.
366 method _reveal_line_now ($request) {
367 my ( $index, $widget, $key, $offset ) = @{$request}{qw(index widget key offset)};
368 my $ui = $self->ui;
369 my $built = $slot_of{$index};
370 my $box = defined $ui && defined $built ? $ui->bounding_box( $built->{slot} ) : undef;
371 my ( $top, $bottom ) = defined $box ? inner_rows( $ui, $self ) : ();
372 unless ( defined $top ) {
373 $self->show_item($index);
374 return 1;
375 }
376 my $row = $self->_row_of( $ui, $widget, $key, $offset );
377 unless ( defined $row ) {
378 reveal_rows( $ui, $self, $box->{y}, $box->{y} + 1 );
379 return 1;
380 }
381 return 0 if $row >= $top && $row < $bottom;
382 reveal_rows( $ui, $self, $row, $row + 1 );
383 return 1;
384 }
385  
386 # The screen row of a character in the last frame: a widget that knows
387 # the row (a code block, by its line) tells it; a text is looked up in
388 # its painted lines. Clay leaves out the lines of a text below the
389 # window, so for a character past the last line painted the text
390 # works the row out from its wrapping. undef while the widget shows
391 # no text for the key yet.
392 method _row_of ( $ui, $widget, $key, $offset ) {
393 my ( $text, $row ) = @{ $widget->reveal_text( $key, $offset ) };
394 if ( defined $row ) {
395 my $box = $ui->bounding_box($widget) // return undef;
396 return $box->{y} + $row;
397 }
398 return undef unless defined $text;
399 my $box = $ui->bounding_box($text) // return undef;
400 my $frame = $ui->can('last_frame') ? $ui->last_frame : undef;
401 my @lines = defined $frame ? $frame->text_rows($text) : ();
402 my $line = ( grep { $_->[1] <= $offset } @lines )[-1];
403 my $cut = !defined $line || ( refaddr($line) == refaddr( $lines[-1] ) && $box->{y} + $box->{height} > $line->[0] + 1 );
404 return $line->[0] unless $cut;
405 return $box->{y} + ( $text->can('row_of_offset') ? $text->row_of_offset( $offset, max( 1, int( $box->{width} + 0.5 ) ) ) : 0 );
406 }
407  
408 method code_offset () {
409 return $code_offset;
410 }
411  
412 # The code blocks of the items with these indexes that are built.
413 method _built_code (@indexes) {
414 return grep { $_->isa('Term::Fabulous::Widget::CodeBlock') } map { $_->{item}->subtree } grep { defined } @slot_of{@indexes};
415 }
416  
417 # Scrolls every code block sideways, as far as the widest one in view
418 # allows; blocks out of view move along, so that they match when they
419 # come back. Only blocks in view that were painted know how much of
420 # them shows.
421 method scroll_code ($columns) {
422 my $visible = $self->visible_items;
423 my @in_view = defined $visible ? grep { $_->columns > 0 } $self->_built_code( $visible->{first} .. $visible->{last} ) : ();
424 my $limit = max 0, map { $_->max_offset } @in_view;
425 my $from = min( $code_offset, $limit );
426 my $wanted = min( max( 0, $from + $columns ), $limit );
427 return 0 if $wanted == $from;
428 $code_offset = $wanted;
429 my %seen;
430 $_->offset($code_offset) foreach grep { !$seen{ refaddr $_ }++ } $self->_document_code, $self->_built_code( keys %slot_of );
431 return 1;
432 }
433  
434 # A notch of the horizontal wheel over a code block scrolls the code,
435 # while it can move; at the end, the notch goes on. Texts and blank
436 # rows take no mouse events, so a notch over them reaches the view
437 # only when the view is the root widget.
438 method _wheel ($event) {
439 my $key = $event->key;
440 my $direction = $key == TF_KEY_MOUSE_WHEEL_LEFT ? -1 : $key == TF_KEY_MOUSE_WHEEL_RIGHT ? 1 : 0;
441 return $CONTINUE unless $direction && $self->scroll_code( $direction * CODE_WHEEL_COLUMNS );
442 $event->use_wheel;
443 return;
444 }
445  
446 # ---------------------------------------------------------------------
447 # Links: one selection over the links of every text of every item
448 # ---------------------------------------------------------------------
449  
450 # The links of an item in tree order, as [ text, link index ].
451 method _links_of ($index) {
452 return map {
453 my $text = $_;
454 map { [ $text, $_ ] } 0 .. $#{ $text->links }
455 } $document->texts($index);
456 }
457  
458 # A selection whose text changed points into nothing.
459 method _selection_holds () {
460 return 0 unless defined $selected;
461 my $text = $selected->{text};
462 return $text->content_revision == $selected->{revision} && $selected->{link} <= $#{ $text->links } ? 1 : 0;
463 }
464  
465 # Shows the selection on the text that has it, and on no other.
466 method _select ( $index = undef, $text = undef, $link = undef ) {
467 $selected->{text}->select_link(undef) if defined $selected && !( defined $text && refaddr( $selected->{text} ) == refaddr($text) );
468 $selected = defined $text ? { index => $index, text => $text, link => $link, revision => $text->content_revision } : undef;
469 $text->select_link($link) if defined $text;
470 return;
471 }
472  
473 method selected_link () {
474 return undef unless $self->_selection_holds;
475 return $selected->{text}->links->[ $selected->{link} ][2];
476 }
477  
478 method select_next_link () {
479 return $self->_select_link(1);
480 }
481  
482 method select_previous_link () {
483 return $self->_select_link(-1);
484 }
485  
486 # From the selected link while its item is in view, else from the
487 # first (last) item in view; the selection stops at the first and the
488 # last link of the document.
489 method _select_link ($direction) {
490 return 0 unless defined $document && $document->count;
491 my $visible = $self->visible_items;
492 my $target;
493 if ( $self->_selection_holds && ( !defined $visible || ( $selected->{index} >= $visible->{first} && $selected->{index} <= $visible->{last} ) ) ) {
494 my @links = $self->_links_of( $selected->{index} );
495 my ($at) = grep { refaddr( $links[$_][0] ) == refaddr( $selected->{text} ) && $links[$_][1] == $selected->{link} } 0 .. $#links;
496 my $next = defined $at ? $at + $direction : -1;
497 $target = $next >= 0 && $next <= $#links ? [ $selected->{index}, @{ $links[$next] } ] : $self->_link_from( $selected->{index} + $direction, $direction );
498 }
499 else {
500 my $start = $direction > 0 ? ( defined $visible ? $visible->{first} : 0 ) : ( defined $visible ? $visible->{last} : $document->count - 1 );
501 $target = $self->_link_from( $start, $direction );
502 }
503 return 0 unless defined $target;
504 $self->_select(@$target);
505 my ( $index, $text, $link ) = @$target;
506 $self->_reveal( $index, $text, undef, $text->links->[$link][0] );
507 return 1;
508 }
509  
510 # The first link (the last, going back) of the items from $start on.
511 method _link_from ( $start, $direction ) {
512 for ( my $index = $start; $index >= 0 && $index < $document->count; $index += $direction ) {
513 my @links = $self->_links_of($index) or next;
514 return [ $index, @{ $direction > 0 ? $links[0] : $links[-1] } ];
515 }
516 return undef;
517 }
518  
519 # The text of the link fires LinkActivate, which bubbles through the
520 # view to the program; a text that is not in the view at the moment
521 # (its item left the window) cannot, and the view fires it instead.
522 method follow_link () {
523 return 0 unless $self->_selection_holds;
524 my ( $text, $link ) = @{$selected}{qw(text link)};
525 return $text->activate_link($link) if $self->contains($text);
526 my ( $start, $end, $target ) = @{ $text->links->[$link] };
527 $self->fire_event( Term::Fabulous::Event::LinkActivate->new( link => $target, index => $link, start => $start, end => $end ) );
528 return 1;
529 }
530  
531 # A link clicked or followed in a text of an item becomes the selected
532 # link, and the event goes on to the program.
533 method _link_clicked ($event) {
534 my $text = $event->target;
535 return $CONTINUE unless blessed $text && $text->isa('Term::Fabulous::Widget::Text');
536 my $index = $self->_item_index_of($text) // return $CONTINUE;
537 $self->_select( $index, $text, $event->index );
538 return $CONTINUE;
539 }
540  
541 # A text inside an item that took the focus (a click on a text with
542 # links does) gives it to the view, which keeps one selection for all
543 # links; the text's first link becomes the selected one, until a
544 # click selects another.
545 method _focus_arrived ($target) {
546 return unless blessed $target && refaddr($target) != refaddr($self) && $target->DOES('Clay::UI::Role::Core::TextNode');
547 my $index = $self->_item_index_of($target) // return;
548 my $ui = $self->ui // return;
549 my $interaction = $ui->interaction;
550 return unless $interaction->can_take_focus($self);
551 $interaction->set_focused_widget($self);
552 $self->_select( $index, $target, 0 ) if $target->isa('Term::Fabulous::Widget::Text') && @{ $target->links };
553 return;
554 }
555  
556 # ---------------------------------------------------------------------
557 # Searching: the texts of every searchable widget of every item
558 # ---------------------------------------------------------------------
559  
560 method query () {
561 return defined $search ? $search->{query} : undef;
562 }
563  
564 method match_count () {
565 return defined $search ? scalar @{ $search->{matches} } : 0;
566 }
567  
568 method current_match () {
569 return defined $search && defined $search->{current} ? $search->{current} + 1 : undef;
570 }
571  
572 # Marks every occurrence and moves to the first one at or after the
573 # top of the view. Returns the number of matches.
574 method search ($text) {
575 die ref($self) . ": search needs a string, got " . describe($text) unless defined $text && !ref $text;
576 $self->_run_search( $text, $self->top_item // 0 );
577 $self->_reveal_match;
578 return $self->match_count;
579 }
580  
581 method _run_search ( $query, $top ) {
582 $self->_unpaint;
583 $search = undef;
584 return unless length $query && defined $document;
585 my @matches = map { [ @$_, $_->[1]->search_revision( $_->[2] ) ] } $document->find_text($query);
586 my $current = first { $matches[$_][0] >= $top } 0 .. $#matches;
587 $current //= 0 if @matches;
588  
589 my ( %groups, @group_of );
590 foreach my $index ( 0 .. $#matches ) {
591 my ( undef, $widget, $key ) = @{ $matches[$index] };
592 my $id = refaddr($widget) . "\0" . _key_string($key);
593 push @{ ( $groups{$id} //= { widget => $widget, key => $key, members => [] } )->{members} }, $index;
594 $group_of[$index] = $id;
595 }
596 $search = { query => $query, matches => \@matches, current => $current, groups => \%groups, group_of => \@group_of, painted => {} };
597 $self->_paint_group($_) foreach keys %groups;
598 return;
599 }
600  
601 sub _key_string ($key) {
602 return 'u' unless defined $key;
603 return ref $key eq 'ARRAY' ? '[' . join( ',', map { _key_string($_) } @$key ) . ']' : "d$key";
604 }
605  
606 # The matches in one text: the current one in the match_current style,
607 # the others in the match style.
608 method _paint_group ($id) {
609 my $group = $search->{groups}{$id};
610 my $look = $self->_look_class;
611 my @style = map { $look->token_style($_) } qw(match match_current);
612 my $current = $search->{current} // -1;
613 my @ranges = map {
614 my $match = $search->{matches}[$_];
615 [ $match->[3], $match->[4], $style[ $_ == $current ? 1 : 0 ] ]
616 } @{ $group->{members} };
617 $group->{widget}->highlight_text( $group->{key}, \@ranges );
618 $search->{painted}{ refaddr $group->{widget} } = $group->{widget};
619 return;
620 }
621  
622 method _unpaint () {
623 return unless defined $search;
624 $_->clear_text_highlights foreach values %{ $search->{painted} };
625 return;
626 }
627  
628 method next_match () {
629 return $self->_step_match(1);
630 }
631  
632 method previous_match () {
633 return $self->_step_match(-1);
634 }
635  
636 # Steps through the matches, around from the last to the first. When a
637 # text changed since the search, the search runs again first, from
638 # the item of the current match.
639 method _step_match ($direction) {
640 return 0 unless defined $search && @{ $search->{matches} };
641 my $stale = first { $_->[1]->search_revision( $_->[2] ) ne $_->[5] } @{ $search->{matches} };
642 if ( defined $stale ) {
643 $self->_run_search( $search->{query}, $search->{matches}[ $search->{current} ][0] );
644 return 0 unless defined $search && @{ $search->{matches} };
645 }
646 my $before = $search->{current};
647 $search->{current} = ( $before + $direction ) % @{ $search->{matches} };
648 my %seen;
649 $self->_paint_group($_) foreach grep { !$seen{$_}++ } @{ $search->{group_of} }[ $before, $search->{current} ];
650 $self->_reveal_match;
651 return 1;
652 }
653  
654 method _reveal_match () {
655 return unless defined $search && defined $search->{current};
656 my ( $index, $widget, $key, $start ) = @{ $search->{matches}[ $search->{current} ] };
657 $self->_reveal( $index, $widget, $key, $start );
658 return;
659 }
660  
661 # Drops the search and the selected link. Returns 1 when there was
662 # anything to drop: a search without matches ends too.
663 method clear_marks () {
664 return 0 unless defined $search || defined $selected;
665 $pending_reveal = undef;
666 $self->_forget_marks;
667 return 1;
668 }
669  
670 method _forget_marks () {
671 $self->_unpaint;
672 $search = undef;
673 $self->_select;
674 return;
675 }
676  
677 # ---------------------------------------------------------------------
678 # The focus: the view, then the interactive widgets of the items
679 # ---------------------------------------------------------------------
680  
681 # Tab and Shift+Tab that come from outside stop at the view
682 # (Clay::UI::Role::Interaction::HasFocusOrder).
683 method get_entry_focus ($direction) {
684 my $ui = $self->ui // return undef;
685 return $ui->interaction->can_take_focus($self) ? $self : undef;
686 }
687  
688 # From the view to the first interactive widget at or below the top
689 # of the view, from a widget to the next one; past the last, out of
690 # the view.
691 method get_next_focus () {
692 my $interaction = $self->ui->interaction;
693 my $focused = $interaction->get_focused_widget;
694 my $from = $self->_focused_item($focused);
695 my $target = defined $from ? $self->_interactive_after( $from, $focused, 1 ) : $self->_interactive_from( $self->top_item // 0, 1 );
696 return $interaction->focus_after( $self, 'next' ) unless defined $target;
697 return $self->_focus_target(@$target);
698 }
699  
700 # From a widget to the one before it, from the first to the view, from
701 # the view out of it.
702 method get_previous_focus () {
703 my $interaction = $self->ui->interaction;
704 my $focused = $interaction->get_focused_widget;
705 my $from = $self->_focused_item($focused) // return $interaction->focus_after( $self, 'previous' );
706 my $target = $self->_interactive_after( $from, $focused, -1 ) // return $self;
707 return $self->_focus_target(@$target);
708 }
709  
710 method _focused_item ($focused) {
711 return undef unless defined $focused && refaddr($focused) != refaddr($self) && $self->contains($focused);
712 return $self->_item_index_of($focused);
713 }
714  
715 # The widgets of an item that take the focus with Tab: not its texts,
716 # whose links the view selects.
717 method _interactive_of ($index) {
718 return grep { $_->DOES('Clay::UI::Role::Interaction::Focusable') && !$_->DOES('Clay::UI::Role::Core::TextNode') && $_->can_focus } $document->item($index)->subtree;
719 }
720  
721 method _interactive_after ( $index, $focused, $direction ) {
722 my @here = $self->_interactive_of($index);
723 my ($at) = grep { refaddr( $here[$_] ) == refaddr($focused) } 0 .. $#here;
724 if ( defined $at ) {
725 my $next = $at + $direction;
726 return [ $index, $here[$next] ] if $next >= 0 && $next <= $#here;
727 }
728 return $self->_interactive_from( $index + $direction, $direction );
729 }
730  
731 method _interactive_from ( $start, $direction ) {
732 return undef unless defined $document;
733 for ( my $index = $start; $index >= 0 && $index < $document->count; $index += $direction ) {
734 my @widgets = $self->_interactive_of($index) or next;
735 return [ $index, $direction > 0 ? $widgets[0] : $widgets[-1] ];
736 }
737 return undef;
738 }
739  
740 # A widget whose item is not built cannot take the focus yet: the view
741 # scrolls to the item and focuses the widget once it is there.
742 method _focus_target ( $index, $widget ) {
743 my $interaction = $self->ui->interaction;
744 return $widget if $interaction->can_take_focus($widget);
745 my $request = { widget => $widget };
746 weaken $request->{widget};
747 weaken( $pending_focus = $request );
748 $self->_follow_frames( focus => sub ($view) { return $view->_continue_focus($request) }, FOCUS_FRAMES );
749 $self->show_item($index);
750 return undef;
751 }
752  
753 # True when the focus request is done: cancelled, replaced, its widget
754 # gone, or focused.
755 method _continue_focus ($request) {
756 return 1 unless _is_current( $pending_focus, $request );
757 my $widget = $request->{widget} // return 1;
758 my $interaction = $self->ui->interaction;
759 return 0 unless $interaction->can_take_focus($widget);
760 $interaction->set_focused_widget($widget);
761 return 1;
762 }
763  
764 # ---------------------------------------------------------------------
765 # Keys
766 # ---------------------------------------------------------------------
767  
768 # The keys of less scroll (Term::Fabulous::Scrolling's scroll_by_key);
769 # these are the others.
770 my %ACTION_OF_KEY = (
771 Left => sub ($self) { $self->scroll_code( -CODE_STEP ) },
772 Right => sub ($self) { $self->scroll_code(CODE_STEP) },
773 l => sub ($self) { $self->select_next_link },
774 L => sub ($self) { $self->select_previous_link },
775 Enter => sub ($self) { $self->follow_link },
776 n => sub ($self) { $self->next_match },
777 N => sub ($self) { $self->previous_match },
778 Escape => sub ($self) { $self->clear_marks },
779 );
780  
781 # A key with an action is used, whether or not the action could move
782 # anything (at the end of the document, Down still belongs to the
783 # document); Enter without a selected link and Escape without marks
784 # go on to the widgets around. Keys a focused widget inside an item
785 # did not use reach the view too: Escape gives the focus back to the
786 # view, Enter goes on.
787 my %PASSES_WHEN_IDLE = map { $_ => 1 } qw(Enter Escape);
788  
789 method _key ($event) {
790 my $name = $event->main_key_name // return $CONTINUE;
791 my $ui = $self->ui;
792 return if defined $ui && defined scroll_by_key( $ui, $self, $name, keys => 'less' );
793 my $action = $ACTION_OF_KEY{$name} // return $CONTINUE;
794 my $focused = defined $ui ? $ui->interaction->get_focused_widget : undef;
795 if ( defined $focused && refaddr($focused) != refaddr($self) ) {
796 return $CONTINUE if $name eq 'Enter';
797 if ( $name eq 'Escape' ) {
798 $ui->interaction->set_focused_widget($self);
799 return;
800 }
801 }
802 my $acted = $action->($self);
803 return $CONTINUE if !$acted && $PASSES_WHEN_IDLE{$name};
804 return;
805 }
806  
807 # ---------------------------------------------------------------------
808 # Frames: what the view shows is reported, reveals and the focus go on
809 # ---------------------------------------------------------------------
810  
811 method prepare_layout :override () {
812 $self->_adopt_new_items;
813 $self->SUPER::prepare_layout;
814 $self->_watch_report;
815 return;
816 }
817  
818 # Work after the next frames (each_frame), for at most $frames frames;
819 # the report comes after it, so that it tells what that work did.
820 method _follow_frames ( $name, $code, $frames ) {
821 $self->each_frame( $code, name => $name, frames => $frames );
822 $self->_watch_report;
823 return;
824 }
825  
826 # After every frame the view reports what it shows.
827 method _watch_report () {
828 $self->each_frame( sub ($view) { $view->_report; return 0 }, name => 'report' );
829 return;
830 }
831  
832 method view_state () {
833 my $visible = defined $document ? $self->visible_items : undef;
834 my $ui = $self->ui;
835 my $section = defined $visible ? $document->section_at( $visible->{first} ) : undef;
836 return {
837 top => defined $visible ? $visible->{first} : undef,
838 bottom => defined $visible ? $visible->{last} : undef,
839 section => $section,
840 section_title => defined $section ? $document->title_of_section($section) : undef,
841 percent => ( defined $ui ? scrolled_percent( $ui, $self ) : undef ) // 100,
842 link => $self->selected_link,
843 query => $self->query,
844 match => $self->current_match,
845 matches => $self->match_count,
846 };
847 }
848  
849 # A frame is reported when anything of the state differs from the last
850 # report; a link that is a reference counts by its identity.
851 method _report () {
852 my $state = $self->view_state;
853 my $key = join "\x1F", map { my $value = $state->{$_}; !defined $value ? '' : ref $value ? refaddr($value) : $value } sort keys %$state;
854 return if $key eq $reported;
855 $reported = $key;
856 $self->fire_event( Term::Fabulous::Event::ViewChange->new(%$state) );
857 return;
858 }
859  
860 # ---------------------------------------------------------------------
861 # KDL
862 # ---------------------------------------------------------------------
863  
864 method layout_properties :common () {
865 return ( $class->SUPER::layout_properties, indent => 'scalar' );
866 }
867 }
868  
869 1;
870  
871 __END__