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