File Coverage

blib/lib/Log/Progress/RenderTTY.pm
Criterion Covered Total %
statement 84 105 80.0
branch 18 38 47.3
condition 15 29 51.7
subroutine 15 18 83.3
pod 2 2 100.0
total 134 192 69.7


line stmt bran cond sub pod time code
1             package Log::Progress::RenderTTY;
2             $Log::Progress::RenderTTY::VERSION = '0.12';
3 1     1   1417 use Moo 2;
  1         19  
  1         6  
4 1     1   323 use Carp;
  1         2  
  1         88  
5 1     1   9 use Try::Tiny;
  1         4  
  1         59  
6 1     1   6 use IO::Handle;
  1         3  
  1         60  
7 1     1   7 use Log::Progress::Parser;
  1         2  
  1         38  
8 1     1   634 use Term::Cap;
  1         3348  
  1         51  
9 1     1   14 use Scalar::Util;
  1         3  
  1         1455  
10              
11             # ABSTRACT: Render progress state on a terminal
12              
13              
14             has listen_resize => ( is => 'ro' );
15             has tty_metrics => ( is => 'lazy', clearer => 1 );
16             has termcap => ( is => 'lazy' );
17             has parser => ( is => 'rw' );
18             has out => ( is => 'rw' );
19             has _prev_output => ( is => 'rw' );
20             has _winch_handler => ( is => 'rw' );
21              
22             sub _build_tty_metrics {
23 1     1   14 my $self= shift;
24 1 50       3931 my $stty= `stty -a` or warn "unable to run 'stty -a' to fetch terminal size\n";
25 1         26 my ($speed)= ($stty =~ /speed[ =]+(\d+)/);
26 1         11 my ($cols)= ($stty =~ /columns[ =]+(\d+)/);
27 1         29 my ($rows)= ($stty =~ /rows[ =]+(\d+)/);
28 1 50 33     36 $self->_init_window_change_watch() if $self->listen_resize and $cols;
29 1   50     145 return { speed => $speed || 9600, cols => $cols || 80, rows => $rows || 25 };
      50        
      50        
30             }
31              
32             sub _build_termcap {
33 1     1   16 my $self= shift;
34 1   50     36 my $speed= $self->tty_metrics->{speed} || 9600;
35 1         55 return Tgetent Term::Cap { TERM => '', OSPEED => $speed };
36             }
37              
38             sub _init_window_change_watch {
39 0     0   0 my $self= shift;
40 0 0       0 return if defined $self->_winch_handler;
41             try {
42 0     0   0 my $existing= $SIG{WINCH};
43 0         0 Scalar::Util::weaken($self);
44             my $handler= sub {
45 0 0       0 $self->clear_tty_metrics if defined $self;
46 0 0       0 goto $existing if defined $existing;
47 0         0 };
48 0         0 $self->_winch_handler([ $handler, $existing ]);
49 0         0 $SIG{WINCH}= $handler;
50             }
51             catch {
52 0     0   0 warn "Can't install SIGWINCH handler\n";
53 0         0 };
54             }
55              
56              
57             sub format {
58 4     4 1 12 my ($self, $state, $dims)= @_;
59            
60             # Build the new string of progress ascii art, but without terminal escapes
61 4         13 my $str= '';
62 4         18 $dims->{message_margin}= $dims->{cols} * .5;
63 4 100       12 if ($state->{step}) {
64 3         5 $dims->{title_width}= 10;
65 3         5 for (values %{ $state->{step} }) {
  3         9  
66             $dims->{title_width}= length($_->{title})
67 11 50 50     36 if length($_->{title} || '') > $dims->{title_width};
68             }
69 3         5 for (sort { $a->{idx} <=> $b->{idx} } values %{ $state->{step} }) {
  17         46  
  3         23  
70 11         35 $str .= $self->_format_step_progress_line($_, $dims);
71             }
72 3         8 $str .= "\n";
73             }
74 4         18 $str .= $self->_format_main_progress_line($state, $dims);
75 4         15 return $str;
76             }
77              
78              
79             sub render {
80 1     1 1 11 my $self= shift;
81 1         2 my ($cols, $rows)= @{ $self->tty_metrics }{'cols','rows'};
  1         17  
82 1         55 my $output= $self->format($self->parser->parse, {
83             cols => $cols,
84             rows => $rows
85             });
86            
87             # Now the fun part. Diff vs. previous output to figure out which lines (if any)
88             # have changed, then move the cursor to those lines and repaint.
89             # To make things extra interesting, the old output might have scrolled off the
90             # screen, and if the new output also scrolls off the screen then we want to
91             # let it happen naturally so that the scroll-back buffer is consistent.
92 1 50       11 my @prev= defined $self->_prev_output? (split /\n/, $self->_prev_output, -1) : ();
93 1         22 my @next= split /\n/, $output, -1;
94             # we leave last line blank, so all calculations are rows-1
95 1 50       27 my $first_vis_line= @prev > ($rows-1)? @prev - ($rows-1) : 0;
96 1 50       5 my $starting_row= @prev > ($rows-1)? 0 : ($rows-1) - @prev;
97 1         105 my $up= $self->termcap->Tputs('up');
98 1         9991 my $down= $self->termcap->Tputs('do');
99 1         89 my $clear_eol= $self->termcap->Tputs('ce');
100 1         52 my $str= '';
101 1         15 my $cursor_row= $rows-1;
102             my $cursor_seek= sub {
103 1     1   3 my $dest_row= shift;
104 1 50       21 if ($cursor_row > $dest_row) {
    50          
105 0         0 $str .= $up x ($cursor_row - $dest_row);
106             } elsif ($dest_row > $cursor_row) {
107 0         0 $str .= $down x ($dest_row - $cursor_row);
108             }
109 1         5 $cursor_row= $dest_row;
110 1         25 };
111 1         4 my $i;
112 1         18 for ($i= $first_vis_line; $i < @prev; $i++) {
113 0 0       0 if ($prev[$i] ne $next[$i]) {
114             # Seek to row
115 0         0 $cursor_seek->($i - $first_vis_line + $starting_row);
116             # clear line and replace
117 0         0 $str .= $clear_eol . $next[$i] . "\n";
118 0         0 $cursor_row++;
119             }
120             }
121 1         10 $cursor_seek->($rows-1);
122             # Now, print any new rows in @next, letting them scroll the screen as needed
123 1         5 while ($i < @next) {
124 8         28 $str .= $next[$i++] . "\n";
125             }
126 1         16 $self->_prev_output($output);
127            
128 1   50     95 ($self->out || \*STDOUT)->print($str);
129             }
130              
131             sub _format_main_progress_line {
132 4     4   10 my ($self, $state, $dims)= @_;
133            
134 4         9 my $message= $state->{message};
135 4 100       11 $message= '' unless defined $message;
136             $message= sprintf("(%d/%d) %s", $state->{current}, $state->{total}, $message)
137 4 100 66     21 if defined $state->{total} and defined $state->{current};
138            
139 4         7 my $max_chars= $dims->{cols} - 8;
140             return sprintf "[%-*s] %3d%%\n %.*s",
141             $max_chars, '=' x int( ($state->{progress}||0) * $max_chars + .000001 ),
142             int( ($state->{progress}||0) * 100 + .0000001 ),
143 4   50     36 $dims->{cols}, $message;
      50        
144             }
145              
146             sub _format_step_progress_line {
147 11     11   36 my ($self, $state, $dims)= @_;
148            
149 11         33 my $message= $state->{message};
150 11 50       21 $message= '' unless defined $message;
151             $message= sprintf("(%d/%d) %s", $state->{current}, $state->{total}, $message)
152 11 100 66     68 if defined $state->{total} and defined $state->{current};
153            
154 11         25 my $max_chars= $dims->{cols} - $dims->{message_margin} - $dims->{title_width} - 11;
155             return sprintf " %-*.*s [%-*s] %3d%% %.*s\n",
156             $dims->{title_width}, $dims->{title_width}, $_->{title},
157             $max_chars, '=' x int( ($state->{progress}||0) * $max_chars + .000001 ),
158             int( ($state->{progress}||0) * 100 + .000001 ),
159 11   50     105 $dims->{message_margin}, $message;
      50        
160             }
161              
162             sub DESTROY {
163 1     1   3878 my $self= shift;
164 1 50       337 if ($self->_winch_handler) {
165 0 0         if ($SIG{WINCH} eq $self->_winch_handler->[0]) {
166 0           $SIG{WINCH}= $self->_winch_handler->[1];
167             } else {
168 0           warn "Can't uninstall SIGWINCH handler\n";
169             }
170 0           $self->_winch_handler(undef);
171             }
172             }
173              
174             1;
175              
176             __END__