]> git.lyx.org Git - features.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
Fix bug #7850 (Preview of inline math misaligned)
[features.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.atof(match.group(2))
118                 descent = string.atof(match.group(3))
119
120                 frac = 0.5
121                 if ascent == 0 and descent == 0:
122                     # This is an empty image, forbid its display
123                     frac = -1.0
124                 elif ascent >= 0 or descent >= 0:
125                     ascent = ascent + tp_ascent
126                     descent = descent - tp_descent
127
128                     if abs(ascent + descent) > 0.1:
129                         frac = ascent / (ascent + descent)
130
131                     # Sanity check
132                     if frac < 0 or frac > 1:
133                             frac = 0.5
134
135                 results.append((int(match.group(1)), frac))
136
137             else:
138                 tp_descent = string.atof(match.group(2))
139                 tp_ascent  = string.atof(match.group(4))
140
141     except:
142         # Unable to open the file, but do nothing here because
143         # the calling function will act on the value of 'success'.
144         warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
145         warning(`sys.exc_type` + ',' + `sys.exc_value`)
146
147     if success == 0:
148         error("Failed to extract metrics info from %s" % log_file)
149
150     return results
151
152 def extract_resolution(log_file, dpi):
153     fontsize_re = re.compile("Preview: Fontsize")
154     magnification_re = re.compile("Preview: Magnification")
155     extract_decimal_re = re.compile("([0-9\.]+)")
156     extract_integer_re = re.compile("([0-9]+)")
157
158     found_fontsize = 0
159     found_magnification = 0
160
161     # Default values
162     magnification = 1000.0
163     fontsize = 10.0
164
165     try:
166         for line in open(log_file, 'r').readlines():
167             if found_fontsize and found_magnification:
168                 break
169
170             if not found_fontsize:
171                 match = fontsize_re.match(line)
172                 if match != None:
173                     match = extract_decimal_re.search(line)
174                     if match == None:
175                         error("Unable to parse: %s" % line)
176                     fontsize = string.atof(match.group(1))
177                     found_fontsize = 1
178                     continue
179
180             if not found_magnification:
181                 match = magnification_re.match(line)
182                 if match != None:
183                     match = extract_integer_re.search(line)
184                     if match == None:
185                         error("Unable to parse: %s" % line)
186                     magnification = string.atof(match.group(1))
187                     found_magnification = 1
188                     continue
189
190     except:
191         warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
192         warning(`sys.exc_type` + ',' + `sys.exc_value`)
193
194     # This is safe because both fontsize and magnification have
195     # non-zero default values.
196     return dpi * (10.0 / fontsize) * (1000.0 / magnification)
197
198
199 def legacy_latex_file(latex_file, fg_color, bg_color):
200     use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
201     fg_color_gr = make_texcolor(fg_color, True)
202     bg_color_gr = make_texcolor(bg_color, True)
203
204     tmp = mkstemp()
205
206     success = 0
207     try:
208         f = open(latex_file, 'r')
209     except:
210         # Unable to open the file, but do nothing here because
211         # the calling function will act on the value of 'success'.
212         warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
213         warning(`sys.exc_type` + ',' + `sys.exc_value`)
214
215     for line in f.readlines():
216         if success:
217             tmp.write(line)
218             continue
219         match = use_preview_re.match(line)
220         if match == None:
221             tmp.write(line)
222             continue
223         success = 1
224         # Package order: color should be loaded before preview
225         # Preview options: add the options lyx and tightpage
226         tmp.write(r"""
227 \usepackage{color}
228 \definecolor{fg}{rgb}{%s}
229 \definecolor{bg}{rgb}{%s}
230 \pagecolor{bg}
231 \usepackage[%s,tightpage]{preview}
232 \makeatletter
233 \g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
234 \g@addto@macro\endpreview{\endgroup}
235 \makeatother
236 """ % (fg_color_gr, bg_color_gr, match.group(1)))
237
238     if success:
239         copyfileobj(tmp, open(latex_file,"wb"), 1)
240
241     return success
242
243
244 def crop_files(pnmcrop, basename):
245     t = pipes.Template()
246     t.append('%s -left' % pnmcrop, '--')
247     t.append('%s -right' % pnmcrop, '--')
248
249     for file in glob.glob("%s*.ppm" % basename):
250         tmp = mkstemp()
251         new = t.open(file, "r")
252         copyfileobj(new, tmp)
253         if not new.close():
254             copyfileobj(tmp, open(file,"wb"), 1)
255
256
257 def legacy_conversion(argv, skipMetrics = False):
258     # Parse and manipulate the command line arguments.
259     if len(argv) == 7:
260         latex = [argv[6]]
261     elif len(argv) != 6:
262         error(usage(argv[0]))
263     else:
264         latex = None
265
266     dir, latex_file = os.path.split(argv[1])
267     if len(dir) != 0:
268         os.chdir(dir)
269
270     dpi = string.atoi(argv[2])
271
272     output_format = argv[3]
273
274     fg_color = argv[4]
275     bg_color = argv[5]
276
277     # External programs used by the script.
278     latex = find_exe_or_terminate(latex or latex_commands)
279
280     pdf_output = latex in pdflatex_commands
281
282     return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
283         bg_color, latex, pdf_output, skipMetrics)
284
285
286 # Add color info to the latex file, since ghostscript doesn't
287 # have the option to set foreground and background colors on
288 # the command line. Run the resulting file through latex.
289 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
290                             latex, pdf_output = False, skipMetrics = False):
291
292     # Move color information, lyx and tightpage options into the latex file.
293     if not legacy_latex_file(latex_file, fg_color, bg_color):
294         error("""Unable to move the color information, and the lyx and tightpage
295             options of preview-latex, into the latex file""")
296
297     # Compile the latex file.
298     latex_status, latex_stdout = run_latex(latex, latex_file)
299     if latex_status:
300       return (latex_status, [])
301
302     if pdf_output:
303         return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
304     else:
305         return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
306
307 # Creates a new LaTeX file from the original with pages specified in
308 # failed_pages, pass it through pdflatex and updates the metrics
309 # from the standard legacy route
310 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
311     gs_device, gs_ext, alpha, resolution, output_format):
312
313     # Search for pdflatex executable
314     pdflatex = find_exe(["pdflatex"])
315     if pdflatex == None:
316         warning("Can't find pdflatex. Some pages failed with all the possible routes.")
317     else:
318         # Create a new LaTeX file from the original but only with failed pages
319         pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
320         filter_pages(latex_file, pdf_latex_file, failed_pages)
321
322         # pdflatex call
323         pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
324
325         pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
326
327         # GhostScript call to produce bitmaps
328         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
329                     '-sOutputFile="%s%%d.%s" ' \
330                     '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
331                     '-r%f "%s"' \
332                     % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
333                         gs_ext, alpha, alpha, resolution, pdf_file)
334         gs_status, gs_stdout = run_command(gs_call)
335         if gs_status:
336             # Give up!
337             warning("Some pages failed with all the possible routes")
338         else:
339             # We've done it!
340             pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
341             pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
342
343             original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
344             destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
345
346             # Join the metrics with the those from dvips and rename the bitmap images
347             join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
348                 original_bitmap, destination_bitmap)
349
350
351 # The file has been processed through latex and we expect dvi output.
352 # Run dvips, taking note whether it was successful.
353 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
354     # External programs used by the script.
355     dvips   = find_exe_or_terminate(["dvips"])
356
357     # Run the dvi file through dvips.
358     dvi_file = latex_file_re.sub(".dvi", latex_file)
359     ps_file  = latex_file_re.sub(".ps",  latex_file)
360
361     dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
362     dvips_failed = False
363
364     dvips_status, dvips_stdout = run_command(dvips_call)
365     if dvips_status:
366         warning('Failed: %s %s ... looking for PDF' \
367             % (os.path.basename(dvips), dvi_file))
368         dvips_failed = True
369
370     return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
371
372
373 # Either latex and dvips have been run and we have a ps file, or
374 # pdflatex has been run and we have a pdf file. Proceed with gs.
375 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
376     # External programs used by the script.
377     gs      = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
378     pnmcrop = find_exe(["pnmcrop"])
379
380     # Files to process
381     pdf_file  = latex_file_re.sub(".pdf", latex_file)
382     ps_file  = latex_file_re.sub(".ps",  latex_file)
383
384     # Extract resolution data for gs from the log file.
385     log_file = latex_file_re.sub(".log", latex_file)
386     resolution = extract_resolution(log_file, dpi)
387
388     # Older versions of gs have problems with a large degree of
389     # anti-aliasing at high resolutions
390     alpha = 4
391     if resolution > 150:
392         alpha = 2
393
394     gs_device = "png16m"
395     gs_ext = "png"
396     if output_format == "ppm":
397         gs_device = "pnmraw"
398         gs_ext = "ppm"
399
400     # Extract the metrics from the log file
401     legacy_metrics = legacy_extract_metrics_info(log_file)
402
403     # List of pages which failed to produce a correct output
404     failed_pages = []
405
406     # Generate the bitmap images
407     if dvips_failed:
408         # dvips failed, maybe there's a PDF, try to produce bitmaps
409         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
410                   '-sOutputFile="%s%%d.%s" ' \
411                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
412                   '-r%f "%s"' \
413                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
414                      gs_ext, alpha, alpha, resolution, pdf_file)
415
416         gs_status, gs_stdout = run_command(gs_call)
417         if gs_status:
418             error("Failed: %s %s" % (os.path.basename(gs), ps_file))
419     else:
420         # Model for calling gs on each file
421         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
422                   '-sOutputFile="%s%%d.%s" ' \
423                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
424                   '-r%f "%%s"' \
425                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
426                      gs_ext, alpha, alpha, resolution)
427
428         i = 0
429         # Collect all the PostScript files (like *.001, *.002, ...)
430         ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
431         ps_files.sort()
432
433         # Call GhostScript for each file
434         for file in ps_files:
435             i = i + 1
436             progress("Processing page %s, file %s" % (i, file))
437             gs_status, gs_stdout = run_command(gs_call % (i, file))
438             if gs_status:
439                 # gs failed, keep track of this
440                 warning("Ghostscript failed on page %s, file %s" % (i, file))
441                 failed_pages.append(i)
442
443     # Pass failed pages to pdflatex
444     if len(failed_pages) > 0:
445         legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
446             gs_device, gs_ext, alpha, resolution, output_format)
447
448     # Crop the images
449     if pnmcrop != None:
450         crop_files(pnmcrop, latex_file_re.sub("", latex_file))
451
452     # Allow to skip .metrics creation for custom management
453     # (see the dvipng method)
454     if not skipMetrics:
455         # Extract metrics info from the log file.
456         metrics_file = latex_file_re.sub(".metrics", latex_file)
457         write_metrics_info(legacy_metrics, metrics_file)
458
459     return (0, legacy_metrics)
460
461
462 if __name__ == "__main__":
463     sys.exit(legacy_conversion(sys.argv)[0])