lib/LaTeXML.pm

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