]> git.lyx.org Git - lyx.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
Mostly documentation for the pythonic part of instant preview.
[lyx.git] / lib / scripts / legacy_lyxpreview2ppm.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file legacy_lyxpreview2ppm.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Angus Leeming
9 # Full author contact details are available in file CREDITS
10
11 # with much advice from members of the preview-latex project:
12 #   David Kastrup, dak@gnu.org and
13 #   Jan-Åke Larsson, jalar@mai.liu.se.
14 # and with much help testing the code under Windows from
15 #   Paul A. Rubin, rubin@msu.edu.
16
17 # This script takes a LaTeX file and generates a collection of
18 # png or ppm image files, one per previewed snippet.
19 # Example usage:
20 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
21
22 # This script takes five arguments:
23 # TEXFILE:       the name of the .tex file to be converted.
24 # SCALEFACTOR:   a scale factor, used to ascertain the resolution of the
25 #                generated image which is then passed to gs.
26 # OUTPUTFORMAT:  the format of the output bitmap image files.
27 #                This particular script can produce only "ppm" format output.
28 # FG_COLOR:      the foreground color as a hexadecimal string, eg '000000'.
29 # BG_COLOR:      the background color as a hexadecimal string, eg 'faf0e6'.
30
31 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
32 # if executed successfully, leave in DIR:
33 # * a (possibly large) number of image files with names
34 #   like BASE[0-9]+.(ppm|png)
35 # * a file BASE.metrics, containing info needed by LyX to position
36 #   the images correctly on the screen.
37
38 # The script uses several external programs and files:
39 # * A latex executable;
40 # * preview.sty;
41 # * dvips;
42 # * gs;
43 # * pdflatex (optional);
44 # * pnmcrop (optional).
45
46 # preview.sty is part of the preview-latex project
47 #   http://preview-latex.sourceforge.net/
48 # Alternatively, it can be obtained from
49 #   CTAN/support/preview-latex/
50
51 # What does this script do?
52 # [legacy_conversion]
53 # 1) Call latex to create a DVI file from LaTeX
54 # [legacy_conversion_step2]
55 # 2) Call dvips to create one PS file for each DVI page
56 # 3) If dvips fails look for PDF and call gs to produce bitmaps
57 # 4) Otherwise call gs on each PostScript file to produce bitmaps
58 # [legacy_conversion_pdflatex]
59 # 5) Keep track of pages on which gs failed and pass them to pdflatex
60 # 6) Call gs on the PDF output from pdflatex to produce bitmaps
61 # 7) Extract and write to file (or return to lyxpreview2bitmap) 
62 #    metrics from both methods (standard and pdflatex)
63
64 # The script uses the old dvi->ps->png conversion route,
65 # which is good when using PSTricks, TikZ or other packages involving
66 # PostScript literals (steps 1, 2, 4).
67 # This script also generates bitmaps from PDF created by a call to
68 # lyxpreview2bitmap.py passing "pdflatex" to the CONVERTER parameter
69 # (step 3).
70 # Finally, there's also has a fallback method based on pdflatex, which 
71 # is required in certain cases, if hyperref is active for instance,
72 # (step 5, 6).
73 # If possible, dvipng should be used, as it's much faster.
74
75 import glob, os, pipes, re, string, sys
76
77 from lyxpreview_tools import copyfileobj, error, find_exe, \
78      find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning, \
79      write_metrics_info, filter_pages, join_metrics_and_rename
80
81 # Pre-compiled regular expression.
82 latex_file_re = re.compile("\.tex$")
83
84 # PATH environment variable
85 path  = string.split(os.environ["PATH"], os.pathsep)
86
87 def usage(prog_name):
88     return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n"\
89            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
90            % prog_name
91
92 # Returns a list of tuples containing page number and ascent fraction
93 # extracted from dvipng output.
94 # Use write_metrics_info to create the .metrics file with this info
95 def legacy_extract_metrics_info(log_file):
96
97     log_re = re.compile("Preview: ([ST])")
98     data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
99
100     tp_ascent  = 0.0
101     tp_descent = 0.0
102
103     success = 0
104     results = []
105     try:
106         for line in open(log_file, 'r').readlines():
107             match = log_re.match(line)
108             if match == None:
109                 continue
110
111             snippet = (match.group(1) == 'S')
112             success = 1
113             match = data_re.search(line)
114             if match == None:
115                 error("Unexpected data in %s\n%s" % (log_file, line))
116
117             if snippet:
118                 ascent  = string.atoi(match.group(2))
119                 descent = string.atoi(match.group(3))
120
121                 frac = 0.5
122                 if ascent >= 0 and descent >= 0:
123                     ascent = float(ascent) + tp_ascent
124                     descent = float(descent) - tp_descent
125
126                     if abs(ascent + descent) > 0.1:
127                         frac = ascent / (ascent + descent)
128
129                     # Sanity check
130                     if frac < 0 or frac > 1:
131                             frac = 0.5
132
133                 results.append((int(match.group(1)), frac))
134
135             else:
136                 tp_descent = string.atof(match.group(2))
137                 tp_ascent  = string.atof(match.group(4))
138
139     except:
140         # Unable to open the file, but do nothing here because
141         # the calling function will act on the value of 'success'.
142         warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
143         warning(`sys.exc_type` + ',' + `sys.exc_value`)
144                 
145     if success == 0:
146         error("Failed to extract metrics info from %s" % log_file)
147         
148     return results
149
150 def extract_resolution(log_file, dpi):
151     fontsize_re = re.compile("Preview: Fontsize")
152     magnification_re = re.compile("Preview: Magnification")
153     extract_decimal_re = re.compile("([0-9\.]+)")
154     extract_integer_re = re.compile("([0-9]+)")
155
156     found_fontsize = 0
157     found_magnification = 0
158
159     # Default values
160     magnification = 1000.0
161     fontsize = 10.0
162
163     try:
164         for line in open(log_file, 'r').readlines():
165             if found_fontsize and found_magnification:
166                 break
167
168             if not found_fontsize:
169                 match = fontsize_re.match(line)
170                 if match != None:
171                     match = extract_decimal_re.search(line)
172                     if match == None:
173                         error("Unable to parse: %s" % line)
174                     fontsize = string.atof(match.group(1))
175                     found_fontsize = 1
176                     continue
177
178             if not found_magnification:
179                 match = magnification_re.match(line)
180                 if match != None:
181                     match = extract_integer_re.search(line)
182                     if match == None:
183                         error("Unable to parse: %s" % line)
184                     magnification = string.atof(match.group(1))
185                     found_magnification = 1
186                     continue
187
188     except:
189         warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
190         warning(`sys.exc_type` + ',' + `sys.exc_value`)
191
192     # This is safe because both fontsize and magnification have
193     # non-zero default values.
194     return dpi * (10.0 / fontsize) * (1000.0 / magnification)
195
196
197 def legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
198     use_preview_dvi_re = re.compile("(\s*\\\\usepackage\[[^]]+)(dvips\]{preview})")
199     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
200
201     tmp = mkstemp()
202
203     success = 0
204     try:
205         for line in open(latex_file, 'r').readlines():
206             match = use_preview_dvi_re.match(line)
207             if match == None:
208                 match = use_preview_pdf_re.match(line)
209                 if match == None:
210                     tmp.write(line)
211                     continue
212                 success = 1
213                 tmp.write("  \\usepackage{color}\n" \
214                       "  \\pagecolor[rgb]{%s}\n" \
215                       "%s\n" \
216                       % (bg_color_gr, match.group()))
217                 continue
218
219             success = 1
220             tmp.write("%stightpage,%s\n" \
221                       "  \\AtBeginDocument{\\AtBeginDvi{%%\n" \
222                       "  \\special{!userdict begin/bop-hook{//bop-hook exec\n" \
223                       "  <%s%s>{255 div}forall setrgbcolor\n" \
224                       "  clippath fill setrgbcolor}bind def end}}}\n" \
225                       % (match.group(1), match.group(2), fg_color, bg_color))
226
227     except:
228         # Unable to open the file, but do nothing here because
229         # the calling function will act on the value of 'success'.
230         warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
231         warning(`sys.exc_type` + ',' + `sys.exc_value`)
232
233     if success:
234         copyfileobj(tmp, open(latex_file,"wb"), 1)
235
236     return success
237
238
239 def crop_files(pnmcrop, basename):
240     t = pipes.Template()
241     t.append('%s -left' % pnmcrop, '--')
242     t.append('%s -right' % pnmcrop, '--')
243
244     for file in glob.glob("%s*.ppm" % basename):
245         tmp = mkstemp()
246         new = t.open(file, "r")
247         copyfileobj(new, tmp)
248         if not new.close():
249             copyfileobj(tmp, open(file,"wb"), 1)
250
251
252 def legacy_conversion(argv, skipMetrics = False):
253     latex_commands = ["latex", "pplatex", "platex", "latex2e"]
254     # Parse and manipulate the command line arguments.
255     if len(argv) == 7:
256         latex_commands = [argv[6]]
257     elif len(argv) != 6:
258         error(usage(argv[0]))
259
260     dir, latex_file = os.path.split(argv[1])
261     if len(dir) != 0:
262         os.chdir(dir)
263
264     dpi = string.atoi(argv[2])
265
266     output_format = argv[3]
267
268     fg_color = argv[4]
269     bg_color = argv[5]
270     bg_color_gr = make_texcolor(argv[5], True)
271
272     # External programs used by the script.
273     latex = find_exe_or_terminate(latex_commands, path)
274
275     # Move color information into the latex file.
276     if not legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
277         error("Unable to move color info into the latex file")
278
279     # Compile the latex file.
280     latex_call = '%s "%s"' % (latex, latex_file)
281
282     latex_status, latex_stdout = run_command(latex_call)
283     if latex_status != None:
284         warning("%s had problems compiling %s" \
285               % (os.path.basename(latex), latex_file))
286
287     return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
288
289 # Creates a new LaTeX file from the original with pages specified in 
290 # failed_pages, pass it through pdflatex and updates the metrics
291 # from the standard legacy route
292 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs, 
293     gs_device, gs_ext, alpha, resolution, output_format):
294         
295     # Search for pdflatex executable
296     pdflatex = find_exe(["pdflatex"], path)
297     if pdflatex == None:
298         warning("Can't find pdflatex. Some pages failed with all the possible routes.")
299     else:
300         # Create a new LaTeX file from the original but only with failed pages
301         pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
302         filter_pages(latex_file, pdf_latex_file, failed_pages)
303             
304         # pdflatex call
305         pdflatex_call = '%s "%s"' % (pdflatex, pdf_latex_file)
306         pdflatex_status, pdflatex_stdout = run_command(pdflatex_call)
307             
308         pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
309             
310         # GhostScript call to produce bitmaps
311         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
312                     '-sOutputFile="%s%%d.%s" ' \
313                     '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
314                     '-r%f "%s"' \
315                     % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
316                         gs_ext, alpha, alpha, resolution, pdf_file)
317         gs_status, gs_stdout = run_command(gs_call)
318         if gs_status != None:
319             # Give up!
320             warning("Some pages failed with all the possible routes")
321         else:
322             # We've done it!
323             pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
324             pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
325                 
326             original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
327             destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
328                 
329             # Join the metrics with the those from dvips and rename the bitmap images
330             join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages, 
331                 original_bitmap, destination_bitmap)
332
333
334 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
335     # External programs used by the script.
336     dvips   = find_exe_or_terminate(["dvips"], path)
337     gs      = find_exe_or_terminate(["gswin32c", "gs"], path)
338     pnmcrop = find_exe(["pnmcrop"], path)
339
340     # Run the dvi file through dvips.
341     dvi_file = latex_file_re.sub(".dvi", latex_file)
342     ps_file  = latex_file_re.sub(".ps",  latex_file)
343     pdf_file  = latex_file_re.sub(".pdf", latex_file)
344
345     dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
346     dvips_failed = False
347
348     dvips_status, dvips_stdout = run_command(dvips_call)
349     if dvips_status != None:
350         warning('Failed: %s %s ... looking for PDF' \
351             % (os.path.basename(dvips), dvi_file))
352         dvips_failed = True
353
354     # Extract resolution data for gs from the log file.
355     log_file = latex_file_re.sub(".log", latex_file)
356     resolution = extract_resolution(log_file, dpi)
357
358     # Older versions of gs have problems with a large degree of
359     # anti-aliasing at high resolutions
360     alpha = 4
361     if resolution > 150:
362         alpha = 2
363
364     gs_device = "png16m"
365     gs_ext = "png"
366     if output_format == "ppm":
367         gs_device = "pnmraw"
368         gs_ext = "ppm"
369
370     # Extract the metrics from the log file
371     legacy_metrics = legacy_extract_metrics_info(log_file)
372     
373     # List of pages which failed to produce a correct output
374     failed_pages = []
375     
376     # Generate the bitmap images
377     if dvips_failed:
378         # dvips failed, maybe there's a PDF, try to produce bitmaps
379         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
380                   '-sOutputFile="%s%%d.%s" ' \
381                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
382                   '-r%f "%s"' \
383                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
384                      gs_ext, alpha, alpha, resolution, pdf_file)
385
386         gs_status, gs_stdout = run_command(gs_call)
387         if gs_status != None:
388             error("Failed: %s %s" % (os.path.basename(gs), ps_file))
389     else:
390         # Model for calling gs on each file
391         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
392                   '-sOutputFile="%s%%d.%s" ' \
393                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
394                   '-r%f "%%s"' \
395                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
396                      gs_ext, alpha, alpha, resolution)
397         
398         i = 0
399         # Collect all the PostScript files (like *.001, *.002, ...)
400         ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
401         ps_files.sort()
402         
403         # Call GhostScript for each file
404         for file in ps_files:
405             i = i + 1
406             gs_status, gs_stdout = run_command(gs_call % (i, file))
407             if gs_status != None:
408                 # gs failed, keep track of this
409                 failed_pages.append(i)
410     
411     # Pass failed pages to pdflatex
412     if len(failed_pages) > 0:
413         legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs, 
414             gs_device, gs_ext, alpha, resolution, output_format)
415
416     # Crop the images
417     if pnmcrop != None:
418         crop_files(pnmcrop, latex_file_re.sub("", latex_file))
419
420     # Allow to skip .metrics creation for custom management
421     # (see the dvipng method)
422     if not skipMetrics:
423         # Extract metrics info from the log file.
424         metrics_file = latex_file_re.sub(".metrics", latex_file)
425         write_metrics_info(legacy_metrics, metrics_file)
426
427     return (0, legacy_metrics)
428
429
430 if __name__ == "__main__":
431     exit(legacy_conversion(sys.argv)[0])