lib/LaTeXML.pm

filter: Statementstmt 93.9% 31 / 33 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 11 / 11 Podpod n/a totaltotal 95.4% 42 / 44 CC 1 SCAR 0.3
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/LaTeXML/Util/Test.pm ↑ Summary lib/LaTeXML/Package.pm »
1 # /=====================================================================\ #
2 # | LaTeXML | #
3 # | Overall LaTeXML Converter | #
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 # | Deyan Ginev <d.ginev@jacobs-university.de> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12 package LaTeXML;
13 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 4 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 4 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 File::Temp->safe_level(File::Temp::HIGH);
20 4 ▶use File::Path qw(rmtree);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 4 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 4 ▶use LaTeXML::Common::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 4 ▶use LaTeXML::Core;
Subroutine BEGIN: called CC=1 SCAR=2.6
25 use LaTeXML::Util::Pack;
26 use LaTeXML::Util::Pathname;
27 use LaTeXML::Util::WWW;
28 use LaTeXML::Util::ObjectDB;
29 use LaTeXML::Post::Scan;
30 use vars qw($VERSION);
31 # This is the main version of LaTeXML being claimed.
32 use version; our $VERSION = version->declare("0.8.4");
33 use LaTeXML::Version;
34 # Derived, more informative version numbers
35 our $FULLVERSION = "LaTeXML version $LaTeXML::VERSION"
36 . ($LaTeXML::Version::REVISION ? "; revision $LaTeXML::Version::REVISION" : '');
37 # Handy identifier string for any executable.
38 our $IDENTITY = "$FindBin::Script ($LaTeXML::FULLVERSION)";
39  
40 our $LOG_STACK = 0;
41  
42 #**********************************************************************
43 #our @IGNORABLE = qw(timeout profile port preamble postamble port destination log removed_math_formats whatsin whatsout math_formats input_limit input_counter dographics mathimagemag );
44  
45 # Switching to white-listing options that are important for new_latexml:
46 our @COMPARABLE = qw(preload paths verbosity strict comments inputencoding includestyles documentid mathparse);
47 our %DAEMON_DB = ();
48  
49 sub new {
50 my ($class, $config) = @_;
51 $config = LaTeXML::Common::Config->new() unless (defined $config);
52 # The daemon should be setting the identity:
53 my $self = bless { opts => $config->options, ready => 0, log => q{}, runtime => {},
54 latexml => undef }, $class;
55 # Special check if the debug directive is on, just to neutralize the bind_log
56 my $debug_directives = $$self{opts}->{debug};
57 $LaTeXML::DEBUG = 1 if (ref $debug_directives eq 'ARRAY') && (grep { /latexml/i } @$debug_directives);
58 $self->bind_log;
59 my $rv = eval { $config->check; };
60 $$self{log} .= $self->flush_log;
61 return $self; }
62  
63 sub prepare_session {
64 my ($self, $config) = @_;
65 # TODO: The defaults feature was never used, do we really want it??
66 #0. Ensure all default keys are present:
67 # (always, as users can specify partial options that build on the defaults)
68 #foreach (keys %{$$self{defaults}}) {
69 # $config->{$_} = $$self{defaults}->{$_} unless exists $config->{$_};
70 #}
71 # 1. Ensure option "sanity"
72 $self->bind_log;
73 my $rv = eval { $config->check; };
74 $$self{log} .= $self->flush_log;
75  
76 my $opts = $config->options;
77 my $opts_comparable = { map { $_ => $$opts{$_} } @COMPARABLE };
78 my $self_opts_comparable = { map { $_ => $$self{opts}{$_} } @COMPARABLE };
79 #TODO: Some options like paths and includes are additive, we need special treatment there
80 #2.2. Compare old and new $opts hash
81 my $something_to_do;
82 $something_to_do = LaTeXML::Util::ObjectDB::compare($opts_comparable, $self_opts_comparable) ? 0 : 1;
83 #2.3. Set new options in converter:
84 $$self{opts} = $opts;
85  
86 #3. If there is something to do, initialize a session:
87 $self->initialize_session if ($something_to_do || (!$$self{ready}));
88  
89 return;
90 }
91  
92 sub initialize_session {
93 my ($self) = @_;
94 $$self{runtime} = {};
95 $self->bind_log;
96 # Empty the package namespace
97 foreach my $subname (keys %LaTeXML::Package::Pool::) {
98 delete $LaTeXML::Package::Pool::{$subname};
99 }
100  
101 my $latexml;
102 my $init_eval_return = eval {
103 # Prepare LaTeXML object
104 local $SIG{'ALRM'} = sub { die "Fatal:conversion:init Failed to initialize LaTeXML state\n" };
105 alarm($$self{opts}{timeout});
106  
107 $latexml = new_latexml($$self{opts});
108  
109 alarm(0);
110 1;
111 };
112 ## NOTE: This will give double errors, if latexml has already handled it!
113 $$latexml{state}->noteStatus('fatal') if $latexml && $@; # Fatal Error?
114 local $@ = 'Fatal:conversion:unknown Session initialization failed! (Unknown reason)' if ((!$init_eval_return) && (!$@));
115 if ($@) { #Fatal occured!
116 print STDERR "$@\n";
117 print STDERR "\nInitialization complete: " . $latexml->getStatusMessage . ". Aborting.\n" if defined $latexml;
118 # Close and restore STDERR to original condition.
119 $$self{log} .= $self->flush_log;
120 $$self{ready} = 0;
121 return;
122 } else {
123 # Demand errorless initialization
124 my $init_status = $latexml->getStatusMessage;
125 if ($init_status =~ /error/i) {
126 print STDERR "\nInitialization complete: " . $init_status . ". Aborting.\n";
127 $$self{log} .= $self->flush_log;
128 $$self{ready} = 0;
129 return;
130 }
131 }
132  
133 # Save latexml in object:
134 $$self{log} .= $self->flush_log;
135 $$self{latexml} = $latexml;
136 $$self{ready} = 1;
137 return;
138 }
139  
140 sub convert {
141 my ($self, $source) = @_;
142 # 1 Prepare for conversion
143 # 1.1 Initialize session if needed:
144 $$self{runtime} = {};
145 $self->initialize_session unless $$self{ready};
146 if (!$$self{ready}) { # We can't initialize, return error:
147 return { result => undef, log => $$self{log}, status => "Initialization failed.", status_code => 3 };
148 }
149  
150 $self->bind_log;
151 # 1.2 Inform of identity, increase conversion counter
152 my $opts = $$self{opts};
153 my $runtime = $$self{runtime};
154 ($$runtime{status}, $$runtime{status_code}) = (undef, undef);
155 if ($$opts{verbosity} >= 0) {
156 print STDERR "$LaTeXML::IDENTITY\n";
157 print STDERR "invoked as [$0 " . join(' ', @ARGV) . "]\n" if $$opts{verbosity} >= 1;
158 print STDERR "processing started " . localtime() . "\n"; }
159  
160 # 1.3 Prepare for What's IN:
161 # We use a new temporary variable to avoid confusion with daemon caching
162 my ($current_preamble, $current_postamble);
163 # 1.3.1 Math needs to magically trigger math mode if needed
164 if ($$opts{whatsin} eq "math") {
165 $current_preamble = 'literal:\begin{document}\ensuremathfollows';
166 $current_postamble = 'literal:\ensuremathpreceeds\end{document}'; }
167 # 1.3.2 Fragments need to have a default pre- and postamble, if none provided
168 elsif ($$opts{whatsin} eq 'fragment') {
169 $current_preamble = $$opts{preamble} || 'standard_preamble.tex';
170 $current_postamble = $$opts{postamble} || 'standard_postamble.tex'; }
171 # 1.3.3 Archives need to get unpacked in a sandbox (with sufficient bookkeeping)
172 elsif ($$opts{whatsin} =~ /^archive/) {
173 # Sandbox the input
174 $$opts{archive_sourcedirectory} = $$opts{sourcedirectory};
175 my $sandbox_directory = File::Temp->newdir(TMPDIR => 1);
176 $$opts{sourcedirectory} = $sandbox_directory;
177 # Extract the archive in the sandbox
178 $source = unpack_source($source, $sandbox_directory);
179 if (!defined $source) { # Unpacking failed to find a source
180 $$opts{sourcedirectory} = $$opts{archive_sourcedirectory};
181 my $log = $self->flush_log;
182 $log .= "\nFatal:invalid:Archive Can't detect a source TeX file!\nStatus:conversion:3\n";
183 return { result => undef, log => $log, status => "Fatal:invalid:Archive Can't detect a source TeX file!", status_code => 3 }; }
184 # Destination magic: If we expect an archive on output, we need to invent the appropriate destination ourselves when not given.
185 # Since the LaTeXML API never writes the final archive file to disk, we just use a pretend sourcename.zip:
186 if (($$opts{whatsout} =~ /^archive/) && (!$$opts{destination})) {
187 $$opts{placeholder_destination} = 1;
188 $$opts{destination} = pathname_name($source) . ".zip"; } }
189  
190 # 1.4 Prepare for What's OUT (if we need a sandbox)
191 if ($$opts{whatsout} =~ /^archive/) {
192 $$opts{archive_sitedirectory} = $$opts{sitedirectory};
193 $$opts{archive_destination} = $$opts{destination};
194 my $destination_name = $$opts{destination} ? pathname_name($$opts{destination}) : 'document';
195 my $sandbox_directory = File::Temp->newdir(TMPDIR => 1);
196 my $extension = $$opts{format};
197 $extension =~ s/\d+$//;
198 $extension =~ s/^epub|mobi$/xhtml/;
199 my $sandbox_destination = "$destination_name.$extension";
200 $$opts{sitedirectory} = $sandbox_directory;
201  
202 if ($$opts{format} eq 'epub') {
203 $$opts{resource_directory} = File::Spec->catdir($sandbox_directory, 'OPS');
204 $$opts{destination} = pathname_concat(File::Spec->catdir($sandbox_directory, 'OPS'), $sandbox_destination); }
205 else {
206 $$opts{destination} = pathname_concat($sandbox_directory, $sandbox_destination); }
207 }
208  
209 # 1.5 Prepare a daemon frame
210 my $latexml = $$self{latexml};
211 $latexml->withState(sub {
212 my ($state) = @_; # Sandbox state
213 $$state{status} = {};
214 $state->pushDaemonFrame;
215 $state->assignValue('_authlist', $$opts{authlist}, 'global');
216 $state->assignValue('REMOTE_REQUEST', (!$$opts{local}), 'global');
217 });
218  
219 # 2 Beginning Core conversion - digest the source:
220 my ($digested, $dom, $serialized) = (undef, undef, undef);
221 my $convert_eval_return = eval {
222 # Should be this, but is overridden by withState.
223 #local $SIG{'ALRM'} = sub { LaTeXML::Common::Error::Fatal('conversion','timeout',
224 # "Conversion timed out after " . $$opts{timeout} . " seconds!\n"); };
225 alarm($$opts{timeout});
226 my $mode = ($$opts{type} eq 'auto') ? 'TeX' : $$opts{type};
227 $digested = $latexml->digestFile($source, preamble => $current_preamble,
228 postamble => $current_postamble,
229 mode => $mode,
230 noinitialize => 1);
231 # 2.1 Now, convert to DOM and output, if desired.
232 if ($digested) {
233 $latexml->withState(sub {
234 if ($$opts{format} eq 'tex') {
235 $serialized = LaTeXML::Core::Token::UnTeX($digested);
236 } elsif ($$opts{format} eq 'box') {
237 $serialized = ($$opts{verbosity} > 0 ? $digested->stringify : $digested->toString);
238 } else { # Default is XML
239 $dom = $latexml->convertDocument($digested);
240 }
241 }); }
242 alarm(0);
243 1;
244 };
245 # 2.2 Bookkeeping in case fatal errors occurred
246 ### Note: this cause double counting if LaTeXML has already handled it.
247 ### But leaving it might might miss errors that sneak through (can that happen?)
248 #### $$latexml{state}->noteStatus('fatal') if $latexml && $@; # Fatal Error?
249 local $@ = 'Fatal:conversion:unknown TeX to XML conversion failed! (Unknown Reason)' if ((!$convert_eval_return) && (!$@));
250 my $eval_report = $@;
251 $$runtime{status} = $latexml->getStatusMessage;
252 $$runtime{status_code} = $latexml->getStatusCode;
253  
254 # End daemon run, by popping frame:
255 $latexml->withState(sub {
256 my ($state) = @_; # Remove current state frame
257 $$opts{searchpaths} = $state->lookupValue('SEARCHPATHS'); # save the searchpaths for post-processing
258 $state->popDaemonFrame;
259 });
260 if ($LaTeXML::UNSAFE_FATAL) {
261 # If the conversion hit an unsafe fatal, we need to reinitialize
262 $LaTeXML::UNSAFE_FATAL = 0;
263 $$self{ready} = 0;
264 }
265 if ($eval_report || ($$runtime{status_code} == 3)) {
266 # Terminate immediately on Fatal errors
267 $$runtime{status_code} = 3;
268 print STDERR $eval_report . "\n" if $eval_report;
269 print STDERR "\nConversion complete: " . $$runtime{status} . ".\n";
270 print STDERR "Status:conversion:" . ($$runtime{status_code} || '0') . "\n";
271 # If we just processed an archive, clean up sandbox directory.
272 if ($$opts{whatsin} =~ /^archive/) {
273 rmtree($$opts{sourcedirectory});
274 $$opts{sourcedirectory} = $$opts{archive_sourcedirectory}; }
275  
276 # Close and restore STDERR to original condition.
277 my $log = $self->flush_log;
278 $serialized = $dom if ($$opts{format} eq 'dom');
279 $serialized = $dom->toString if ($dom && (!defined $serialized));
280 # Using the Core::Document::serialize_aux, so need an explicit encode into bytes
281 $serialized = Encode::encode('UTF-8', $serialized) if $serialized;
282  
283 return { result => $serialized, log => $log, status => $$runtime{status}, status_code => $$runtime{status_code} }; }
284 else {
285 # Standard report, if we're not in a Fatal case
286 print STDERR "\nConversion complete: " . $$runtime{status} . ".\n"; }
287  
288 # 2.3 Clean up and exit if we only wanted the serialization of the core conversion
289 if ($serialized) {
290 # If serialized has been set, we are done with the job
291 # If we just processed an archive, clean up sandbox directory.
292 if ($$opts{whatsin} =~ /^archive/) {
293 rmtree($$opts{sourcedirectory});
294 $$opts{sourcedirectory} = $$opts{archive_sourcedirectory}; }
295 my $log = $self->flush_log;
296 return { result => $serialized, log => $log, status => $$runtime{status}, status_code => $$runtime{status_code} };
297 }
298  
299 # 3 If desired, post-process
300 my $result = $dom;
301 if ($$opts{post} && $dom) {
302 if (!$dom->documentElement) {
303 # Make a completely empty document have at least one element for post-processing
304 # important for utility features such as packing .zip archives for output
305 $$dom{document}->setDocumentElement($$dom{document}->createElement("document"));
306 }
307 $result = $self->convert_post($dom);
308 }
309 # 4 Clean-up: undo everything we sandboxed
310 if ($$opts{whatsin} =~ /^archive/) {
311 rmtree($$opts{sourcedirectory});
312 $$opts{sourcedirectory} = $$opts{archive_sourcedirectory}; }
313 if ($$opts{whatsout} =~ /^archive/) {
314 rmtree($$opts{sitedirectory});
315 $$opts{sitedirectory} = $$opts{archive_sitedirectory};
316 $$opts{destination} = $$opts{archive_destination};
317 if (delete $$opts{placeholder_destination}) {
318 delete $$opts{destination}; } }
319  
320 # 5 Output -- if not using Post::Writer, which never considers this serialization logic
321 # 5.1 Serialize the XML/HTML result (or just return the Perl object, if requested)
322 # GOAL: $serialized must contain a utf8-encoded string at the return.
323 # NOTES: This is difficult, because we can be serializing different objects, with different serialization logic
324 # 1. Byte strings: LaTeXML's Document::serialize_aux, and XML::LibXML::Document's toString and toStringHTML
325 # which have NOT been encoded into utf-8, so we need an explicit encode before printing/returning
326 # 2. Unreliable: the fragment case, which uses XML::LibXML::Element (and hence Node's) toString method,
327 # is sometimes already encoded as UTF-8. In fact, the documentation claims it is by default:
328 # https://metacpan.org/pod/distribution/XML-LibXML/lib/XML/LibXML/Node.pod#toString
329 # Digging to the bottom of the code, we reach:
330 # https://metacpan.org/source/SHLOMIF/XML-LibXML-2.0200/LibXML.xs#L5212
331 # which *will* set the utf8 flag iff the "HAVE_UTF8" flag was set on the system which compiled libxml
332 # that's pretty terrifying in fact, since we can't rely that libxml returns the same encoding cross-platform for its default behavior!
333 # 3. Reliable: Always explicitly request the document encoding to be used in serializing a Node
334 # by passing a second true flag into toString(1,1) to ensure that the encoding is handled explicitly at the libxml2 level
335 # 4. Other: returning a DOM object programmatically, or a non-XML representation (archives), has no serialization component, result is returned as-is
336 undef $serialized;
337 my $ref_result = ref($result) || '';
338 if ($$opts{format} eq 'dom') { # No serialize needed in DOM output case
339 $serialized = $result; }
340 elsif ($ref_result =~ /^(:?LaTe)?XML/) {
341 if ($$opts{format} =~ /^jats|x(ht)?ml$/) {
342 if ($ref_result =~ /Document$/) {
343 $serialized = $result->toString(1);
344 $serialized = Encode::encode('UTF-8', $serialized) if $serialized;
345 } else { # fragment case
346 $serialized = $result->toString(1, 1);
347 } }
348 elsif ($$opts{format} =~ /^html/) {
349 if (ref($result) =~ /^LaTeXML::(Post::)?Document$/) {
350 # Needs explicit encode call, toStringHTML returns Perl byte strings
351 $serialized = $result->getDocument->toStringHTML;
352 $serialized = Encode::encode('UTF-8', $serialized) if $serialized; }
353 else { # fragment case
354 local $XML::LibXML::setTagCompression = 1;
355 $serialized = $result->toString(1, 1); } } }
356 # Compressed/archive/other case, just pass on
357 else { $serialized = $result; }
358  
359 # 5.2 Finalize logging and return a response containing the document result, log and status
360 print STDERR "Status:conversion:" . ($$runtime{status_code} || '0') . " \n";
361 my $log = $self->flush_log;
362 return { result => $serialized, log => $log, status => $$runtime{status}, 'status_code' => $$runtime{status_code} };
363 }
364  
365 ###########################################
366 #### Converter Management #####
367 ###########################################
368 sub get_converter {
369 my ($self, $config) = @_;
370 # TODO: Make this more flexible via an admin interface later
371 my $key = $config->get('cache_key') || $config->get('profile') || 'custom';
372 my $d = $DAEMON_DB{$key};
373 if (!defined $d) {
374 $d = LaTeXML->new($config->clone);
375 $DAEMON_DB{$key} = $d; }
376 return $d; }
377  
378 ###########################################
379 #### Helper routines #####
380 ###########################################
381 sub convert_post {
382 my ($self, $dom) = @_;
383 my $opts = $$self{opts};
384 my $runtime = $$self{runtime};
385 my ($xslt, $parallel, $math_formats, $format, $verbosity, $defaultresources, $embed) =
386 map { $$opts{$_} } qw(stylesheet parallelmath math_formats format verbosity defaultresources embed);
387 $verbosity = $verbosity || 0;
388  
389 my %PostOPS = (verbosity => $verbosity,
390 validate => $$opts{validate},
391 sourceDirectory => $$opts{sourcedirectory},
392 siteDirectory => $$opts{sitedirectory},
393 resource_directory => $$opts{resource_directory},
394 searchpaths => $$opts{searchpaths},
395 nocache => 1,
396 destination => $$opts{destination},
397 is_html => $$opts{is_html});
398 # Compute destinationDirectory here,
399 # so that we don't depend on post-processing returning a usable Post::Document (Fatal-resilience)
400 if ($PostOPS{destination}) {
401 my ($dir, $name, $ext) = pathname_split($PostOPS{destination});
402 $PostOPS{destinationDirectory} = $dir || '.'; }
403  
404 #Postprocess
405 $parallel = $parallel || 0;
406  
407 my $DOCUMENT = LaTeXML::Post::Document->new($dom, %PostOPS);
408 my @procs = ();
409 #TODO: Add support for the following:
410 my $dbfile = $$opts{dbfile};
411 if (defined $dbfile && !-f $dbfile) {
412 if (my $dbdir = pathname_directory($dbfile)) {
413 pathname_mkdir($dbdir); } }
414 my $DB = LaTeXML::Util::ObjectDB->new(dbfile => $dbfile, %PostOPS);
415 ### Advanced Processors:
416 if ($$opts{split}) {
417 require LaTeXML::Post::Split;
418 push(@procs, LaTeXML::Post::Split->new(split_xpath => $$opts{splitpath}, splitnaming => $$opts{splitnaming},
419 db => $DB, %PostOPS)); }
420 my $scanner = ($$opts{scan} || $DB) && (LaTeXML::Post::Scan->new(
421 db => $DB,
422 labelids => $$opts{splitnaming} && ($$opts{splitnaming} =~ /^label/),
423 %PostOPS));
424 push(@procs, $scanner) if $$opts{scan};
425 if (!($$opts{prescan})) {
426 if ($$opts{index}) {
427 require LaTeXML::Post::MakeIndex;
428 push(@procs, LaTeXML::Post::MakeIndex->new(db => $DB, permuted => $$opts{permutedindex},
429 split => $$opts{splitindex}, scanner => $scanner,
430 %PostOPS)); }
431 require LaTeXML::Post::MakeBibliography;
432 push(@procs, LaTeXML::Post::MakeBibliography->new(db => $DB, bibliographies => $$opts{bibliographies},
433 split => $$opts{splitbibliography}, scanner => $scanner,
434 %PostOPS));
435 if ($$opts{crossref}) {
436 require LaTeXML::Post::CrossRef;
437 push(@procs, LaTeXML::Post::CrossRef->new(
438 db => $DB, urlstyle => $$opts{urlstyle},
439 extension => $$opts{extension},
440 ($$opts{numbersections} ? (number_sections => 1) : ()),
441 ($$opts{navtoc} ? (navigation_toc => $$opts{navtoc}) : ()),
442 %PostOPS)); }
443 if ($$opts{picimages}) {
444 require LaTeXML::Post::PictureImages;
445 push(@procs, LaTeXML::Post::PictureImages->new(%PostOPS));
446 }
447 if ($$opts{dographics}) {
448 # TODO: Rethink full-fledged graphics support
449 require LaTeXML::Post::Graphics;
450 my @g_options = ();
451 if ($$opts{graphicsmaps} && scalar(@{ $$opts{graphicsmaps} })) {
452 my @maps = map { [split(/\./, $_)] } @{ $$opts{graphicsmaps} };
453 push(@g_options, (graphics_types => [map { $$_[0] } @maps],
454 type_properties => { map { ($$_[0] => { destination_type => ($$_[1] || $$_[0]) }) } @maps })); }
455 push(@procs, LaTeXML::Post::Graphics->new(@g_options, %PostOPS));
456 }
457 if ($$opts{svg}) {
458 require LaTeXML::Post::SVG;
459 push(@procs, LaTeXML::Post::SVG->new(%PostOPS)); }
460 if (@$math_formats) {
461 my @mprocs = ();
462 ### # If XMath is not first, it must be at END! Or... ???
463 foreach my $fmt (@$math_formats) {
464 if ($fmt eq 'xmath') {
465 require LaTeXML::Post::XMath;
466 push(@mprocs, LaTeXML::Post::XMath->new(%PostOPS)); }
467 elsif ($fmt eq 'pmml') {
468 require LaTeXML::Post::MathML::Presentation;
469 push(@mprocs, LaTeXML::Post::MathML::Presentation->new(
470 linelength => $$opts{linelength},
471 (defined $$opts{plane1} ? (plane1 => $$opts{plane1}) : (plane1 => 1)),
472 ($$opts{hackplane1} ? (hackplane1 => 1) : ()),
473 %PostOPS)); }
474 elsif ($fmt eq 'cmml') {
475 require LaTeXML::Post::MathML::Content;
476 push(@mprocs, LaTeXML::Post::MathML::Content->new(
477 (defined $$opts{plane1} ? (plane1 => $$opts{plane1}) : (plane1 => 1)),
478 ($$opts{hackplane1} ? (hackplane1 => 1) : ()),
479 %PostOPS)); }
480 elsif ($fmt eq 'om') {
481 require LaTeXML::Post::OpenMath;
482 push(@mprocs, LaTeXML::Post::OpenMath->new(
483 (defined $$opts{plane1} ? (plane1 => $$opts{plane1}) : (plane1 => 1)),
484 ($$opts{hackplane1} ? (hackplane1 => 1) : ()),
485 %PostOPS)); }
486 elsif ($fmt eq 'images') {
487 require LaTeXML::Post::MathImages;
488 push(@mprocs, LaTeXML::Post::MathImages->new(magnification => $$opts{mathimagemag},
489 %PostOPS)); }
490 elsif ($fmt eq 'svg') {
491 require LaTeXML::Post::MathImages;
492 push(@mprocs, LaTeXML::Post::MathImages->new(magnification => $$opts{mathimagemag},
493 imagetype => 'svg',
494 %PostOPS)); }
495 elsif ($fmt eq 'mathtex') {
496 require LaTeXML::Post::TeXMath;
497 push(@mprocs, LaTeXML::Post::TeXMath->new(%PostOPS)); }
498 elsif ($fmt eq 'mathlex') {
499 require LaTeXML::Post::LexMath;
500 push(@mprocs, LaTeXML::Post::LexMath->new(%PostOPS)); }
501 }
502 ### $keepXMath = 0 unless defined $keepXMath;
503 ### OR is $parallelmath ALWAYS on whenever there's more than one math processor?
504 if ($parallel) {
505 my $main = shift(@mprocs);
506 $main->setParallel(@mprocs);
507 push(@procs, $main); }
508 else {
509 push(@procs, @mprocs); }
510 }
511 if ($xslt) {
512 require LaTeXML::Post::XSLT;
513 my $parameters = { LATEXML_VERSION => "'$LaTeXML::VERSION'" };
514 my @searchpaths = ('.', $DOCUMENT->getSearchPaths);
515 # store these for the XSLT; XSLT Processor will copy resources where needed.
516 foreach my $css (@{ $$opts{css} }) {
517 push(@{ $$parameters{CSS} }, $css); }
518 foreach my $js (@{ $$opts{javascript} }) {
519 push(@{ $$parameters{JAVASCRIPT} }, $js); }
520 if ($$opts{icon}) {
521 $$parameters{ICON} = $$opts{icon}; }
522 if (!defined $$opts{timestamp}) { $$opts{timestamp} = localtime(); }
523 if ($$opts{timestamp}) { $$parameters{TIMESTAMP} = "'" . $$opts{timestamp} . "'"; }
524 # Now add in the explicitly given XSLT parameters
525 foreach my $parm (@{ $$opts{xsltparameters} }) {
526 if ($parm =~ /^\s*(\w+)\s*:\s*(.*)$/) {
527 $$parameters{$1} = "'" . $2 . "'"; }
528 else {
529 warn "xsltparameter not in recognized format: 'name:value' got: '$parm'\n"; }
530 }
531  
532 push(@procs, LaTeXML::Post::XSLT->new(stylesheet => $xslt,
533 parameters => $parameters,
534 searchpaths => [@searchpaths],
535 noresources => (defined $$opts{defaultresources}) && !$$opts{defaultresources},
536 %PostOPS));
537 }
538 }
539  
540 # If we are doing a local conversion OR
541 # we are going to package into an archive
542 # write all the files to disk during post-processing
543 if ($$opts{destination} &&
544 (($$opts{local} && ($$opts{whatsout} eq 'document'))
545 || ($$opts{whatsout} =~ /^archive/))) {
546 require LaTeXML::Post::Writer;
547 push(@procs, LaTeXML::Post::Writer->new(
548 format => $format, omit_doctype => $$opts{omit_doctype},
549 %PostOPS));
550 }
551  
552 # Do the actual post-processing:
553 my @postdocs;
554 my $latexmlpost = LaTeXML::Post->new(verbosity => $verbosity || 0);
555 my $post_eval_return = eval {
556 local $SIG{'ALRM'} = sub { die "Fatal:conversion:post-processing timed out.\n" };
557 alarm($$opts{timeout});
558 @postdocs = $latexmlpost->ProcessChain($DOCUMENT, @procs);
559 alarm(0);
560 1;
561 };
562 # 3.1 Bookkeeping if a post-processing Fatal error occurred
563 local $@ = 'Fatal:conversion:unknown Post-processing failed! (Unknown Reason)'
564 if ((!$post_eval_return) && (!$@));
565 if ($@) { #Fatal occured!
566 $$runtime{status_code} = 3;
567 local $@ = 'Fatal:conversion:unknown ' . $@ unless $@ =~ /^\n?\S*Fatal:/s;
568 print STDERR $@;
569 undef @postdocs; # Empty document for fatals, for sanity's sake
570 }
571  
572 # Finalize by arranging any manifests and packaging the output.
573 # If our format requires a manifest, create one
574 if (($$opts{whatsout} =~ /^archive/) && ($format !~ /^x?html|xml/)) {
575 require LaTeXML::Post::Manifest;
576 my $manifest_maker = LaTeXML::Post::Manifest->new(db => $DB, format => $format, log => $$opts{log}, %PostOPS);
577 $manifest_maker->process(@postdocs); }
578 # Archives: when a relative --log is requested, write to sandbox prior packing
579 if ($$opts{log} && ($$opts{whatsout} =~ /^archive/) && (!pathname_is_absolute($$opts{log}))) {
580 ### We can't rely on the ->getDestinationDirectory method, as Fatal post-processing jobs have UNDEF @postdocs !!!
581 ### my $destination_directory = $postdocs[0]->getDestinationDirectory();
582 my $destination_directory = $PostOPS{destinationDirectory};
583 my $log_file = pathname_absolute($$opts{log}, $destination_directory);
584 if (pathname_is_contained($log_file, $destination_directory)) {
585 print STDERR "\nPost-processing complete: " . $latexmlpost->getStatusMessage . "\n";
586 print STDERR "processing finished " . localtime() . "\n" if $verbosity >= 0;
587 my $archive_log_status_code = max($$runtime{status_code}, $latexmlpost->getStatusCode);
588 print STDERR "Status:conversion:" . $archive_log_status_code . " \n";
589 open my $log_fh, '>', $log_file;
590 print $log_fh $self->flush_log;
591 close $log_fh;
592 $self->bind_log; }
593 else { print STDERR "Error:I/O:log The target log file isn't contained in the destination directory!\n"; } }
594 # Handle the output packaging
595  
596 my ($postdoc) = pack_collection(collection => [@postdocs], whatsout => $$opts{whatsout}, format => $format, %PostOPS);
597  
598 $DB->finish;
599  
600 # Merge postprocessing and main processing reports
601 ### HACKY until we use a single Core::State object, we'll just "wing it" for status messages:
602 my $post_status = $latexmlpost->getStatusMessage;
603 if ($post_status ne $$runtime{status}) { # Just so that we avoid double "No problem" reporting
604 $$runtime{status} .= "\n" . $post_status;
605 }
606 $$runtime{status_code} = max($$runtime{status_code}, $latexmlpost->getStatusCode);
607 ### HACKY END
608  
609 print STDERR "\nPost-processing complete: " . $latexmlpost->getStatusMessage . "\n";
610 print STDERR "processing finished " . localtime() . "\n" if $verbosity >= 0;
611 # Avoid writing the main file twice (non-archive documents):
612 if ($$opts{destination} && $$opts{local} && ($$opts{whatsout} eq 'document')) {
613 undef $postdoc; }
614 return $postdoc; }
615  
616 sub new_latexml {
617 my ($opts) = @_;
618  
619 # TODO: Do this in a GOOD way to support filepath/URL/string snippets
620 # If we are given string preloads, load them and remove them from the preload list:
621 my $preloads = $$opts{preload};
622 my (@pre, @str_pre);
623 foreach my $pre (@$preloads) {
624 if (pathname_is_literaldata($pre)) {
625 push @str_pre, $pre;
626 } else {
627 push @pre, $pre;
628 }
629 }
630 require LaTeXML;
631 my $latexml = LaTeXML::Core->new(preload => [@pre], searchpaths => [@{ $$opts{paths} }],
632 graphicspaths => ['.'],
633 verbosity => $$opts{verbosity}, strict => $$opts{strict},
634 includecomments => $$opts{comments},
635 inputencoding => $$opts{inputencoding},
636 includestyles => $$opts{includestyles},
637 documentid => $$opts{documentid},
638 nomathparse => $$opts{nomathparse}, # Backwards compatibility
639 mathparse => $$opts{mathparse});
640  
641 if (my @baddirs = grep { !-d $_ } @{ $$opts{paths} }) {
642 warn "\n$LaTeXML::IDENTITY : these path directories do not exist: " . join(', ', @baddirs) . "\n"; }
643  
644 $latexml->withState(sub {
645 my ($state) = @_;
646 $latexml->initializeState('TeX.pool', @{ $$latexml{preload} || [] });
647 });
648  
649 # TODO: Do again, need to do this in a GOOD way as well:
650 $latexml->digestFile($_, noinitialize => 1) foreach (@str_pre);
651 print STDERR "\n\n"; # Flush a pair of newlines to delimit the initalization
652 return $latexml;
653 }
654  
655 sub bind_log {
656 my ($self) = @_;
657 # HACK HACK HACK !!! Refactor with proplery scoped logging !!!
658 $LaTeXML::LOG_STACK++; # May the modern Perl community forgive me for this hack...
659 return if $LaTeXML::LOG_STACK > 1;
660 # TODO: Move away from global file handles, they will inevitably end up causing problems..
661  
662 if (!$LaTeXML::DEBUG) { # Debug will use STDERR for logs
663 # Tie STDERR to log:
664 my $log_handle;
665 open($log_handle, ">>", \$$self{log}) or croak "Can't redirect STDERR to log! Dying...";
666 *STDERR_SAVED = *STDERR;
667 *STDERR = *$log_handle;
668 binmode(STDERR, ':encoding(UTF-8)');
669 $LaTeXML::Common::Error::COLORIZED_LOGGING = -t STDERR;
670 $$self{log_handle} = $log_handle;
671 }
672 return; }
673  
674 sub flush_log {
675 my ($self) = @_;
676 # HACK HACK HACK !!! Refactor with proplery scoped logging !!!
677 $LaTeXML::LOG_STACK--; # May the modern Perl community forgive me for this hack...
678 return '' if $LaTeXML::LOG_STACK > 0;
679  
680 # Close and restore STDERR to original condition.
681 if (!$LaTeXML::DEBUG) {
682 close $$self{log_handle};
683 delete $$self{log_handle};
684 *STDERR = *STDERR_SAVED;
685 $LaTeXML::Common::Error::COLORIZED_LOGGING = -t STDERR;
686 }
687 my $log = $$self{log};
688 $$self{log} = q{};
689 return $log; }
690  
691 1;
692  
693 __END__
« lib/LaTeXML/Util/Test.pm ↑ Summary lib/LaTeXML/Package.pm »