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