]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
update layout files to format 101
[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 from __future__ import print_function
79
80 import getopt, glob, os, re, shutil, sys, tempfile
81
82 import lyxpreview_tools
83
84 from legacy_lyxpreview2ppm import extract_resolution, legacy_conversion_step1
85
86 from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
87      error, filter_pages, find_exe, find_exe_or_terminate, \
88      join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
89      pdflatex_commands, progress, run_command, run_latex, run_tex, \
90      warning, write_metrics_info
91
92 PY2 = sys.version_info[0] == 2
93
94 def usage(prog_name):
95     msg = """
96 Usage: %s <options> <input file>
97
98 Options:
99   --dpi=<res>:   Resolution per inch (default: 128)
100   --png, --ppm:  Select the output format (default: png)
101   --fg=<color>:  Foreground color (default: black, ie '000000')
102   --bg=<color>:  Background color (default: white, ie 'ffffff')
103   --latex=<exe>: Specify the executable for latex (default: latex)
104   --bibtex=<exe>: Specify the executable for bibtex (default: bibtex)
105   --lilypond:    Preprocess through lilypond-book (default: false)
106   --lilypond-book=<exe>:
107                  The executable for lilypond-book (default: lilypond-book)
108
109   -d, --debug:   Show the output from external commands
110   -h, --help:    Show this help screen and exit
111   -v, --verbose: Show progress messages
112
113 The colors are hexadecimal strings, eg 'faf0e6'."""
114     return msg % prog_name
115
116 # Returns a list of tuples containing page number and ascent fraction
117 # extracted from dvipng output.
118 # Use write_metrics_info to create the .metrics file with this info
119 def extract_metrics_info(dvipng_stdout):
120     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
121     # and glyph numbers from mktexpk. The glyph numbers always match
122     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
123     page_re = re.compile(r"\[([0-9]+)[^]]");
124     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
125
126     success = 0
127     page = ""
128     pos = 0
129     results = []
130     while 1:
131         match = page_re.search(dvipng_stdout, pos)
132         if match == None:
133             break
134         page = match.group(1)
135         pos = match.end()
136         match = metrics_re.search(dvipng_stdout, pos)
137         if match == None:
138             break
139         success = 1
140
141         # Calculate the 'ascent fraction'.
142         descent = float(match.group(1))
143         ascent  = float(match.group(2))
144
145         frac = 0.5
146         if ascent < 0:
147             # This is an empty image, forbid its display
148             frac = -1.0
149         elif ascent >= 0 or descent >= 0:
150             if abs(ascent + descent) > 0.1:
151                 frac = ascent / (ascent + descent)
152
153             # Sanity check
154             if frac < 0:
155                 frac = 0.5
156
157         results.append((int(page), frac))
158         pos = match.end() + 2
159
160     if success == 0:
161         error("Failed to extract metrics info from dvipng")
162
163     return results
164
165
166 def fix_latex_file(latex_file, pdf_output):
167     # python 2 does not allow to declare a string as raw byte so we double
168     # the backslashes and remove the r preffix
169     def_re = re.compile(b"(\\\\newcommandx|\\\\global\\\\long\\\\def)"
170                         b"(\\\\[a-zA-Z]+)")
171
172     tmp = tempfile.TemporaryFile()
173
174     changed = False
175     macros = []
176     for line in open(latex_file, 'rb').readlines():
177         if not pdf_output and line.startswith(b"\\documentclass"):
178             changed = True
179             line += b"\\PassOptionsToPackage{draft}{microtype}\n"
180         else:
181             match = def_re.match(line)
182             if match != None:
183                 macroname = match.group(2)
184                 if macroname in macros:
185                     definecmd = match.group(1)
186                     if definecmd == b"\\newcommandx":
187                         changed = True
188                         line = line.replace(definecmd, b"\\renewcommandx")
189                 else:
190                     macros.append(macroname)
191         tmp.write(line)
192
193     if changed:
194         copyfileobj(tmp, open(latex_file,"wb"), 1)
195
196     return changed
197
198
199 def convert_to_ppm_format(pngtopnm, basename):
200     png_file_re = re.compile(r"\.png$")
201
202     for png_file in glob.glob("%s*.png" % basename):
203         ppm_file = png_file_re.sub(".ppm", png_file)
204
205         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
206         p2p_status, p2p_stdout = run_command(p2p_cmd)
207         if p2p_status:
208             error("Unable to convert %s to ppm format" % png_file)
209
210         ppm = open(ppm_file, 'w')
211         ppm.write(p2p_stdout)
212         os.remove(png_file)
213
214 # Returns a tuple of:
215 # ps_pages: list of page indexes of pages containing PS literals
216 # pdf_pages: list of page indexes of pages requiring running pdflatex
217 # page_count: total number of pages
218 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
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     # and inclusion of PDF/PNG/JPG files.
227     # This is required for correct rendering of PSTricks and TikZ
228     dv2dt = find_exe_or_terminate(["dv2dt"])
229     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
230
231     # The output from dv2dt goes to stdout
232     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
233     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
234     hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
235     pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
236
237     # Parse the dtl file looking for PostScript specials and pdflatex files.
238     # Pages using PostScript specials or pdflatex files are recorded in
239     # ps_pages or pdf_pages, respectively, and then used to create a
240     # different LaTeX file for processing in legacy mode.
241     # If hyperref is detected, the corresponding page is recorded in pdf_pages.
242     page_has_ps = False
243     page_has_pdf = False
244     page_index = 0
245     ps_pages = []
246     pdf_pages = []
247     ps_or_pdf_pages = []
248
249     for line in dv2dt_output.split("\n"):
250         # New page
251         if line.startswith("bop"):
252             page_has_ps = False
253             page_has_pdf = False
254             page_index += 1
255
256         # End of page
257         if line.startswith("eop") and (page_has_ps or page_has_pdf):
258             # We save in a list all the PostScript/PDF pages
259             if page_has_ps:
260                 ps_pages.append(page_index)
261             else:
262                 pdf_pages.append(page_index)
263             ps_or_pdf_pages.append(page_index)
264
265         if psliteral_re.match(line) != None:
266             # Literal PostScript special detected!
267             # If hyperref is detected, put this page on the pdf pages list
268             if hyperref_re.match(line) != None:
269                 page_has_ps = False
270                 page_has_pdf = True
271             else:
272                 page_has_ps = True
273         elif pdffile_re.match(line) != None:
274             # Inclusion of pdflatex image file detected!
275             page_has_pdf = True
276
277     # Create the -pp parameter for dvipng
278     pages_parameter = ""
279     if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
280         # Don't process Postscript/PDF pages with dvipng by selecting the
281         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
282         pages_parameter = " -pp "
283         skip = True
284         last = -1
285
286         # Use page ranges, as a list of pages could exceed command line
287         # maximum length (especially under Win32)
288         for index in range(1, page_index + 1):
289             if (not index in ps_or_pdf_pages) and skip:
290                 # We were skipping pages but current page shouldn't be skipped.
291                 # Add this page to -pp, it could stay alone or become the
292                 # start of a range.
293                 pages_parameter += str(index)
294                 # Save the starting index to avoid things such as "11-11"
295                 last = index
296                 # We're not skipping anymore
297                 skip = False
298             elif (index in ps_or_pdf_pages) and (not skip):
299                 # We weren't skipping but current page should be skipped
300                 if last != index - 1:
301                     # If the start index of the range is the previous page
302                     # then it's not a range
303                     pages_parameter += "-" + str(index - 1)
304
305                 # Add a separator
306                 pages_parameter += ","
307                 # Now we're skipping
308                 skip = True
309
310         # Remove the trailing separator
311         pages_parameter = pages_parameter.rstrip(",")
312         # We've to manage the case in which the last page is closing a range
313         if (not index in ps_or_pdf_pages) and (not skip) and (last != index):
314                 pages_parameter += "-" + str(index)
315
316     return (ps_pages, pdf_pages, page_index, pages_parameter)
317
318 def main(argv):
319     # Set defaults.
320     dpi = 128
321     fg_color = "000000"
322     bg_color = "ffffff"
323     bibtex = None
324     latex = None
325     lilypond = False
326     lilypond_book = None
327     output_format = "png"
328     script_name = argv[0]
329
330     # Parse and manipulate the command line arguments.
331     try:
332         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
333             "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
334             "lilypond-book=", "png", "ppm", "verbose"])
335     except getopt.GetoptError as err:
336         error("%s\n%s" % (err, usage(script_name)))
337
338     opts.reverse()
339     for opt, val in opts:
340         if opt in ("-h", "--help"):
341             print(usage(script_name))
342             sys.exit(0)
343         elif opt == "--bibtex":
344             bibtex = [val]
345         elif opt == "--bg":
346             bg_color = val
347         elif opt in ("-d", "--debug"):
348             lyxpreview_tools.debug = True
349         elif opt == "--dpi":
350             try:
351                 dpi = int(val)
352             except:
353                 error("Cannot convert %s to an integer value" % val)
354         elif opt == "--fg":
355             fg_color = val
356         elif opt == "--latex":
357             latex = [val]
358         elif opt == "--lilypond":
359             lilypond = True
360         elif opt == "--lilypond-book":
361             lilypond_book = [val]
362         elif opt in ("--png", "--ppm"):
363             output_format = opt[2:]
364         elif opt in ("-v", "--verbose"):
365             lyxpreview_tools.verbose = True
366
367     # Determine input file
368     if len(args) != 1:
369         err = "A single input file is required, %s given" % (len(args) or "none")
370         error("%s\n%s" % (err, usage(script_name)))
371
372     input_path = args[0]
373     dir, latex_file = os.path.split(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     if lyxpreview_tools.verbose:
382         f_out = open('verbose.txt', 'a')
383         sys.stdout = f_out
384         sys.stderr = f_out
385
386     # Echo the settings
387     progress("Running Python %s" % str(sys.version_info[:3]))
388     progress("Starting %s..." % script_name)
389     if os.name == "nt":
390         progress("Use win32_modules: %d" % lyxpreview_tools.use_win32_modules)
391     progress("Output format: %s" % output_format)
392     progress("Foreground color: %s" % fg_color)
393     progress("Background color: %s" % bg_color)
394     progress("Resolution (dpi): %s" % dpi)
395     progress("File to process: %s" % input_path)
396
397     # For python > 2 convert strings to bytes
398     if not PY2:
399         fg_color = bytes(fg_color, 'ascii')
400         bg_color = bytes(bg_color, 'ascii')
401
402     fg_color_dvipng = make_texcolor(fg_color, False)
403     bg_color_dvipng = make_texcolor(bg_color, False)
404
405     # For python > 2 convert bytes to string
406     if not PY2:
407         fg_color_dvipng = fg_color_dvipng.decode('ascii')
408         bg_color_dvipng = bg_color_dvipng.decode('ascii')
409
410     # External programs used by the script.
411     latex = find_exe_or_terminate(latex or latex_commands)
412     bibtex = find_exe(bibtex or bibtex_commands)
413     if lilypond:
414         lilypond_book = find_exe_or_terminate(lilypond_book or
415             ["lilypond-book --safe"])
416
417     # These flavors of latex are known to produce pdf output
418     pdf_output = latex in pdflatex_commands
419
420     progress("Latex command: %s" % latex)
421     progress("Latex produces pdf output: %s" % pdf_output)
422     progress("Bibtex command: %s" % bibtex)
423     progress("Lilypond-book command: %s" % lilypond_book)
424     progress("Preprocess through lilypond-book: %s" % lilypond)
425     progress("Altering the latex file for font size and colors")
426
427     # Make sure that multiple defined macros and the microtype package
428     # don't cause issues in the latex file.
429     fix_latex_file(latex_file, pdf_output)
430
431     if lilypond:
432         progress("Preprocess the latex file through %s" % lilypond_book)
433         if pdf_output:
434             lilypond_book += " --pdf"
435         lilypond_book += " --latex-program=%s" % latex.split()[0]
436
437         # Make a copy of the latex file
438         lytex_file = latex_file_re.sub(".lytex", latex_file)
439         shutil.copyfile(latex_file, lytex_file)
440
441         # Preprocess the latex file through lilypond-book.
442         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
443
444     if pdf_output:
445         progress("Using the legacy conversion method (PDF support)")
446         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
447             bg_color, latex, pdf_output)
448
449     # This can go once dvipng becomes widespread.
450     dvipng = find_exe(["dvipng"])
451     if dvipng == None:
452         progress("Using the legacy conversion method (dvipng not found)")
453         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
454             bg_color, latex, pdf_output)
455
456     dv2dt = find_exe(["dv2dt"])
457     if dv2dt == None:
458         progress("Using the legacy conversion method (dv2dt not found)")
459         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
460             bg_color, latex, pdf_output)
461
462     pngtopnm = ""
463     if output_format == "ppm":
464         pngtopnm = find_exe(["pngtopnm"])
465         if pngtopnm == None:
466             progress("Using the legacy conversion method (pngtopnm not found)")
467             return legacy_conversion_step1(latex_file, dpi, output_format,
468                 fg_color, bg_color, latex, pdf_output)
469
470     # Compile the latex file.
471     error_pages = []
472     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
473     latex_log = latex_file_re.sub(".log", latex_file)
474     if latex_status:
475         progress("Will try to recover from %s failure" % latex)
476         error_pages = check_latex_log(latex_log)
477
478     # The dvi output file name
479     dvi_file = latex_file_re.sub(".dvi", latex_file)
480
481     # If there's no DVI output, look for PDF and go to legacy or fail
482     if not os.path.isfile(dvi_file):
483         # No DVI, is there a PDF?
484         pdf_file = latex_file_re.sub(".pdf", latex_file)
485         if os.path.isfile(pdf_file):
486             progress("%s produced a PDF output, fallback to legacy." \
487                 % (os.path.basename(latex)))
488             progress("Using the legacy conversion method (PDF support)")
489             return legacy_conversion_step1(latex_file, dpi, output_format,
490                 fg_color, bg_color, latex, True)
491         else:
492             error("No DVI or PDF output. %s failed." \
493                 % (os.path.basename(latex)))
494
495     # Look for PS literals or inclusion of pdflatex files in DVI pages
496     # ps_pages: list of indexes of pages containing PS literals
497     # pdf_pages: list of indexes of pages requiring running pdflatex
498     # page_count: total number of pages
499     # pages_parameter: parameter for dvipng to exclude pages with PostScript
500     (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
501
502     # If all pages need PostScript or pdflatex, directly use the legacy method.
503     if len(ps_pages) == page_count:
504         progress("Using the legacy conversion method (PostScript support)")
505         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
506             bg_color, latex, pdf_output)
507     elif len(pdf_pages) == page_count:
508         progress("Using the legacy conversion method (PDF support)")
509         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
510             bg_color, "pdflatex", True)
511
512     # Retrieve resolution
513     resolution = extract_resolution(latex_log, dpi)
514
515     # Run the dvi file through dvipng.
516     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
517         % (dvipng, resolution, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
518     dvipng_status, dvipng_stdout = run_command(dvipng_call)
519
520     if dvipng_status:
521         warning("%s failed to generate images from %s... fallback to legacy method" \
522               % (os.path.basename(dvipng), dvi_file))
523         progress("Using the legacy conversion method (dvipng failed)")
524         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
525             bg_color, latex, pdf_output)
526
527     # Extract metrics info from dvipng_stdout.
528     metrics_file = latex_file_re.sub(".metrics", latex_file)
529     dvipng_metrics = extract_metrics_info(dvipng_stdout)
530
531     # If some pages require PostScript pass them to legacy method
532     if len(ps_pages) > 0:
533         # Create a new LaTeX file just for the snippets needing
534         # the legacy method
535         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
536         filter_pages(latex_file, legacy_latex_file, ps_pages)
537
538         # Pass the new LaTeX file to the legacy method
539         progress("Pages %s include postscript specials" % ps_pages)
540         progress("Using the legacy conversion method (PostScript support)")
541         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
542             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
543
544         # Now we need to mix metrics data from dvipng and the legacy method
545         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
546         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
547
548         # Join metrics from dvipng and legacy, and rename legacy bitmaps
549         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
550             original_bitmap, destination_bitmap)
551
552     # If some pages require running pdflatex pass them to legacy method
553     if len(pdf_pages) > 0:
554         # Create a new LaTeX file just for the snippets needing
555         # the legacy method
556         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
557         filter_pages(latex_file, legacy_latex_file, pdf_pages)
558
559         # Pass the new LaTeX file to the legacy method
560         progress("Pages %s require processing with pdflatex" % pdf_pages)
561         progress("Using the legacy conversion method (PDF support)")
562         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
563             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
564
565         # Now we need to mix metrics data from dvipng and the legacy method
566         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
567         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
568
569         # Join metrics from dvipng and legacy, and rename legacy bitmaps
570         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
571             original_bitmap, destination_bitmap)
572
573     # Invalidate metrics for pages that produced errors
574     if len(error_pages) > 0:
575         error_count = 0
576         for index in error_pages:
577             if index not in ps_pages and index not in pdf_pages:
578                 dvipng_metrics.pop(index - 1)
579                 dvipng_metrics.insert(index - 1, (index, -1.0))
580                 error_count += 1
581         if error_count:
582             warning("Failed to produce %d preview snippet(s)" % error_count)
583
584     # Convert images to ppm format if necessary.
585     if output_format == "ppm":
586         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
587
588     # Actually create the .metrics file
589     write_metrics_info(dvipng_metrics, metrics_file)
590
591     return (0, dvipng_metrics)
592
593 if __name__ == "__main__":
594     sys.exit(main(sys.argv)[0])