]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
Remove profiling.py
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 # file lyxpreview2bitmap.py
2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
4
5 # author Angus Leeming
6 # with much advice from members of the preview-latex project:
7 # David Kastrup, dak@gnu.org and
8 # Jan-Åke Larsson, jalar@mai.liu.se.
9
10 # Full author contact details are available in file CREDITS
11
12 # This script takes a LaTeX file and generates a collection of
13 # png or ppm image files, one per previewed snippet.
14
15 # Pre-requisites:
16 # * python 2.4 or later (subprocess module);
17 # * A latex executable;
18 # * preview.sty;
19 # * dvipng;
20 # * dv2dt;
21 # * pngtoppm (if outputing ppm format images).
22
23 # preview.sty and dvipng are part of the preview-latex project
24 # http://preview-latex.sourceforge.net/
25
26 # preview.sty can alternatively be obtained from
27 # CTAN/support/preview-latex/
28
29 # Example usage:
30 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
31
32 # This script takes one obligatory argument:
33 #
34 #   <input file>:  The name of the .tex file to be converted.
35 #
36 # and these optional arguments:
37 #
38 #   --png, --ppm:  The desired output format. Either 'png' or 'ppm'.
39 #   --dpi=<res>:   A scale factor, used to ascertain the resolution of the
40 #                  generated image which is then passed to gs.
41 #   --fg=<color>:  The foreground color as a hexadecimal string, eg '000000'.
42 #   --bg=<color>:  The background color as a hexadecimal string, eg 'faf0e6'.
43 #   --latex=<exe>: The converter for latex files. Default is latex.
44 #   --bibtex=<exe>: The converter for bibtex files. Default is bibtex.
45 #   --lilypond:    Preprocess through lilypond-book. Default is false.
46 #   --lilypond-book=<exe>:
47 #                  The converter for lytex files. Default is lilypond-book.
48 #
49 #   -d, --debug    Show the output from external commands.
50 #   -h, --help     Show an help screen and exit.
51 #   -v, --verbose  Show progress messages.
52
53 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
54 # if executed successfully, leave in DIR:
55 # * a (possibly large) number of image files with names
56 #   like BASE[0-9]+.png
57 # * a file BASE.metrics, containing info needed by LyX to position
58 #   the images correctly on the screen.
59
60 # What does this script do?
61 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
62 # 2) If the output is a PDF fallback to legacy
63 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
64 #    PostScript literals, not well supported by dvipng. Pages
65 #    containing them are passed to the legacy method in a new LaTeX file.
66 # 4) Call dvipng on the pages without PS literals
67 # 5) Join metrics info coming from both methods (legacy and dvipng)
68 #    and write them to file
69
70 # dvipng is fast but gives problem in several cases, like with
71 # PSTricks, TikZ and other packages using PostScript literals
72 # for all these cases the legacy route is taken (step 3).
73 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
74 # paramter is pdflatex we have to fallback to legacy route (step 2).
75
76
77 import getopt, glob, os, re, shutil, sys, tempfile
78
79 import lyxpreview_tools
80
81 from legacy_lyxpreview2ppm import extract_resolution, legacy_conversion_step1
82
83 from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
84      error, filter_pages, find_exe, find_exe_or_terminate, \
85      join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
86      pdflatex_commands, progress, run_command, run_latex, run_tex, \
87      warning, write_metrics_info
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(r"\[([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 = float(match.group(1))
138         ascent  = float(match.group(2))
139
140         frac = 0.5
141         if ascent < 0:
142             # This is an empty image, forbid its display
143             frac = -1.0
144         elif ascent >= 0 or descent >= 0:
145             if abs(ascent + descent) > 0.1:
146                 frac = ascent / (ascent + descent)
147
148             # Sanity check
149             if frac < 0:
150                 frac = 0.5
151
152         results.append((int(page), frac))
153         pos = match.end() + 2
154
155     if success == 0:
156         error("Failed to extract metrics info from dvipng")
157
158     return results
159
160
161 def fix_latex_file(latex_file, pdf_output):
162     # python 2 does not allow to declare a string as raw byte so we double
163     # the backslashes and remove the r preffix
164     def_re = re.compile(b"(\\\\newcommandx|\\\\global\\\\long\\\\def)"
165                         b"(\\\\[a-zA-Z]+)")
166
167     tmp = tempfile.TemporaryFile()
168
169     changed = False
170     macros = []
171     for line in open(latex_file, 'rb').readlines():
172         if not pdf_output and line.startswith(b"\\documentclass"):
173             changed = True
174             line += b"\\PassOptionsToPackage{draft}{microtype}\n"
175         else:
176             match = def_re.match(line)
177             if match != None:
178                 macroname = match.group(2)
179                 if macroname in macros:
180                     definecmd = match.group(1)
181                     if definecmd == b"\\newcommandx":
182                         changed = True
183                         line = line.replace(definecmd, b"\\renewcommandx")
184                 else:
185                     macros.append(macroname)
186         tmp.write(line)
187
188     if changed:
189         copyfileobj(tmp, open(latex_file,"wb"), 1)
190
191     return changed
192
193
194 def convert_to_ppm_format(pngtopnm, basename):
195     png_file_re = re.compile(r"\.png$")
196
197     for png_file in glob.glob("%s*.png" % basename):
198         ppm_file = png_file_re.sub(".ppm", png_file)
199
200         p2p_cmd = f'{pngtopnm} "{png_file}"'
201         p2p_status, p2p_stdout = run_command(p2p_cmd)
202         if p2p_status:
203             error("Unable to convert %s to ppm format" % png_file)
204
205         ppm = open(ppm_file, 'w')
206         ppm.write(p2p_stdout)
207         os.remove(png_file)
208
209 # Returns a tuple of:
210 # ps_pages: list of page indexes of pages containing PS literals
211 # pdf_pages: list of page indexes of pages requiring running pdflatex
212 # page_count: total number of pages
213 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
214 def find_ps_pages(dvi_file):
215     # latex failed
216     # FIXME: try with pdflatex
217     if not os.path.isfile(dvi_file):
218         error("No DVI output.")
219
220     # Check for PostScript specials in the dvi, badly supported by dvipng,
221     # and inclusion of PDF/PNG/JPG files.
222     # This is required for correct rendering of PSTricks and TikZ
223     dv2dt = find_exe_or_terminate(["dv2dt"])
224     dv2dt_call = f'{dv2dt} "{dvi_file}"'
225
226     # The output from dv2dt goes to stdout
227     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
228     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
229     hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
230     pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
231
232     # Parse the dtl file looking for PostScript specials and pdflatex files.
233     # Pages using PostScript specials or pdflatex files are recorded in
234     # ps_pages or pdf_pages, respectively, and then used to create a
235     # different LaTeX file for processing in legacy mode.
236     # If hyperref is detected, the corresponding page is recorded in pdf_pages.
237     page_has_ps = False
238     page_has_pdf = False
239     page_index = 0
240     ps_pages = []
241     pdf_pages = []
242     ps_or_pdf_pages = []
243
244     for line in dv2dt_output.split("\n"):
245         # New page
246         if line.startswith("bop"):
247             page_has_ps = False
248             page_has_pdf = False
249             page_index += 1
250
251         # End of page
252         if line.startswith("eop") and (page_has_ps or page_has_pdf):
253             # We save in a list all the PostScript/PDF pages
254             if page_has_ps:
255                 ps_pages.append(page_index)
256             else:
257                 pdf_pages.append(page_index)
258             ps_or_pdf_pages.append(page_index)
259
260         if psliteral_re.match(line) != None:
261             # Literal PostScript special detected!
262             # If hyperref is detected, put this page on the pdf pages list
263             if hyperref_re.match(line) != None:
264                 page_has_ps = False
265                 page_has_pdf = True
266             else:
267                 page_has_ps = True
268         elif pdffile_re.match(line) != None:
269             # Inclusion of pdflatex image file detected!
270             page_has_pdf = True
271
272     # Create the -pp parameter for dvipng
273     pages_parameter = ""
274     if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
275         # Don't process Postscript/PDF pages with dvipng by selecting the
276         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
277         pages_parameter = " -pp "
278         skip = True
279         last = -1
280
281         # Use page ranges, as a list of pages could exceed command line
282         # maximum length (especially under Win32)
283         for index in range(1, page_index + 1):
284             if (not index in ps_or_pdf_pages) and skip:
285                 # We were skipping pages but current page shouldn't be skipped.
286                 # Add this page to -pp, it could stay alone or become the
287                 # start of a range.
288                 pages_parameter += str(index)
289                 # Save the starting index to avoid things such as "11-11"
290                 last = index
291                 # We're not skipping anymore
292                 skip = False
293             elif (index in ps_or_pdf_pages) and (not skip):
294                 # We weren't skipping but current page should be skipped
295                 if last != index - 1:
296                     # If the start index of the range is the previous page
297                     # then it's not a range
298                     pages_parameter += "-" + str(index - 1)
299
300                 # Add a separator
301                 pages_parameter += ","
302                 # Now we're skipping
303                 skip = True
304
305         # Remove the trailing separator
306         pages_parameter = pages_parameter.rstrip(",")
307         # We've to manage the case in which the last page is closing a range
308         if (not index in ps_or_pdf_pages) and (not skip) and (last != index):
309                 pages_parameter += "-" + str(index)
310
311     return (ps_pages, pdf_pages, page_index, pages_parameter)
312
313 def main(argv):
314     # Set defaults.
315     dpi = 128
316     fg_color = "000000"
317     bg_color = "ffffff"
318     bibtex = None
319     latex = None
320     lilypond = False
321     lilypond_book = None
322     output_format = "png"
323     script_name = argv[0]
324
325     # Parse and manipulate the command line arguments.
326     try:
327         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
328             "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
329             "lilypond-book=", "png", "ppm", "verbose"])
330     except getopt.GetoptError as err:
331         error(f"{err}\n{usage(script_name)}")
332
333     opts.reverse()
334     for opt, val in opts:
335         if opt in ("-h", "--help"):
336             print(usage(script_name))
337             sys.exit(0)
338         elif opt == "--bibtex":
339             bibtex = [val]
340         elif opt == "--bg":
341             bg_color = val
342         elif opt in ("-d", "--debug"):
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             lyxpreview_tools.verbose = True
361
362     # Determine input file
363     if len(args) != 1:
364         err = "A single input file is required, %s given" % (len(args) or "none")
365         error(f"{err}\n{usage(script_name)}")
366
367     input_path = args[0]
368     dir, latex_file = os.path.split(input_path)
369
370     # Check for the input file
371     if not os.path.exists(input_path):
372         error('File "%s" not found.' % input_path)
373     if len(dir) != 0:
374         os.chdir(dir)
375
376     if lyxpreview_tools.verbose:
377         f_out = open('verbose.txt', 'a')
378         sys.stdout = f_out
379         sys.stderr = f_out
380
381     # Echo the settings
382     progress("Running Python %s" % str(sys.version_info[:3]))
383     progress("Starting %s..." % script_name)
384     if os.name == "nt":
385         progress("Use win32_modules: %d" % lyxpreview_tools.use_win32_modules)
386     progress("Output format: %s" % output_format)
387     progress("Foreground color: %s" % fg_color)
388     progress("Background color: %s" % bg_color)
389     progress("Resolution (dpi): %s" % dpi)
390     progress("File to process: %s" % input_path)
391
392     fg_color = bytes(fg_color, 'ascii')
393     bg_color = bytes(bg_color, 'ascii')
394
395     fg_color_dvipng = make_texcolor(fg_color, False).decode('ascii')
396     bg_color_dvipng = make_texcolor(bg_color, False).decode('ascii')
397
398     # External programs used by the script.
399     latex = find_exe_or_terminate(latex or latex_commands)
400     bibtex = find_exe(bibtex or bibtex_commands)
401     if lilypond:
402         lilypond_book = find_exe_or_terminate(lilypond_book or
403             ["lilypond-book --safe"])
404
405     # These flavors of latex are known to produce pdf output
406     pdf_output = latex in pdflatex_commands
407
408     progress("Latex command: %s" % latex)
409     progress("Latex produces pdf output: %s" % pdf_output)
410     progress("Bibtex command: %s" % bibtex)
411     progress("Lilypond-book command: %s" % lilypond_book)
412     progress("Preprocess through lilypond-book: %s" % lilypond)
413     progress("Altering the latex file for font size and colors")
414
415     # Make sure that multiple defined macros and the microtype package
416     # don't cause issues in the latex file.
417     fix_latex_file(latex_file, pdf_output)
418
419     if lilypond:
420         progress("Preprocess the latex file through %s" % lilypond_book)
421         if pdf_output:
422             lilypond_book += " --pdf"
423         lilypond_book += " --latex-program=%s" % latex.split()[0]
424
425         # Make a copy of the latex file
426         lytex_file = latex_file_re.sub(".lytex", latex_file)
427         shutil.copyfile(latex_file, lytex_file)
428
429         # Preprocess the latex file through lilypond-book.
430         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
431
432     if pdf_output:
433         progress("Using the legacy conversion method (PDF support)")
434         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
435             bg_color, latex, pdf_output)
436
437     # This can go once dvipng becomes widespread.
438     dvipng = find_exe(["dvipng"])
439     if dvipng == None:
440         progress("Using the legacy conversion method (dvipng not found)")
441         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
442             bg_color, latex, pdf_output)
443
444     dv2dt = find_exe(["dv2dt"])
445     if dv2dt == None:
446         progress("Using the legacy conversion method (dv2dt not found)")
447         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
448             bg_color, latex, pdf_output)
449
450     pngtopnm = ""
451     if output_format == "ppm":
452         pngtopnm = find_exe(["pngtopnm"])
453         if pngtopnm == None:
454             progress("Using the legacy conversion method (pngtopnm not found)")
455             return legacy_conversion_step1(latex_file, dpi, output_format,
456                 fg_color, bg_color, latex, pdf_output)
457
458     # Compile the latex file.
459     error_pages = []
460     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
461     latex_log = latex_file_re.sub(".log", latex_file)
462     if latex_status:
463         progress("Will try to recover from %s failure" % latex)
464         error_pages = check_latex_log(latex_log)
465
466     # The dvi output file name
467     dvi_file = latex_file_re.sub(".dvi", latex_file)
468
469     # If there's no DVI output, look for PDF and go to legacy or fail
470     if not os.path.isfile(dvi_file):
471         # No DVI, is there a PDF?
472         pdf_file = latex_file_re.sub(".pdf", latex_file)
473         if os.path.isfile(pdf_file):
474             progress("%s produced a PDF output, fallback to legacy." \
475                 % (os.path.basename(latex)))
476             progress("Using the legacy conversion method (PDF support)")
477             return legacy_conversion_step1(latex_file, dpi, output_format,
478                 fg_color, bg_color, latex, True)
479         else:
480             error("No DVI or PDF output. %s failed." \
481                 % (os.path.basename(latex)))
482
483     # Look for PS literals or inclusion of pdflatex files in DVI pages
484     # ps_pages: list of indexes of pages containing PS literals
485     # pdf_pages: list of indexes of pages requiring running pdflatex
486     # page_count: total number of pages
487     # pages_parameter: parameter for dvipng to exclude pages with PostScript
488     (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
489
490     # If all pages need PostScript or pdflatex, directly use the legacy method.
491     if len(ps_pages) == page_count:
492         progress("Using the legacy conversion method (PostScript support)")
493         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
494             bg_color, latex, pdf_output)
495     elif len(pdf_pages) == page_count:
496         progress("Using the legacy conversion method (PDF support)")
497         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
498             bg_color, "pdflatex", True)
499
500     # Retrieve resolution
501     resolution = extract_resolution(latex_log, dpi)
502
503     # Run the dvi file through dvipng.
504     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
505         % (dvipng, resolution, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
506     dvipng_status, dvipng_stdout = run_command(dvipng_call)
507
508     if dvipng_status:
509         warning("%s failed to generate images from %s... fallback to legacy method" \
510               % (os.path.basename(dvipng), dvi_file))
511         progress("Using the legacy conversion method (dvipng failed)")
512         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
513             bg_color, latex, pdf_output)
514
515     # Extract metrics info from dvipng_stdout.
516     metrics_file = latex_file_re.sub(".metrics", latex_file)
517     dvipng_metrics = extract_metrics_info(dvipng_stdout)
518
519     # If some pages require PostScript pass them to legacy method
520     if len(ps_pages) > 0:
521         # Create a new LaTeX file just for the snippets needing
522         # the legacy method
523         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
524         filter_pages(latex_file, legacy_latex_file, ps_pages)
525
526         # Pass the new LaTeX file to the legacy method
527         progress("Pages %s include postscript specials" % ps_pages)
528         progress("Using the legacy conversion method (PostScript support)")
529         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
530             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
531
532         # Now we need to mix metrics data from dvipng and the legacy method
533         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
534         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
535
536         # Join metrics from dvipng and legacy, and rename legacy bitmaps
537         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
538             original_bitmap, destination_bitmap)
539
540     # If some pages require running pdflatex pass them to legacy method
541     if len(pdf_pages) > 0:
542         # Create a new LaTeX file just for the snippets needing
543         # the legacy method
544         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
545         filter_pages(latex_file, legacy_latex_file, pdf_pages)
546
547         # Pass the new LaTeX file to the legacy method
548         progress("Pages %s require processing with pdflatex" % pdf_pages)
549         progress("Using the legacy conversion method (PDF support)")
550         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
551             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
552
553         # Now we need to mix metrics data from dvipng and the legacy method
554         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
555         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
556
557         # Join metrics from dvipng and legacy, and rename legacy bitmaps
558         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
559             original_bitmap, destination_bitmap)
560
561     # Invalidate metrics for pages that produced errors
562     if len(error_pages) > 0:
563         error_count = 0
564         for index in error_pages:
565             if index not in ps_pages and index not in pdf_pages:
566                 dvipng_metrics.pop(index - 1)
567                 dvipng_metrics.insert(index - 1, (index, -1.0))
568                 error_count += 1
569         if error_count:
570             warning("Failed to produce %d preview snippet(s)" % error_count)
571
572     # Convert images to ppm format if necessary.
573     if output_format == "ppm":
574         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
575
576     # Actually create the .metrics file
577     write_metrics_info(dvipng_metrics, metrics_file)
578
579     return (0, dvipng_metrics)
580
581 if __name__ == "__main__":
582     sys.exit(main(sys.argv)[0])