lib/LaTeXML/Post/Graphics.pm untested

filter: Statementstmt 0.0% 0 / 156 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 63 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 307 CC 31 SCAR 50.7
CC
31
Cov
0%
transformGraphic
380.0
findGraphicFile
20.0
getTypeProperties
20.0
CRAP 159.5
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 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 NoteProgressDetailed(" [Using graphicspaths: "
93 . join(', ', @$LaTeXML::Post::Graphics::SEARCHPATHS) . "]");
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} }; }
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 $node->setAttribute('imagesrc', $src);
167 $node->setAttribute('imagewidth', $width) if defined $width;
168 $node->setAttribute('imageheight', $height) if defined $height;
169 return; }
170  
171 sub processGraphic {
172 my ($self, $doc, $node) = @_;
173 my $source = $self->findGraphicFile($doc, $node);
174 if (!$source) {
175 Warn('expected', 'source', $node, "No graphic source found; skipping",
176 "source was " . ($node->getAttribute('graphic') || 'none'));
177 $node->setAttribute('imagesrc', $node->getAttribute('graphic'));
178 return; }
179 my $transform = $self->getTransform($node);
180 my ($image, $width, $height) = $self->transformGraphic($doc, $node, $source, $transform);
181 # $image should probably be relative already, except corner applications?
182 # But definitely should be stored in doc relative to the doc itself!
183 $self->setGraphicSrc($node, pathname_relative($image, $doc->getDestinationDirectory),
184 $width, $height) if $image;
185 return; }
186  
187 #======================================================================
188  
189 sub transformGraphic {
190 my ($self, $doc, $node, $source, $transform) = @_;
191 my $sourcedir = $doc->getSourceDirectory;
192 ($sourcedir) = $doc->getSearchPaths unless $sourcedir; # Fishing...
193 my ($reldir, $name, $srctype)
194 = pathname_split(pathname_relative($source, $sourcedir));
195 my %properties = $self->getTypeProperties($source, $transform);
196 return Warn('unexpected', 'graphics_format', undef,
197 "Don't know what to do with graphics file format '$source'") unless %properties;
198 my $type = $properties{destination_type} || $srctype;
199 my $key = (ref $self) . ':' . join('|', "$reldir$name.$srctype.$type",
200 map { join(' ', @$_) } @$transform);
201 NoteProgressDetailed("\n[Processing $source as key=$key]");
202  
203 my $dest = $self->desiredResourcePathname($doc, $node, $source, $type);
204 if (my $prev = $doc->cacheLookup($key)) { # Image was processed on previous run?
205 if ($prev =~ /^(.*?)\|(\d*)\|(\d*)$/) {
206 my ($cached, $width, $height) = ($1, $2, $3);
207 $width = undef unless $width;
208 $height = undef unless $height;
209 # If so, check that it is still there, up to date, etc.
210 if ((!defined $dest) || ($cached eq $dest)) {
211 my $absdest = pathname_absolute($cached, $doc->getDestinationDirectory);
212 if (pathname_timestamp($source) <= pathname_timestamp($absdest)) {
213 NoteProgressDetailed(" [Reuse $cached @ " . ($width || '?') . " x " . ($height || '?') . "]");
214 return ($cached, $width, $height); } } } }
215 # Trivial scaling case: Use original image with (at most) different width & height.
216 my $triv_scaling = $$self{trivial_scaling} && ($type eq $srctype)
217 && image_graphicx_is_trivial($transform);
218 # But first check if we have the capabilities to do complex scaling!
219 if (!$triv_scaling && (defined $properties{raster}) && !$properties{raster}) {
220 Warn("limitation", $source, undef,
221 "Cannot (yet) apply complex transforms to non-raster images",
222 join(',', map { join(' ', @$_) } grep { !($_->[0] =~ /^scale/) } @$transform));
223 $triv_scaling = 1;
224 $transform = image_graphicx_trivialize($transform); }
225 if (!image_can_image()) {
226 if ($type ne $srctype) {
227 Error('imageprocessing', 'imageclass', undef,
228 "No image processing module found to convert types",
229 "Skipping $source=>$type.",
230 "Please install one of: " . join(',', image_classes()));
231 return; }
232 elsif (!$triv_scaling) {
233 Error('imageprocessing', 'imageclass', undef,
234 "No image processing module found for complex transformations",
235 "Simplifying transformation of $source.",
236 "Please install one of: " . join(',', image_classes()));
237 $triv_scaling = 1;
238 $transform = image_graphicx_trivialize($transform); }
239 }
240 my ($image, $width, $height);
241 if ($triv_scaling) {
242 # With a simple scaling transformation we can preserve path & file-names
243 # But only if we can mimic the relative path in the site directory.
244 # Get image source file relative to the document's source file
245 $dest = pathname_relative($source, $doc->getSourceDirectory);
246 # and it's (eventual) absolute path in the destination directory
247 # assuming it had the same relative path from the destination file.
248 my $absdest = pathname_absolute($dest, $doc->getDestinationDirectory);
249 # Now IFF that is a valid relative path WITHIN the site directory, we'll use it.
250 # Otherwise, we'd better fall back to a generated name.
251 if (!pathname_is_contained($absdest, $doc->getSiteDirectory)) {
252 $dest = $self->generateResourcePathname($doc, $node, $source, $type);
253 $absdest = $doc->checkDestination($dest); }
254  
255 NoteProgressDetailed(" [Destination $absdest]");
256 ($width, $height) = image_graphicx_trivial($source, $transform, ddpt => $$self{ddpt});
257 if (!($width && $height)) {
258 if (!image_can_image()) {
259 Warn('imageprocessing', 'imagesize', undef,
260 "No image processing module found for image sizing",
261 "Will omit image size for $source",
262 "Please install one of: " . join(',', image_classes())); }
263 else {
264 Warn('expected', 'image', undef,
265 "Couldn't get usable image size for $source"); } }
266 pathname_copy($source, $absdest)
267 or Warn('I/O', $absdest, undef, "Couldn't copy $source to $absdest", "Response was: $!");
268 NoteProgressDetailed(" [Copied to $dest @ " . ($width || '?') . " x " . ($height || '?') . "]"); }
269 else {
270 # With a complex transformation, we really needs a new name (well, don't we?)
271 $dest = $self->generateResourcePathname($doc, $node, $source, $type) unless $dest;
272 my $absdest = $doc->checkDestination($dest);
273 NoteProgressDetailed(" [Destination $absdest]");
274 ($image, $width, $height) = image_graphicx_complex($source, $transform,
275 ddpt => $$self{ddpt}, background => $$self{background}, %properties);
276 if (!($image && $width && $height)) {
277 Warn('expected', 'image', undef,
278 "Couldn't get usable image for $source");
279 return; }
280 NoteProgressDetailed(" [Writing to $absdest]");
281 image_write($image, $absdest) or return; }
282  
283 $doc->cacheStore($key, "$dest|" . ($width || '') . '|' . ($height || ''));
284 NoteProgressDetailed(" [done with $key]");
285 return ($dest, $width, $height); }
286  
287 #======================================================================
288 1;