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