<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># autolatex - Translator.pm
# Copyright (C) 2014-2015  Stephane Galland &lt;galland@arakhne.org&gt;
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

=pod

=head1 NAME

Translator.pm - Translator Utilities

=head1 DESCRIPTION

Permits to get translators and to resolve conflicts on them.

To use this library, type C&lt;use AutoLaTeX::Core::Translator;&gt;.

=head1 FUNCTIONS

The provided functions are:

=over 4

=cut
package AutoLaTeX::Core::Translator;

$VERSION = '21.0';
@ISA = ('Exporter');
@EXPORT = qw( &amp;getTranslatorFilesFrom &amp;getLoadableTranslatorList &amp;getTranslatorList
	      &amp;detectConflicts @ALL_LEVELS 
	      &amp;makeTranslatorHumanReadable &amp;extractTranslatorNameComponents
	      &amp;readTranslatorFile &amp;runRootTranslator &amp;runTranslator &amp;loadTranslator
              &amp;loadTranslatorsFromConfiguration &amp;loadTranslatableImageList ) ;
@EXPORT_OK = qw();

require 5.014;
use strict;
use utf8;
use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION @ALL_LEVELS);
use Carp;
use File::Spec;
use File::Basename;
use File::Path qw(make_path remove_tree);
use File::Copy;

use AutoLaTeX::Core::Util;
use AutoLaTeX::Core::Config;
use AutoLaTeX::Core::IntUtils;
use AutoLaTeX::Core::OS;

#Â&nbsp;Sorted list of the levels
our @ALL_LEVELS = ('system', 'user', 'project');

# Data for the translators
my %ROOT_TRANSLATORS = ();

=pod

=item * extractTranslatorNameComponents($)

Parse a complete translator name to extract the components.
The name must have the syntax:
=over 8

=item * C&lt;"I&lt;source&gt;2I&lt;target&gt;"&gt;

=item * C&lt;"I&lt;source&gt;2I&lt;target&gt;+I&lt;target2&gt;"&gt;

=item * C&lt;"I&lt;source&gt;2I&lt;target&gt;_I&lt;variante&gt;"&gt;

=item * C&lt;"I&lt;source&gt;2I&lt;target&gt;+I&lt;target2&gt;_I&lt;variante&gt;"&gt;

=back

I&lt;Parameters:&gt;

=over 8

=item * The name to parse (string).

=back

I&lt;Returns:&gt; a hashtable containing the components of the name. The keys are:

=over 8

=item * C&lt;name&gt; is the name of the translator.

=item * C&lt;full-source&gt; is the decoded of the source type.

=item * C&lt;source&gt; is the source type given in the parameter of the function.

=item * C&lt;target&gt; is the decoded target.

=item * C&lt;variante&gt; is the decoded variante.

=item * C&lt;basename&gt; is the basename of the translator.

=back

=cut
sub extractTranslatorNameComponents($) {
	my $name = shift;
	if ($name =~ /^([a-zA-Z+-]+)2([a-zA-Z0-9-]+)(?:\+([a-zA-Z0-9+-]+))?(?:_(.*))?$/) {
		my $source = $1;
		my $target = $2;
		my $target2 = $3||'';
		my $variante = $4||'';
		my $osource = "$source";
		my $basename = "${source}2${target}${target2}";
		if ($target2) {
			if ($target2 eq 'tex') {
				$source = "ltx.$source";
			}
			elsif ($target2 eq 'layers') {
				$source = "layers.$source";
			}
			elsif ($target2 eq 'layers+tex' || $target2 eq 'tex+layers') {
				$source = "layers.ltx.$source";
			}
			else {
				$target .= "+$target2";
			}
		}
		return { 'name' =&gt; $name, 'full-source' =&gt; $source, 'source' =&gt; $osource, 'target' =&gt; $target, 'variante' =&gt; $variante, 'basename' =&gt; $basename };
	}
	return undef;
}

=pod

=item * makeTranslatorHumanReadable($)

Replies a human readable string that corresponds to the specified translator data.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;description&gt; is the description of the translator (hasharray). The value of the parameter may be obtained with C&lt;extractTranslatorNameComponents()&gt;.

=back

I&lt;Returns:&gt; the description of the translator.

=cut
sub makeTranslatorHumanReadable($) {
	my $data = shift;
	if ($data-&gt;{'variante'}) {
		return formatText(_T("Translate {} to {} with {} alternative"),
					$data-&gt;{'full-source'},
					$data-&gt;{'target'},
					$data-&gt;{'variante'});
	}
	else {
		return formatText(_T("Translate {} to {}"),
					$data-&gt;{'full-source'},
					$data-&gt;{'target'});
	}
}

=pod

=item * getTranslatorFilesFrom($)

Replies the descriptions of the translator files installed on the system.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;configuration&gt; (hashtable) is the current configuration of AutoLaTeX.

=item * C&lt;directory&gt; (string) is the path to the directory to explore.

=item * C&lt;fileSet&gt; (hashtable) is the associative array in which the discovered translators will be put.

=item * C&lt;recursive&gt; (boolean) indicates if the function must recurse in the directories.

=item * C&lt;warn&gt; (boolean) indicates if the warning may be output or not.

=item * C&lt;onlyincluded&gt; (boolean) indicates if only the included translated will be considered as discovered.

=item * C&lt;level&gt; (string) is the level to consider (see C&lt;@ALL_LEVELS&gt;).

=back

I&lt;Returns:&gt; nothing.

=cut
sub getTranslatorFilesFrom(\%$\%$$$;$) {
	my $configuration = shift;
	my $filename = shift;
	my $fileSet = shift;
	my $recursive = shift;
	my $warn = shift;
	my $onlyincluded = shift;
	my $level = shift || 'unknown';
	my $ispdfmode = ($configuration-&gt;{'generation.generation type'} || 'pdf') eq 'pdf';
	local *DIR;
	if (-d "$filename") {
		my @dirs = ( "$filename" );
		while (@dirs) {
			my $dirname = shift @dirs;
			formatText(_T("Get translator list from {}"),$dirname);
			if (opendir(*DIR,"$dirname")) {
				while (my $file = readdir(*DIR)) {
					if ( ! isIgnorableDirectory($file) ) {
						my $fullname = File::Spec-&gt;catfile("$dirname","$file");
						if (-d "$fullname") {
							push @dirs, "$fullname" if ($recursive);
						}
						elsif ($file =~ /^([a-zA-Z+-]+2[a-zA-Z0-9+-]+(?:_[a-zA-Z0-9_+-]+)?).transdef$/i) {
							my $scriptname = "$1";
							if ($onlyincluded) {
								$fileSet-&gt;{"$scriptname"} = extractTranslatorNameComponents($scriptname);
								$fileSet-&gt;{"$scriptname"}{'human-readable'} = makeTranslatorHumanReadable($fileSet-&gt;{"$scriptname"});
								$fileSet-&gt;{"$scriptname"}{'file'} = "$fullname";
								$fileSet-&gt;{"$scriptname"}{'level'} = "$level";
								$fileSet-&gt;{"$scriptname"}{'ispdfmode'} = $ispdfmode;
							}					
							else {
								$fileSet-&gt;{"$scriptname"} = "$fullname";
							}
						}
					}
				}
				closedir(*DIR);
			}
			else {
				printWarn("$dirname:","$!");
			}
		}
	}
	elsif ($warn) {
		printWarn("$filename:","$!");
	}
	1;
}

=pod

=item * resolveConflicts($)

Resolve conflicts between translator inclusions.

I&lt;Parameter:&gt;

=over 8

=item * C&lt;includedTranslators&gt; (hashtable) is the loaded translators. The keys are the names of the translators, and the values are the filenames of the translators.

=back

I&lt;Returns:&gt; nothing.

=cut
sub resolveConflicts(\%) {
	my $includedTranslators = shift;
	my %bysources = ();
	#Â&nbsp;The targets with "*+tex" are translated into sources "ltx.*"
	#Â&nbsp;The targets with "*+layers" are translated into sources "layers.*"
	while (my ($trans,$transfile) = each (%{$includedTranslators})) {
		my $components = extractTranslatorNameComponents($trans);
		if ($components) {
			if (!$bysources{$components-&gt;{'full-source'}}) {
				$bysources{$components-&gt;{'full-source'}} = [];
			}
			push @{$bysources{$components-&gt;{'full-source'}}}, { 
				'source' =&gt; $components-&gt;{'source'},
				'target' =&gt; $components-&gt;{'target'},
				'variante' =&gt; $components-&gt;{'variante'},
				'filename' =&gt; "$transfile" };
		}
	}

	while (my ($source,$trans) = each(%bysources)) {
		if (@{$trans}&gt;1) {
			my $msg = '';
			my ($excludemsg,$excludename);
			foreach my $t (@{$trans}) {
				$msg .= ",\n" if ($msg);
				$msg .= makeTranslatorHumanReadable($t);
				if (!$excludename) {
					$excludename = $t-&gt;{'source'}."2".$t-&gt;{'target'};
					$excludename .= "_".$t-&gt;{'variante'} if ($t-&gt;{'variante'});
				}
				if (!$excludemsg) {
					$excludemsg = "[$excludename]\ninclude module = no\n";
				}
			}
			printErr(formatText(_T("Several possibilities exist for generating a figure from a {} file:\n{}\n\nYou must specify which to include (resp. exclude) with --include (resp. --exclude).\n\nIt is recommended to update your {} file with the following configuration for each translator to exclude (example on the translator {}):\n\n{}\n"),
				$source,
				$msg,
				getUserConfigFilename(),
				$excludename,
				$excludemsg));
		}
	}
	1;
}

=pod

=item B&lt;detectConflicts(\%)&gt;

Replies the list of the translators that are in conflict.

I&lt;Parameters:&gt;

=over 8

=item * List of translator pairs (translator name =&gt; hashtable)

=back

I&lt;Returns:&gt; a hashtable containing (level =&gt; hash of translator descriptions) pairs.

=cut
sub detectConflicts(\%) {
	die('first parameter of detectConflicts() is not a hash')
		unless (isHash($_[0]));
	my %bysources = ();
	#Â&nbsp;Build the list of included translators
	while (my ($name,$data) = each(%{$_[0]})) {
		# By default a module is included
		for(my $i=0; $i&lt;@ALL_LEVELS; $i++) {
			my $level = $ALL_LEVELS[$i];
			if ($data-&gt;{'included'}{$level}) {
				$bysources{$level}{$data-&gt;{'full-source'}}{$data-&gt;{'name'}} = $data;
				# Propagate the inclusion to the following levels
				for(my $j=$i+1; $j&lt;@ALL_LEVELS; $j++) {
					my $flevel = $ALL_LEVELS[$j];
					$bysources{$flevel}{$data-&gt;{'full-source'}}{$data-&gt;{'name'}} = $data;
				}
			}
			elsif (defined($data-&gt;{'included'}{$level})) {
				#Â&nbsp;Propagate the non inclusion to the following levels
				# This action cancels previous propagation of included translators
				for(my $j=$i; $j&lt;@ALL_LEVELS; $j++) {
					my $flevel = $ALL_LEVELS[$j];
					if ($bysources{$flevel}{$data-&gt;{'full-source'}}) {
						delete $bysources{$flevel}{$data-&gt;{'full-source'}}{$data-&gt;{'name'}};
					}
				}
			}
			elsif ($i==0) {
				#Â&nbsp;By default a module is included
				# Propagate the inclusion to the following levels
				$bysources{$level}{$data-&gt;{'full-source'}}{$data-&gt;{'name'}} = $data;
				for(my $j=$i+1; $j&lt;@ALL_LEVELS; $j++) {
					my $flevel = $ALL_LEVELS[$j];
					$bysources{$flevel}{$data-&gt;{'full-source'}}{$data-&gt;{'name'}} = $data;
				}
			}
		}
	}

	# Remove the translators that are not under conflict
	foreach my $level (@ALL_LEVELS) {
		foreach my $source (keys %{$bysources{$level}}) {
			my @keys = keys %{$bysources{$level}{$source}};
			if (@keys&lt;=1) {
				delete $bysources{$level}{$source};
			}
		}
		unless ($bysources{$level}) {
			delete $bysources{$level};
		}
	}

	return %bysources;
}

=pod

=item B&lt;getLoadableTranslatorList(\%)&gt;

Replies the list of the translators that could be loaded.

I&lt;Parameters:&gt;

=over 8

=item * hashtable that contains the current configuration, and that will
be updating by this function.

=back

I&lt;Returns:&gt; a hashtable containing (translator name =&gt; translator file) pairs.

=cut
sub getLoadableTranslatorList(\%) {
	local *DIR;

	my %includes = ();

	#Â&nbsp;Load distribution modules
	my $filename = File::Spec-&gt;catfile(getAutoLaTeXDir(),"translators");
	printDbg(formatText(_T("Get loadable translators from {}"),$filename));
	printDbgIndent();
	opendir(*DIR,"$filename")
		or printErr("$filename:","$!");
	while (my $file = readdir(*DIR)) {
		if ((!isIgnorableDirectory($file))&amp;&amp;
		    ($file =~ /^(.*)\.transdef$/i)) {
			my $fullname = File::Spec-&gt;rel2abs(File::Spec-&gt;catfile("$filename","$file"));
			my $scriptname = "$1";
			if ((!exists $_[0]-&gt;{"$scriptname.include module"})||
			    (cfgBoolean($_[0]-&gt;{"$scriptname.include module"}))) {
				$includes{"$scriptname"} = "$fullname";
			}
			else {
				printDbg(formatText(_T("Translator {} is ignored"),$scriptname));
			}
		}
	}
	closedir(*DIR);
	printDbgUnindent();

	#Â&nbsp;Load user modules recursively from ~/.autolatex/translators
	getTranslatorFilesFrom(
		%{$_[0]},
		File::Spec-&gt;catfile(getUserConfigDirectory(),"translators"),
		%includes,
		1, # recursion
		0, # no warning
		0, # only included translators
		'user' # configuration level
		);

	#Â&nbsp;Load user modules non-recursively the paths specified inside the configurations
	if ($_[0]-&gt;{'generation.translator include path'}) {
		my @paths = ();
		if ((isArray($_[0]-&gt;{'generation.translator include path'}))||
		    (isHash($_[0]-&gt;{'generation.translator include path'}))) {
			@paths = @{$_[0]-&gt;{'generation.translator include path'}};
		}
		else  {
			push @paths, $_[0]-&gt;{'generation.translator include path'};
		}
		foreach my $path (@paths) {
			getTranslatorFilesFrom(
				%{$_[0]},
				"$path",
				%includes,
				0, # no recursion
				1, #Â&nbsp;warning
				0, # only included translators
				'user' # configuration level
			);
		}
	}

	resolveConflicts(%includes);

	return %includes;
}

=pod

=item B&lt;getTranslatorList(\%;$)&gt;

Replies the list of the translators and their status.

I&lt;Parameters:&gt;

=over 8

=item * hashtable that contains the configuration.

=item * recurse on user inclusion directories

=back

I&lt;Returns:&gt; a hashtable containing (translator name =&gt; { 'file' =&gt; translator file,
'level' =&gt; installation level, 'ispdfmode' =&gt; boolean value indicating that
the pdf mode is one } ) pairs.

=cut
sub getTranslatorList(\%;$) {
	local *DIR;
	die('first parameter of getTranslatorList() is not a hash')
		unless(isHash($_[0]));

	my $recurse = $_[1];
	$recurse = 1 unless (defined($recurse));

	my $ispdfmode = ($_[0]-&gt;{'generation.generation type'} || 'pdf') eq 'pdf';

	my %translators = ();

	#Â&nbsp;Load distribution modules
	my $filename = File::Spec-&gt;catfile(getAutoLaTeXDir(),"translators");
	printDbg(formatText(_T("Get translators from {}"),$filename));
	printDbgIndent();
	opendir(*DIR,"$filename") or printErr("$filename:","$!");
	while (my $file = readdir(*DIR)) {
		if ((!isIgnorableDirectory($file))&amp;&amp;
		    ($file =~ /^(.*)\.transdef$/i)) {
			my $fullname = File::Spec-&gt;rel2abs(File::Spec-&gt;catfile("$filename","$file"));
			my $scriptname = "$1";
			$translators{"$scriptname"} = extractTranslatorNameComponents($scriptname);
			$translators{"$scriptname"}{'human-readable'} = makeTranslatorHumanReadable($translators{"$scriptname"});
			$translators{"$scriptname"}{'file'} = "$fullname";
			$translators{"$scriptname"}{'level'} = 'system';
			$translators{"$scriptname"}{'ispdfmode'} = $ispdfmode;
		}
	}
	closedir(*DIR);
	printDbgUnindent();

	if ($recurse) {
		#Â&nbsp;Load user modules recursively from ~/.autolatex/translators
		getTranslatorFilesFrom(
			%{$_[0]},
			File::Spec-&gt;catfile(getUserConfigDirectory(),"translators"),
			%translators,
			1, # recursion
			0, # no warning
			1, # all included and not-included translators
			'user' # configuration level
			);

		#Â&nbsp;Load user modules non-recursively the paths specified inside the configurations
		if ($_[0]-&gt;{'generation.translator include path'}) {
			my @paths = ();
			if ((isArray($_[0]-&gt;{'generation.translator include path'}))||
			    (isHash($_[0]-&gt;{'generation.translator include path'}))) {
				@paths = @{$_[0]-&gt;{'generation.translator include path'}};
			}
			else  {
				push @paths, $_[0]-&gt;{'generation.translator include path'};
			}
			foreach my $path (@paths) {
				getTranslatorFilesFrom(
					%{$_[0]},
					"$path",
					%translators,
					0, # no recursion
					1, #Â&nbsp;warning
					1, # all included and not-included translators
					'user' # configuration level
				);
			}
		}
	} #Â&nbsp;if ($recurse)

	return %translators;
}

=pod

=item B&lt;readTranslatorFile($$)&gt;

Replies the content of a translator definition file.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;file&gt; is the name of the file to parse.

=item * C&lt;ispdfmode&gt; indicates of AutoLaTeX is in pdf mode (true) or in eps mode (false).

=back

I&lt;Returns:&gt; a hashtable containing the entries of the definition.

=cut
sub readTranslatorFile($$) {
	my $file = shift || confess('you must pass a filename to readTranslatorFile($$)');
	my $ispdfmode = shift;
	my %content = ();
	local *FILE;
	open(*FILE, "&lt; $file") or printErr("$file: $!");
	my $curvar = '';
	my $eol = undef;
	my $lineno = 0;
	while (my $line = &lt;FILE&gt;) {
		$lineno++;
		if ($eol) {
			if ($line =~ /^\Q$eol\E\s*$/) {
				$eol = undef;
				$curvar = undef;
			}
			elsif ($curvar) {
				$content{"$curvar"}{'value'} .= $line;
			}
		}
		elsif ($line !~ /^\s*[#;]/) {
			if ($line =~ /^\s*([azA-Z0-9_]+)(?:\s+with\s+(.*?))?(?:\s+for\s+((?:pdf)|(?:eps)))?\s*=\&lt;\&lt;([a-zA-Z0-9_]+)\s*(.*?)\s*$/i) {
				($curvar, my $interpreter, my $mode, $eol, my $value) = ($1, $2, $3, $4, $5);
				if (!$mode ||
				    ($ispdfmode &amp;&amp; lc($mode) eq 'pdf') ||
				    (!$ispdfmode &amp;&amp; lc($mode) eq 'eps')) {
					$curvar = uc($curvar);
					$content{"$curvar"} = {
						'lineno' =&gt; $lineno,
						'value' =&gt; $value,
						'interpreter' =&gt; ($interpreter ? lc($interpreter) : undef),
					};
				}
				else {
					$curvar = '';
				}
			}
			elsif ($line =~ /^\s*([azA-Z0-9_]+)(?:\s+with\s+(.*?))?(?:\s+for\s+((?:pdf)|(?:eps)))?\s*=\s*(.*?)\s*$/i) {
				my ($var, $interpreter, $mode, $value) = ($1, $2, $3, $4);
				if (!$mode ||
				    ($ispdfmode &amp;&amp; lc($mode) eq 'pdf') ||
				    (!$ispdfmode &amp;&amp; lc($mode) eq 'eps')) {
					$curvar = undef;
					$eol = undef;
					$content{uc("$var")} = {
						'lineno' =&gt; $lineno,
						'value' =&gt; $value,
						'interpreter' =&gt; ($interpreter ? lc($interpreter) : undef),
					};
				}
			}
			elsif ($line !~ /^\s*$/) {
				printErr(formatText(_T("Line outside a definition ({}:{})."),$lineno, $file));
			}
		}
	}
	close(*FILE);
	if ($eol) {
		printErr(formatText(_T("The block for the variable '{}' is not closed. Keyword '{}' was not found ({}:{})."),
				$curvar, $eol, $file, $lineno));
	}


	# Translate the values into suitable Perl objects
	if (exists $content{'INPUT_EXTENSIONS'}{'value'}) {
		my @exts = split(/\s+/, ($content{'INPUT_EXTENSIONS'}{'value'} || ''));
		$content{'INPUT_EXTENSIONS'}{'value'} = [];
		foreach my $e (@exts) {
			if ($e !~ /^\^s*$/) {
				if ($e !~ /^[\.+]/) {
					$e = ".$e";
				}
				push @{$content{'INPUT_EXTENSIONS'}{'value'}}, $e;
			}
		}
	}

	if (exists $content{'OUTPUT_EXTENSIONS'}{'value'}) {
		my @exts = split(/\s+/, ($content{'OUTPUT_EXTENSIONS'}{'value'} || ''));
		$content{'OUTPUT_EXTENSIONS'}{'value'} = [];
		foreach my $e (@exts) {
			if ($e !~ /^\^s*$/) {
				if ($e !~ /^\./) {
					$e = ".$e";
				}
				push @{$content{'OUTPUT_EXTENSIONS'}{'value'}}, $e;
			}
		}
	}

	if (exists $content{'TRANSLATOR_PERL_DEPENDENCIES'}{'value'}) {
		my @exts = split(/\s+/, ($content{'TRANSLATOR_PERL_DEPENDENCIES'}{'value'} || ''));
		$content{'TRANSLATOR_PERL_DEPENDENCIES'}{'value'} = [];
		while (@exts) {
			my $e = shift @exts;
			if ($exts[0] &amp;&amp;
			    ( ($exts[0] =~ /^\Q'\E.*?\Q'\E$/) ||
			      ($exts[0] =~ /^\Qqw(\E.+?\Q)\E$/) ||
			      ($exts[0] =~ /^\Qqw{\E.+?\Q}\E$/))) {
				my $p = shift @exts;
				$e .= " $p";
			}
			push @{$content{'TRANSLATOR_PERL_DEPENDENCIES'}{'value'}}, $e;
		}
	}

	if (exists $content{'FILES_TO_CLEAN'}{'value'}) {
		my @patterns = split(/\s+/, ($content{'FILES_TO_CLEAN'}{'value'} || ''));
		$content{'FILES_TO_CLEAN'}{'value'} = [];
		foreach my $p (@patterns) {
			if ($p !~ /^\^s*$/) {
				push @{$content{'FILES_TO_CLEAN'}{'value'}}, $p;
			}
		}
	}

	return \%content;
}

=pod

=item B&lt;runRootTranslator(\%$$\%$;$)&gt;

Run the translator on a file as a root translator.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;configuration&gt; is AutoLaTeX configuration.

=item * C&lt;name&gt; is name of the translator.

=item * C&lt;in&gt; is the name of the input file.

=item * C&lt;translators&gt; definition of all the translators.

=item * C&lt;force&gt; indicates if the translation is always run (true) or only if the source file is more recent than the target file.

=back

I&lt;Returns:&gt; true if a file was created; otherwise false.

=cut

sub runRootTranslator(\%$$\%$) {
	my $configuration = shift || confess("configuration is mandatory");
	my $transname = shift || confess("transname is mandatory");
	my $in = shift || confess("input is mandatory");
	my $translators = shift || confess("translators are mandatory");
	my $force = shift;

	my $out = undef;
	my @transexts = sort {
				my $la = length($a);
				my $lb = length($b);
				my $c = $lb &lt;=&gt; $la;
				if ($c) {
					($c);
				}
				else {
					($a cmp $b);
				}
			}
			@{$translators-&gt;{"$transname"}{'transdef'}{'INPUT_EXTENSIONS'}{'value'}};
	my $i = 0;
	while (($i&lt;@transexts) &amp;&amp; (!$out)) {
		if ($in =~ /^(.+)\Q$transexts[$i]\E$/i) {
			$out = "$1";
		}
		$i++;
	}
	$out = "$in" unless ($out);
	$out .= $translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}[0] || '';

	$ROOT_TRANSLATORS{'configuration'} = $configuration;
	$ROOT_TRANSLATORS{'translators'} = $translators;
	$ROOT_TRANSLATORS{'force'} = $force;
	$ROOT_TRANSLATORS{'loglevel'} = 1;
	$ROOT_TRANSLATORS{'fail-on-error'} = 1;

	return _runTranslator(
		$configuration,
		$translators,
		$transname,
		$in, 
		$out,
		$force,
		1,
		1);
}

=pod

=item B&lt;runTranslator($$$)&gt;

Run the translator on a file.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;name&gt; is name of the translator.

=item * C&lt;in&gt; is the name of the input file.

=item * C&lt;out&gt; is the name of the output file.

=item * C&lt;failOnError&gt; (optional) indicates if the translator must fail on error or not.

=back

I&lt;Returns:&gt; true if a file was created; otherwise false.

=cut
sub runTranslator($$$;$) {
	my $transname = shift || confess("name is mandatory");
	my $in = shift || confess("input is mandatory");
	my $out = shift || confess("output is mandatory");
	my $failOnError = shift;
	if (!$ROOT_TRANSLATORS{'translators'}) {
		printErr(_T("You cannot call runTranslator() outside the call stack of runRootTranslator()."));
	}
	if (!defined($failOnError)) {
		$failOnError = $ROOT_TRANSLATORS{'fail-on-error'};
	}
	printDbgIndent();
	my $savedFailure = $ROOT_TRANSLATORS{'fail-on-error'};
	$ROOT_TRANSLATORS{'fail-on-error'} = $failOnError;
	$ROOT_TRANSLATORS{'loglevel'}++;
	my $r = _runTranslator(
			$ROOT_TRANSLATORS{'configuration'},
			$ROOT_TRANSLATORS{'translators'},
			$transname,
			$in,
			$out,
			$ROOT_TRANSLATORS{'force'},
			$ROOT_TRANSLATORS{'loglevel'},
			$failOnError);
	$ROOT_TRANSLATORS{'loglevel'}--;
	$ROOT_TRANSLATORS{'fail-on-error'} = $savedFailure;
	printDbgUnindent();
	return $r;
}

# Private translator function
sub _runTranslator($$$$$$$$) {
	my $configuration = shift || confess("configuration is mandatory");
	my $translators = shift || confess("translators are mandatory");
	my $transname = shift || confess("transname is mandatory");
	my $in = shift || confess("input is mandatory");
	my $out = shift || confess("output is mandatory");
	my $force = shift;
	my $logLevel = shift;
	my $failOnError = shift;
	my $ispdfmode = (($configuration-&gt;{'generation.generation type'} || 'pdf') eq 'pdf');
	my $isepsmode = !$ispdfmode;

	$in = File::Spec-&gt;rel2abs("$in");
	$out = File::Spec-&gt;rel2abs("$out");
	
	if (! -r "$in") {
		my $errmsg = formatText(_T("{}: file not found or not readable."), $in);
		if ($failOnError) {
			printErr($errmsg);
		}
		else {
			print STDERR formatErr($errmsg);
			return 0;
		}
	}

	if (!exists $translators-&gt;{"$transname"} ||
	    !exists $translators-&gt;{"$transname"}{'transdef'} ||
	    !$translators-&gt;{"$transname"}{'transdef'}) {
		# The requested translator was not enabled by the user.
		# We try to enable it on the fly.
		loadTranslator($transname, $translators);
	}

	# Try to avoid the translation if the source file is no more recent than the target file.
	if (!$force) {
		my $inChange = lastFileChange("$in");
		my $outChange = lastFileChange("$out");
		if (!defined($outChange)) {
			# No out file, try to detect other types of generated files
			local *DIR;
			my $dirname = dirname("$out");
			if (opendir(*DIR, "$dirname")) {
				my $fn;
				my $ext = $translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}[0] || '';
				my $bn = basename($out, $ext);
				while (!defined($outChange) &amp;&amp; ($fn = readdir(*DIR))) {
					if (!isIgnorableDirectory($fn)
							&amp;&amp; $fn =~ /^(\Q${bn}_\E.*)\Q$ext\E$/s) {
						my $ffn = File::Spec-&gt;catfile("$dirname", "$fn");
						my $t = lastFileChange("$ffn");
						if (defined($t) &amp;&amp; (!defined($outChange) || $t&lt;$outChange)) {
							$outChange = $t;
						}
					}
				}
				closedir(*DIR);
			}
		}

		if (defined($outChange) &amp;&amp; $inChange&lt;$outChange) {
			# No need to translate again
			printDbgFor(2, formatText(_T("{} is up-to-date."), basename($out)));
			return 1;
		} else {
			printDbgFor(3, formatText(_T("in={}; out={}."), $outChange, $inChange));
		}
	}

	if ($logLevel) {
		printDbgFor($logLevel, formatText(_T("{} -&gt; {}"), basename($in), basename($out)));
	}

	if ($translators-&gt;{"$transname"}{'transdef'}{'COMMAND_LINE'}{'value'}) {
		################################
		# Run an external command line #
		################################
		my $cli = ($translators-&gt;{"$transname"}{'transdef'}{'COMMAND_LINE'}{'value'} || '');
		# Create the environment of variables for the CLI
		my %environment = (%{$translators-&gt;{"$transname"}{'environment_variables'}});
		while (my ($k,$v) = each(%{$configuration})) {
			if (!isArray($v) &amp;&amp; !isHash($v)) {
				$environment{$k} = $v;
			}
		}
		$environment{'in'} = $in;
		$environment{'out'} = $out;
		my $inext;
		while ((!$inext)&amp;&amp; ((undef,my $e) = each @{$translators-&gt;{"$transname"}{'transdef'}{'INPUT_EXTENSIONS'}{'value'}})) {
			if ($in =~ /\Q$e\E$/i) {
				$inext = $e;
			}
		}
		if (!$inext) {
			$inext = $translators-&gt;{"$transname"}{'transdef'}{'INPUT_EXTENSIONS'}{'value'}[0];
		}
		$environment{'inext'} = $inext;
		my $ext = $translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}[0] || '';
		$environment{'outbasename'} = basename($out, $ext);
		$environment{'outwoext'} = File::Spec-&gt;catfile(dirname($out), $environment{'outbasename'});
		# Create the CLI to run
		my @cli = parseCLI(\%environment, "$cli");
		
		if (getDebugLevel&gt;=4) {
			$cli = '$';
			foreach my $elt (@cli) {
				$cli .= " ".addSlashes($elt);
			}
			printDbg("$cli");
		}

		runCommandOrFail(@cli);
	}
	elsif ($translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_FUNCTION'}{'value'}) {
		#########################
		# Run the embedded code #
		#########################
		my $lineno = $translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_FUNCTION'}{'lineno'} - 1;
		my $interpreter = $translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_FUNCTION'}{'interpreter'};

		my @inexts = @{$translators-&gt;{"$transname"}{'transdef'}{'INPUT_EXTENSIONS'}{'value'}};
		my $inext;
		while ((!$inext)&amp;&amp; ((undef,my $e) = each @inexts)) {
			if ($in =~ /\Q$e\E$/i) {
				$inext = $e;
			}
		}
		if (!$inext) {
			$inext = $inexts[0];
		}
		my $outext = $translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}[0];
		my @outexts = @{$translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}};
		my $ext = $translators-&gt;{"$transname"}{'transdef'}{'OUTPUT_EXTENSIONS'}{'value'}[0] || '';
		my $outbasename = basename($out, $ext);
		my $outwoext = File::Spec-&gt;catfile(dirname($out), $outbasename);

		if (!$interpreter || $interpreter eq 'perl') {
			#
			# PERL INTERPRETER
			#
			my $code;
			{
				my $perlDeps = $translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_PERL_DEPENDENCIES'}{'value'} || [];
				$code = "{\n";
				if ($perlDeps) {
					foreach my $dep (@{$perlDeps}) {
						$code .= "use ".$dep.";\n";
						$lineno++;
					}
				}
				$code .= $translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_FUNCTION'}{'value'};
				$code .= "}\n";
			}		
		
			my $c = eval $code;
			if (!defined($c) &amp;&amp; $@) {
				my $msg = "$@";
				$msg =~ s/(\(eval\s+[0-9]+\)\s*line\s+)([0-9]+)/$1.($2 + $lineno)."($2)"/egsi;
				$msg = formatText(_T("Error in the TRANSLATOR_FUNCTION of '{}':\n{}"), $transname, $msg);
				if ($failOnError) {
					printErr($msg);
				}
				else {
					#print STDERR formatErr($msg);
					return 0;
				}
			}
			# Return the last value of the translator's script
			return $c;
		}
		else {
			#
			# OTHER INTERPRETER
			#
			my $wrapper;
			eval "use AutoLaTeX::Interpreter::$interpreter; \$wrapper = AutoLaTeX::Interpreter::$interpreter-&gt;new();";
			if (!$wrapper) {
				my $errmsg = formatText(_T("Cannot find an interpreter wrapper for {}: {}"), $interpreter, ($@||''));
				if ($failOnError) {
					printErr($errmsg);
				}
				else {
					print STDERR formatErr($errmsg);
					return 0;
				}
			}
			
			$wrapper-&gt;define_global_variable('_in', $in);
			$wrapper-&gt;define_global_variable('_out', $out);
			$wrapper-&gt;define_global_variable('_inexts', \@inexts);
			$wrapper-&gt;define_global_variable('_inext', $inext);
			$wrapper-&gt;define_global_variable('_outext', $outext);
			$wrapper-&gt;define_global_variable('_outexts', \@outexts);
			$wrapper-&gt;define_global_variable('_ext', $ext);
			$wrapper-&gt;define_global_variable('_outbasename', $outbasename);
			$wrapper-&gt;define_global_variable('_outwoext', $outwoext);

			my $code = $translators-&gt;{"$transname"}{'transdef'}{'TRANSLATOR_FUNCTION'}{'value'} || '';
			$wrapper-&gt;run($code);
		}
	}
	else {
		my $errmsg = formatText(_T("Unable to find the method of translation for '{}'."), $transname);
		if ($failOnError) {
			printErr($errmsg);
		}
		else {
			print STDERR formatErr($errmsg);
			return 0;
		}
	}

	return 1;
}


=pod

=item B&lt;loadTranslator()&gt;

Load the all the data needed to run a translator.
This function read the translator definition (transdef)
file; it sets the 'environment_variables' entry; and
it make symbolic link from the translator basename to
the translator itself.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;name&gt; is the name of the translator to load.

=item * C&lt;translators&gt; is the associative array that contains all the informations
about all the translators.

=back

I&lt;Returns:&gt; true if a file was created; otherwise false.

=cut
sub loadTranslator($\%) {
	my $name = shift || confess('you must pass the name of the translator to load');
	my $translators = shift || confess('you must pass the descriptions of the translators');

	printDbgFor(4, formatText(_T("Searching translator '{}'."), $name));

	# Check if the translator name corresponds to an existing translator.
	# If not, try to find a variante.
	if (!exists $translators-&gt;{$name} || 
	    !$translators-&gt;{$name} ||
	    !$translators-&gt;{$name}{'file'}) {
		my $loadedlinkname = undef;
		my $linkname = undef;
		while ((!$loadedlinkname) &amp;&amp; (my ($k,$v) = each (%{$translators}))) {
			if (isHash($v) &amp;&amp; $v-&gt;{'basename'} &amp;&amp; $v-&gt;{'basename'} eq $name
				&amp;&amp; $v-&gt;{'file'}) {
				if (exists $v-&gt;{'transdef'}) {
					$loadedlinkname = $k;
				}
				else {
					$linkname = $k;	
				}
			}
		}
		if (!$linkname &amp;&amp; !$loadedlinkname) {
			printErr(formatText(_T("The translator '{}' cannot be found."), $name));
		}
		elsif ($loadedlinkname) {
			$linkname = $loadedlinkname;
		}
		printDbgFor(4, formatText(_T("Linking '{}' to '{}'."), $name, $linkname));
		$translators-&gt;{"$name"} = $translators-&gt;{"$linkname"};
		$name = $linkname;
	}

	# Load the translator if not already loaded
	if (exists $translators-&gt;{$name}{'transdef'}) {
		printDbgFor(4, formatText(_T("'{}' is already loaded."), $name));
	}
	else {
		printDbgFor(4, formatText(_T("Loading translator '{}'."), $name));
		# Read the translator definition
		$translators-&gt;{$name}{'transdef'} = readTranslatorFile(
							$translators-&gt;{$name}{'file'},
							$translators-&gt;{$name}{'ispdfmode'});
		# Add environment variables
		while ( my ($k,$v) = each(%{$translators-&gt;{$name}{'transdef'}})) {
			if ($v &amp;&amp; $v-&gt;{'value'} &amp;&amp; !isHash($v-&gt;{'value'}) &amp;&amp; !isArray($v-&gt;{'value'})) {
				$translators-&gt;{$name}{'environment_variables'}{"$k"} = $v-&gt;{'value'};
			}
		}
	}

}


=pod

=item B&lt;loadTranslatorsFromConfiguration(%%)&gt;

Run the algorithm that permits to load the translator
according to a given configuration.
This function is provided to be invoked by the main
program of AutoLaTex, or any other program that is
needing to load the list of translators according
to a configuration.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;configuration&gt; is the associative array that contains the configuration.

=item * C&lt;data&gt; is the associative array that IS FILLED with the data of the loaded translators.

=back

I&lt;Returns:&gt; Nothing

=cut
sub loadTranslatorsFromConfiguration(\%\%) {
	my $configuration = shift or confess("First parameter is mandatory: the associative array of the configuration");
	my $data = shift or confess("Second parameter is mandatory: the associative array of loaded data");
	if (!$data-&gt;{'translators'}) {
		%{$data-&gt;{'translators'}} = getTranslatorList(%{$configuration});
	}
	if (!$data-&gt;{'loadableTranslators'}) {
		%{$data-&gt;{'loadableTranslators'}} = getLoadableTranslatorList(%{$configuration});

		foreach my $translator (keys %{$data-&gt;{'loadableTranslators'}}) {
			# Load the translator
			loadTranslator($translator, %{$data-&gt;{'translators'}});

			# Extract image extensions
			foreach my $input (@{$data-&gt;{'translators'}{$translator}{'transdef'}{'INPUT_EXTENSIONS'}{'value'}}) {
				$data-&gt;{'imageDatabase'}{"$input"}{'translator'} = $translator;
			}
		}
	}
	return undef;
}


=pod

=item B&lt;loadTranslatableImageList(%%)&gt;

Run the algorithm that permits to load the list
of the images that should be processed by the translators.
This function is provided to be invoked by the main
program of AutoLaTex, or any other program that is
needing this list.

I&lt;Parameters:&gt;

=over 8

=item * C&lt;configuration&gt; is the associative array that contains the configuration.

=item * C&lt;data&gt; is the associative array that IS FILLED with the data of the pictures.

=item * C&lt;skipManualAssignment&gt; (optional) is a boolean flag that indicates if the manual
assignments with C&lt;"*.files to convert"&gt; from the configuration must be skipped.

=back

I&lt;Returns:&gt; Nothing

=cut
sub loadTranslatableImageList(\%\%;$) {
	my $configuration = shift or confess("First parameter is mandatory: the associative array of the configuration");
	my $data = shift or confess("Second parameter is mandatory: the associative array of loaded data");
	my $skipManualAssignment = shift;
	if (!$data-&gt;{'imageDatabaseReady'} &amp;&amp; exists $configuration-&gt;{'generation.image directory'}) {
		$data-&gt;{'numberOfImages'} = 0;
		my $separator = getPathListSeparator();
		# Prepare the configuration entries '*.files to convert'
		if (!$skipManualAssignment) {
			$configuration-&gt;{'__private__'}{'files to convert'} = {};
			while (my ($k,$v) = each(%{$configuration})) {
				if ($k =~ /^(.+)\.files\s+to\s+convert$/) {
					my $trans = $1;
					my @t = split(/\s*\Q$separator\E\s*/, $v);
					foreach my $t (@t) {
						$t = File::Spec-&gt;rel2abs($t, $configuration-&gt;{'__private__'}{'input.project directory'});
						$configuration-&gt;{'__private__'}{'files to convert'}{$t} = $trans;
					}
				}
			}
		}
		# Detect the image from the file system
		local* DIR;
		printDbg(formatText(_T("Detecting images inside '{}'"), $configuration-&gt;{'generation.image directory'}));
		my $rawdirs = $configuration-&gt;{'generation.image directory'};
		$rawdirs =~ s/^\s+//s;
		$rawdirs =~ s/\s+$//s;
		if ($rawdirs) {
			my $separators = getPathListSeparator() || '';
			my @dirs = split( /[$separators]/is, $rawdirs);
			my @imageExtensions = keys %{$data-&gt;{'imageDatabase'}};
			@imageExtensions = sort {
							my $la = length($a);
							my $lb = length($b);
							if ($la==$lb) {
								($a cmp $b);
							}
							else {
								($lb - $la);
							}
						} @imageExtensions;
			while (@dirs) {
				my $dir = shift @dirs;
				$dir = File::Spec-&gt;rel2abs($dir, $configuration-&gt;{'__private__'}{'input.project directory'});
				if (opendir(*DIR, "$dir")) {
					while (my $fn = readdir(*DIR)) {
						if (!isIgnorableDirectory($fn)) {
							my $ffn = File::Spec-&gt;catfile("$dir", "$fn");
							if (-d "$ffn") {
								push @dirs, "$ffn";
							}
							else {
								my $selectedExtension = undef;
								if (!$skipManualAssignment &amp;&amp;
								    $configuration-&gt;{'__private__'}{'files to convert'}{$ffn}) {
									my $trans = $configuration-&gt;{'__private__'}{'files to convert'}{$ffn};
									$selectedExtension = "$separator$separator$trans$separator$separator";
									$data-&gt;{'imageDatabase'}{"$selectedExtension"}{'translator'} = $trans;
									loadTranslator($trans, %{$data-&gt;{'translators'}});
								}
								if (!$selectedExtension) {
									for(my $i=0; !$selectedExtension &amp;&amp; $i&lt;@imageExtensions; ++$i) {
										if ($fn =~ /\Q$imageExtensions[$i]\E$/i) {
											$selectedExtension = $imageExtensions[$i];
										}
									}
								}
								if ($selectedExtension) {
									if (!$data-&gt;{'imageDatabase'}{"$selectedExtension"}{'files'}) {
										$data-&gt;{'imageDatabase'}{"$selectedExtension"}{'files'} = [];
									}
									push @{$data-&gt;{'imageDatabase'}{"$selectedExtension"}{'files'}}, "$ffn";
									$data-&gt;{'activatedImageExtensions'}{"$selectedExtension"} = 1;
									$data-&gt;{'numberOfImages'}++;
								}
							}
						}
					}
					closedir(*DIR);
				}
			}
		}
		if ($data-&gt;{'activatedImageExtensions'}) {
			my @keys = keys %{$data-&gt;{'activatedImageExtensions'}};
			$data-&gt;{'activatedImageExtensions'} = \@keys;
		}
		$data-&gt;{'imageDatabaseReady'} = 1;
	}
	return undef;
}

1;
__END__
=back

=head1 BUG REPORT AND FEEDBACK

To report bugs, provide feedback, suggest new features, etc. visit the AutoLaTeX Project management page at &lt;http://www.arakhne.org/autolatex/&gt; or send email to the author at L&lt;galland@arakhne.org&gt;.

=head1 LICENSE

S&lt;GNU Public License (GPL)&gt;

=head1 COPYRIGHT

S&lt;Copyright (c) 1998-14 StÃ©phane Galland E&lt;lt&gt;galland@arakhne.orgE&lt;gt&gt;&gt;

=head1 SEE ALSO

L&lt;autolatex-dev&gt;
</pre></body></html>