lib/LaTeXML/Util/Pack.pm untested

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