]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
python3: fix the preview framework to work with both python 2 and 3
[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
81
82 from legacy_lyxpreview2ppm import extract_resolution, legacy_conversion_step1
83
84 from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
85      error, filter_pages, find_exe, find_exe_or_terminate, \
86      join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
87      mkstemp, pdflatex_commands, progress, run_command, run_latex, run_tex, \
88      warning, write_metrics_info
89
90
91 def usage(prog_name):
92     msg = """
93 Usage: %s <options> <input file>
94
95 Options:
96   --dpi=<res>:   Resolution per inch (default: 128)
97   --png, --ppm:  Select the output format (default: png)
98   --fg=<color>:  Foreground color (default: black, ie '000000')
99   --bg=<color>:  Background color (default: white, ie 'ffffff')
100   --latex=<exe>: Specify the executable for latex (default: latex)
101   --bibtex=<exe>: Specify the executable for bibtex (default: bibtex)
102   --lilypond:    Preprocess through lilypond-book (default: false)
103   --lilypond-book=<exe>:
104                  The executable for lilypond-book (default: lilypond-book)
105
106   -d, --debug:   Show the output from external commands
107   -h, --help:    Show this help screen and exit
108   -v, --verbose: Show progress messages
109
110 The colors are hexadecimal strings, eg 'faf0e6'."""
111     return msg % prog_name
112
113 # Returns a list of tuples containing page number and ascent fraction
114 # extracted from dvipng output.
115 # Use write_metrics_info to create the .metrics file with this info
116 def extract_metrics_info(dvipng_stdout):
117     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
118     # and glyph numbers from mktexpk. The glyph numbers always match
119     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
120     page_re = re.compile("\[([0-9]+)[^]]");
121     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
122
123     success = 0
124     page = ""
125     pos = 0
126     results = []
127     while 1:
128         match = page_re.search(dvipng_stdout, pos)
129         if match == None:
130             break
131         page = match.group(1)
132         pos = match.end()
133         match = metrics_re.search(dvipng_stdout, pos)
134         if match == None:
135             break
136         success = 1
137
138         # Calculate the 'ascent fraction'.
139         descent = float(match.group(1))
140         ascent  = float(match.group(2))
141
142         frac = 0.5
143         if ascent < 0:
144             # This is an empty image, forbid its display
145             frac = -1.0
146         elif ascent >= 0 or descent >= 0:
147             if abs(ascent + descent) > 0.1:
148                 frac = ascent / (ascent + descent)
149
150             # Sanity check
151             if frac < 0:
152                 frac = 0.5
153
154         results.append((int(page), frac))
155         pos = match.end() + 2
156
157     if success == 0:
158         error("Failed to extract metrics info from dvipng")
159
160     return results
161
162
163 def fix_latex_file(latex_file, pdf_output):
164     def_re = re.compile(rb"(\\newcommandx|\\global\\long\\def)(\\[a-zA-Z]+)")
165
166     tmp = mkstemp()
167
168     changed = False
169     macros = []
170     for line in open(latex_file, 'rb').readlines():
171         if not pdf_output and line.startswith(b"\\documentclass"):
172             changed = True
173             line += b"\\PassOptionsToPackage{draft}{microtype}\n"
174         else:
175             match = def_re.match(line)
176             if match != None:
177                 macroname = match.group(2)
178                 if macroname in macros:
179                     definecmd = match.group(1)
180                     if definecmd == b"\\newcommandx":
181                         changed = True
182                         line = line.replace(definecmd, b"\\renewcommandx")
183                 else:
184                     macros.append(macroname)
185         tmp.write(line)
186
187     if changed:
188         copyfileobj(tmp, open(latex_file,"wb"), 1)
189
190     return changed
191
192
193 def convert_to_ppm_format(pngtopnm, basename):
194     png_file_re = re.compile("\.png$")
195
196     for png_file in glob.glob("%s*.png" % basename):
197         ppm_file = png_file_re.sub(".ppm", png_file)
198
199         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
200         p2p_status, p2p_stdout = run_command(p2p_cmd)
201         if p2p_status:
202             error("Unable to convert %s to ppm format" % png_file)
203
204         ppm = open(ppm_file, 'w')
205         ppm.write(p2p_stdout)
206         os.remove(png_file)
207
208 # Returns a tuple of:
209 # ps_pages: list of page indexes of pages containing PS literals
210 # pdf_pages: list of page indexes of pages requiring running pdflatex
211 # page_count: total number of pages
212 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
213 def find_ps_pages(dvi_file):
214     # latex failed
215     # FIXME: try with pdflatex
216     if not os.path.isfile(dvi_file):
217         error("No DVI output.")
218
219     # Check for PostScript specials in the dvi, badly supported by dvipng,
220     # and inclusion of PDF/PNG/JPG files.
221     # This is required for correct rendering of PSTricks and TikZ
222     dv2dt = find_exe_or_terminate(["dv2dt"])
223     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
224
225     # The output from dv2dt goes to stdout
226     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
227     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
228     hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
229     pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
230
231     # Parse the dtl file looking for PostScript specials and pdflatex files.
232     # Pages using PostScript specials or pdflatex files are recorded in
233     # ps_pages or pdf_pages, respectively, and then used to create a
234     # different LaTeX file for processing in legacy mode.
235     # If hyperref is detected, the corresponding page is recorded in pdf_pages.
236     page_has_ps = False
237     page_has_pdf = False
238     page_index = 0
239     ps_pages = []
240     pdf_pages = []
241     ps_or_pdf_pages = []
242
243     for line in dv2dt_output.split("\n"):
244         # New page
245         if line.startswith("bop"):
246             page_has_ps = False
247             page_has_pdf = False
248             page_index += 1
249
250         # End of page
251         if line.startswith("eop") and (page_has_ps or page_has_pdf):
252             # We save in a list all the PostScript/PDF pages
253             if page_has_ps:
254                 ps_pages.append(page_index)
255             else:
256                 pdf_pages.append(page_index)
257             ps_or_pdf_pages.append(page_index)
258
259         if psliteral_re.match(line) != None:
260             # Literal PostScript special detected!
261             # If hyperref is detected, put this page on the pdf pages list
262             if hyperref_re.match(line) != None:
263                 page_has_ps = False
264                 page_has_pdf = True
265             else:
266                 page_has_ps = True
267         elif pdffile_re.match(line) != None:
268             # Inclusion of pdflatex image file detected!
269             page_has_pdf = True
270
271     # Create the -pp parameter for dvipng
272     pages_parameter = ""
273     if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
274         # Don't process Postscript/PDF 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_or_pdf_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_or_pdf_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_or_pdf_pages) and (not skip) and (last != index):
308                 pages_parameter += "-" + str(index)
309
310     return (ps_pages, pdf_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 as 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 = int(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     # External programs used by the script.
389     latex = find_exe_or_terminate(latex or latex_commands)
390     bibtex = find_exe(bibtex or bibtex_commands)
391     if lilypond:
392         lilypond_book = find_exe_or_terminate(lilypond_book or
393             ["lilypond-book --safe"])
394
395     # These flavors of latex are known to produce pdf output
396     pdf_output = latex in pdflatex_commands
397
398     progress("Latex command: %s" % latex)
399     progress("Latex produces pdf output: %s" % pdf_output)
400     progress("Bibtex command: %s" % bibtex)
401     progress("Lilypond-book command: %s" % lilypond_book)
402     progress("Preprocess through lilypond-book: %s" % lilypond)
403     progress("Altering the latex file for font size and colors")
404
405     # Make sure that multiple defined macros and the microtype package
406     # don't cause issues in the latex file.
407     fix_latex_file(latex_file, pdf_output)
408
409     if lilypond:
410         progress("Preprocess the latex file through %s" % lilypond_book)
411         if pdf_output:
412             lilypond_book += " --pdf"
413         lilypond_book += " --latex-program=%s" % latex.split()[0]
414
415         # Make a copy of the latex file
416         lytex_file = latex_file_re.sub(".lytex", latex_file)
417         shutil.copyfile(latex_file, lytex_file)
418
419         # Preprocess the latex file through lilypond-book.
420         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
421
422     if pdf_output:
423         progress("Using the legacy conversion method (PDF support)")
424         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
425             bg_color, latex, pdf_output)
426
427     # This can go once dvipng becomes widespread.
428     dvipng = find_exe(["dvipng"])
429     if dvipng == None:
430         progress("Using the legacy conversion method (dvipng not found)")
431         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
432             bg_color, latex, pdf_output)
433
434     dv2dt = find_exe(["dv2dt"])
435     if dv2dt == None:
436         progress("Using the legacy conversion method (dv2dt not found)")
437         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
438             bg_color, latex, pdf_output)
439
440     pngtopnm = ""
441     if output_format == "ppm":
442         pngtopnm = find_exe(["pngtopnm"])
443         if pngtopnm == None:
444             progress("Using the legacy conversion method (pngtopnm not found)")
445             return legacy_conversion_step1(latex_file, dpi, output_format,
446                 fg_color, bg_color, latex, pdf_output)
447
448     # Compile the latex file.
449     error_pages = []
450     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
451     latex_log = latex_file_re.sub(".log", latex_file)
452     if latex_status:
453         progress("Will try to recover from %s failure" % latex)
454         error_pages = check_latex_log(latex_log)
455
456     # The dvi output file name
457     dvi_file = latex_file_re.sub(".dvi", latex_file)
458
459     # If there's no DVI output, look for PDF and go to legacy or fail
460     if not os.path.isfile(dvi_file):
461         # No DVI, is there a PDF?
462         pdf_file = latex_file_re.sub(".pdf", latex_file)
463         if os.path.isfile(pdf_file):
464             progress("%s produced a PDF output, fallback to legacy." \
465                 % (os.path.basename(latex)))
466             progress("Using the legacy conversion method (PDF support)")
467             return legacy_conversion_step1(latex_file, dpi, output_format,
468                 fg_color, bg_color, latex, True)
469         else:
470             error("No DVI or PDF output. %s failed." \
471                 % (os.path.basename(latex)))
472
473     # Look for PS literals or inclusion of pdflatex files in DVI pages
474     # ps_pages: list of indexes of pages containing PS literals
475     # pdf_pages: list of indexes of pages requiring running pdflatex
476     # page_count: total number of pages
477     # pages_parameter: parameter for dvipng to exclude pages with PostScript
478     (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
479
480     # If all pages need PostScript or pdflatex, directly use the legacy method.
481     if len(ps_pages) == page_count:
482         progress("Using the legacy conversion method (PostScript support)")
483         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
484             bg_color, latex, pdf_output)
485     elif len(pdf_pages) == page_count:
486         progress("Using the legacy conversion method (PDF support)")
487         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
488             bg_color, "pdflatex", True)
489
490     # Retrieve resolution
491     resolution = extract_resolution(latex_log, dpi)
492
493     # Run the dvi file through dvipng.
494     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
495         % (dvipng, resolution, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
496     dvipng_status, dvipng_stdout = run_command(dvipng_call)
497
498     if dvipng_status:
499         warning("%s failed to generate images from %s... fallback to legacy method" \
500               % (os.path.basename(dvipng), dvi_file))
501         progress("Using the legacy conversion method (dvipng failed)")
502         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
503             bg_color, latex, pdf_output)
504
505     # Extract metrics info from dvipng_stdout.
506     metrics_file = latex_file_re.sub(".metrics", latex_file)
507     dvipng_metrics = extract_metrics_info(dvipng_stdout)
508
509     # If some pages require PostScript pass them to legacy method
510     if len(ps_pages) > 0:
511         # Create a new LaTeX file just for the snippets needing
512         # the legacy method
513         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
514         filter_pages(latex_file, legacy_latex_file, ps_pages)
515
516         # Pass the new LaTeX file to the legacy method
517         progress("Pages %s include postscript specials" % ps_pages)
518         progress("Using the legacy conversion method (PostScript support)")
519         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
520             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
521
522         # Now we need to mix metrics data from dvipng and the legacy method
523         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
524         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
525
526         # Join metrics from dvipng and legacy, and rename legacy bitmaps
527         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
528             original_bitmap, destination_bitmap)
529
530     # If some pages require running pdflatex pass them to legacy method
531     if len(pdf_pages) > 0:
532         # Create a new LaTeX file just for the snippets needing
533         # the legacy method
534         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
535         filter_pages(latex_file, legacy_latex_file, pdf_pages)
536
537         # Pass the new LaTeX file to the legacy method
538         progress("Pages %s require processing with pdflatex" % pdf_pages)
539         progress("Using the legacy conversion method (PDF support)")
540         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
541             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
542
543         # Now we need to mix metrics data from dvipng and the legacy method
544         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
545         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
546
547         # Join metrics from dvipng and legacy, and rename legacy bitmaps
548         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
549             original_bitmap, destination_bitmap)
550
551     # Invalidate metrics for pages that produced errors
552     if len(error_pages) > 0:
553         error_count = 0
554         for index in error_pages:
555             if index not in ps_pages and index not in pdf_pages:
556                 dvipng_metrics.pop(index - 1)
557                 dvipng_metrics.insert(index - 1, (index, -1.0))
558                 error_count += 1
559         if error_count:
560             warning("Failed to produce %d preview snippet(s)" % error_count)
561
562     # Convert images to ppm format if necessary.
563     if output_format == "ppm":
564         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
565
566     # Actually create the .metrics file
567     write_metrics_info(dvipng_metrics, metrics_file)
568
569     return (0, dvipng_metrics)
570
571 if __name__ == "__main__":
572     sys.exit(main(sys.argv)[0])