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