]> git.lyx.org Git - lyx.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
Update my email and status.
[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 # * 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 # 0) Process command-line arguments
55 # [legacy_conversion_step1]
56 # 1) Call latex to create a DVI file from LaTeX
57 # [legacy_conversion_step2]
58 # 2) Call dvips to create one PS file for each DVI page
59 # [legacy_conversion_step3]
60 # 3) If dvips fails look for PDF and call gs to produce bitmaps
61 # 4) Otherwise call gs on each PostScript file to produce bitmaps
62 # [legacy_conversion_pdflatex]
63 # 5) Keep track of pages on which gs failed and pass them to pdflatex
64 # 6) Call gs on the PDF output from pdflatex to produce bitmaps
65 # 7) Extract and write to file (or return to lyxpreview2bitmap)
66 #    metrics from both methods (standard and pdflatex)
67
68 # The script uses the old dvi->ps->png conversion route,
69 # which is good when using PSTricks, TikZ or other packages involving
70 # PostScript literals (steps 1, 2, 4).
71 # This script also generates bitmaps from PDF created by a call to
72 # lyxpreview2bitmap.py passing "pdflatex" to the CONVERTER parameter
73 # (step 3).
74 # Finally, there's also has a fallback method based on pdflatex, which
75 # is required in certain cases, if hyperref is active for instance,
76 # (step 5, 6).
77 # If possible, dvipng should be used, as it's much faster.
78
79 import glob, os, pipes, re, string, sys
80
81 from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
82      find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
83      latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
84      run_command, run_latex, warning, write_metrics_info
85
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):
198     use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
199     fg_color_gr = make_texcolor(fg_color, True)
200     bg_color_gr = make_texcolor(bg_color, True)
201
202     tmp = mkstemp()
203
204     success = 0
205     try:
206         f = open(latex_file, 'r')
207     except:
208         # Unable to open the file, but do nothing here because
209         # the calling function will act on the value of 'success'.
210         warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
211         warning(`sys.exc_type` + ',' + `sys.exc_value`)
212
213     for line in f.readlines():
214         if success:
215             tmp.write(line)
216             continue
217         match = use_preview_re.match(line)
218         if match == None:
219             tmp.write(line)
220             continue
221         success = 1
222         # Package order: color should be loaded before preview
223         # Preview options: add the options lyx and tightpage
224         tmp.write(r"""
225 \usepackage{color}
226 \definecolor{fg}{rgb}{%s}
227 \definecolor{bg}{rgb}{%s}
228 \pagecolor{bg}
229 \usepackage[%s,lyx,tightpage]{preview}
230 \makeatletter
231 \g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
232 \g@addto@macro\endpreview{\endgroup}
233 \makeatother
234 """ % (fg_color_gr, bg_color_gr, match.group(1)))
235
236     if success:
237         copyfileobj(tmp, open(latex_file,"wb"), 1)
238
239     return success
240
241
242 def crop_files(pnmcrop, basename):
243     t = pipes.Template()
244     t.append('%s -left' % pnmcrop, '--')
245     t.append('%s -right' % pnmcrop, '--')
246
247     for file in glob.glob("%s*.ppm" % basename):
248         tmp = mkstemp()
249         new = t.open(file, "r")
250         copyfileobj(new, tmp)
251         if not new.close():
252             copyfileobj(tmp, open(file,"wb"), 1)
253
254
255 def legacy_conversion(argv, skipMetrics = False):
256     # Parse and manipulate the command line arguments.
257     if len(argv) == 7:
258         latex = [argv[6]]
259     elif len(argv) != 6:
260         error(usage(argv[0]))
261     else:
262         latex = None
263
264     dir, latex_file = os.path.split(argv[1])
265     if len(dir) != 0:
266         os.chdir(dir)
267
268     dpi = string.atoi(argv[2])
269
270     output_format = argv[3]
271
272     fg_color = argv[4]
273     bg_color = argv[5]
274
275     # External programs used by the script.
276     latex = find_exe_or_terminate(latex or latex_commands)
277
278     pdf_output = latex in pdflatex_commands
279
280     return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
281         bg_color, latex, pdf_output, skipMetrics)
282
283
284 # Add color info to the latex file, since ghostscript doesn't
285 # have the option to set foreground and background colors on
286 # the command line. Run the resulting file through latex.
287 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
288                             latex, pdf_output = False, skipMetrics = False):
289
290     # Move color information, lyx and tightpage options into the latex file.
291     if not legacy_latex_file(latex_file, fg_color, bg_color):
292         error("""Unable to move the color information, and the lyx and tightpage
293             options of preview-latex, into the latex file""")
294
295     # Compile the latex file.
296     latex_status, latex_stdout = run_latex(latex, latex_file)
297
298     if pdf_output:
299         return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
300     else:
301         return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
302
303 # Creates a new LaTeX file from the original with pages specified in
304 # failed_pages, pass it through pdflatex and updates the metrics
305 # from the standard legacy route
306 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
307     gs_device, gs_ext, alpha, resolution, output_format):
308
309     # Search for pdflatex executable
310     pdflatex = find_exe(["pdflatex"])
311     if pdflatex == None:
312         warning("Can't find pdflatex. Some pages failed with all the possible routes.")
313     else:
314         # Create a new LaTeX file from the original but only with failed pages
315         pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
316         filter_pages(latex_file, pdf_latex_file, failed_pages)
317
318         # pdflatex call
319         pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
320
321         pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
322
323         # GhostScript call to produce bitmaps
324         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
325                     '-sOutputFile="%s%%d.%s" ' \
326                     '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
327                     '-r%f "%s"' \
328                     % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
329                         gs_ext, alpha, alpha, resolution, pdf_file)
330         gs_status, gs_stdout = run_command(gs_call)
331         if gs_status:
332             # Give up!
333             warning("Some pages failed with all the possible routes")
334         else:
335             # We've done it!
336             pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
337             pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
338
339             original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
340             destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
341
342             # Join the metrics with the those from dvips and rename the bitmap images
343             join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
344                 original_bitmap, destination_bitmap)
345
346
347 # The file has been processed through latex and we expect dvi output.
348 # Run dvips, taking note whether it was successful.
349 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
350     # External programs used by the script.
351     dvips   = find_exe_or_terminate(["dvips"])
352
353     # Run the dvi file through dvips.
354     dvi_file = latex_file_re.sub(".dvi", latex_file)
355     ps_file  = latex_file_re.sub(".ps",  latex_file)
356
357     dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
358     dvips_failed = False
359
360     dvips_status, dvips_stdout = run_command(dvips_call)
361     if dvips_status:
362         warning('Failed: %s %s ... looking for PDF' \
363             % (os.path.basename(dvips), dvi_file))
364         dvips_failed = True
365
366     return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
367
368
369 # Either latex and dvips have been run and we have a ps file, or
370 # pdflatex has been run and we have a pdf file. Proceed with gs.
371 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
372     # External programs used by the script.
373     gs      = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
374     pnmcrop = find_exe(["pnmcrop"])
375
376     # Files to process
377     pdf_file  = latex_file_re.sub(".pdf", latex_file)
378     ps_file  = latex_file_re.sub(".ps",  latex_file)
379
380     # Extract resolution data for gs from the log file.
381     log_file = latex_file_re.sub(".log", latex_file)
382     resolution = extract_resolution(log_file, dpi)
383
384     # Older versions of gs have problems with a large degree of
385     # anti-aliasing at high resolutions
386     alpha = 4
387     if resolution > 150:
388         alpha = 2
389
390     gs_device = "png16m"
391     gs_ext = "png"
392     if output_format == "ppm":
393         gs_device = "pnmraw"
394         gs_ext = "ppm"
395
396     # Extract the metrics from the log file
397     legacy_metrics = legacy_extract_metrics_info(log_file)
398
399     # List of pages which failed to produce a correct output
400     failed_pages = []
401
402     # Generate the bitmap images
403     if dvips_failed:
404         # dvips failed, maybe there's a PDF, try to produce bitmaps
405         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
406                   '-sOutputFile="%s%%d.%s" ' \
407                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
408                   '-r%f "%s"' \
409                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
410                      gs_ext, alpha, alpha, resolution, pdf_file)
411
412         gs_status, gs_stdout = run_command(gs_call)
413         if gs_status:
414             error("Failed: %s %s" % (os.path.basename(gs), ps_file))
415     else:
416         # Model for calling gs on each file
417         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
418                   '-sOutputFile="%s%%d.%s" ' \
419                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
420                   '-r%f "%%s"' \
421                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
422                      gs_ext, alpha, alpha, resolution)
423
424         i = 0
425         # Collect all the PostScript files (like *.001, *.002, ...)
426         ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
427         ps_files.sort()
428
429         # Call GhostScript for each file
430         for file in ps_files:
431             i = i + 1
432             progress("Processing page %s, file %s" % (i, file))
433             gs_status, gs_stdout = run_command(gs_call % (i, file))
434             if gs_status:
435                 # gs failed, keep track of this
436                 warning("Ghostscript failed on page %s, file %s" % (i, file))
437                 failed_pages.append(i)
438
439     # Pass failed pages to pdflatex
440     if len(failed_pages) > 0:
441         legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
442             gs_device, gs_ext, alpha, resolution, output_format)
443
444     # Crop the images
445     if pnmcrop != None:
446         crop_files(pnmcrop, latex_file_re.sub("", latex_file))
447
448     # Allow to skip .metrics creation for custom management
449     # (see the dvipng method)
450     if not skipMetrics:
451         # Extract metrics info from the log file.
452         metrics_file = latex_file_re.sub(".metrics", latex_file)
453         write_metrics_info(legacy_metrics, metrics_file)
454
455     return (0, legacy_metrics)
456
457
458 if __name__ == "__main__":
459     sys.exit(legacy_conversion(sys.argv)[0])