]> git.lyx.org Git - lyx.git/blobdiff - lib/scripts/lyxpreview2bitmap.py
The way this was previously, it had to fail if the GUI language
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
index de4121f2dbca750ea22ed3226c0a8d070ad22d00..95bb895380a0e4de7efdaa1585ca121e7b624c05 100755 (executable)
 
 import getopt, glob, os, re, shutil, string, sys
 
-from legacy_lyxpreview2ppm import legacy_conversion_step1
+from legacy_lyxpreview2ppm import extract_resolution, legacy_conversion_step1
 
-from lyxpreview_tools import bibtex_commands, copyfileobj, error, \
-     filter_pages, find_exe, find_exe_or_terminate, join_metrics_and_rename, \
-     latex_commands, latex_file_re, make_texcolor, mkstemp, pdflatex_commands, \
-     progress, run_command, run_latex, run_tex, warning, write_metrics_info
+from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
+     error, filter_pages, find_exe, find_exe_or_terminate, \
+     join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
+     mkstemp, pdflatex_commands, progress, run_command, run_latex, run_tex, \
+     warning, write_metrics_info
 
 
 def usage(prog_name):
@@ -157,27 +158,29 @@ def extract_metrics_info(dvipng_stdout):
     return results
 
 
-def fix_latex_file(latex_file):
-    documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
-    newcommandx_re = re.compile("^(\\\\newcommandx)(.+)")
+def fix_latex_file(latex_file, pdf_output):
+    def_re = re.compile(r"(\\newcommandx|\\global\\long\\def)(\\[a-zA-Z]+)")
 
     tmp = mkstemp()
 
-    changed = 0
+    changed = False
+    macros = []
     for line in open(latex_file, 'r').readlines():
-        match = documentclass_re.match(line)
-        if match != None:
-            changed = 1
-            tmp.write("%s%s\n" % (match.group(1), match.group(3)))
-            continue
-
-        match = newcommandx_re.match(line)
-        if match == None:
-            tmp.write(line)
-            continue
-
-        changed = 1
-        tmp.write("\\providecommandx%s\n" % match.group(2))
+        if not pdf_output and line.startswith("\\documentclass"):
+            changed = True
+            line += "\\PassOptionsToPackage{draft}{microtype}\n"
+        else:
+            match = def_re.match(line)
+            if match != None:
+                macroname = match.group(2)
+                if macroname in macros:
+                    definecmd = match.group(1)
+                    if definecmd == "\\newcommandx":
+                        changed = True
+                        line = line.replace(definecmd, "\\renewcommandx")
+                else:
+                    macros.append(macroname)
+        tmp.write(line)
 
     if changed:
         copyfileobj(tmp, open(latex_file,"wb"), 1)
@@ -220,12 +223,14 @@ def find_ps_pages(dvi_file):
     # The output from dv2dt goes to stdout
     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
-    pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*.(pdf|png|jpg)")
+    hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
+    pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
 
     # Parse the dtl file looking for PostScript specials and pdflatex files.
     # Pages using PostScript specials or pdflatex files are recorded in
     # ps_pages or pdf_pages, respectively, and then used to create a
     # different LaTeX file for processing in legacy mode.
+    # If hyperref is detected, the corresponding page is recorded in pdf_pages.
     page_has_ps = False
     page_has_pdf = False
     page_index = 0
@@ -251,9 +256,13 @@ def find_ps_pages(dvi_file):
 
         if psliteral_re.match(line) != None:
             # Literal PostScript special detected!
-            page_has_ps = True
-
-        if pdffile_re.match(line) != None:
+            # If hyperref is detected, put this page on the pdf pages list
+            if hyperref_re.match(line) != None:
+                page_has_ps = False
+                page_has_pdf = True
+            else:
+                page_has_ps = True
+        elif pdffile_re.match(line) != None:
             # Inclusion of pdflatex image file detected!
             page_has_pdf = True
 
@@ -391,9 +400,9 @@ def main(argv):
     progress("Preprocess through lilypond-book: %s" % lilypond)
     progress("Altering the latex file for font size and colors")
 
-    # Omit font size specification in latex file and make sure multiple
-    # defined macros are not an issue.
-    fix_latex_file(latex_file)
+    # Make sure that multiple defined macros and the microtype package
+    # don't cause issues in the latex file.
+    fix_latex_file(latex_file, pdf_output)
 
     if lilypond:
         progress("Preprocess the latex file through %s" % lilypond_book)
@@ -435,7 +444,12 @@ def main(argv):
                 fg_color, bg_color, latex, pdf_output)
 
     # Compile the latex file.
-    run_latex(latex, latex_file, bibtex)
+    error_pages = []
+    latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
+    latex_log = latex_file_re.sub(".log", latex_file)
+    if latex_status:
+        progress("Will try to recover from %s failure" % latex)
+        error_pages = check_latex_log(latex_log)
 
     # The dvi output file name
     dvi_file = latex_file_re.sub(".dvi", latex_file)
@@ -471,9 +485,12 @@ def main(argv):
         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
             bg_color, "pdflatex", True)
 
+    # Retrieve resolution
+    resolution = extract_resolution(latex_log, dpi)
+
     # Run the dvi file through dvipng.
     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
-        % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
+        % (dvipng, resolution, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
     dvipng_status, dvipng_stdout = run_command(dvipng_call)
 
     if dvipng_status:
@@ -516,7 +533,7 @@ def main(argv):
         filter_pages(latex_file, legacy_latex_file, pdf_pages)
 
         # Pass the new LaTeX file to the legacy method
-        progress("Pages %s include pdflatex image files" % pdf_pages)
+        progress("Pages %s require processing with pdflatex" % pdf_pages)
         progress("Using the legacy conversion method (PDF support)")
         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
@@ -529,6 +546,17 @@ def main(argv):
         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
             original_bitmap, destination_bitmap)
 
+    # Invalidate metrics for pages that produced errors
+    if len(error_pages) > 0:
+        error_count = 0
+        for index in error_pages:
+            if index not in ps_pages and index not in pdf_pages:
+                dvipng_metrics.pop(index - 1)
+                dvipng_metrics.insert(index - 1, (index, -1.0))
+                error_count += 1
+        if error_count:
+            warning("Failed to produce %d preview snippet(s)" % error_count)
+
     # Convert images to ppm format if necessary.
     if output_format == "ppm":
         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))