]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
7929ae014ef4b2bc77ab21da799469666bba1447
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpreview2bitmap.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 # with much advice from members of the preview-latex project:
10 # David Kastrup, dak@gnu.org and
11 # Jan-Åke Larsson, jalar@mai.liu.se.
12
13 # Full author contact details are available in file CREDITS
14
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
17
18 # Pre-requisites:
19 # * A latex executable;
20 # * preview.sty;
21 # * dvipng;
22 # * dv2dt;
23 # * pngtoppm (if outputing ppm format images).
24
25 # preview.sty and dvipng are part of the preview-latex project
26 # http://preview-latex.sourceforge.net/
27
28 # preview.sty can alternatively be obtained from
29 # CTAN/support/preview-latex/
30
31 # Example usage:
32 # lyxpreview2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
33
34 # This script takes six arguments:
35 # FORMAT:   The desired output format. Either 'png' or 'ppm'.
36 # TEXFILE:  the name of the .tex file to be converted.
37 # DPI:      a scale factor, used to ascertain the resolution of the
38 #           generated image which is then passed to gs.
39 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
40 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
41 # CONVERTER: the converter (optional). Default is latex.
42
43 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
44 # if executed successfully, leave in DIR:
45 # * a (possibly large) number of image files with names
46 #   like BASE[0-9]+.png
47 # * a file BASE.metrics, containing info needed by LyX to position
48 #   the images correctly on the screen.
49
50 # What does this script do?
51 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
52 # 2) If the output is a PDF fallback to legacy
53 # 3) Otherwise check each page of the DVI (with dv2dt) looking for 
54 #    PostScript literals, not well supported by dvipng. Pages 
55 #    containing them are passed to the legacy method in a new LaTeX file.
56 # 4) Call dvipng on the pages without PS literals
57 # 5) Join metrics info coming from both methods (legacy and dvipng)
58 #    and write them to file
59
60 # dvipng is fast but gives problem in several cases, like with
61 # PSTricks, TikZ and other packages using PostScript literals
62 # for all these cases the legacy route is taken (step 3).
63 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
64 # paramter is pdflatex we have to fallback to legacy route (step 2).
65
66 import glob, os, re, string, sys
67
68 from legacy_lyxpreview2ppm import legacy_conversion, \
69      legacy_conversion_step2, legacy_extract_metrics_info, filter_pages
70      
71 from lyxpreview_tools import copyfileobj, error, find_exe, \
72      find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning, \
73      write_metrics_info, join_metrics_and_rename
74
75
76 # Pre-compiled regular expressions.
77 latex_file_re = re.compile("\.tex$")
78
79 # PATH environment variable
80 path  = string.split(os.environ["PATH"], os.pathsep)
81
82 def usage(prog_name):
83     return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
84            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
85            % prog_name
86     
87 # Returns a list of tuples containing page number and ascent fraction
88 # extracted from dvipng output.
89 # Use write_metrics_info to create the .metrics file with this info
90 def extract_metrics_info(dvipng_stdout):
91     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
92     # and glyph numbers from mktexpk. The glyph numbers always match
93     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
94     page_re = re.compile("\[([0-9]+)[^]]");
95     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
96
97     success = 0
98     page = ""
99     pos = 0
100     results = []
101     while 1:
102         match = page_re.search(dvipng_stdout, pos)
103         if match == None:
104             break
105         page = match.group(1)
106         pos = match.end()
107         match = metrics_re.search(dvipng_stdout, pos)
108         if match == None:
109             break
110         success = 1
111
112         # Calculate the 'ascent fraction'.
113         descent = string.atof(match.group(1))
114         ascent  = string.atof(match.group(2))
115
116         frac = 0.5
117         if ascent >= 0 or descent >= 0:
118             if abs(ascent + descent) > 0.1:
119                 frac = ascent / (ascent + descent)
120
121             # Sanity check
122             if frac < 0:
123                 frac = 0.5
124
125         results.append((int(page), frac))
126         pos = match.end() + 2
127
128     if success == 0:
129         error("Failed to extract metrics info from dvipng")
130     
131     return results
132
133
134 def color_pdf(latex_file, bg_color, fg_color):
135     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
136
137     tmp = mkstemp()
138     
139     fg = ""
140     if fg_color != "0.000000,0.000000,0.000000":
141         fg = '  \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
142     
143     success = 0
144     try:
145         for line in open(latex_file, 'r').readlines():
146             match = use_preview_pdf_re.match(line)
147             if match == None:
148                 tmp.write(line)
149                 continue
150             success = 1
151             tmp.write("  \\usepackage{color}\n" \
152                   "  \\pagecolor[rgb]{%s}\n" \
153                   "%s" \
154                   "%s\n" \
155                   % (bg_color, fg, match.group()))
156             continue
157
158     except:
159         # Unable to open the file, but do nothing here because
160         # the calling function will act on the value of 'success'.
161         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
162         warning(`sys.exc_type` + ',' + `sys.exc_value`)
163
164     if success:
165         copyfileobj(tmp, open(latex_file,"wb"), 1)
166
167     return success
168
169
170 def fix_latex_file(latex_file):
171     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt)(.)(.+)")
172
173     tmp = mkstemp()
174
175     changed = 0
176     for line in open(latex_file, 'r').readlines():
177         match = documentclass_re.match(line)
178         if match == None:
179             tmp.write(line)
180             continue
181
182         changed = 1
183         tmp.write("%s%s%s\n" % (match.group(1), match.group(3), match.group(4)))
184
185     if changed:
186         copyfileobj(tmp, open(latex_file,"wb"), 1)
187
188     return
189
190
191 def convert_to_ppm_format(pngtopnm, basename):
192     png_file_re = re.compile("\.png$")
193
194     for png_file in glob.glob("%s*.png" % basename):
195         ppm_file = png_file_re.sub(".ppm", png_file)
196
197         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
198         p2p_status, p2p_stdout = run_command(p2p_cmd)
199         if p2p_status != None:
200             error("Unable to convert %s to ppm format" % png_file)
201
202         ppm = open(ppm_file, 'w')
203         ppm.write(p2p_stdout)
204         os.remove(png_file)
205
206 # Returns a tuple of:
207 # ps_pages: list of page indexes of pages containing PS literals
208 # page_count: total number of pages
209 # pages_parameter: parameter for dvipng to exclude pages with PostScript
210 def find_ps_pages(dvi_file):
211     # latex failed
212     # FIXME: try with pdflatex
213     if not os.path.isfile(dvi_file):
214         error("No DVI output.")
215         
216     # Check for PostScript specials in the dvi, badly supported by dvipng
217     # This is required for correct rendering of PSTricks and TikZ
218     dv2dt = find_exe_or_terminate(["dv2dt"], path)
219     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
220  
221     # The output from dv2dt goes to stdout
222     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
223     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
224
225     # Parse the dtl file looking for PostScript specials.
226     # Pages using PostScript specials are recorded in ps_pages and then
227     # used to create a different LaTeX file for processing in legacy mode.
228     page_has_ps = False
229     page_index = 0
230     ps_pages = []
231
232     for line in dv2dt_output.split("\n"):
233         # New page
234         if line.startswith("bop"):
235             page_has_ps = False
236             page_index += 1
237
238         # End of page
239         if line.startswith("eop") and page_has_ps:
240             # We save in a list all the PostScript pages
241             ps_pages.append(page_index)
242
243         if psliteral_re.match(line) != None:
244             # Literal PostScript special detected!
245             page_has_ps = True
246     
247     # Create the -pp parameter for dvipng
248     pages_parameter = ""
249     if len(ps_pages) > 0 and len(ps_pages) < page_index:
250         # Don't process Postscript pages with dvipng by selecting the
251         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
252         pages_parameter = " -pp "
253         skip = True
254         last = -1
255
256         # Use page ranges, as a list of pages could exceed command line
257         # maximum length (especially under Win32)
258         for index in xrange(1, page_index + 1):
259             if (not index in ps_pages) and skip:
260                 # We were skipping pages but current page shouldn't be skipped.
261                 # Add this page to -pp, it could stay alone or become the
262                 # start of a range.
263                 pages_parameter += str(index)
264                 # Save the starting index to avoid things such as "11-11"
265                 last = index
266                 # We're not skipping anymore
267                 skip = False
268             elif (index in ps_pages) and (not skip):
269                 # We weren't skipping but current page should be skipped
270                 if last != index - 1:
271                     # If the start index of the range is the previous page
272                     # then it's not a range
273                     pages_parameter += "-" + str(index - 1)
274
275                 # Add a separator
276                 pages_parameter += ","
277                 # Now we're skipping
278                 skip = True
279
280         # Remove the trailing separator
281         pages_parameter = pages_parameter.rstrip(",")
282         # We've to manage the case in which the last page is closing a range
283         if (not index in ps_pages) and (not skip) and (last != index):
284                 pages_parameter += "-" + str(index)
285
286     return (ps_pages, page_index, pages_parameter)
287
288 def main(argv):
289     # Parse and manipulate the command line arguments.
290     if len(argv) != 6 and len(argv) != 7:
291         error(usage(argv[0]))
292
293     output_format = string.lower(argv[1])
294
295     dir, latex_file = os.path.split(argv[2])
296     if len(dir) != 0:
297         os.chdir(dir)
298
299     dpi = string.atoi(argv[3])
300     fg_color = make_texcolor(argv[4], False)
301     bg_color = make_texcolor(argv[5], False)
302
303     fg_color_gr = make_texcolor(argv[4], True)
304     bg_color_gr = make_texcolor(argv[5], True)
305
306     # External programs used by the script.
307     if len(argv) == 7:
308         latex = argv[6]
309     else:
310         latex = find_exe_or_terminate(["latex", "pplatex", "platex", "latex2e"], path)
311
312     # Omit font size specification in latex file.
313     fix_latex_file(latex_file)
314
315     # This can go once dvipng becomes widespread.
316     dvipng = find_exe(["dvipng"], path)
317     if dvipng == None:
318         # The data is input to legacy_conversion in as similar
319         # as possible a manner to that input to the code used in
320         # LyX 1.3.x.
321         vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex ]
322         return legacy_conversion(vec)
323
324     pngtopnm = ""
325     if output_format == "ppm":
326         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
327
328     # Move color information for PDF into the latex file.
329     if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
330         error("Unable to move color info into the latex file")
331
332     # Compile the latex file.
333     latex_call = '%s "%s"' % (latex, latex_file)
334
335     latex_status, latex_stdout = run_command(latex_call)
336     if latex_status != None:
337         warning("%s had problems compiling %s" \
338               % (os.path.basename(latex), latex_file))
339
340     if latex == "xelatex":
341         warning("Using XeTeX")
342         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
343         return legacy_conversion_step2(latex_file, dpi, output_format)
344
345     # The dvi output file name
346     dvi_file = latex_file_re.sub(".dvi", latex_file)
347
348     # If there's no DVI output, look for PDF and go to legacy or fail
349     if not os.path.isfile(dvi_file):
350         # No DVI, is there a PDF?
351         pdf_file = latex_file_re.sub(".pdf", latex_file)
352         if os.path.isfile(pdf_file):
353             warning("%s produced a PDF output, fallback to legacy." % \
354                 (os.path.basename(latex)))
355             return legacy_conversion_step2(latex_file, dpi, output_format)
356         else:
357             error("No DVI or PDF output. %s failed." \
358                 % (os.path.basename(latex)))
359
360     # Look for PS literals in DVI pages
361     # ps_pages: list of page indexes of pages containing PS literals
362     # page_count: total number of pages
363     # pages_parameter: parameter for dvipng to exclude pages with PostScript
364     (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
365     
366     # If all pages need PostScript, directly use the legacy method.
367     if len(ps_pages) == page_count:
368         vec = [argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex]
369         return legacy_conversion(vec)
370
371     # Run the dvi file through dvipng.
372     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
373                   % (dvipng, dpi, fg_color, bg_color, pages_parameter, dvi_file)
374     dvipng_status, dvipng_stdout = run_command(dvipng_call)
375
376     if dvipng_status != None:
377         warning("%s failed to generate images from %s... fallback to legacy method" \
378               % (os.path.basename(dvipng), dvi_file))
379         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
380         return legacy_conversion_step2(latex_file, dpi, output_format)
381
382     # Extract metrics info from dvipng_stdout.
383     metrics_file = latex_file_re.sub(".metrics", latex_file)
384     dvipng_metrics = extract_metrics_info(dvipng_stdout)
385
386     # If some pages require PostScript pass them to legacy method
387     if len(ps_pages) > 0:
388         # Create a new LaTeX file just for the snippets needing
389         # the legacy method
390         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
391         filter_pages(latex_file, legacy_latex_file, ps_pages)
392
393         # Pass the new LaTeX file to the legacy method
394         vec = [ argv[0], latex_file_re.sub("_legacy.tex", argv[2]), \
395                 argv[3], argv[1], argv[4], argv[5], latex ]
396         legacy_metrics = legacy_conversion(vec, True)[1]
397         
398         # Now we need to mix metrics data from dvipng and the legacy method
399         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
400         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
401         
402         # Join metrics from dvipng and legacy, and rename legacy bitmaps
403         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages, 
404             original_bitmap, destination_bitmap)
405
406     # Convert images to ppm format if necessary.
407     if output_format == "ppm":
408         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
409
410     # Actually create the .metrics file
411     write_metrics_info(dvipng_metrics, metrics_file)
412     
413     return (0, dvipng_metrics)
414
415 if __name__ == "__main__":
416     exit(main(sys.argv)[0])