blib/lib/Term/Fabulous.pm

filter: Statementstmt 88.2% 15 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.3% 21 / 23 CC 1 SCAR 0.5
CC
1
Cov
88%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Term/Fabulous/Widget/Element.pm ↑ Summary blib/lib/Term/Fabulous/Static.pm »
1 package Term::Fabulous;
2  
3 1 ▶use v5.32;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 our $VERSION = '0.02';
9  
10 1 ▶use Object::Pad 0.825;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 ▶use Clay::UI;
Subroutine BEGIN: called CC=1 SCAR=2.6
13 use Term::Fabulous::Render;
14 use Term::Fabulous::Terminal::Termbox;
15  
16 class Term::Fabulous
17 :isa(Clay::UI)
18 :does(Term::Fabulous::Render)
19 :strict(params)
20 {
21 use Clay::UI::Revision qw(current_revision);
22 use Clay::XS qw(CLAY_RENDER_COMMAND_TYPE_TEXT);
23 use Feature::Compat::Try;
24 use IO::Async::Handle;
25 use IO::Async::OS;
26 use IO::Async::Loop;
27 use IO::Async::Signal;
28 use IO::Async::Timer::Countdown;
29 use IO::Async::Timer::Periodic;
30 use List::Util qw(any);
31 use Scalar::Util qw(blessed looks_like_number refaddr weaken);
32 use Time::HiRes ();
33 use Term::Fabulous::Termbox qw(
34 TB_EVENT_KEY TB_EVENT_MOUSE TB_EVENT_RESIZE
35 TB_KEY_MOUSE_LEFT TB_KEY_MOUSE_MIDDLE TB_KEY_MOUSE_RIGHT TB_KEY_MOUSE_RELEASE TB_KEY_MOUSE_WHEEL_UP TB_KEY_MOUSE_WHEEL_DOWN
36 TF_KEY_MOUSE_MOVE TF_KEY_MOUSE_WHEEL_LEFT TF_KEY_MOUSE_WHEEL_RIGHT
37 TB_KEY_CTRL_C TB_KEY_TAB TB_KEY_BACK_TAB TB_MOD_MOTION
38 );
39 use Term::Fabulous::Event::KeyPress;
40 use Term::Fabulous::Event::Mouse;
41 use Term::Fabulous::Event::MouseMove;
42 use Term::Fabulous::Event::Resize;
43 use Term::Fabulous::Event::Start;
44 use Term::Fabulous::Color;
45 use Term::Fabulous::Render::Geometry qw(cell_rect);
46 use Term::Fabulous::Unicode qw(cluster_columns grapheme_clusters);
47  
48 my %IS_BUTTON = map { $_ => 1 } TB_KEY_MOUSE_LEFT, TB_KEY_MOUSE_MIDDLE, TB_KEY_MOUSE_RIGHT;
49  
50 use constant WATCHED_SIGNALS => qw(TERM INT HUP);
51 use constant WHEEL_NOTCH_ROWS => 3;
52 use constant WHEEL_NOTCH_COLUMNS => 3;
53  
54 # IO::Async wakes the loop when a terminal handle is readable; Perl's
55 # select on Windows watches sockets only, so the terminal is polled there.
56 use constant INPUT_HANDLES_ARE_WATCHABLE => $^O ne 'MSWin32';
57  
58 # step draws until no frame is due; a tree that changes again in every
59 # frame would never settle.
60 use constant MAX_FRAME_BATCHES_PER_STEP => 100;
61  
62 field $inline :param :reader = undef; # the rows of the inline region, or undef for the full screen
63 field $mouse :param :reader = undef;
64 field $kitty_keyboard :param :reader = 1;
65 field $stop_on_ctrl_c :param :reader = 1;
66 field $terminal :param :reader //= Term::Fabulous::Terminal::Termbox->new;
67 field $clock :param = sub { Time::HiRes::time() };
68 field $loop :reader;
69 field $termbox_draw_interval :reader = 1 / 30;
70 field $termbox_resize_debounce_interval :reader = 1 / 10;
71 field $termbox_input_poll_interval :reader = 1 / 60;
72  
73 field $_running = 0; # whether run's loop is active
74 field @_notifiers;
75 field $_resize_timer;
76 field $_draw_timer;
77 field %_signals_before; # the caller's %SIG entries for the signals run watches
78 field $_pending_resize;
79 field $_pointer; # the pointer state as last reported
80 field @_pointer_queue; # pointer states no frame has shown to Clay yet
81 field $_wheel_rows = 0; # wheel scrolling since the last frame
82 field $_wheel_columns = 0;
83 field $_frame_requested = 1; # invalidate() or input since the last frame
84 field $_frame_due_at; # the earliest time a widget asked for a frame at, on the clock
85 field $_drawn_revision = -1; # the Clay::UI revision the last frame showed
86 field $_shown_down = 0; # the button state the last frame showed Clay
87 field $_frame_seconds = 0; # how long the last frame took to draw
88 field $_frame_ended_at = 0; # when it was drawn, on the clock
89 field $_hovered_text; # the RichText whose link is under the pointer, weakened
90  
91 sub BUILDARGS ( $class, %params ) {
92 die "Term::Fabulous: measure_text cannot be replaced; text is always measured in terminal columns" if exists $params{measure_text};
93 return %params;
94 }
95  
96 ADJUST {
97 die "Term::Fabulous: root must consume Clay::UI::Role::Events::Emitter to receive input events, got " . ref( $self->root )
98 unless $self->root->DOES('Clay::UI::Role::Events::Emitter');
99 }
100  
101 ADJUST {
102 die "Term::Fabulous: inline must be a whole number of rows of at least 1, got '$inline'"
103 if defined $inline && $inline !~ /\A[1-9][0-9]*\z/;
104 die "Term::Fabulous: inline mode has no mouse support; leave out mouse or pass mouse => 0"
105 if defined $inline && $mouse;
106 $mouse //= defined $inline ? 0 : 1;
107 die "Term::Fabulous: terminal must consume Term::Fabulous::Role::Terminal, got " . ( ref $terminal || "'$terminal'" )
108 unless blessed $terminal && $terminal->DOES('Term::Fabulous::Role::Terminal');
109 die "Term::Fabulous: clock must be a code reference, got " . ( defined $clock ? "'$clock'" : 'undef' )
110 unless ref $clock eq 'CODE';
111 die "Term::Fabulous: stop_on_ctrl_c must be a boolean, got a " . ref($stop_on_ctrl_c) . " reference" if ref $stop_on_ctrl_c;
112 $stop_on_ctrl_c = $stop_on_ctrl_c ? 1 : 0;
113 }
114  
115 method cell_target () {
116 return $terminal->cell_target;
117 }
118  
119 method kitty_keyboard_active () {
120 return $terminal->kitty_keyboard_active;
121 }
122  
123 # The screen behind the widgets: the theme's background token, which
124 # every frame paints first. A token with alpha 0 leaves the terminal's
125 # own background (Term::Fabulous::Render).
126 method screen_background () {
127 my $color = Term::Fabulous::Color->new( color => $self->theme->token('background') );
128 return $color->alpha > 0 ? $color : undef;
129 }
130  
131 method pointer_state () {
132 return undef unless defined $_pointer;
133 return {%$_pointer};
134 }
135  
136 method invalidate () {
137 $_frame_requested = 1;
138 return $self;
139 }
140  
141 method now () {
142 return $clock->();
143 }
144  
145 # A frame is due at the earliest of the times asked for; the request is
146 # forgotten when a frame is drawn, so an animation asks again from it.
147 method request_frame_at ($time) {
148 die "Term::Fabulous: request_frame_at needs a time in seconds, got " . ( defined $time ? "'$time'" : 'undef' )
149 unless defined $time && !ref $time && looks_like_number($time);
150 $_frame_due_at = $time if !defined $_frame_due_at || $time < $_frame_due_at;
151 return $self;
152 }
153  
154 method find_by_id ($id) {
155 my $root = $self->root;
156 die "Term::Fabulous: the root widget " . ref($root) . " cannot search by id (no find_by_id method)" unless $root->can('find_by_id');
157 return $root->find_by_id($id);
158 }
159  
160 method run () {
161 die "Term::Fabulous: run is active already; it cannot be called again until it returns" if $_running;
162  
163 my $opened = $self->_open_terminal;
164 try {
165 $loop = IO::Async::Loop->new;
166 $self->_attach_notifiers;
167 $_running = 1;
168 $loop->later( sub { $self->_start($opened) } );
169 $loop->run;
170  
171 # The frame that stays on the screen shows the final state; frames
172 # start after Start, with the frame timer.
173 $self->_draw_frame if defined $inline && $_draw_timer->is_running;
174 }
175 catch ($error) {
176  
177 # Perl reports an uncaught exception before unwinding into
178 # finally; restore the terminal first so the message stays visible.
179 $self->_end_run;
180 die $error;
181 }
182 finally {
183 $self->_end_run; # also runs when an event handler calls exit()
184 }
185 return;
186 }
187  
188 method step (%options) {
189 my @unknown = grep { $_ ne 'paced' } sort keys %options;
190 die "Term::Fabulous: step does not accept @unknown (known options: paced)" if @unknown;
191 die "Term::Fabulous: step cannot be called while run is active; run reads the input and draws by itself" if $_running;
192  
193 $self->_fire_start if $self->_open_terminal;
194 $self->_read_input;
195 $self->_apply_resize;
196  
197 my $frames = 0;
198 foreach my $batch ( 1 .. MAX_FRAME_BATCHES_PER_STEP ) {
199 return $frames unless $self->_frame_is_due( $options{paced} );
200 $frames += $self->_draw_pending;
201 }
202 die "Term::Fabulous: step drew " . MAX_FRAME_BATCHES_PER_STEP . " rounds of frames and another frame is still due; a widget changes in every frame\n";
203 }
204  
205 # Returns 1 when it opened the terminal, 0 when it was open already.
206 method _open_terminal () {
207 return 0 if $terminal->is_open;
208 $terminal->open( inline => $inline, mouse => $mouse, kitty_keyboard => $kitty_keyboard );
209 $self->invalidate_canvases; # a fresh screen holds no canvas cells
210 my ( $width, $height ) = $terminal->size;
211 $self->width($width);
212 $self->height($height);
213 return 1;
214 }
215  
216 method _end_run () {
217 $_running = 0;
218 $self->_detach_notifiers;
219 $terminal->close;
220 return;
221 }
222  
223 method _stop_run () {
224 $loop->stop if $_running;
225 return;
226 }
227  
228 # Signals and timers; the terminal input is watched from _start on.
229 method _attach_notifiers () {
230 my $stop = sub { $loop->stop };
231  
232 $_resize_timer = IO::Async::Timer::Countdown->new(
233 delay => $termbox_resize_debounce_interval,
234 on_expire => sub { $self->_apply_resize },
235 );
236 $_draw_timer = IO::Async::Timer::Periodic->new(
237 interval => $termbox_draw_interval,
238 on_tick => sub { $self->_draw_frame },
239 );
240  
241 die "Term::Fabulous: the signal handlers of an earlier run were not restored" if %_signals_before;
242 my @signals = IO::Async::OS->HAVE_SIGNALS ? WATCHED_SIGNALS : (); # IO::Async watches no signals on Windows
243 %_signals_before = map { $_ => $SIG{$_} } @signals;
244 $self->_add_notifiers(
245 ( map { IO::Async::Signal->new( name => $_, on_receipt => $stop ) } @signals ),
246 $_resize_timer,
247 $_draw_timer,
248 );
249 return;
250 }
251  
252 # A notifier the loop refused is not remembered, so that _detach_notifiers
253 # does not fail on it and hide the error.
254 method _add_notifiers (@notifiers) {
255 foreach my $notifier (@notifiers) {
256 $loop->add($notifier);
257 push @_notifiers, $notifier;
258 }
259 return;
260 }
261  
262 # Start fires from inside the running loop, so its listeners can use
263 # $ui->loop (add notifiers, stop it); frames are drawn and input is
264 # read only after it. A terminal step opened has had its Start.
265 method _start ($opened) {
266 $self->_fire_start if $opened;
267 $_draw_timer->start;
268 $self->_watch_terminal_input;
269 $self->_read_input; # keys the terminal read ahead while the terminal queries waited for their answers
270 return;
271 }
272  
273 method _fire_start () {
274 $self->root->fire_event( Term::Fabulous::Event::Start->new( width => $self->width, height => $self->height ) );
275 return;
276 }
277  
278 # A terminal whose handles cannot be watched (none, or on Windows) is
279 # asked for its events at a steady rate instead.
280 method _watch_terminal_input () {
281 my @handles = INPUT_HANDLES_ARE_WATCHABLE ? $terminal->read_handles : ();
282 return $self->_poll_terminal_input unless @handles;
283  
284 my @input_watchers = map {
285 IO::Async::Handle->new( read_handle => $_, on_read_ready => sub { $self->_read_input } )
286 } @handles;
287 $self->_add_notifiers(@input_watchers);
288  
289 # IO::Async switches watched handles to non-blocking mode. A handle
290 # may share that flag with the terminal's own descriptor (termbox
291 # gives up on a partial write() of a frame), so switch them back.
292 # Readiness notification does not depend on the flag, and nothing
293 # here reads from these handles.
294 foreach my $watcher (@input_watchers) {
295 defined $watcher->read_handle->blocking(1)
296 or die "Term::Fabulous: cannot restore blocking mode on a terminal descriptor: $!\n";
297 }
298 return;
299 }
300  
301 method _poll_terminal_input () {
302 my $poll_timer = IO::Async::Timer::Periodic->new(
303 interval => $termbox_input_poll_interval,
304 on_tick => sub { $self->_read_input },
305 );
306 $self->_add_notifiers($poll_timer);
307 $poll_timer->start;
308 return;
309 }
310  
311 method _detach_notifiers () {
312 foreach my $notifier (@_notifiers) {
313 my $owner = $notifier->loop;
314 $owner->remove($notifier) if defined $owner;
315 }
316 $self->_restore_signal_handlers;
317 @_notifiers = ();
318 $_resize_timer = undef;
319 $_draw_timer = undef;
320 $_pending_resize = undef;
321 $_wheel_rows = 0;
322 $_wheel_columns = 0;
323 @_pointer_queue = ();
324 $_frame_requested = 1; # the next run starts with a frame
325 return;
326 }
327  
328 # IO::Async resets a signal it stops watching to the default action;
329 # the caller's handler comes back, unless another watcher (one the
330 # program added to the loop) keeps IO::Async's handler in place.
331 method _restore_signal_handlers () {
332 foreach my $name ( keys %_signals_before ) {
333 $SIG{$name} = $_signals_before{$name} unless defined $SIG{$name};
334 }
335 %_signals_before = ();
336 return;
337 }
338  
339 # One tick of the frame timer.
340 method _draw_frame () {
341 return if $_resize_timer->is_running;
342 $self->_draw_pending if $self->_frame_is_due(1);
343 return;
344 }
345  
346 # A frame is due when something asked for one (invalidate, a key, a
347 # click, a resize), when wheel input or a button press or release waits
348 # to be shown to Clay, or when a widget changed since the last frame
349 # (the Clay::UI revision). Paced, pointer motion alone gets at most
350 # every other slice of time: when frames are slow, moving the mouse
351 # must not keep the loop busy with nothing but redrawing.
352 method _frame_is_due ($paced) {
353 return 1 if $_frame_requested || $_wheel_rows || $_wheel_columns;
354 return 1 if current_revision() != $_drawn_revision;
355 return 1 if defined $_frame_due_at && $clock->() >= $_frame_due_at;
356 return 0 unless @_pointer_queue;
357 return 1 if !$paced || any { $_->{down} != $_shown_down } @_pointer_queue;
358 return $clock->() - $_frame_ended_at >= $_frame_seconds ? 1 : 0;
359 }
360  
361 # Clay takes one button state per frame, so every queued pointer state
362 # gets a frame of its own; the wheel movement goes with the first. A
363 # frame shows the revision its layout pass started at (changes the
364 # frame's own events and preparations made included); a change after
365 # it (an after_draw callback, say) leaves the next frame due. Returns
366 # the number of frames drawn.
367 method _draw_pending () {
368 my @pointers = splice @_pointer_queue;
369 push @pointers, $_pointer unless @pointers;
370 my ( $columns, $rows ) = ( $_wheel_columns, $_wheel_rows );
371 ( $_wheel_columns, $_wheel_rows ) = ( 0, 0 );
372 $_frame_requested = 0;
373 $_frame_due_at = undef;
374  
375 my $started = $clock->();
376 foreach my $pointer (@pointers) {
377 $_pointer = $pointer;
378 $_shown_down = defined $pointer ? $pointer->{down} : 0;
379 $self->draw( scroll_cells => [ $columns, $rows ] );
380 $_drawn_revision = $self->laid_out_revision;
381 ( $columns, $rows ) = ( 0, 0 );
382 }
383 $_frame_ended_at = $clock->();
384 $_frame_seconds = $_frame_ended_at - $started;
385 return scalar @pointers;
386 }
387  
388 method _read_input () {
389 while ( defined( my $event = $terminal->next_event ) ) {
390 $self->_dispatch_event($event);
391 }
392 die "Term::Fabulous: the terminal was closed (end of input)\n" if $terminal->input_ended;
393 return;
394 }
395  
396 method _dispatch_event ($event) {
397 my $type = $event->type;
398 return $self->_on_key($event) if $type == TB_EVENT_KEY;
399 return $self->_on_mouse($event) if $type == TB_EVENT_MOUSE;
400 return $self->_on_resize($event) if $type == TB_EVENT_RESIZE;
401 die "Term::Fabulous: unknown terminal event type '$type'";
402 }
403  
404 method _on_key ($event) {
405 $_frame_requested = 1; # listeners may change anything
406 my $target = $self->interaction->get_focused_widget // $self->root;
407 $target->fire_event( Term::Fabulous::Event::KeyPress->of($event) );
408  
409 my ( $key, $is_special_key ) = ( $event->key, $event->ch == 0 );
410 $self->_stop_run if $is_special_key && $stop_on_ctrl_c && $key == TB_KEY_CTRL_C;
411 return if $target->can('captures_tab') && $target->captures_tab;
412 $self->interaction->focus_next if $is_special_key && $key == TB_KEY_TAB;
413 $self->interaction->focus_previous if $is_special_key && $key == TB_KEY_BACK_TAB;
414 return;
415 }
416  
417 # The pointer motion a MouseMove reports makes no frame due by itself
418 # (see _frame_is_due); listeners that change a widget make one due.
419 method _on_mouse ($event) {
420 my ( $x, $y, $key ) = ( $event->x, $event->y, $event->key );
421 my $newest = @_pointer_queue ? $_pointer_queue[-1] : $_pointer;
422 my $down
423 = $key == TB_KEY_MOUSE_LEFT ? 1
424 : _releases_left_button($event) ? 0
425 : ( defined $newest ? $newest->{down} : 0 );
426 $_pointer = { x => $x, y => $y, down => $down };
427 $self->_queue_pointer($_pointer);
428  
429 my $frame = $self->last_frame;
430 my @topmost = $frame->topmost_at( $x, $y );
431 my $target = $self->_emitter_among( $frame, @topmost ) // $self->root;
432 my ( $text, $offset ) = $self->_text_at( $frame, $topmost[0], $x );
433 if ( $key == TF_KEY_MOUSE_MOVE ) {
434 $self->_hover_link_at( $text, $offset );
435 $target->fire_event( Term::Fabulous::Event::MouseMove->of($event) );
436 return;
437 }
438  
439 $_frame_requested = 1; # listeners may change anything
440 my $is_press = $IS_BUTTON{$key} && !( $event->mod & TB_MOD_MOTION );
441 $self->interaction->set_focused_widget( $self->_focusable_at_or_above( $text // $target ) )
442 if $is_press && $key == TB_KEY_MOUSE_LEFT && !_keeps_focus_on_click($target);
443 my $mouse_event = Term::Fabulous::Event::Mouse->of($event);
444 $target->fire_event($mouse_event);
445  
446 # A Mouse listener may have taken the text out of the tree.
447 $text->click_at( $offset, $key, $x, $y ) if $is_press && defined $text && $self->_owns($text);
448  
449 # A widget that scrolled itself has used the wheel notch.
450 return if $mouse_event->wheel_used;
451 $_wheel_rows += WHEEL_NOTCH_ROWS if $key == TB_KEY_MOUSE_WHEEL_UP;
452 $_wheel_rows -= WHEEL_NOTCH_ROWS if $key == TB_KEY_MOUSE_WHEEL_DOWN;
453 $_wheel_columns += WHEEL_NOTCH_COLUMNS if $key == TF_KEY_MOUSE_WHEEL_LEFT;
454 $_wheel_columns -= WHEEL_NOTCH_COLUMNS if $key == TF_KEY_MOUSE_WHEEL_RIGHT;
455 return;
456 }
457  
458 # Motion replaces the newest queued state; a press or a release adds
459 # one, so a press and a release within the same frame are both shown
460 # to Clay.
461 method _queue_pointer ($pointer) {
462 if ( @_pointer_queue && $_pointer_queue[-1]{down} == $pointer->{down} ) {
463 $_pointer_queue[-1] = $pointer;
464 return;
465 }
466 push @_pointer_queue, $pointer;
467 return;
468 }
469  
470 # A release whose button the terminal did not name counts as the left.
471 sub _releases_left_button ($event) {
472 return 0 unless $event->key == TB_KEY_MOUSE_RELEASE;
473 my $button = $event->ch;
474 return $button == 0 || $button == TB_KEY_MOUSE_LEFT ? 1 : 0;
475 }
476  
477 # Whether a press on a widget leaves the focus where it is: the widget
478 # or one of its ancestors says so (a menu bar does).
479 sub _keeps_focus_on_click ($widget) {
480 for ( my $node = $widget; defined $node; $node = $node->parent ) {
481 return 1 if $node->can('keeps_focus_on_click') && $node->keeps_focus_on_click;
482 }
483 return 0;
484 }
485  
486 # The widget a click focuses: the nearest one that can take focus now.
487 method _focusable_at_or_above ($widget) {
488 my $interaction = $self->interaction;
489 for ( my $node = $widget; defined $node; $node = $node->parent ) {
490 return $node if $interaction->can_take_focus($node);
491 }
492 return undef;
493 }
494  
495 method _on_resize ($event) {
496 my ( $width, $height ) = ( $event->w, $event->h );
497 return if $width < 1 || $height < 1;
498  
499 # termbox has already rebuilt its buffers for the new size, keeping
500 # only the cells inside both sizes: no canvas is intact any more,
501 # even when the size ends up where it was.
502 $self->invalidate_canvases;
503 $_pending_resize = [ $width, $height ];
504 return unless defined $_resize_timer; # step applies it at once
505 $_resize_timer->is_running ? $_resize_timer->reset : $_resize_timer->start;
506 return;
507 }
508  
509 method _apply_resize () {
510 return unless defined $_pending_resize;
511 my ( $width, $height ) = $terminal->apply_resize(@$_pending_resize);
512 $_pending_resize = undef;
513  
514 $self->root->fire_event( Term::Fabulous::Event::Resize->new( width => $width, height => $height, is_post_event => 0 ) );
515 $self->width($width);
516 $self->height($height);
517 $self->root->fire_event( Term::Fabulous::Event::Resize->new( width => $width, height => $height, is_post_event => 1 ) );
518 $_frame_requested = 1;
519 $self->_read_input; # keys the terminal read ahead while the terminal queries waited for their answers
520 return;
521 }
522  
523 # Topmost event emitter among the commands of the frame painted at a
524 # cell (topmost first) that is still part of this UI: a listener may
525 # have removed it since. Text widgets fire events but are skipped: a
526 # click on text goes to the widget behind it (and fires TextClick on
527 # the text, see _text_at).
528 method _emitter_among ( $frame, @topmost ) {
529 foreach my $index (@topmost) {
530 my $command = $frame->command($index);
531 next if $command->{commandType} == CLAY_RENDER_COMMAND_TYPE_TEXT;
532 my $widget = $self->widget_for( $command->{userData} );
533 return $widget if defined $widget && $widget->DOES('Clay::UI::Role::Events::Emitter') && $self->_owns($widget);
534 }
535 return undef;
536 }
537  
538 # The Text whose line is the topmost command painted at a cell, and the
539 # offset in its text of the character in the cell's column; an empty
540 # list when the cell holds none.
541 method _text_at ( $frame, $index, $x ) {
542 return () unless defined $index;
543 my $command = $frame->command($index);
544 return () unless $command->{commandType} == CLAY_RENDER_COMMAND_TYPE_TEXT;
545 my $widget = $self->widget_for( $command->{userData} );
546 return () unless defined $widget && $widget->isa('Term::Fabulous::Widget::Text') && $self->_owns($widget);
547 my $offset = _offset_at_column( $command, $x ) // return ();
548 return ( $widget, $offset );
549 }
550  
551 # Where the character drawn at the column lies in the widget's text:
552 # the line's clusters advance as Term::Fabulous::Render::Text draws
553 # them, from the left edge of the line's box.
554 sub _offset_at_column ( $command, $x ) {
555 my ($column) = cell_rect( $command->{boundingBox} );
556 return undef if $x < $column;
557 my $data = $command->{renderData};
558 my $offset = $data->{stringOffset} // 0;
559 foreach my $cluster ( grapheme_clusters( $data->{stringContents} ) ) {
560 $column += cluster_columns($cluster);
561 return $offset if $x < $column;
562 $offset += length $cluster;
563 }
564 return undef;
565 }
566  
567 # The link under the pointer looks hovered; the one it was over before
568 # no longer does.
569 method _hover_link_at ( $text, $offset ) {
570 my $link = defined $text && $text->can('hover_link') ? $text->link_at($offset) : undef;
571 my $hovered = defined $link ? $text : undef;
572 $_hovered_text->hover_link(undef) if defined $_hovered_text && !( defined $hovered && refaddr($hovered) == refaddr($_hovered_text) );
573 $_hovered_text = $hovered;
574 return unless defined $hovered;
575 weaken $_hovered_text;
576 $hovered->hover_link($link);
577 return;
578 }
579  
580 method _owns ($widget) {
581 my $ui = $widget->can('ui') ? $widget->ui : undef;
582 return defined $ui && refaddr($ui) == refaddr($self) ? 1 : 0;
583 }
584 }
585  
586 1;
587  
588 __END__
« blib/lib/Term/Fabulous/Widget/Element.pm ↑ Summary blib/lib/Term/Fabulous/Static.pm »