]> git.lyx.org Git - features.git/blob - lib/scripts/lyxpreview2bitmap.py
Better error and progress messages for lyxpreview.
[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 # * python 2.4 or later (subprocess module);
20 # * A latex executable;
21 # * preview.sty;
22 # * dvipng;
23 # * dv2dt;
24 # * pngtoppm (if outputing ppm format images).
25
26 # preview.sty and dvipng are part of the preview-latex project
27 # http://preview-latex.sourceforge.net/
28
29 # preview.sty can alternatively be obtained from
30 # CTAN/support/preview-latex/
31
32 # Example usage:
33 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
34
35 # This script takes one obligatory argument:
36 #
37 #   <input file>:  The name of the .tex file to be converted.
38 #
39 # and these optional arguments:
40 #
41 #   --png, --ppm:  The desired output format. Either 'png' or 'ppm'.
42 #   --dpi=<res>:   A scale factor, used to ascertain the resolution of the
43 #                  generated image which is then passed to gs.
44 #   --fg=<color>:  The foreground color as a hexadecimal string, eg '000000'.
45 #   --bg=<color>:  The background color as a hexadecimal string, eg 'faf0e6'.
46 #   --latex=<exe>: The converter for latex files. Default is latex.
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, \
81      legacy_conversion_step2, legacy_extract_metrics_info
82
83 from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
84      find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
85      latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
86      run_command, warning, write_metrics_info
87
88
89 def usage(prog_name):
90     msg = """
91 Usage: %s <options> <input file>
92
93 Options:
94   --dpi=<res>:   Resolution per inch (default: 128)
95   --png, --ppm:  Select the output format (default: png)
96   --fg=<color>:  Foreground color (default: black, ie '000000')
97   --bg=<color>:  Background color (default: white, ie 'ffffff')
98   --latex=<exe>: Specify the executable for latex (default: latex)
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 or descent >= 0:
141             if abs(ascent + descent) > 0.1:
142                 frac = ascent / (ascent + descent)
143
144             # Sanity check
145             if frac < 0:
146                 frac = 0.5
147
148         results.append((int(page), frac))
149         pos = match.end() + 2
150
151     if success == 0:
152         error("Failed to extract metrics info from dvipng")
153
154     return results
155
156
157 def color_pdf(latex_file, bg_color, fg_color):
158     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
159
160     tmp = mkstemp()
161
162     fg = ""
163     if fg_color != "0.000000,0.000000,0.000000":
164         fg = '  \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
165
166     success = 0
167     try:
168         for line in open(latex_file, 'r').readlines():
169             match = use_preview_pdf_re.match(line)
170             if match == None:
171                 tmp.write(line)
172                 continue
173             success = 1
174             tmp.write("  \\usepackage{color}\n" \
175                   "  \\pagecolor[rgb]{%s}\n" \
176                   "%s" \
177                   "%s\n" \
178                   % (bg_color, fg, match.group()))
179             continue
180
181     except:
182         # Unable to open the file, but do nothing here because
183         # the calling function will act on the value of 'success'.
184         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
185         warning(`sys.exc_type` + ',' + `sys.exc_value`)
186
187     if success:
188         copyfileobj(tmp, open(latex_file,"wb"), 1)
189
190     return success
191
192
193 def fix_latex_file(latex_file):
194     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
195
196     tmp = mkstemp()
197
198     changed = 0
199     for line in open(latex_file, 'r').readlines():
200         match = documentclass_re.match(line)
201         if match == None:
202             tmp.write(line)
203             continue
204
205         changed = 1
206         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
207
208     if changed:
209         copyfileobj(tmp, open(latex_file,"wb"), 1)
210
211     return changed
212
213
214 def convert_to_ppm_format(pngtopnm, basename):
215     png_file_re = re.compile("\.png$")
216
217     for png_file in glob.glob("%s*.png" % basename):
218         ppm_file = png_file_re.sub(".ppm", png_file)
219
220         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
221         p2p_status, p2p_stdout = run_command(p2p_cmd)
222         if p2p_status:
223             error("Unable to convert %s to ppm format" % png_file)
224
225         ppm = open(ppm_file, 'w')
226         ppm.write(p2p_stdout)
227         os.remove(png_file)
228
229 # Returns a tuple of:
230 # ps_pages: list of page indexes of pages containing PS literals
231 # page_count: total number of pages
232 # pages_parameter: parameter for dvipng to exclude pages with PostScript
233 def find_ps_pages(dvi_file):
234     # latex failed
235     # FIXME: try with pdflatex
236     if not os.path.isfile(dvi_file):
237         error("No DVI output.")
238
239     # Check for PostScript specials in the dvi, badly supported by dvipng
240     # This is required for correct rendering of PSTricks and TikZ
241     dv2dt = find_exe_or_terminate(["dv2dt"])
242     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
243
244     # The output from dv2dt goes to stdout
245     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
246     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
247
248     # Parse the dtl file looking for PostScript specials.
249     # Pages using PostScript specials are recorded in ps_pages and then
250     # used to create a different LaTeX file for processing in legacy mode.
251     page_has_ps = False
252     page_index = 0
253     ps_pages = []
254
255     for line in dv2dt_output.split("\n"):
256         # New page
257         if line.startswith("bop"):
258             page_has_ps = False
259             page_index += 1
260
261         # End of page
262         if line.startswith("eop") and page_has_ps:
263             # We save in a list all the PostScript pages
264             ps_pages.append(page_index)
265
266         if psliteral_re.match(line) != None:
267             # Literal PostScript special detected!
268             page_has_ps = True
269
270     # Create the -pp parameter for dvipng
271     pages_parameter = ""
272     if len(ps_pages) > 0 and len(ps_pages) < page_index:
273         # Don't process Postscript pages with dvipng by selecting the
274         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
275         pages_parameter = " -pp "
276         skip = True
277         last = -1
278
279         # Use page ranges, as a list of pages could exceed command line
280         # maximum length (especially under Win32)
281         for index in xrange(1, page_index + 1):
282             if (not index in ps_pages) and skip:
283                 # We were skipping pages but current page shouldn't be skipped.
284                 # Add this page to -pp, it could stay alone or become the
285                 # start of a range.
286                 pages_parameter += str(index)
287                 # Save the starting index to avoid things such as "11-11"
288                 last = index
289                 # We're not skipping anymore
290                 skip = False
291             elif (index in ps_pages) and (not skip):
292                 # We weren't skipping but current page should be skipped
293                 if last != index - 1:
294                     # If the start index of the range is the previous page
295                     # then it's not a range
296                     pages_parameter += "-" + str(index - 1)
297
298                 # Add a separator
299                 pages_parameter += ","
300                 # Now we're skipping
301                 skip = True
302
303         # Remove the trailing separator
304         pages_parameter = pages_parameter.rstrip(",")
305         # We've to manage the case in which the last page is closing a range
306         if (not index in ps_pages) and (not skip) and (last != index):
307                 pages_parameter += "-" + str(index)
308
309     return (ps_pages, page_index, pages_parameter)
310
311 def main(argv):
312     # Set defaults.
313     dpi = 128
314     fg_color = "000000"
315     bg_color = "ffffff"
316     latex = None
317     lilypond = False
318     lilypond_book = None
319     output_format = "png"
320     script_name = argv[0]
321
322     # Parse and manipulate the command line arguments.
323     try:
324         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bg=", "debug",
325             "dpi=", "fg=", "help", "latex=", "lilypond", "lilypond-book=",
326             "png", "ppm", "verbose"])
327     except getopt.GetoptError, err:
328         error("%s\n%s" % (err, usage(script_name)))
329
330     opts.reverse()
331     for opt, val in opts:
332         if opt in ("-h", "--help"):
333             print usage(script_name)
334             sys.exit(0)
335         elif opt == "--bg":
336             bg_color = val
337         elif opt in ("-d", "--debug"):
338             import lyxpreview_tools
339             lyxpreview_tools.debug = True
340         elif opt == "--dpi":
341             try:
342                 dpi = string.atoi(val)
343             except:
344                 error("Cannot convert %s to an integer value" % val)
345         elif opt == "--fg":
346             fg_color = val
347         elif opt == "--latex":
348             latex = [val]
349         elif opt == "--lilypond":
350             lilypond = True
351         elif opt == "--lilypond-book":
352             lilypond_book = [val]
353         elif opt in ("--png", "--ppm"):
354             output_format = opt[2:]
355         elif opt in ("-v", "--verbose"):
356             import lyxpreview_tools
357             lyxpreview_tools.verbose = True
358
359     # Determine input file
360     if len(args) != 1:
361         err = "A single input file is required, %s given" % (len(args) or "none")
362         error("%s\n%s" % (err, usage(script_name)))
363
364     input_path = args[0]
365     dir, latex_file = os.path.split(input_path)
366
367     # Echo the settings
368     progress("Starting %s..." % script_name)
369     progress("Output format: %s" % output_format)
370     progress("Foreground color: %s" % fg_color)
371     progress("Background color: %s" % bg_color)
372     progress("Resolution (dpi): %s" % dpi)
373     progress("File to process: %s" % input_path)
374
375     # Check for the input file
376     if not os.path.exists(input_path):
377         error('File "%s" not found.' % input_path)
378     if len(dir) != 0:
379         os.chdir(dir)
380
381     fg_color_dvipng = make_texcolor(fg_color, False)
382     bg_color_dvipng = make_texcolor(bg_color, False)
383
384     fg_color_gr = make_texcolor(fg_color, True)
385     bg_color_gr = make_texcolor(bg_color, True)
386
387     # External programs used by the script.
388     latex = find_exe_or_terminate(latex or latex_commands)
389     if lilypond:
390         lilypond_book = find_exe_or_terminate(lilypond_book or ["lilypond-book"])
391
392     # These flavors of latex are known to produce pdf output
393     pdf_output = latex in pdflatex_commands
394
395     progress("Latex command: %s" % latex)
396     progress("Latex produces pdf output: %s" % pdf_output)
397     progress("Lilypond-book command: %s" % lilypond_book)
398     progress("Preprocess through lilypond-book: %s" % lilypond)
399     progress("Altering the latex file for font size and colors")
400
401     # Omit font size specification in latex file.
402     if not fix_latex_file(latex_file):
403         warning("Unable to remove font size from the latex file")
404
405     if lilypond:
406         progress("Preprocess the latex file through %s" % lilypond_book)
407         if pdf_output:
408             lilypond_book += ' --pdf'
409
410         # Make a copy of the latex file
411         lytex_file = latex_file_re.sub(".lytex", latex_file)
412         shutil.copyfile(latex_file, lytex_file)
413
414         # Preprocess the latex file through lilypond-book.
415         lytex_call = '%s --safe --latex-program=%s "%s"' % (lilypond_book,
416             latex, lytex_file)
417         lytex_status, lytex_stdout = run_command(lytex_call)
418         if lytex_status:
419             warning("%s failed to compile %s" \
420                 % (os.path.basename(lilypond_book), lytex_file))
421
422     # This can go once dvipng becomes widespread.
423     dvipng = find_exe(["dvipng"])
424     if dvipng == None:
425         # The data is input to legacy_conversion in as similar
426         # as possible a manner to that input to the code used in
427         # LyX 1.3.x.
428         progress("Using the legacy conversion method (dvipng not found)")
429         vec = [ script_name, input_path, str(dpi), output_format, fg_color, bg_color, latex ]
430         return legacy_conversion(vec)
431
432     pngtopnm = ""
433     if output_format == "ppm":
434         pngtopnm = find_exe_or_terminate(["pngtopnm"])
435
436     # Move color information for PDF into the latex file.
437     if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
438         warning("Unable to move color info into the latex file")
439
440     # Compile the latex file.
441     latex_call = '%s "%s"' % (latex, latex_file)
442
443     latex_status, latex_stdout = run_command(latex_call)
444     if latex_status:
445         warning("%s had problems compiling %s" \
446               % (os.path.basename(latex), latex_file))
447
448     if latex == "xelatex":
449         warning("Using XeTeX")
450         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
451         return legacy_conversion_step2(latex_file, dpi, output_format)
452
453     # The dvi output file name
454     dvi_file = latex_file_re.sub(".dvi", latex_file)
455
456     # If there's no DVI output, look for PDF and go to legacy or fail
457     if not os.path.isfile(dvi_file):
458         # No DVI, is there a PDF?
459         pdf_file = latex_file_re.sub(".pdf", latex_file)
460         if os.path.isfile(pdf_file):
461             progress("%s produced a PDF output, fallback to legacy." \
462                 % (os.path.basename(latex)))
463             return legacy_conversion_step2(latex_file, dpi, output_format)
464         else:
465             error("No DVI or PDF output. %s failed." \
466                 % (os.path.basename(latex)))
467
468     # Look for PS literals in DVI pages
469     # ps_pages: list of page indexes of pages containing PS literals
470     # page_count: total number of pages
471     # pages_parameter: parameter for dvipng to exclude pages with PostScript
472     (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
473
474     # If all pages need PostScript, directly use the legacy method.
475     if len(ps_pages) == page_count:
476         vec = [ script_name, input_path, str(dpi), output_format, fg_color, bg_color, latex ]
477         progress("Using the legacy conversion method (PostScript support)")
478         return legacy_conversion(vec)
479
480     # Run the dvi file through dvipng.
481     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
482         % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
483     dvipng_status, dvipng_stdout = run_command(dvipng_call)
484
485     if dvipng_status:
486         warning("%s failed to generate images from %s... fallback to legacy method" \
487               % (os.path.basename(dvipng), dvi_file))
488         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
489         progress("Using the legacy conversion method (dvipng failed)")
490         return legacy_conversion_step2(latex_file, dpi, output_format)
491
492     # Extract metrics info from dvipng_stdout.
493     metrics_file = latex_file_re.sub(".metrics", latex_file)
494     dvipng_metrics = extract_metrics_info(dvipng_stdout)
495
496     # If some pages require PostScript pass them to legacy method
497     if len(ps_pages) > 0:
498         # Create a new LaTeX file just for the snippets needing
499         # the legacy method
500         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
501         filter_pages(latex_file, legacy_latex_file, ps_pages)
502
503         # Pass the new LaTeX file to the legacy method
504         vec = [ script_name, latex_file_re.sub("_legacy.tex", input_path),
505                 str(dpi), output_format, fg_color, bg_color, latex ]
506         progress("Pages %s include postscript specials" % ps_pages)
507         progress("Using the legacy conversion method (PostScript support)")
508         legacy_metrics = legacy_conversion(vec, True)[1]
509
510         # Now we need to mix metrics data from dvipng and the legacy method
511         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
512         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
513
514         # Join metrics from dvipng and legacy, and rename legacy bitmaps
515         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
516             original_bitmap, destination_bitmap)
517
518     # Convert images to ppm format if necessary.
519     if output_format == "ppm":
520         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
521
522     # Actually create the .metrics file
523     write_metrics_info(dvipng_metrics, metrics_file)
524
525     return (0, dvipng_metrics)
526
527 if __name__ == "__main__":
528     exit(main(sys.argv)[0])