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

filter: Statementstmt 0.0% 0 / 180 Branchbran 0.0% 0 / 80 Conditioncond 0.0% 0 / 31 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 331 CC 2 SCAR 8.7
CC
2
Cov
0%
_load_imager
6.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.4
1 package Term::Fabulous::Widget::Image;
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 Term::Fabulous::Widget::Display;
11  
12 our $VERSION = '0.05';
13  
14 class Term::Fabulous::Widget::Image
15 :isa(Term::Fabulous::Widget::Display)
16 :strict(params)
17 {
18 use Feature::Compat::Try;
19 use List::Util (); # max and min are methods elsewhere in the family
20 use MIME::Base64 qw(decode_base64);
21 use POSIX qw(ceil);
22 use Term::Fabulous::Check qw(describe one_of);
23 use Term::Fabulous::Render::Attr qw(cell_color_attr);
24 use Term::Fabulous::Unicode qw(string_columns);
25  
26 use constant UPPER_HALF => "\x{2580}";
27 use constant LOWER_HALF => "\x{2584}";
28  
29 # What the widget shows instead of the image when Imager is missing,
30 # and the columns it wraps at unless the layout gives it a width.
31 use constant NOTICE => 'Image needs the Perl module Imager, which is not installed.';
32 use constant NOTICE_WIDTH => 28;
33  
34 # Imager is optional: without it the widget shows the notice. Any
35 # other error than a missing Imager.pm is a broken installation.
36 sub _load_imager () { ## no critic (Subroutines::RequireFinalReturn) PPI does not parse try/catch
37 try {
38 require Imager;
39 }
40 catch ($error) {
41 die $error unless $error =~ /\ACan't locate Imager\.pm /;
42 return 0;
43 }
44 return 1;
45 }
46 use constant HAS_IMAGER => _load_imager();
47  
48 my @FITS = qw(contain stretch none);
49 my @SOURCES = qw(file data base64 data_url);
50  
51 field $fit :param = 'none';
52  
53 # Where the image came from: one of @SOURCES and the value given for
54 # it, undef without an image.
55 field $source_kind;
56 field $source;
57  
58 # The decoded image as 8-bit RGBA; undef without an image or Imager.
59 field $picture;
60  
61 ADJUST :params ( :$file = undef, :$data = undef, :$base64 = undef, :$data_url = undef ) {
62 $fit = one_of( $self, fit => $fit, @FITS );
63 my %given = ( file => $file, data => $data, base64 => $base64, data_url => $data_url );
64 my @kinds = grep { defined $given{$_} } @SOURCES;
65 die ref($self) . ": give at most one of file, data, base64 and data_url, got @kinds" if @kinds > 1;
66 $self->_load( $kinds[0], $given{ $kinds[0] } ) if @kinds;
67 }
68  
69 method theme_family :common () {
70 return 'image';
71 }
72  
73 method themed_params :common () {
74 return ( $class->SUPER::themed_params, notice_color => [ 'notice', 'normal', 'cell_color' ] );
75 }
76  
77 # ---------------------------------------------------------------------
78 # Sources
79 # ---------------------------------------------------------------------
80  
81 # Replaces the image with the one of a source, or removes it for undef.
82 # A source that cannot be read dies and leaves the old image.
83 method _load ( $kind, $value ) {
84 die ref($self) . ": $kind must be a string, got " . describe($value) if ref $value;
85 my $decoded = defined $value && HAS_IMAGER ? _rgba_image( $self->_decoded( $kind, $value ) ) : undef;
86 ( $source_kind, $source, $picture ) = defined $value ? ( $kind, $value, $decoded ) : ( undef, undef, undef );
87 $self->mark_changed;
88 return $value;
89 }
90  
91 method _decoded ( $kind, $value ) {
92 my $image = $kind eq 'file' ? Imager->new( file => $value ) : Imager->new( data => $self->_bytes_of( $kind, $value ) );
93 return $image if defined $image;
94 my $origin = $kind eq 'file' ? "the file '$value'" : "the $kind given";
95 die ref($self) . ": cannot read an image from $origin: " . Imager->errstr;
96 }
97  
98 method _bytes_of ( $kind, $value ) {
99 return $self->_base64_bytes( base64 => $value ) if $kind eq 'base64';
100 return $self->_data_url_bytes($value) if $kind eq 'data_url';
101  
102 my $bytes = $value;
103 die ref($self) . ": data must be a byte string, got characters above 0xFF" unless utf8::downgrade( $bytes, 1 );
104 return $bytes;
105 }
106  
107 # Base64 in either alphabet (RFC 4648 base64 or base64url), padded or
108 # not; whitespace is ignored.
109 method _base64_bytes ( $name, $text ) {
110 my $digits = $text =~ s/\s+//gr =~ tr{-_}{+/}r;
111 my $length = length( $digits =~ s/=+\z//r );
112 die ref($self) . ": $name must be base64 or base64url text" unless $digits =~ m{\A[A-Za-z0-9+/]*={0,2}\z} && $length % 4 != 1;
113 return decode_base64($digits);
114 }
115  
116 # data:[<media type>][;base64],<data>; the media type is not needed,
117 # Imager recognizes the format by its content.
118 method _data_url_bytes ($url) {
119 my ( $parameters, $payload ) = $url =~ /\Adata:([^,]*),(.*)\z/s or die ref($self) . ": data_url must be a data URL ('data:image/png;base64,...')";
120 return $self->_base64_bytes( data_url => $payload ) if $parameters =~ /;base64\z/i;
121 return $payload =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ger;
122 }
123  
124 # The image as 8-bit RGBA, whatever its type and channels.
125 sub _rgba_image ($image) {
126 my $rgba = $image->to_rgb8;
127 $rgba = $rgba->convert( preset => 'rgb' ) if $rgba->getchannels < 3;
128 $rgba = $rgba->convert( preset => 'addalpha' ) if $rgba->getchannels == 3;
129 return $rgba;
130 }
131  
132 # ---------------------------------------------------------------------
133 # Accessors
134 # ---------------------------------------------------------------------
135  
136 method _source_of ($kind) {
137 return defined $source_kind && $source_kind eq $kind ? $source : undef;
138 }
139  
140 method file (@new) { return @new ? $self->_load( file => $new[0] ) : $self->_source_of('file') }
141 method data (@new) { return @new ? $self->_load( data => $new[0] ) : $self->_source_of('data') }
142 method base64 (@new) { return @new ? $self->_load( base64 => $new[0] ) : $self->_source_of('base64') }
143 method data_url (@new) { return @new ? $self->_load( data_url => $new[0] ) : $self->_source_of('data_url') }
144  
145 method fit (@new) {
146 return $fit unless @new;
147 $fit = one_of( $self, fit => $new[0], @FITS );
148 $self->mark_changed;
149 return $fit;
150 }
151  
152 method notice_color (@new) { return @new ? $self->set_look( notice_color => $new[0] ) : $self->look_value('notice_color') }
153  
154 # The decoded picture as 8-bit RGBA, undef without one, for subclasses.
155 method _picture () { return $picture }
156  
157 method image_width () { return defined $picture ? $picture->getwidth : undef }
158 method image_height () { return defined $picture ? $picture->getheight : undef }
159  
160 method layout_properties :common () {
161 return ( $class->SUPER::layout_properties, map { $_ => 'scalar' } qw(file base64 data_url fit) );
162 }
163  
164 # ---------------------------------------------------------------------
165 # Painting
166 # ---------------------------------------------------------------------
167  
168 # What the widget shows instead of the image, undef when it can show it.
169 method _notice () {
170 return HAS_IMAGER ? undef : NOTICE;
171 }
172  
173 method natural_size () {
174 my $notice = $self->_notice;
175 return $self->_notice_size($notice) if defined $notice;
176 return ( 0, 0 ) unless defined $picture;
177 return ( $picture->getwidth, ceil( $picture->getheight / 2 ) );
178 }
179  
180 # Translucent pixels are mixed with the background below the widget.
181 method paint_key :override () {
182 return ( $self->SUPER::paint_key, join ',', @{ $self->background_below( translucent => 1 ) // [] } );
183 }
184  
185 method paint () {
186 my $notice = $self->_notice;
187 return $self->_paint_notice($notice) if defined $notice;
188 return unless defined $picture;
189  
190 my ( $width, $height, $x0, $y0 ) = $self->_placement( $self->columns, 2 * $self->rows );
191 my $shown = $self->_scaled( $width, $height );
192 my $background = $self->background_below( translucent => 1 );
193 my $first = List::Util::max( 0, $x0 );
194 my $count = List::Util::min( $self->columns, $x0 + $width ) - $first;
195 foreach my $row ( 0 .. $self->rows - 1 ) {
196 my ( $tops, $bottoms ) = map { _pixel_attrs( $shown, $_, $first - $x0, $count, $background ) } 2 * $row - $y0, 2 * $row + 1 - $y0;
197 $self->_paint_cell( $first + $_, $row, $tops->[$_], $bottoms->[$_] ) foreach 0 .. $count - 1;
198 }
199 return;
200 }
201  
202 # The size the image is drawn in, in pixels, and the pixel its top left
203 # corner lands on, in an area of the given pixels. It is centered, so
204 # with fit 'none' an image larger than the area is cut on every side.
205 method _placement ( $area_width, $area_height ) {
206 my ( $width, $height ) = ( $picture->getwidth, $picture->getheight );
207 if ( $fit eq 'stretch' ) {
208 ( $width, $height ) = ( $area_width, $area_height );
209 }
210 elsif ( $fit eq 'contain' ) {
211 my $factor = List::Util::min( $area_width / $width, $area_height / $height );
212 ( $width, $height ) = map { List::Util::max( 1, int( $_ * $factor + 0.5 ) ) } $width, $height;
213 }
214 return ( $width, $height, int( ( $area_width - $width ) / 2 ), int( ( $area_height - $height ) / 2 ) );
215 }
216  
217 # Enlarging repeats pixels, which keeps pixel art crisp; shrinking
218 # mixes them.
219 method _scaled ( $width, $height ) {
220 my ( $original_width, $original_height ) = ( $picture->getwidth, $picture->getheight );
221 return $picture if $width == $original_width && $height == $original_height;
222 my $enlarging = $width >= $original_width && $height >= $original_height;
223 return $picture->scale( xpixels => $width, ypixels => $height, type => 'nonprop', qtype => $enlarging ? 'preview' : 'mixing' );
224 }
225  
226 # The attributes of $count pixels of image row $y from column $x; none
227 # for a row outside the image.
228 sub _pixel_attrs ( $image, $y, $x, $count, $background ) {
229 return [] if $y < 0 || $y >= $image->getheight || $count < 1;
230 my @samples = $image->getsamples( y => $y, x => $x, width => $count, type => '8bit' );
231 return [ map { _pixel_attr( @samples[ 4 * $_ .. 4 * $_ + 3 ], $background ) } 0 .. $count - 1 ];
232 }
233  
234 # No color where the pixel is transparent, its own where it is opaque
235 # or nothing is below to mix with, else the mix with the background.
236 sub _pixel_attr ( $red, $green, $blue, $alpha, $background ) {
237 return undef if $alpha == 0;
238 my @rgb = ( $red, $green, $blue );
239 @rgb = map { int( ( $rgb[$_] * $alpha + $background->[$_] * ( 255 - $alpha ) ) / 255 + 0.5 ) } 0 .. 2 if $alpha < 255 && defined $background;
240 return cell_color_attr( color => ( $rgb[0] << 16 ) | ( $rgb[1] << 8 ) | $rgb[2] );
241 }
242  
243 # A cell shows its upper pixel as the color of an upper half block and
244 # the lower one as the background, or a lower half block alone.
245 method _paint_cell ( $x, $y, $top, $bottom ) {
246 return $self->put_attrs( $x, $y, UPPER_HALF, $top, $bottom ) if defined $top;
247 return $self->put_attrs( $x, $y, LOWER_HALF, $bottom, undef ) if defined $bottom;
248 return;
249 }
250  
251 # ---------------------------------------------------------------------
252 # The notice shown instead of the image
253 # ---------------------------------------------------------------------
254  
255 method _notice_size ($notice) {
256 my @lines = _wrapped( $notice, NOTICE_WIDTH );
257 return ( List::Util::max( map { string_columns($_) } @lines ), scalar @lines );
258 }
259  
260 method _paint_notice ($notice) {
261 my @lines = _wrapped( $notice, $self->columns );
262 my $fg = $self->color_attr( $self->notice_color );
263 $self->paint_text( 0, $_, $lines[$_], $fg, undef ) foreach 0 .. List::Util::min( $#lines, $self->rows - 1 );
264 return;
265 }
266  
267 # The words of a text in lines of at most $width columns; a longer
268 # word is a line of its own.
269 sub _wrapped ( $text, $width ) {
270 my @lines;
271 foreach my $word ( split ' ', $text ) {
272 if ( @lines && string_columns("$lines[-1] $word") <= $width ) {
273 $lines[-1] .= " $word";
274 next;
275 }
276 push @lines, $word;
277 }
278 return @lines;
279 }
280 }
281  
282 1;
283  
284 __END__