lib/LaTeXML/Util/Pack.pm untested

filter: Statementstmt 0.0% 0 / 241 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 74 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 437 CC 53 SCAR 60.3
CC
53
Cov
0%
unpack_source
870.0
get_math
90.0
pack_collection
56.0
CRAP 414.6
1 # /=====================================================================\ #
2 # | LaTeXML::Util::Pack | #
3 # | Packs the requested output (document, fragment, math, archive) | #
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 package LaTeXML::Util::Pack;
13 use strict;
14 use warnings;
15  
16 use LaTeXML::Util::Pathname;
17 use File::Spec::Functions qw(catfile);
18 use File::Path qw(rmtree);
19 use IO::String;
20 use Archive::Zip qw(:CONSTANTS :ERROR_CODES);
21  
22 use base qw(Exporter);
23 our @EXPORT = qw(&unpack_source &pack_collection);
24 our $archive_file_exclusion_regex = qr/(?:^\.)|(?:\.(?:zip|gz|epub|tex|bib|mobi|cache)$)|(?:~$)/;
25  
26 sub unpack_source {
27 my ($source, $sandbox_directory) = @_;
28 my $main_source;
29 my $zip_handle = Archive::Zip->new();
30 if (pathname_is_literaldata($source)) {
31 # If literal, just use the data
32 $source =~ s/^literal\://;
33 my $content_handle = IO::String->new($source);
34 unless ($zip_handle->readFromFileHandle($content_handle) == AZ_OK) {
35 print STDERR "Fatal:I/O:Archive Can't read in literal archive:\n $source\n"; } }
36 else { # Otherwise, read in from file
37 unless ($zip_handle->read($source) == AZ_OK) {
38 print STDERR "Fatal:I/O:Archive Can't read in source archive: $source\n"; } }
39 # Extract the Perl zip datastructure to the temporary directory
40 foreach my $member ($zip_handle->memberNames()) {
41 $zip_handle->extractMember($member, catfile($sandbox_directory, $member)); }
42 # Set $source to point to the main TeX file in that directory
43 my @TeX_file_members = map { $_->fileName() } $zip_handle->membersMatching('\.tex$');
44 if (!@TeX_file_members) { # No .tex file? Try files with no, or unusually long, extensions
45 @TeX_file_members = grep { !/\./ || /\.[^.]{4,}$/ } map { $_->fileName() } $zip_handle->members();
46 }
47  
48 # Heuristically determine the input (borrowed from arXiv::FileGuess)
49 my %Main_TeX_likelihood;
50 my %Main_TeX_level;
51 my @vetoed = ();
52 foreach my $tex_file (@TeX_file_members) {
53 # Read in the content
54 $tex_file = catfile($sandbox_directory, $tex_file);
55 # Open file and read first few bytes to do magic sequence identification
56 # note that file will be auto-closed when $FILE_TO_GUESS goes out of scope
57 open(my $FILE_TO_GUESS, '<', $tex_file) ||
58 (print STDERR "failed to open '$tex_file' to guess its format: $!. Continuing.\n");
59 local $/ = "\n";
60 my ($maybe_tex, $maybe_tex_priority, $maybe_tex_priority2);
61 TEX_FILE_TRAVERSAL:
62 while (<$FILE_TO_GUESS>) {
63 if ((/\%auto-ignore/ && $. <= 10) || # Ignore
64 ($. <= 10 && /\\input texinfo/) || # TeXInfo
65 ($. <= 10 && /\%auto-include/)) # Auto-include
66 { $Main_TeX_likelihood{$tex_file} = 0; last TEX_FILE_TRAVERSAL; } # Not primary
67 if ($. <= 12 && /^\r?%\&([^\s\n]+)/) {
68 if ($1 eq 'latex209' || $1 eq 'biglatex' || $1 eq 'latex' || $1 eq 'LaTeX') {
69 $Main_TeX_likelihood{$tex_file} = 3; last TEX_FILE_TRAVERSAL; } # LaTeX
70 else {
71 $Main_TeX_likelihood{$tex_file} = 1; last TEX_FILE_TRAVERSAL; } } # Mac TeX
72 # All subsequent checks have lines with '%' in them chopped.
73 # if we need to look for a % then do it earlier!
74 s/\%[^\r]*//;
75 if (/(?:^|\r)\s*\\document(?:style|class)/) {
76 $Main_TeX_likelihood{$tex_file} = 3; last TEX_FILE_TRAVERSAL; } # LaTeX
77 if (/(?:^|\r)\s*(?:\\font|\\magnification|\\input|\\def|\\special|\\baselineskip|\\begin)/) {
78 $maybe_tex = 1; }
79 if (/\\(?:input|include)(?:\s+|\{)([^ \}]+)/) {
80 $maybe_tex = 1;
81 # the argument of \input can't be the main file
82 # (it could in very elaborate multi-target setups, but we DON'T support those)
83 # so veto it.
84 my $vetoed_file = $1;
85 if ($vetoed_file eq 'amstex') { # TeX Priority
86 $Main_TeX_likelihood{$tex_file} = 2; last TEX_FILE_TRAVERSAL; }
87 if ($vetoed_file !~ /\./) {
88 $vetoed_file .= '.tex';
89 }
90 my $base = $tex_file;
91 $base =~ s/\/[^\/]+$//;
92 $vetoed_file = "$base/$vetoed_file";
93 push @vetoed, $vetoed_file; }
94 if (/(?:^|\r)\s*\\(?:end|bye)(?:\s|$)/) {
95 $maybe_tex_priority = 1; }
96 if (/\\(?:end|bye)(?:\s|$)/) {
97 $maybe_tex_priority2 = 1; }
98 if (/\\input *(?:harv|lanl)mac/ || /\\input\s+phyzzx/) {
99 $Main_TeX_likelihood{$tex_file} = 1; last TEX_FILE_TRAVERSAL; } # Mac TeX
100 if (/beginchar\(/) {
101 $Main_TeX_likelihood{$tex_file} = 0; last TEX_FILE_TRAVERSAL; } # MetaFont
102 if (/(?:^|\r)\@(?:book|article|inbook|unpublished)\{/i) {
103 $Main_TeX_likelihood{$tex_file} = 0; last TEX_FILE_TRAVERSAL; } # BibTeX
104 if (/^begin \d{1,4}\s+[^\s]+\r?$/) {
105 if ($maybe_tex_priority) {
106 $Main_TeX_likelihood{$tex_file} = 2; last TEX_FILE_TRAVERSAL; } # TeX Priority
107 if ($maybe_tex) {
108 $Main_TeX_likelihood{$tex_file} = 1; last TEX_FILE_TRAVERSAL; } # TeX
109 $Main_TeX_likelihood{$tex_file} = 0; last TEX_FILE_TRAVERSAL; } # UUEncoded or PC
110 if (m/paper deliberately replaced by what little/) {
111 $Main_TeX_likelihood{$tex_file} = 0; last TEX_FILE_TRAVERSAL; }
112 }
113 close $FILE_TO_GUESS || warn "couldn't close file: $!";
114 if (!defined $Main_TeX_likelihood{$tex_file}) {
115 if ($maybe_tex_priority) {
116 $Main_TeX_likelihood{$tex_file} = 2; }
117 elsif ($maybe_tex_priority2) {
118 $Main_TeX_likelihood{$tex_file} = 1.5; }
119 elsif ($maybe_tex) {
120 $Main_TeX_likelihood{$tex_file} = 1; }
121 else {
122 $Main_TeX_likelihood{$tex_file} = 0; }
123 }
124 }
125 # Veto files that were e.g. arguments of \input macros
126 for my $filename (@vetoed) {
127 delete $Main_TeX_likelihood{$filename};
128 }
129 # The highest likelihood (>0) file gets to be the main source.
130 my @files_by_likelihood = sort { $Main_TeX_likelihood{$b} <=> $Main_TeX_likelihood{$a} } grep { $Main_TeX_likelihood{$_} > 0 } keys %Main_TeX_likelihood;
131 if (@files_by_likelihood) {
132 # If we have a tie for max score, grab the alphanumerically first file (to ensure deterministic runs)
133 my $max_likelihood = $Main_TeX_likelihood{ $files_by_likelihood[0] };
134 @files_by_likelihood = grep { $Main_TeX_likelihood{$_} == $max_likelihood } @files_by_likelihood;
135 # only keep the high scorers closest to the root of the archive
136 my $min_count = 100;
137 foreach my $file (@files_by_likelihood) {
138 my $count = $file =~ tr/\///;
139 $Main_TeX_level{$file} = $count;
140 $min_count = $count if $min_count > $count; }
141 @files_by_likelihood = grep { $Main_TeX_level{$_} == $min_count } @files_by_likelihood;
142 # last tie-breaker is lexicographical order
143 @files_by_likelihood = sort { $a cmp $b } @files_by_likelihood;
144 # set the main source
145 $main_source = shift @files_by_likelihood; }
146  
147 # If failed, clean up sandbox directory.
148 rmtree($sandbox_directory) unless $main_source;
149 # Return the main source from the unpacked files in the sandbox directory (or undef if failed)
150 return $main_source;
151 }
152  
153 # Options:
154 # whatsout: determine what shape and size we want to pack into
155 # admissible: document (default), fragment, math, archive
156 # siteDirectory: the directory to compress into a ZIP archive
157 # collection: the collection of documents to be packed
158 sub pack_collection {
159 my (%options) = @_;
160 my @packed_docs;
161 my $whatsout = $options{whatsout};
162 my @docs = @{ $options{collection} };
163 # Archive once if requested
164 if ($whatsout =~ /^archive/) {
165 my $archive = get_archive($options{siteDirectory}, $whatsout);
166 # TODO: Error API should be integrated once generalized to Util::
167 #Fatal("I/O", $self, $docs[0], "Writing archive to IO::String handle failed") unless defined $archive;
168 print STDERR "Fatal:I/O:Archive Writing archive to IO::String handle failed" unless defined $archive;
169 return ($archive); }
170 # Otherwise pack each document passed
171 foreach my $doc (@docs) {
172 next unless defined $doc;
173 if ((!$whatsout) || ($whatsout eq 'document')) {
174 push @packed_docs, $doc; } # Document is no-op
175 elsif ($whatsout eq 'fragment') {
176 # If we want an embedable snippet, unwrap to body's "main" div
177 push @packed_docs, get_embeddable($doc); }
178 elsif ($whatsout eq 'math') {
179 # Math output - least common ancestor of all math in the document
180 push @packed_docs, get_math($doc);
181 unlink('LaTeXML.cache'); }
182 else { push @packed_docs, $doc; } }
183 return @packed_docs; }
184  
185 ## Helpers for pack_collection:
186 sub get_archive {
187 my ($directory, $whatsout) = @_;
188 # Zip and send back
189 my $archive = Archive::Zip->new();
190 opendir(my $dirhandle, $directory)
191 # TODO: Switch to Error API
192 # or Fatal('expected', 'directory', undef,
193 # "Expected a directory to archive '$directory':", $@);
194 or (print STDERR 'Fatal:expected:directory Failed to compress directory \'$directory\': $@');
195 my @entries = grep { /^[^.]/ } readdir($dirhandle);
196 closedir $dirhandle;
197 my @files = grep { !/$archive_file_exclusion_regex/ && -f pathname_concat($directory, $_) } @entries;
198 my @subdirs = grep { -d File::Spec->catdir($directory, $_) } @entries;
199 # We want to first add the files instead of simply invoking ->addTree on the top level
200 # without ANY file attributes at all,
201 # since EPUB is VERY picky about the first entry in the archive starting at byte 38 (file 'mimetype')
202 @files = sort @files;
203 my @nomime_files = grep { !/^mimetype$/ } @files;
204 if (scalar(@nomime_files) != scalar(@files)) {
205 @files = ('mimetype', @nomime_files); }
206 foreach my $file (@files) {
207 local $/ = undef;
208 my $FH;
209 my $pathname = pathname_concat($directory, $file);
210 open $FH, "<", $pathname
211 # TODO: Switch to Error API
212 #or Fatal('I/O', $pathname, undef, "File $pathname is not readable.");
213 or (print STDERR "Fatal:I/O:$pathname File $pathname is not readable.");
214 my $file_contents = <$FH>;
215 close($FH);
216 # Only compress the textual files
217 my $compression_level = ($file =~ /css|js|xml|html$/) ?
218 COMPRESSION_DEFLATED
219 : COMPRESSION_STORED;
220 $archive->addString($file_contents, $file,)->desiredCompressionMethod($compression_level); }
221  
222 foreach my $subdir (sort @subdirs) {
223 my $current_dir = File::Spec->catdir($directory, $subdir);
224 $archive->addTree($current_dir, $subdir, sub { !/$archive_file_exclusion_regex/ }, COMPRESSION_STORED); }
225  
226 my $payload;
227 if ($whatsout =~ /^archive(::zip)?$/) {
228 my $content_handle = IO::String->new($payload);
229 undef $payload unless ($archive->writeToFileHandle($content_handle) == AZ_OK); }
230 elsif ($whatsout eq 'archive::zip::perl') {
231 $payload = $archive; }
232 return $payload; }
233  
234 sub get_math {
235 my ($doc) = @_;
236 my $math_xpath = '//*[local-name()="math" or local-name()="Math"]';
237 return unless defined $doc;
238 my @mnodes = $doc->findnodes($math_xpath);
239 my $math_count = scalar(@mnodes);
240 if (!$math_count) { # If no real math nodes, look for math image nodes
241 my $math_img_xpath = '//*[local-name()="img" and @class="ltx_Math"]';
242 @mnodes = $doc->findnodes($math_img_xpath);
243 $math_count = scalar(@mnodes);
244 }
245 if (!$math_count) {
246 return get_embeddable($doc); }
247 my $math = $mnodes[0];
248 if ($math_count > 1) {
249 my $math_found = 0;
250 while ($math_found != $math_count) {
251 $math_found = $math->findnodes('.' . $math_xpath)->size;
252 $math_found++ if ($math->localname =~ /^math$/i);
253 $math = $math->parentNode if ($math_found != $math_count);
254 }
255 $math = $math->parentNode while ($math->nodeName =~ '^t[rd]$'); }
256 if ($math) {
257 my $imagesrc = $math->getAttribute('imagesrc') || $math->getAttribute('src');
258 if ($imagesrc && $imagesrc =~ /[.]svg$/) {
259 # Return the SVG directly
260 $math = LaTeXML::Common::XML::Parser->new()->parseFile($imagesrc);
261 $math = $math && $math->getDocumentElement;
262 }
263 # Copy over document namespace declarations:
264 # NOTE: This copies ALL the namespaces, not just the needed ones!
265 foreach ($doc->getDocumentElement->getNamespaces) {
266 $math->setNamespace($_->getData, $_->getLocalName, 0); } }
267 return $math; }
268  
269 sub get_embeddable {
270 my ($doc) = @_;
271 return unless defined $doc;
272 my ($embeddable) = $doc->findnodes('//*[contains(@class,"ltx_document")]');
273 if ($embeddable) {
274 # Only one child? Then get it, must be a inline-compatible one!
275 while (($embeddable->nodeName eq 'div') && (scalar(@{ $embeddable->childNodes }) == 1) &&
276 ($embeddable->getAttribute('class') =~ /^ltx_(page_(main|content)|document|para|header)$/) &&
277 (!defined $embeddable->getAttribute('style'))) {
278 if (defined $embeddable->firstChild) {
279 $embeddable = $embeddable->firstChild; }
280 else {
281 last; }
282 }
283 # Is the root a <p>? Make it a span then, if it has only math/text/spans - it should be inline
284 # For MathJax-like inline conversion mode
285 # TODO: Make sure we are schema-complete wrt nestable inline elements, and maybe find a smarter way to do this?
286 if (($embeddable->nodeName eq 'p') && ((@{ $embeddable->childNodes }) == (grep { $_->nodeName =~ /math|text|span/ } $embeddable->childNodes))) {
287 $embeddable->setNodeName('span');
288 $embeddable->setAttribute('class', 'text');
289 }
290  
291 # Copy over document namespace declarations:
292 foreach ($doc->getDocumentElement->getNamespaces) {
293 $embeddable->setNamespace($_->getData, $_->getLocalName, 0);
294 }
295 # Also, copy RDFa attributes:
296 foreach my $rdfa_attr (qw(prefix property content resource about typeof rel rev datatype)) {
297 if (my $rdfa_value = $doc->getDocumentElement->getAttribute($rdfa_attr)) {
298 $embeddable->setAttribute($rdfa_attr, $rdfa_value); } }
299 }
300 return $embeddable || $doc; }
301  
302 1;
303  
304 __END__