]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
Try hard to obtain an instant preview.
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 # -*- coding: utf-8 -*-
2
3 # file lyxpreview2bitmap.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Angus Leeming
8 # with much advice from members of the preview-latex project:
9 # David Kastrup, dak@gnu.org and
10 # Jan-Åke Larsson, jalar@mai.liu.se.
11
12 # Full author contact details are available in file CREDITS
13
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
16
17 # Pre-requisites:
18 # * python 2.4 or later (subprocess module);
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 #   --bibtex=<exe>: The converter for bibtex files. Default is bibtex.
47 #   --lilypond:    Preprocess through lilypond-book. Default is false.
48 #   --lilypond-book=<exe>:
49 #                  The converter for lytex files. Default is lilypond-book.
50 #
51 #   -d, --debug    Show the output from external commands.
52 #   -h, --help     Show an help screen and exit.
53 #   -v, --verbose  Show progress messages.
54
55 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
56 # if executed successfully, leave in DIR:
57 # * a (possibly large) number of image files with names
58 #   like BASE[0-9]+.png
59 # * a file BASE.metrics, containing info needed by LyX to position
60 #   the images correctly on the screen.
61
62 # What does this script do?
63 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
64 # 2) If the output is a PDF fallback to legacy
65 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
66 #    PostScript literals, not well supported by dvipng. Pages
67 #    containing them are passed to the legacy method in a new LaTeX file.
68 # 4) Call dvipng on the pages without PS literals
69 # 5) Join metrics info coming from both methods (legacy and dvipng)
70 #    and write them to file
71
72 # dvipng is fast but gives problem in several cases, like with
73 # PSTricks, TikZ and other packages using PostScript literals
74 # for all these cases the legacy route is taken (step 3).
75 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
76 # paramter is pdflatex we have to fallback to legacy route (step 2).
77
78 import getopt, glob, os, re, shutil, string, sys
79
80 from legacy_lyxpreview2ppm import legacy_conversion_step1
81
82 from lyxpreview_tools import bibtex_commands, copyfileobj, error, \
83      filter_pages, find_exe, find_exe_or_terminate, join_metrics_and_rename, \
84      latex_commands, latex_file_re, make_texcolor, mkstemp, pdflatex_commands, \
85      progress, run_command, run_latex, run_tex, warning, write_metrics_info
86
87
88 def usage(prog_name):
89     msg = """
90 Usage: %s <options> <input file>
91
92 Options:
93   --dpi=<res>:   Resolution per inch (default: 128)
94   --png, --ppm:  Select the output format (default: png)
95   --fg=<color>:  Foreground color (default: black, ie '000000')
96   --bg=<color>:  Background color (default: white, ie 'ffffff')
97   --latex=<exe>: Specify the executable for latex (default: latex)
98   --bibtex=<exe>: Specify the executable for bibtex (default: bibtex)
99   --lilypond:    Preprocess through lilypond-book (default: false)
100   --lilypond-book=<exe>:
101                  The executable for lilypond-book (default: lilypond-book)
102
103   -d, --debug:   Show the output from external commands
104   -h, --help:    Show this help screen and exit
105   -v, --verbose: Show progress messages
106
107 The colors are hexadecimal strings, eg 'faf0e6'."""
108     return msg % prog_name
109
110 # Returns a list of tuples containing page number and ascent fraction
111 # extracted from dvipng output.
112 # Use write_metrics_info to create the .metrics file with this info
113 def extract_metrics_info(dvipng_stdout):
114     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
115     # and glyph numbers from mktexpk. The glyph numbers always match
116     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
117     page_re = re.compile("\[([0-9]+)[^]]");
118     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
119
120     success = 0
121     page = ""
122     pos = 0
123     results = []
124     while 1:
125         match = page_re.search(dvipng_stdout, pos)
126         if match == None:
127             break
128         page = match.group(1)
129         pos = match.end()
130         match = metrics_re.search(dvipng_stdout, pos)
131         if match == None:
132             break
133         success = 1
134
135         # Calculate the 'ascent fraction'.
136         descent = string.atof(match.group(1))
137         ascent  = string.atof(match.group(2))
138
139         frac = 0.5
140         if ascent < 0:
141             # This is an empty image, forbid its display
142             frac = -1.0
143         elif ascent >= 0 or descent >= 0:
144             if abs(ascent + descent) > 0.1:
145                 frac = ascent / (ascent + descent)
146
147             # Sanity check
148             if frac < 0:
149                 frac = 0.5
150
151         results.append((int(page), frac))
152         pos = match.end() + 2
153
154     if success == 0:
155         error("Failed to extract metrics info from dvipng")
156
157     return results
158
159
160 def fix_latex_file(latex_file):
161     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
162
163     tmp = mkstemp()
164
165     changed = 0
166     for line in open(latex_file, 'r').readlines():
167         match = documentclass_re.match(line)
168         if match == None:
169             tmp.write(line)
170             continue
171
172         changed = 1
173         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
174
175     if changed:
176         copyfileobj(tmp, open(latex_file,"wb"), 1)
177
178     return changed
179
180
181 def convert_to_ppm_format(pngtopnm, basename):
182     png_file_re = re.compile("\.png$")
183
184     for png_file in glob.glob("%s*.png" % basename):
185         ppm_file = png_file_re.sub(".ppm", png_file)
186
187         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
188         p2p_status, p2p_stdout = run_command(p2p_cmd)
189         if p2p_status:
190             error("Unable to convert %s to ppm format" % png_file)
191
192         ppm = open(ppm_file, 'w')
193         ppm.write(p2p_stdout)
194         os.remove(png_file)
195
196 # Returns a tuple of:
197 # ps_pages: list of page indexes of pages containing PS literals
198 # page_count: total number of pages
199 # pages_parameter: parameter for dvipng to exclude pages with PostScript
200 def find_ps_pages(dvi_file):
201     # latex failed
202     # FIXME: try with pdflatex
203     if not os.path.isfile(dvi_file):
204         error("No DVI output.")
205
206     # Check for PostScript specials in the dvi, badly supported by dvipng
207     # This is required for correct rendering of PSTricks and TikZ
208     dv2dt = find_exe_or_terminate(["dv2dt"])
209     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
210
211     # The output from dv2dt goes to stdout
212     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
213     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
214
215     # Parse the dtl file looking for PostScript specials.
216     # Pages using PostScript specials are recorded in ps_pages and then
217     # used to create a different LaTeX file for processing in legacy mode.
218     page_has_ps = False
219     page_index = 0
220     ps_pages = []
221
222     for line in dv2dt_output.split("\n"):
223         # New page
224         if line.startswith("bop"):
225             page_has_ps = False
226             page_index += 1
227
228         # End of page
229         if line.startswith("eop") and page_has_ps:
230             # We save in a list all the PostScript pages
231             ps_pages.append(page_index)
232
233         if psliteral_re.match(line) != None:
234             # Literal PostScript special detected!
235             page_has_ps = True
236
237     # Create the -pp parameter for dvipng
238     pages_parameter = ""
239     if len(ps_pages) > 0 and len(ps_pages) < page_index:
240         # Don't process Postscript pages with dvipng by selecting the
241         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
242         pages_parameter = " -pp "
243         skip = True
244         last = -1
245
246         # Use page ranges, as a list of pages could exceed command line
247         # maximum length (especially under Win32)
248         for index in xrange(1, page_index + 1):
249             if (not index in ps_pages) and skip:
250                 # We were skipping pages but current page shouldn't be skipped.
251                 # Add this page to -pp, it could stay alone or become the
252                 # start of a range.
253                 pages_parameter += str(index)
254                 # Save the starting index to avoid things such as "11-11"
255                 last = index
256                 # We're not skipping anymore
257                 skip = False
258             elif (index in ps_pages) and (not skip):
259                 # We weren't skipping but current page should be skipped
260                 if last != index - 1:
261                     # If the start index of the range is the previous page
262                     # then it's not a range
263                     pages_parameter += "-" + str(index - 1)
264
265                 # Add a separator
266                 pages_parameter += ","
267                 # Now we're skipping
268                 skip = True
269
270         # Remove the trailing separator
271         pages_parameter = pages_parameter.rstrip(",")
272         # We've to manage the case in which the last page is closing a range
273         if (not index in ps_pages) and (not skip) and (last != index):
274                 pages_parameter += "-" + str(index)
275
276     return (ps_pages, page_index, pages_parameter)
277
278 def main(argv):
279     # Set defaults.
280     dpi = 128
281     fg_color = "000000"
282     bg_color = "ffffff"
283     bibtex = None
284     latex = None
285     lilypond = False
286     lilypond_book = None
287     output_format = "png"
288     script_name = argv[0]
289
290     # Parse and manipulate the command line arguments.
291     try:
292         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
293             "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
294             "lilypond-book=", "png", "ppm", "verbose"])
295     except getopt.GetoptError, err:
296         error("%s\n%s" % (err, usage(script_name)))
297
298     opts.reverse()
299     for opt, val in opts:
300         if opt in ("-h", "--help"):
301             print usage(script_name)
302             sys.exit(0)
303         elif opt == "--bibtex":
304             bibtex = [val]
305         elif opt == "--bg":
306             bg_color = val
307         elif opt in ("-d", "--debug"):
308             import lyxpreview_tools
309             lyxpreview_tools.debug = True
310         elif opt == "--dpi":
311             try:
312                 dpi = string.atoi(val)
313             except:
314                 error("Cannot convert %s to an integer value" % val)
315         elif opt == "--fg":
316             fg_color = val
317         elif opt == "--latex":
318             latex = [val]
319         elif opt == "--lilypond":
320             lilypond = True
321         elif opt == "--lilypond-book":
322             lilypond_book = [val]
323         elif opt in ("--png", "--ppm"):
324             output_format = opt[2:]
325         elif opt in ("-v", "--verbose"):
326             import lyxpreview_tools
327             lyxpreview_tools.verbose = True
328
329     # Determine input file
330     if len(args) != 1:
331         err = "A single input file is required, %s given" % (len(args) or "none")
332         error("%s\n%s" % (err, usage(script_name)))
333
334     input_path = args[0]
335     dir, latex_file = os.path.split(input_path)
336
337     # Echo the settings
338     progress("Starting %s..." % script_name)
339     progress("Output format: %s" % output_format)
340     progress("Foreground color: %s" % fg_color)
341     progress("Background color: %s" % bg_color)
342     progress("Resolution (dpi): %s" % dpi)
343     progress("File to process: %s" % input_path)
344
345     # Check for the input file
346     if not os.path.exists(input_path):
347         error('File "%s" not found.' % input_path)
348     if len(dir) != 0:
349         os.chdir(dir)
350
351     fg_color_dvipng = make_texcolor(fg_color, False)
352     bg_color_dvipng = make_texcolor(bg_color, False)
353
354     # External programs used by the script.
355     latex = find_exe_or_terminate(latex or latex_commands)
356     bibtex = find_exe(bibtex or bibtex_commands)
357     if lilypond:
358         lilypond_book = find_exe_or_terminate(lilypond_book or
359             ["lilypond-book --safe"])
360
361     # These flavors of latex are known to produce pdf output
362     pdf_output = latex in pdflatex_commands
363
364     progress("Latex command: %s" % latex)
365     progress("Latex produces pdf output: %s" % pdf_output)
366     progress("Bibtex command: %s" % bibtex)
367     progress("Lilypond-book command: %s" % lilypond_book)
368     progress("Preprocess through lilypond-book: %s" % lilypond)
369     progress("Altering the latex file for font size and colors")
370
371     # Omit font size specification in latex file.
372     fix_latex_file(latex_file)
373
374     if lilypond:
375         progress("Preprocess the latex file through %s" % lilypond_book)
376         if pdf_output:
377             lilypond_book += " --pdf"
378         lilypond_book += " --latex-program=%s" % latex.split()[0]
379
380         # Make a copy of the latex file
381         lytex_file = latex_file_re.sub(".lytex", latex_file)
382         shutil.copyfile(latex_file, lytex_file)
383
384         # Preprocess the latex file through lilypond-book.
385         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
386
387     if pdf_output:
388         progress("Using the legacy conversion method (PDF support)")
389         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
390             bg_color, latex, pdf_output)
391
392     # This can go once dvipng becomes widespread.
393     dvipng = find_exe(["dvipng"])
394     if dvipng == None:
395         progress("Using the legacy conversion method (dvipng not found)")
396         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
397             bg_color, latex, pdf_output)
398
399     dv2dt = find_exe(["dv2dt"])
400     if dv2dt == None:
401         progress("Using the legacy conversion method (dv2dt not found)")
402         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
403             bg_color, latex, pdf_output)
404
405     pngtopnm = ""
406     if output_format == "ppm":
407         pngtopnm = find_exe(["pngtopnm"])
408         if pngtopnm == None:
409             progress("Using the legacy conversion method (pngtopnm not found)")
410             return legacy_conversion_step1(latex_file, dpi, output_format,
411                 fg_color, bg_color, latex, pdf_output)
412
413     # Compile the latex file.
414     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
415     if latex_status:
416         progress("Using the legacy conversion method and pdflatex (latex failed)")
417         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
418             bg_color, "pdflatex", True)
419
420     # The dvi output file name
421     dvi_file = latex_file_re.sub(".dvi", latex_file)
422
423     # If there's no DVI output, look for PDF and go to legacy or fail
424     if not os.path.isfile(dvi_file):
425         # No DVI, is there a PDF?
426         pdf_file = latex_file_re.sub(".pdf", latex_file)
427         if os.path.isfile(pdf_file):
428             progress("%s produced a PDF output, fallback to legacy." \
429                 % (os.path.basename(latex)))
430             progress("Using the legacy conversion method (PDF support)")
431             return legacy_conversion_step1(latex_file, dpi, output_format,
432                 fg_color, bg_color, latex, True)
433         else:
434             error("No DVI or PDF output. %s failed." \
435                 % (os.path.basename(latex)))
436
437     # Look for PS literals in DVI pages
438     # ps_pages: list of page indexes of pages containing PS literals
439     # page_count: total number of pages
440     # pages_parameter: parameter for dvipng to exclude pages with PostScript
441     (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
442
443     # If all pages need PostScript, directly use the legacy method.
444     if len(ps_pages) == page_count:
445         progress("Using the legacy conversion method (PostScript support)")
446         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
447             bg_color, latex, pdf_output)
448
449     # Run the dvi file through dvipng.
450     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
451         % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
452     dvipng_status, dvipng_stdout = run_command(dvipng_call)
453
454     if dvipng_status:
455         warning("%s failed to generate images from %s... fallback to legacy method" \
456               % (os.path.basename(dvipng), dvi_file))
457         progress("Using the legacy conversion method (dvipng failed)")
458         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
459             bg_color, latex, pdf_output)
460
461     # Extract metrics info from dvipng_stdout.
462     metrics_file = latex_file_re.sub(".metrics", latex_file)
463     dvipng_metrics = extract_metrics_info(dvipng_stdout)
464
465     # If some pages require PostScript pass them to legacy method
466     if len(ps_pages) > 0:
467         # Create a new LaTeX file just for the snippets needing
468         # the legacy method
469         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
470         filter_pages(latex_file, legacy_latex_file, ps_pages)
471
472         # Pass the new LaTeX file to the legacy method
473         progress("Pages %s include postscript specials" % ps_pages)
474         progress("Using the legacy conversion method (PostScript support)")
475         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
476             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
477
478         # Now we need to mix metrics data from dvipng and the legacy method
479         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
480         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
481
482         # Join metrics from dvipng and legacy, and rename legacy bitmaps
483         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
484             original_bitmap, destination_bitmap)
485
486     # Convert images to ppm format if necessary.
487     if output_format == "ppm":
488         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
489
490     # Actually create the .metrics file
491     write_metrics_info(dvipng_metrics, metrics_file)
492
493     return (0, dvipng_metrics)
494
495 if __name__ == "__main__":
496     sys.exit(main(sys.argv)[0])