Debian Codegraph @

texk/texlive/linked_scripts/fragmaster/fragmaster.pl

raw
1 #!/usr/bin/perl -w
2
3 ######################################################################
4 #
5 # fragmaster.pl
6 #
7 # creates EPS and PDF graphics from source EPS and control files
8 # with \psfrag commands
9 #
10 # Version: 1.6
11 #
12 # Copyright (C) 2004 Tilman Vogel <tilman vogel web de> (dot at dot)
13 # Copyright (C) 2011 Agustin Martin <agustin martin hispalinux es> (dot at dot)
14 #
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 2 of the License, or
18 # (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License along
26 # with this program; if not, write to the Free Software Foundation, Inc.,
27 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #
29 # See pod section at the end of this script for more information
30 # ----------------------------------------------------------------------------
31
32 use strict;
33 use Cwd;
34 use File::Temp qw(tempdir);
35 use Pod::Usage;
36
37 my $force;
38 my $debug;
39 my $global_dirfm_mtime;
40 my $global_dirfm_file = "fragmaster.dfm";
41 my $fragmaster_status = "fragmaster.sts";
42 my $global_fmclass = "article";
43 my $global_fmclassopt = "12pt";
44 my $global_fmopt = "";
45 my @global_fmhead = ();
46 my @global_fmfile = ();
47 my %dirdata_last_status = ();
48
49
50 foreach my $option ( @ARGV ){
51 if ( $option eq "--force" ){
52 $force++;
53 } elsif ( $option eq "--debug" ){
54 print STDERR "Debug enabled\n";
55 $debug++;
56 } elsif ( $option =~ s/^--dirfm(=|\#)// ) {
57 if ( -e $option ){
58 $global_dirfm_file = $option;
59 print STDERR "fragmaster: using \"$global_dirfm_file\" directory control file.\n"
60 if $debug;
61 } else {
62 die "fragmaster: Could not find given \"$option\" directory control file. Aborting ....\n";
63 }
64 } elsif ( $option eq "-h" || $option eq "--help" ) {
65 pod2usage(1);
66 exit 1;
67 } elsif ( $option eq "-m" || $option eq "--man" ) {
68 pod2usage(-exitstatus => 0, -verbose => 2);
69 exit 1;
70 } else {
71 print STDERR "\nfragmaster: Unsupported option \"$option\"\n\n";
72 pod2usage(1);
73 exit 1;
74 }
75 }
76
77 # Function definitions
78
79 # ----------------------------------------------------------------------------
80 sub win32_which {
81 # ----------------------------------------------------------------------------
82 # Look if given basename matches a win32 executable under $PATH
83 # ----------------------------------------------------------------------------
84 my $basename = shift;
85 my @extensions = (".exe");
86
87 foreach my $path ( '.', split(';',$ENV{'PATH'}) ){
88 foreach my $ext ( @extensions ){
89 my $exec_location = "$path\\$basename$ext";
90 if ( -x "$exec_location" ){
91 print STDERR "fragmaster: Found gs executable at \"$exec_location\"\n"
92 if $debug;
93 return $basename;
94 } else {
95 print STDERR "fragmaster: No gs executable found at \"$exec_location\"\n"
96 if $debug;
97 }
98 }
99 }
100 }
101
102 # ----------------------------------------------------------------------------
103 sub parse_fmfile {
104 # ----------------------------------------------------------------------------
105 my $file = shift;
106 my %fmdata = ();
107 my @fmfile = (); # A copy of original file
108 my @fmhead = (); # Preamble to use
109 my $fmopt; # Options to \includegraphics
110 my $fmclass; # Class to use
111 my $fmclassopt; # Options for class invocation
112
113 die "fragmaster::parse_fmfile: No file to parse passed as argument. Aborting ...\n"
114 unless $file;
115
116 open FMFILE, "<$file"
117 or die "fragmaster: Cannot read \"$file\"!. Aborting ...\n";
118
119 while (<FMFILE>) {
120 chomp;
121 push @fmfile, " $_%";
122 s/\s+$//; # Strip trailing whitespace
123 $fmopt = $1 if /fmopt:\s*(.*)/;
124 $fmclass = $1 if /fmclass:\s*(.*)/;
125 $fmclassopt = $1 if /fmclassopt:\s*(.*)/;
126 if (/head:/) {
127 while(<FMFILE>) {
128 chomp;
129 push @fmfile, " $_%";
130 last if /end head/;
131 # Remove comment prefix
132 s/^[\s%]*//;
133 push @fmhead, "$_%";
134 }
135 }
136 }
137 close FMFILE;
138 $fmdata{'fmfile'} = \@fmfile if scalar @fmfile;
139 $fmdata{'fmpreamble'} = \@fmhead if scalar @fmhead;
140 $fmdata{'fmclass'} = $fmclass if $fmclass;
141 $fmdata{'fmclassopt'} = $fmclassopt if $fmclassopt;
142 $fmdata{'fmopt'} = $fmopt if $fmopt;
143 print STDERR
144 "fragmaster::parse_fmfile: Keys found in \"$file\": ",
145 join(', ',sort keys %fmdata ), "\n"
146 if $debug;
147 return \%fmdata;
148 }
149
150 # ----------------------------------------------------------------------------
151
152 my $cwd = getcwd;
153
154 die "fragmaster: Current path contains whitespace. LaTeX cannot handle this correctly, move somewhere else. Aborting ... \n"
155 if $cwd =~ /\s/;
156
157 # Get modification time for $global_dirfm_file if exists. Also used as existence flag.
158 $global_dirfm_mtime = -M $global_dirfm_file if ( -e $global_dirfm_file );
159
160 # Look for fragmaster _fm files.
161 my %all_basenames = ();
162 foreach (<*_fm>){
163 s/_fm$//;
164 $all_basenames{$_}++;
165 }
166 die "fragmaster: No fm_files found. Aborting ...\n"
167 unless ( scalar %all_basenames );
168
169 # Check if there is a status file for last processing with dir control file
170 if ( -e $fragmaster_status ){
171 open my $LAST, "< $fragmaster_status"
172 or die "fragmaster: Could not open \"$fragmaster_status\" for read. Aborting ...\n";
173 while ( <$LAST> ){
174 next if m/^\s*\#/;
175 next if m/^\s*~/;
176 chomp;
177 if ( m/^([^:]+):(.*)$/ ) {
178 $dirdata_last_status{$1} = $2;
179 print STDERR "fragmaster: Last dfm used for \"$1\": \"$dirdata_last_status{$1}\"\n"
180 if $debug;
181 } else {
182 print STDERR "fragmaster: Wrongly formatted line in \"$fragmaster_status\": \"$_\". Ignoring ...\n";
183 }
184 }
185 close $LAST;
186 }
187
188 # Remove no longer present files from status file
189 foreach my $base ( sort keys %dirdata_last_status ){
190 delete $dirdata_last_status{$base} unless ( defined $all_basenames{$base} );
191 }
192
193 # For each _fm file found, check if we need to rebuild
194 my %doit_basenames = ();
195 foreach my $base ( sort keys %all_basenames ) {
196 my $fm_file = "$base" . "_fm";
197 my $source = "$fm_file.eps";
198
199 if ( -f $source ) {
200 my $dest_eps = "$base.eps";
201 my $dest_pdf = "$base.pdf";
202 my $do_it = $force;
203
204 unless ( $do_it ) {
205 # Rebuild if there is any mismatch betwen last and current per-dir file.
206 if ( $global_dirfm_mtime ){
207 if ( defined $dirdata_last_status{$base} ){
208 $do_it++ unless ( $global_dirfm_file eq $dirdata_last_status{$base} );
209 } else {
210 $do_it++;
211 }
212 } elsif ( defined $dirdata_last_status{$base} ){
213 $do_it++;
214 }
215 }
216
217 unless ( $do_it ) {
218 if ( -f $dest_eps && -f $dest_pdf ){
219 # Sort after modification times. Redo if any source is newer than any dest.
220 my @dest_stamps = (-M $dest_eps, -M $dest_pdf);
221 my @sources_stamps = (-M $fm_file, -M $source );
222 push @sources_stamps, $global_dirfm_mtime if $global_dirfm_mtime;
223 my $oldest_dest = (sort { $b <=> $a } @dest_stamps)[0];
224 my $youngest_source = (sort { $a <=> $b } @sources_stamps)[0];
225 $do_it++ if $oldest_dest > $youngest_source;
226 } else {
227 $do_it++;
228 }
229 }
230
231 $doit_basenames{$base}++ if $do_it;
232 } else {
233 print "fragmaster: \"$fm_file\" skipped. Cannot find associated EPS file \"$source\".\n";
234 }
235 }
236
237 # Do nothing if targets are up to date and --force was not set
238 unless ( scalar %doit_basenames ){
239 print STDERR "fragmaster: all targets are up-to-date.\n";
240 exit;
241 }
242
243 # Create master tempdir for the temporary files
244 my $base_tempdir =
245 tempdir( "fragmaster.XXXXXX", # Use a fragmaster prefix for base tempdir
246 CLEANUP => ( ! $debug ), # Remove tempdir tree on exit unless $debug
247 DIR => $cwd ) # Create base tempdir under current dir
248 or die "fragmaster: Cannot make temporary directory!";
249 print "fragmaster: Using $base_tempdir/\n";
250
251 # Check which name to use for ghostscript.
252 my $gs_prog = "gs";
253
254 if ( $^O =~ /^MSWin/ ){
255 $gs_prog = win32_which("gswin32c") # Try first standard name
256 || win32_which("mgs") # Be kind with miktex
257 || "gswin32c"; # May be a wrapper with different extension. Try.
258 }
259
260 # If we have a per-directory control file with values set, use them to override defaults.
261 if ( -e $global_dirfm_file ){
262 my $fmdata = parse_fmfile($global_dirfm_file);
263 $global_fmclass = $fmdata->{'fmclass'} if ( defined $fmdata->{'fmclass'} );
264 $global_fmclassopt = $fmdata->{'fmclassopt'} if ( defined $fmdata->{'fmclassopt'} );
265 $global_fmopt = $fmdata->{'fmopt'} if ( defined $fmdata->{'fmopt'} );
266 @global_fmhead = @{$fmdata->{'fmpreamble'}} if ( defined $fmdata->{'fmpreamble'} );
267 }
268
269 # (Re-)build targets
270 foreach my $base ( sort keys %doit_basenames ) {
271 my $fm_file = "$base" . "_fm";
272 my $source = "$fm_file.eps";
273 my $dest_eps = "$base.eps";
274 my $dest_pdf = "$base.pdf";
275
276 print "fragmaster: $fm_file, $source -> $dest_eps, $dest_pdf\n";
277
278 # Parse per-graphic _fm control file
279 my $fmdata = parse_fmfile($fm_file);
280 my $fmclass = ( defined $fmdata->{'fmclass'} ) ? $fmdata->{'fmclass'} : $global_fmclass;
281 my $fmclassopt = ( defined $fmdata->{'fmclassopt'} ) ? $fmdata->{'fmclassopt'} : $global_fmclassopt;
282 my $fmopt = ( defined $fmdata->{'fmopt'} ) ? $fmdata->{'fmopt'} : $global_fmopt;
283 my @fmhead = ( defined $fmdata->{'fmpreamble'} ) ? @{$fmdata->{'fmpreamble'}} : @global_fmhead;
284 my @fmfile = ( defined $fmdata->{'fmfile'} ) ? @{$fmdata->{'fmfile'}} : @global_fmfile;
285
286 my $texstring = "\\documentclass[$fmclassopt]{$fmclass}
287 \\usepackage{graphicx,psfrag,color}
288 ";
289 # Enter heading info
290 $texstring .= "$_\n" foreach (@fmhead);
291
292 $texstring .= '
293 \setlength{\topmargin}{-1in}
294 \setlength{\headheight}{0pt}
295 \setlength{\headsep}{0pt}
296 \setlength{\topskip}{0pt}
297 \setlength{\textheight}{\paperheight}
298 \setlength{\oddsidemargin}{-1in}
299 \setlength{\evensidemargin}{-1in}
300 \setlength{\textwidth}{\paperwidth}
301 \setlength{\parindent}{0pt}
302 \special{! TeXDict begin /landplus90{true}store end }
303 %\special{! statusdict /setpage undef }
304 %\special{! statusdict /setpageparams undef }
305 \pagestyle{empty}
306 \newsavebox{\pict}
307 \graphicspath{{../../}}
308
309 \begin{document}
310 \begin{lrbox}{\pict}%
311 ';
312 $texstring .= "$_\n" foreach (@fmfile);
313 $texstring .= " \\includegraphics[$fmopt]{$source}%\n";
314 $texstring .= ' \end{lrbox}
315 \special{papersize=\the\wd\pict,\the\ht\pict}
316 \usebox{\pict}
317 \end{document}
318 ';
319
320 my $tempdir = "$base_tempdir/$base";
321 mkdir $tempdir;
322
323 # Writing TeX file
324 open TEXFILE, ">$tempdir/fm.tex"
325 or die "fragmaster: Cannot write LaTeX file!";
326 print TEXFILE $texstring;
327 close TEXFILE;
328
329 chdir($tempdir)
330 or die "fragmaster: Cannot chdir to \"$tempdir\"!. Aborting ...\n";
331
332 system("latex fm.tex") == 0
333 or die "fragmaster: Cannot latex \"fm.tex\"!. Aborting ...\n";
334
335 # Using -E here, causes dvips to detect
336 # the psfrag phantom stuff and to set the BoundingBox wrong
337 system("dvips -E -P pdf fm.dvi -o fm.ps") == 0
338 or die "fragmaster: Cannot dvips!. Aborting ...\n";
339
340 chdir($cwd)
341 or die "fragmaster: Cannot chdir back up!. Aborting ...\n";
342
343 # Read original eps file as created by dvips -E.
344 my $psfile;
345 {
346 local $/ = undef;
347 open PS, "<$tempdir/fm.ps"
348 or die "fragmaster: Cannot read \"fm.ps\"!. Aborting ...\n";
349 $psfile = <PS>;
350 close PS;
351 }
352
353 # Calculate real Bounding Box using ghostscript bbox device, also available
354 # in strippped-down texlive gs. Currently, it writes result only to STDERR.
355 my $bbox_line;
356 my $bbox_cmd = "$gs_prog -q -sDEVICE#bbox -dNOPAUSE -dBATCH \"$tempdir/fm.ps\" 2> \"$tempdir/fm.bb\"";
357 print STDERR "fragmaster: $bbox_cmd\n" if $debug;
358 system("$bbox_cmd") == 0
359 or die "fragmaster: Failed to obtain Bounding Box file with ghostscript bbox device.\n";
360 open BB,"<$tempdir/fm.bb"
361 or die "fragmaster: Could not read Bounding Box file \"$tempdir/fm.bb\". Aborting ...\n";
362 while (<BB>) {
363 if ( /^\%\%BoundingBox:/ ){
364 chomp;
365 $bbox_line = $_;
366 last;
367 }
368 }
369 close BB;
370 die "fragmaster: No Bounding Box entry found in \"$tempdir/fm.bb\". Aborting ...\n"
371 unless $bbox_line;
372 print STDERR "fragmaster: $bbox_line\n"
373 if $debug;
374
375 # Fix Bounding Box and write corrected eps file.
376 $psfile =~ s/^\%\%BoundingBox:.*/$bbox_line/m;
377 open EPS, ">$dest_eps"
378 or die "fragmaster: Cannot write \"$dest_eps\"!. Aborting ...\n";
379 print EPS $psfile;
380 close EPS;
381
382 # Create pdf file after corrected ps file.
383 system("epstopdf $dest_eps --outfile=$dest_pdf") == 0
384 or die "fragmaster: Cannot epstopdf!. Aborting ...\n";
385
386 # Update per-dir info in status file if everything was OK. We need to do this
387 # after processing each entry. Otherwise an error may leave things inconsistent.
388 if ( $global_dirfm_mtime ){
389 $dirdata_last_status{$base} = $global_dirfm_file; # Mark per-dir file used
390 } else {
391 delete $dirdata_last_status{$base}; # or leave empty otherwise
392 }
393
394 print STDERR
395 "fragmaster: \"$base\" processed, current files with dfm: \n [" ,
396 join(', ',sort keys %dirdata_last_status),
397 "]\n"
398 if $debug;
399 open my $LAST, "> $fragmaster_status"
400 or die "fragmaster: Could not open \"$fragmaster_status\" for write. Aborting ...\n";
401
402 print $LAST "\# This file is automatically generated by fragmaster. Do not edit.\n";
403 foreach ( sort keys %dirdata_last_status ){
404 print $LAST "$_:$dirdata_last_status{$_}\n";
405 }
406 close $LAST;
407 }
408
409 __END__
410
411 =pod
412
413 =head1 NAME
414
415 fragmaster - Using psfrag constructs with pdflatex
416
417 =head1 SYNOPSIS
418
419 fragmaster [options]
420
421 Create EPS and PDF files with embedded psfrag substitutions.
422
423 Options:
424 -h,--help Brief usage guide.
425 -m,--man Show full man page (needs perldoc)
426 --debug Show more info and leave temporary files behind.
427 --force Rebuild everything ignoring modification times.
428 --dirfm=file Use given file as optional per-directory
429 fragmaster fm control file instead of default
430 "fragmaster.dfm".
431
432 =head1 DESCRIPTION
433
434 B<fragmaster> is a perl script that helps using psfrag constructs with
435 B<pdflatex>.
436
437 B<psfrag> is a LaTeX package which allows to replace text elements in
438 included EPS graphics by arbitrary LaTeX output. Because B<psfrag>
439 uses Postscript for making the replacements, in principle you can't
440 use B<psfrag> with B<pdflatex> which doesn't have any interfaces to
441 postscript.
442
443 B<fragmaster> produces a new EPS from your original EPS which already
444 contains all those B<psfrag> replacements. This new EPS graphic
445 actually can be converted to PDF including all replacements. The
446 resulting "encapsulated" PDF can then be used with pdflatex.
447
448 B<fragmaster> will scan the current directory for files which end in
449 F<_fm> and have a F<_fm.eps> counterpart.
450 Looking at the modification dates, the script checks if the output
451 files have to be rebuilt and does so if necessary
452 (a little like "make" would do it).
453
454 In your LaTeX document you can include the produced graphics using
455
456 \includegraphics{<graphics>}
457
458 conveniently omitting file extension.
459 B<latex> will choose the EPS, B<pdflatex> will choose the PDF.
460
461 =head2 B<fragmaster> control file and other related files.
462
463 To use the script you have to create two files per graphic:
464
465 * <graphics>_fm.eps: the EPS file itself,
466 * <graphics>_fm: a fragmaster control file.
467
468 From these files the psfragged graphics will be created:
469
470 * <graphics>.eps,
471 * <graphics>.pdf
472
473 The F<_fm> control file is basically a LaTeX file
474 (with optionally special comments) and can look like this:
475
476 % Just an ordinary comment
477 %
478 % Some special comments:
479 % fmclass: book
480 % fmclassopt: 11pt
481 % fmopt: width=6cm
482 %
483 % Another special comment:
484 % head:
485 % \usepackage{amsmath}
486 % end head
487
488 % psfrag commands:
489 \psfrag{x}{$x$}
490 \psfrag{y}{$y = x^2$}
491
492 Special comment C<fmclass:> will make the script use given class
493 instead of default C<article> class.
494
495 Special comment C<fmclassopt:> will make the script use given options
496 as class options instead of default C<12pt>.
497
498 The special comment C<fmopt:> will be evaluated such that the
499 following text will by passed as optional argument to
500 C<\includegraphics>.
501 This way you can e.g. adjust the relation between graphics size
502 and font size using something like C<fmopt: width=6cm>.
503 No global default for this.
504
505 The special comment construct C<head:/end head> causes the lines in
506 between to be included in the preamble of the LaTeX temporary document
507 after having the leading comment characters "%" stripped off.
508 This way, you can include LaTeX packages, as in C<\usepackage{amsmath}>.
509 No global default for this.
510
511 =head2 Per-directory B<fragmaster> dir control file.
512
513 You can set per-directory C<fmclass:>, C<fmclassopt:>, C<fmopt:> and
514 C<head:/end head> options by means of a per-directory fragmaster control
515 file F<fragmaster.dfm> with similar syntax as above.
516 You can use another file by means of the B<--dirfm> option.
517 Note that options set this way are mutually exclusive, any option set
518 in per-file F<_fm> file will completely override associated option in
519 per-directory file, and options set in per-directory file will
520 override initial defaults (C<\documentclass[12pt]{article}>).
521 Empty options are ignored.
522
523 This is work in progress and still needs extensive checking. Double-check
524 that modification date based rebuilds are working properly.
525
526 =head1 KNOWN PROBLEMS
527
528 In case the EPS will be produced as landscape graphics, i.e. B<gv> shows
529 I<Landscape> instead of I<Portrait> in the menu bar, and the graphic will
530 end up turned around 90 degrees in your document, then it is likely
531 that your original EPS is wider than it is tall.
532 In this case some (more recent) versions of B<dvips> make the "smart"
533 assumption that your graphic is landscape, even though the graphic's
534 proportions don't tell anything about the orientation of its contents...
535 This still can happen in case your input EPS matches a standard paper size.
536
537 Anyway, you can make B<dvips> behave nicer by specifying the following
538 line in F</usr/share/texmf/dvips/config/config.pdf>
539 (or a local equivalent inside F</usr/local/share/texmf>):
540
541 @ custom 0pt 0pt
542
543 In the likely case that you're wondering why, I'd recommend the
544 B<dvipsk> sources warmly to you...
545
546 =head1 AUTHOR
547
548 Tilman Vogel <tilman vogel web de> (dot at dot) and
549 Agustin Martin <agustin martin hispalinux es> (dot at dot)
550
551 =head1 HISTORY
552
553 This script was inspired by a posting from
554 Karsten Roemke <k roemke gmx de> (dot at dot) with subject
555 "psfrag pdflatex, lange her"
556 in de.comp.text.tex on 2003-11-11 05:25:44 PST.
557
558 Karsten Roemke was inspired for his solution by postings from
559 Thomas Wimmer.
560
561 =head1 COPYRIGHT
562
563 Copyright (C) 2004 Tilman Vogel
564 Copyright (C) 2011 Agustin Martin
565
566 This program is free software; you can redistribute it and/or modify
567 it under the terms of the GNU General Public License as published by
568 the Free Software Foundation; either version 2 of the License, or
569 (at your option) any later version.