lib/LaTeXML/Post/Graphics.pm untested

filter: Statementstmt 0.0% 0 / 158 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 63 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 325 CC 39 SCAR 58.2
CC
39
Cov
0%
transformGraphic
702.0
findGraphicFile
20.0
getTypeProperties
20.0
CRAP 337.1
1 # /=====================================================================\ #
2 # | LaTeXML::Post::Graphics | #
3 # | Graphics postprocessing for LaTeXML | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12 #======================================================================
13 # Adapted from graphics-support.perl of LaTeX2HTML (which I had rewritten)
14 #======================================================================
15 package LaTeXML::Post::Graphics;
16 use strict;
17 use warnings;
18 use LaTeXML::Util::Pathname;
19 use LaTeXML::Util::Image;
20 use LaTeXML::Post;
21 use base qw(LaTeXML::Post::Processor);
22  
23 #======================================================================
24 # Options:
25 # dpi : dots per inch for target medium.
26 # ignore_options : list of graphicx options to be ignored.
27 # warn_options : list of graphicx options to cause warning if used.
28 # trivial_scaling : If true, web images that only need scaling will be used as-is
29 # assuming the user agent scale the image.
30 # background : background color when filling or transparency.
31 # type_properties : hash of types=>hash.
32 # The hash for each type can have the following
33 # destination_type : the type to convert the file to if different.
34 # transparent : if true, the background color will be made transparent.
35 # quality : the `quality' used for the image.
36 # ncolors : the image will be quantized to ncolors.
37 # prescale : If true, and there are leading (or only) scaling commands,
38 # compute the new image size and re-read the image into that size
39 # This is useful for getting the best antialiasing for postscript, eg.
40 # unit= (pixel|point) : What unit the image size is given in.
41 # autocrop : if the image should be cropped (trimmed) when loaded.
42 # desirability : a number indicating how good of a mapping this entry is.
43 # This helps choose between two sources that can map to the
44 # same destination type.
45 # An entry whose source & destination types are the same
46 # has desirability=10.
47  
48 sub new {
49 my ($class, %options) = @_;
50 my $self = $class->SUPER::new(%options);
51 $$self{dppt} = (($options{dpi} || 90) / 72.0); # Dots per point.
52 $$self{ignore_options} = $options{ignore_options} || [];
53 $$self{trivial_scaling} = $options{trivial_scaling} || 1;
54 $$self{graphics_types} = $options{graphics_types}
55 || [qw(svg png gif jpg jpeg
56 eps ps postscript ai pdf)];
57 $$self{type_properties} = $options{type_properties}
58 || {
59 ai => { destination_type => 'png',
60 transparent => 1,
61 prescale => 1, ncolors => '400%', quality => 90, unit => 'point' },
62 pdf => { destination_type => 'png',
63 transparent => 1,
64 prescale => 1, ncolors => '400%', quality => 90, unit => 'point' },
65 ps => { destination_type => 'png', transparent => 1,
66 prescale => 1, ncolors => '400%', quality => 90, unit => 'point' },
67 eps => { destination_type => 'png', transparent => 1,
68 prescale => 1, ncolors => '400%', quality => 90, unit => 'point' },
69 jpg => { destination_type => 'jpg',
70 ncolors => '400%', unit => 'pixel' },
71 jpeg => { destination_type => 'jpeg',
72 ncolors => '400%', unit => 'pixel' },
73 gif => { destination_type => 'gif', transparent => 1,
74 ncolors => '400%', unit => 'pixel' },
75 png => { destination_type => 'png', transparent => 1,
76 ncolors => '400%', unit => 'pixel' },
77 svg => { destination_type => 'svg',
78 raster => 0, desirability => 11 }, # use these, as is
79 };
80 $$self{background} = $options{background} || "#FFFFFF";
81 return $self; }
82  
83 # Return a list of XML nodes which have graphics that need processing.
84 sub toProcess {
85 my ($self, $doc) = @_;
86 return $doc->findnodes('//ltx:graphics[not(@imagesrc)]'); }
87  
88 sub process {
89 my ($self, $doc, @nodes) = @_;
90 local $LaTeXML::Post::Graphics::SEARCHPATHS
91 = [map { pathname_canonical($_) } $self->findGraphicsPaths($doc), $doc->getSearchPaths];
92 Debug(" [Using graphicspaths: "
93 . join(', ', @$LaTeXML::Post::Graphics::SEARCHPATHS) . "]") if $LaTeXML::DEBUG{images};
94 foreach my $node (@nodes) {
95 $self->processGraphic($doc, $node); }
96 $doc->closeCache; # If opened.
97 return $doc; }
98  
99 #======================================================================
100 # Potentially customizable operations.
101 # find graphics file
102 # Need to deal with source directory, as well as graphicspath.
103  
104 # Extract any graphicspath PI's from the document and return a reference
105 # to a list of search paths.
106 sub findGraphicsPaths {
107 my ($self, $doc) = @_;
108 my @paths = ();
109 foreach my $pi ($doc->findnodes('.//processing-instruction("latexml")')) {
110 if ($pi->textContent =~ /^\s*graphicspath\s*=\s*([\"\'])(.*?)\1\s*$/) {
111 push(@paths, $2); } }
112 return @paths; }
113  
114 sub getGraphicsSourceTypes {
115 my ($self) = @_;
116 return @{ $$self{graphics_types} }, map { uc($_); } @{ $$self{graphics_types} }; }
117  
118 # Return the pathname to an appropriate image.
119 sub findGraphicFile {
120 my ($self, $doc, $node) = @_;
121 if (my $source = $node->getAttribute('graphic')) {
122 # Find all acceptable image files, in order of search paths
123 my ($dir, $name, $reqtype) = pathname_split($source);
124 # Ignore the requested type? Or should it increase desirability?
125 my $file = pathname_concat($dir, $name);
126 my @paths = pathname_findall($file, paths => $LaTeXML::Post::Graphics::SEARCHPATHS,
127 # accept empty type, incase bad type name, but actual file's content is known type.
128 types => ['', $self->getGraphicsSourceTypes]);
129 my ($best, $bestpath) = (-1, undef);
130 # Now, find the first image that is either the correct type,
131 # or has the most desirable type mapping
132 foreach my $path (@paths) {
133 my $type = pathname_type($path);
134 my $props = $$self{type_properties}{$type};
135 my $desirability = $$props{desirability} || ($type eq ($$props{destination_type} || 'notype') ? 10 : 0);
136 if ($desirability > $best) {
137 $best = $desirability;
138 $bestpath = $path; } }
139 return $bestpath; }
140 else {
141 return; } }
142  
143 #======================================================================
144 # Return the Transform to be used for this node
145 # Default is based on parsing the graphicx options
146 sub getTransform {
147 my ($self, $node) = @_;
148 my $options = $node->getAttribute('options');
149 return ($options ? image_graphicx_parse($options) : []); }
150  
151 # Get a hash of the image processing properties to be applied to this image.
152 sub getTypeProperties {
153 my ($self, $source, $options) = @_;
154 my ($dir, $name, $ext) = pathname_split($source);
155 my $props = $$self{type_properties}{ lc($ext) };
156 if (!$props) {
157 # If we don't have a known file type, try a bit harder (maybe less efficient)
158 if (my $type = image_type($source)) {
159 $props = $$self{type_properties}{ lc($type) }; } }
160 return ($props ? %$props : ()); }
161  
162 # Set the attributes of the graphics node to record the image file name,
163 # width and height.
164 sub setGraphicSrc {
165 my ($self, $node, $src, $width, $height) = @_;
166 # If we are on windows, the $src path will be used for a URI context from the 'imagesrc' attribute,
167 # so we can already switch it to the canonical slashified form
168 $node->setAttribute('imagesrc', pathname_to_url($src));
169 $node->setAttribute('imagewidth', $width) if defined $width;
170 $node->setAttribute('imageheight', $height) if defined $height;
171 return; }
172  
173 sub processGraphic {
174 my ($self, $doc, $node) = @_;
175 my $source = $self->findGraphicFile($doc, $node);
176 if (!$source) {
177 Warn('expected', 'source', $node, "No graphic source found; skipping",
178 "source was " . ($node->getAttribute('graphic') || 'none'));
179 $node->setAttribute('imagesrc', $node->getAttribute('graphic'));
180 return; }
181 my $transform = $self->getTransform($node);
182 my ($image, $width, $height) = $self->transformGraphic($doc, $node, $source, $transform);
183 # $image should probably be relative already, except corner applications?
184 # But definitely should be stored in doc relative to the doc itself!
185 $self->setGraphicSrc($node, pathname_relative($image, $doc->getDestinationDirectory),
186 $width, $height) if $image;
187 return; }
188  
189 #======================================================================
190  
191 sub transformGraphic {
192 my ($self, $doc, $node, $source, $transform) = @_;
193 my $sourcedir = $doc->getSourceDirectory;
194 ($sourcedir) = $doc->getSearchPaths unless $sourcedir; # Fishing...
195 my ($reldir, $name, $srctype)
196 = pathname_split(pathname_relative($source, $sourcedir));
197 my %properties = $self->getTypeProperties($source, $transform);
198 return Warn('unexpected', 'graphics_format', undef,
199 "Don't know what to do with graphics file format '$source'") unless %properties;
200 my $type = $properties{destination_type} || $srctype;
201 my $key = (ref $self) . ':' . join('|', "$reldir$name.$srctype.$type",
202 map { join(' ', @$_) } @$transform);
203 Debug("Processing $source as key=$key") if $LaTeXML::DEBUG{images};
204  
205 my $dest = $self->desiredResourcePathname($doc, $node, $source, $type);
206 if (my $prev = $doc->cacheLookup($key)) { # Image was processed on previous run?
207 if ($prev =~ /^(.*?)\|(\d*)\|(\d*)$/) {
208 my ($cached, $width, $height) = ($1, $2, $3);
209 $width = undef unless $width;
210 $height = undef unless $height;
211 # If so, check that it is still there, up to date, etc.
212 if ((!defined $dest) || ($cached eq $dest)) {
213 my $absdest = pathname_absolute($cached, $doc->getDestinationDirectory);
214 if (pathname_timestamp($source) <= pathname_timestamp($absdest)) {
215 Debug(" [Reuse $cached @ " . ($width || '?') . " x " . ($height || '?') . "]")
216 if $LaTeXML::DEBUG{images};
217 return ($cached, $width, $height); } } } }
218 # Trivial scaling case: Use original image with (at most) different width & height.
219 my $triv_scaling = $$self{trivial_scaling} && ($type eq $srctype)
220 && image_graphicx_is_trivial($transform);
221 # But first check if we have the capabilities to do complex scaling!
222 if (!$triv_scaling && (defined $properties{raster}) && !$properties{raster}) {
223 Warn("limitation", $source, undef,
224 "Cannot (yet) apply complex transforms to non-raster images",
225 join(',', map { join(' ', @$_) } grep { !($_->[0] =~ /^scale/) } @$transform));
226 $triv_scaling = 1;
227 $transform = image_graphicx_trivialize($transform); }
228 if (!image_can_image()) {
229 if ($type ne $srctype) {
230 Error('imageprocessing', 'imageclass', undef,
231 "No image processing module found to convert types",
232 "Skipping $source=>$type.",
233 "Please install one of: " . join(',', image_classes()));
234 return; }
235 elsif (!$triv_scaling) {
236 Error('imageprocessing', 'imageclass', undef,
237 "No image processing module found for complex transformations",
238 "Simplifying transformation of $source.",
239 "Please install one of: " . join(',', image_classes()));
240 $triv_scaling = 1;
241 $transform = image_graphicx_trivialize($transform); }
242 }
243 my ($image, $width, $height);
244 if ($triv_scaling) {
245 # With a simple scaling transformation we can preserve path & file-names
246 # But only if we can mimic the relative path in the site directory.
247 # Get image source file relative to the document's source file
248 $dest = pathname_relative($source, $doc->getSourceDirectory);
249 # and it's (eventual) absolute path in the destination directory
250 # assuming it had the same relative path from the destination file.
251 my $absdest = pathname_absolute($dest, $doc->getDestinationDirectory);
252 # Now IFF that is a valid relative path WITHIN the site directory, we'll use it.
253 # Otherwise, we'd better fall back to a generated name.
254 if (!pathname_is_contained($absdest, $doc->getSiteDirectory)) {
255 $dest = $self->generateResourcePathname($doc, $node, $source, $type);
256 $absdest = $doc->checkDestination($dest); }
257  
258 Debug(" [Destination $absdest]") if $LaTeXML::DEBUG{images};
259 ($width, $height) = image_graphicx_trivial($source, $transform, ddpt => $$self{ddpt});
260 if (!($width && $height)) {
261 if (!image_can_image()) {
262 Warn('imageprocessing', 'imagesize', undef,
263 "No image processing module found for image sizing",
264 "Will omit image size for $source",
265 "Please install one of: " . join(',', image_classes())); }
266 else {
267 Warn('expected', 'image', undef,
268 "Couldn't get usable image size for $source"); } }
269 pathname_copy($source, $absdest)
270 or Warn('I/O', $absdest, undef, "Couldn't copy $source to $absdest", "Response was: $!");
271 Debug(" [Copied to $dest @ " . ($width || '?') . " x " . ($height || '?') . "]")
272 if $LaTeXML::DEBUG{images}; }
273 else {
274 # With a complex transformation, we really needs a new name (well, don't we?)
275 $dest = $self->generateResourcePathname($doc, $node, $source, $type) unless $dest;
276 my $absdest = $doc->checkDestination($dest);
277 Debug(" [Destination $absdest]") if $LaTeXML::DEBUG{images};
278 ($image, $width, $height) = image_graphicx_complex($source, $transform,
279 ddpt => $$self{ddpt}, background => $$self{background}, %properties);
280 if (!($image && $width && $height)) {
281 Warn('expected', 'image', undef,
282 "Couldn't get usable image for $source");
283 return; }
284 Debug(" [Writing to $absdest]") if $LaTeXML::DEBUG{images};
285 image_write($image, $absdest) or return; }
286  
287 $doc->cacheStore($key, "$dest|" . ($width || '') . '|' . ($height || ''));
288 Debug(" [done with $key]") if $LaTeXML::DEBUG{images};
289 return ($dest, $width, $height); }
290  
291 #======================================================================
292 1;