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