]> git.lyx.org Git - lyx.git/blob - development/autotests/useSystemFonts.pl
Cmate export tests: Thinko, using entry as array also in cases where it is not
[lyx.git] / development / autotests / useSystemFonts.pl
1 #! /usr/bin/env perl
2 # -*- mode: perl; -*-
3 #
4 # file useSystemFonts.pl
5 # 1.) Copies lyx-files to another location
6 # 2.) While copying,
7 #   2a.) searches for relative references to files and
8 #        replaces them with absolute ones
9 #   2b.) Changes default fonts to use non-tex-fonts
10 #
11 # Syntax: perl useSystemFonts.pl sourceFile destFile format
12 # Each param represents a path to a file
13 # sourceFile: full path to a lyx file
14 # destFile: destination path
15 #   Each subdocument will be copied into a subdirectory of dirname(destFile)
16 # format: any string of the form '[a-zA-Z0-9]+', e.g. pdf5
17 #
18 # This file is free software; you can redistribute it and/or
19 # modify it under the terms of the GNU General Public
20 # License as published by the Free Software Foundation; either
21 # version 2 of the License, or (at your option) any later version.
22 #
23 # This software is distributed in the hope that it will be useful,
24 # but WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26 # General Public License for more details.
27 #
28 # You should have received a copy of the GNU General Public
29 # License along with this software; if not, write to the Free Software
30 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
31 #
32 # Copyright (c) 2013 Kornel Benko <kornel@lyx.org>
33 #           (c) 2013 Scott Kostyshak <skotysh@lyx.org>
34
35 use strict;
36
37 BEGIN {
38   use File::Spec;
39   my $p = File::Spec->rel2abs( __FILE__ );
40   $p =~ s/[\/\\]?[^\/\\]+$//;
41   unshift(@INC, "$p");
42 }
43 use File::Basename;
44 use File::Path;
45 use File::Copy "cp";
46 use File::Temp qw/ :POSIX /;
47 use lyxStatus;
48
49 # Prototypes
50 sub printCopiedDocuments($);
51 sub interpretedCopy($$$$);
52 sub copyFoundSubdocuments($);
53 sub copyJob($$);
54 sub isrelativeFix($$$);
55 sub isrelative($$$);
56 sub createTemporaryFileName($$$);
57 sub copyJobPending($$);
58 sub addNewJob($$$$$);
59 sub addFileCopyJob($$$$$);
60 sub getNewNameOf($$);
61 sub getlangs($$);
62 sub simplifylangs($);
63 sub getLangEntry();
64
65 # convert lyx file to be compilable with xetex
66
67 my ($source, $dest, $format, $fontT, $encodingT, $languageFile, $rest) = @ARGV;
68 my %encodings = ();      # Encoding with TeX fonts, depending on language tag
69
70 diestack("Too many arguments") if (defined($rest));
71 diestack("Sourcefilename not defined") if (! defined($source));
72 diestack("Destfilename not defined") if (! defined($dest));
73 diestack("Format (e.g. pdf4) not defined") if (! defined($format));
74 diestack("Font type (e.g. texF) not defined") if (! defined($fontT));
75 diestack("Encoding (e.g. ascii) not defined") if (! defined($encodingT));
76
77 $source = File::Spec->rel2abs($source);
78 $dest = File::Spec->rel2abs($dest);
79
80 my %font = ();
81 my $lang = "main";
82 if ($source =~ /\/([a-z][a-z](_[A-Z][A-Z])?)[\/_]/) {
83   $lang = $1;
84 }
85
86 my $inputEncoding = undef;
87 if ($fontT eq "systemF") {
88 }
89 elsif ($encodingT ne "default") {
90   # set input encoding to the requested value
91   $inputEncoding = {
92         "search" => '.*', # this will be substituted from '\inputencoding'-line
93         "out" => $encodingT,
94     };
95 }
96 elsif (0) { # set to '1' to enable setting of inputencoding
97   # use tex font here
98   my %encoding = ();
99   if (defined($languageFile)) {
100     # The 2 lines below does not seem to have any effect
101     #&getlangs($languageFile, \%encoding);
102     #&simplifylangs(\%encoding);
103   }
104   if ($format =~ /^(pdf4)$/) { # xelatex
105     # set input encoding to 'ascii' always
106     $inputEncoding = {
107       "search" => '.*', # this will be substituted from '\inputencoding'-line
108       "out" => "ascii",
109     };
110   }
111   elsif ($format =~ /^(dvi3|pdf5)$/) { # (dvi)?lualatex
112     # when to set input encoding to 'ascii'?
113     if (defined($encoding{$lang})) {
114       $inputEncoding = {
115         "search" => '.*', # this will be substituted from '\inputencoding'-line
116         "out" => $encoding{$lang},
117       };
118     }
119   }
120 }
121
122 my $sourcedir = dirname($source);
123 my $destdir = dirname($dest);
124 if (! -d $destdir) {
125   diestack("could not make dir \"$destdir\"") if (! mkpath $destdir);
126 }
127
128 my $destdirOfSubdocuments;
129 {
130   my ($name, $pat, $suffix) = fileparse($source, qr/\.[^.]*/);
131   my $ext = $format . "-$lang";
132   $name =~ s/_/-/g;
133   $destdirOfSubdocuments = "$destdir/tmp-$ext" . "-$name"; # Global var, something TODO here
134 }
135
136 if(-d $destdirOfSubdocuments) {
137   rmtree($destdirOfSubdocuments);
138 }
139 mkpath($destdirOfSubdocuments); #  for possibly included files
140
141 my %IncludedFiles = ();
142 my %type2hash = (
143   "copy_only" => "copyonly",
144   "interpret" => "interpret");
145
146 addNewJob($source, $dest, "interpret", {}, \%IncludedFiles);
147
148 copyFoundSubdocuments(\%IncludedFiles);
149
150 #printCopiedDocuments(\%IncludedFiles);
151
152 exit(0);
153 ###########################################################
154
155 sub printCopiedDocuments($)
156 {
157   my ($rFiles) = @_;
158   for my $k (keys %{$rFiles}) {
159     my $rJob = $rFiles->{$k};
160     for my $j ( values %type2hash) {
161       if (defined($rJob->{$j})) {
162         print "$j: $k->$rJob->{$j}, " . $rJob->{$j . "copied"} . "\n";
163       }
164     }
165   }
166 }
167
168 sub interpretedCopy($$$$)
169 {
170   my ($source, $dest, $destdirOfSubdocuments, $rFiles) = @_;
171   my $sourcedir = dirname($source);
172   my $res = 0;
173
174   diestack("could not read \"$source\"") if (!open(FI, $source));
175   diestack("could not write \"$dest\"") if (! open(FO, '>', $dest));
176
177   initLyxStack(\%font, $fontT, $inputEncoding);
178
179   my $fi_line_no = 0;
180   my @path_errors = ();
181   while (my $l = <FI>) {
182     $fi_line_no += 1;
183     $l =~ s/[\n\r]+$//;
184     #chomp($l);
185     my $rStatus = checkLyxLine($l);
186     if ($rStatus->{found}) {
187       my $rF = $rStatus->{result};
188       if ($rStatus->{"filetype"} eq "replace_only") {
189         # e.g. if no files involved (font chage etc)
190         $l = join('', @{$rF});
191       }
192       else {
193         my $filelist = $rStatus->{filelist};
194         my $fidx = $rStatus->{fileidx};
195         my $separator = $rStatus->{"separator"};
196         my $foundrelative = 0;
197         for my $f (@{$filelist}) {
198           my @isrel = isrelative($f,
199                                   $sourcedir,
200                                   $rStatus->{ext});
201           if ($isrel[0]) {
202             $foundrelative = 1;
203             my $ext = $isrel[1];
204             if ($rStatus->{"filetype"} eq "prefix_only") {
205               $f = getNewNameOf("$sourcedir/$f", $rFiles);
206             }
207             else {
208               my ($newname, $res1);
209               my @extlist = ();
210               if (ref($rStatus->{ext}) eq "ARRAY" && defined($rStatus->{ext}->[1])) {
211                 @extlist = @{$rStatus->{ext}};
212               }
213               else {
214                 @extlist = ($ext);
215               }
216               my $created = 0;
217               for my $extx (@extlist) {
218                 if (-e "$sourcedir/$f$extx") {
219                   ($newname, $res1) = addFileCopyJob("$sourcedir/$f$extx",
220                                                   "$destdirOfSubdocuments",
221                                                   $rStatus->{"filetype"},
222                                                   $rFiles, $created);
223                   print "Added ($res1) file \"$sourcedir/$f$ext\" to be copied to \"$newname\"\n";
224                   if (!$created && $extx ne "") {
225                     $newname =~ s/$extx$//;
226                   }
227                   $created = 1;
228                 }
229               }
230               $f = $newname;
231               $res += $res1;
232             }
233           }
234           else {
235             if (! -e "$f") {
236               # Non relative (e.g. with absolute path) file should exist
237               if ($rStatus->{"filetype"} eq "interpret") {
238                 # filetype::interpret should be interpreted by lyx or latex and therefore emit error
239                 # We prinnt a warning instead
240                 print "WARNING: Interpreted file \"$f\" not found, at \"$source:$fi_line_no\"\n";
241               }
242               elsif ($rStatus->{"filetype"} eq "prefix_only") {
243                 # filetype::prefix_only should be interpreted by latex
244                 print "WARNING: Prefixed file \"$f\" not found, at \"$source:$fi_line_no\"\n";
245               }
246               else {
247                 # Collect the path-error-messages
248                 push(@path_errors, "File \"$f(" . $rStatus->{"filetype"} . ")\" not found, at \"$source:$fi_line_no\"");
249               }
250             }
251           }
252         }
253         if ($foundrelative) {
254           # The result can be relative too
255           my @rel_list = ();
256           for my $fr (@{$filelist}) {
257             push(@rel_list, File::Spec->abs2rel($fr, $destdir));
258           }
259           $rF->[$fidx] = join($separator, @rel_list);
260           $l = join('', @{$rF});
261         }
262       }
263     }
264     print FO "$l\n";
265   }
266   close(FI);
267   close(FO);
268   if (@path_errors > 0) {
269     for my $entry (@path_errors) {
270       print "ERROR: $entry\n";
271     }
272     diestack("Aborted because of path errors in \"$source\"");
273   }
274
275   closeLyxStack();
276   return($res);
277 }
278
279 sub copyFoundSubdocuments($)
280 {
281   my ($rFiles) = @_;
282   my $res = 0;
283   do {
284     $res = 0;
285     my %copylist = ();
286
287     for my $filename (keys  %{$rFiles}) {
288       next if (! copyJobPending($filename, $rFiles));
289       $copylist{$filename} = 1;
290     }
291     for my $f (keys %copylist) {
292       # Second loop needed, because here $rFiles may change
293       my ($res1, @destfiles) = copyJob($f, $rFiles);
294       $res += $res1;
295       for my $destfile (@destfiles) {
296         print "res1 = $res1 for \"$f\" to be copied to $destfile\n";
297       }
298     }
299   } while($res > 0);            #  loop, while $rFiles changed
300 }
301
302 sub copyJob($$)
303 {
304   my ($source, $rFiles) = @_;
305   my $sourcedir = dirname($source);
306   my $res = 0;
307   my @dest = ();
308
309   for my $k (values %type2hash) {
310     if ($rFiles->{$source}->{$k}) {
311       if (! $rFiles->{$source}->{$k . "copied"}) {
312         $rFiles->{$source}->{$k . "copied"} = 1;
313         my $dest = $rFiles->{$source}->{$k};
314         push(@dest, $dest);
315         if ($k =~ /^copyonly/) {
316           diestack("Could not copy \"$source\" to \"$dest\"") if (! cp($source, $dest));
317         }
318         else {
319           interpretedCopy($source, $dest, $destdirOfSubdocuments, $rFiles);
320         }
321         $res += 1;
322       }
323     }
324   }
325   return($res, @dest);
326 }
327
328 # Trivial check
329 sub isrelativeFix($$$)
330 {
331   my ($f, $sourcedir, $ext) = @_;
332
333   return(1, $ext) if  (-e "$sourcedir/$f$ext");
334   return(0,0);
335 }
336
337 sub isrelative($$$)
338 {
339   my ($f, $sourcedir, $ext) = @_;
340
341   if (ref($ext) eq "ARRAY") {
342     for my $ext2 (@{$ext}) {
343       my @res = isrelativeFix($f, $sourcedir, $ext2);
344       if ($res[0]) {
345         return(@res);
346       }
347     }
348     return(0,0);
349   }
350   else {
351     return(isrelativeFix($f, $sourcedir, $ext));
352   }
353 }
354
355 my $oldfname = "";
356
357 sub createTemporaryFileName($$$)
358 {
359   my ($source, $destdir, $created) = @_;
360
361   # get the basename to be used for the template
362   my ($name, $path, $suffix) = fileparse($source, qr/\.[^.]*/);
363   #print "source = $source, name = $name, path = $path, suffix = $suffix\n";
364   my $template = "xx-$name" . "-";
365   my $fname;
366   if (! $created) {
367     $fname = File::Temp::tempnam($destdir, $template);
368     $oldfname = $fname;
369   }
370   else {
371     $fname = $oldfname;
372   }
373
374   # Append extension from source
375   if ($suffix ne "") {
376     $fname .= "$suffix";
377   }
378   return($fname);
379 }
380
381 # Check, if file not copied yet
382 sub copyJobPending($$)
383 {
384   my ($f, $rFiles) = @_;
385   for my $t (values %type2hash) {
386     if (defined($rFiles->{$f}->{$t})) {
387       return 1 if (! $rFiles->{$f}->{$t . "copied"});
388     }
389   }
390   return 0;
391 }
392
393 sub addNewJob($$$$$)
394 {
395   my ($source, $newname, $hashname, $rJob, $rFiles) = @_;
396
397   $rJob->{$hashname} = $newname;
398   $rJob->{$hashname . "copied"} = 0;
399   $rFiles->{$source} = $rJob;
400 }
401
402 sub addFileCopyJob($$$$$)
403 {
404   my ($source, $destdirOfSubdocuments, $filetype, $rFiles, $created) = @_;
405   my ($res, $newname) = (0, undef);
406   my $rJob = $rFiles->{$source};
407
408   my $hashname = $type2hash{$filetype};
409   if (! defined($hashname)) {
410     diestack("unknown filetype \"$filetype\"");
411   }
412   if (!defined($rJob->{$hashname})) {
413     addNewJob($source,
414                createTemporaryFileName($source, $destdirOfSubdocuments, $created),
415                "$hashname", $rJob, $rFiles);
416     $res = 1;
417   }
418   $newname = $rJob->{$hashname};
419   return($newname, $res);
420 }
421
422 sub getNewNameOf($$)
423 {
424   my ($f, $rFiles) = @_;
425   my $resultf = $f;
426
427   if (defined($rFiles->{$f})) {
428     for my $t (values %type2hash) {
429       if (defined($rFiles->{$f}->{$t})) {
430         $resultf = $rFiles->{$f}->{$t};
431         last;
432       }
433     }
434   }
435   return($resultf);
436 }
437
438 sub getlangs($$)
439 {
440   my ($languagefile, $rencoding) = @_;
441
442   if (open(FI, $languagefile)) {
443     while (my $l = <FI>) {
444       if ($l =~ /^Language/) {
445         my ($lng, $enc) = &getLangEntry();
446         if (defined($lng)) {
447           $rencoding->{$lng} = $enc;
448         }
449       }
450     }
451     close(FI);
452   }
453 }
454
455 sub simplifylangs($)
456 {
457   my ($rencoding) = @_;
458   my $base = "";
459   my $enc = "";
460   my $differ = 0;
461   my @klist = ();
462   my @klist2 = ();
463   for my $k (reverse sort keys %{$rencoding}) {
464     my @tag = split('_', $k);
465     if ($tag[0] eq $base) {
466       push(@klist, $k);
467       if ($rencoding->{$k} ne $enc) {
468         $differ = 1;
469       }
470     }
471     else {
472       # new base, check that old base was OK
473       if ($base ne "") {
474         if ($differ == 0) {
475           $rencoding->{$base} = $enc;
476           push(@klist2, @klist);
477         }
478       }
479       @klist = ($k);
480       $base = $tag[0];
481       $enc = $rencoding->{$k};
482       $differ = 0;
483     }
484   }
485   if ($base ne "") {
486     # close handling for last entry too
487     if ($differ == 0) {
488       $rencoding->{$base} = $enc;
489       push(@klist2, @klist);
490     }
491   }
492   for my $k (@klist2) {
493     delete($rencoding->{$k});
494   }
495 }
496
497 sub getLangEntry()
498 {
499   my ($lng, $enc) = (undef, undef);
500   while (my $l = <FI>) {
501     chomp($l);
502     if ($l =~ /^\s*Encoding\s+([^ ]+)\s*$/) {
503       $enc = $1;
504     }
505     elsif ($l =~ /^\s*LangCode\s+([^ ]+)\s*$/) {
506       $lng = $1;
507     }
508     elsif ($l =~ /^\s*End\s*$/) {
509       last;
510     }
511   }
512   if (defined($lng) && defined($enc)) {
513     return($lng, $enc);
514   }
515   else {
516     return(undef, undef);
517   }
518 }