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