]> git.lyx.org Git - lyx.git/blobdiff - lib/scripts/lyxpreview_tools.py
* lyxpreview_tool.py : Allow to look for commands with arguments.
[lyx.git] / lib / scripts / lyxpreview_tools.py
index 7d22b6514a1273f7f68df9b88f6ed709b3b53537..767689f98ccaf800c946a5dedd31b7a2c47edc1c 100644 (file)
 
 # A repository of the following functions, used by the lyxpreview2xyz scripts.
 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
-# run_command, warning
+# progress, run_command, warning
 
-import os, re, string, sys, tempfile
+# Requires python 2.4 or later (subprocess module).
+
+import os, re, string, subprocess, sys, tempfile
+
+
+# Control the output to stdout
+debug = False
+verbose = False
+
+# Known flavors of latex
+latex_commands = ("latex", "pplatex", "platex", "latex2e")
+pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
+
+# Pre-compiled regular expressions
+latex_file_re = re.compile(r"\.tex$")
+
+# PATH and PATHEXT environment variables
+path = os.environ["PATH"].split(os.pathsep)
+extlist = ['']
+if "PATHEXT" in os.environ:
+    extlist += os.environ["PATHEXT"].split(os.pathsep)
 
 use_win32_modules = 0
 if os.name == "nt":
@@ -29,17 +49,23 @@ if os.name == "nt":
         import win32security
         import winerror
     except:
-        sys.stderr.write("Consider installing the PyWin extension modules "\
+        sys.stderr.write("Consider installing the PyWin extension modules " \
                          "if you're irritated by windows appearing briefly.\n")
         use_win32_modules = 0
 
 
+def progress(message):
+    global verbose
+    if verbose:
+        sys.stdout.write("Progress: %s\n" % message)
+
+
 def warning(message):
-    sys.stderr.write(message + '\n')
+    sys.stderr.write("Warning: %s\n" % message)
 
 
 def error(message):
-    sys.stderr.write(message + '\n')
+    sys.stderr.write("Error: %s\n" % message)
     sys.exit(1)
 
 
@@ -59,12 +85,11 @@ def make_texcolor(hexcolor, graphics):
         return "rgb %f %f %f" % (red, green, blue)
 
 
-def find_exe(candidates, path):
-    extlist = ['']
-    if os.environ.has_key("PATHEXT"):
-        extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
+def find_exe(candidates):
+    global extlist, path
 
-    for prog in candidates:
+    for command in candidates:
+        prog = command.split()[0]
         for directory in path:
             for ext in extlist:
                 full_path = os.path.join(directory, prog + ext)
@@ -73,13 +98,13 @@ def find_exe(candidates, path):
                     # have found it). Return just the basename to avoid
                     # problems when the path to the executable contains
                     # spaces.
-                    return os.path.basename(full_path)
+                    return command
 
     return None
 
 
-def find_exe_or_terminate(candidates, path):
-    exe = find_exe(candidates, path)
+def find_exe_or_terminate(candidates):
+    exe = find_exe(candidates)
     if exe == None:
         error("Unable to find executable from '%s'" % string.join(candidates))
 
@@ -87,10 +112,18 @@ def find_exe_or_terminate(candidates, path):
 
 
 def run_command_popen(cmd):
-    handle = os.popen(cmd, 'r')
-    cmd_stdout = handle.read()
-    cmd_status = handle.close()
-
+    if os.name == 'nt':
+        unix = False
+    else:
+        unix = True
+    pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
+        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
+    cmd_stdout = pipe.communicate()[0]
+    cmd_status = pipe.returncode
+
+    global debug
+    if debug:
+        sys.stdout.write(cmd_stdout)
     return cmd_status, cmd_stdout
 
 
@@ -138,10 +171,14 @@ def run_command_win32(cmd):
     if win32process.GetExitCodeProcess(process):
         return -3, ""
 
-    return None, data
+    global debug
+    if debug:
+        sys.stdout.write(data)
+    return 0, data
 
 
 def run_command(cmd):
+    progress("Running %s" % cmd)
     if use_win32_modules:
         return run_command_win32(cmd)
     else:
@@ -220,3 +257,52 @@ def write_metrics_info(metrics_info, metrics_file):
     for metric in metrics_info:
         metrics.write("Snippet %s %f\n" % metric)
     metrics.close()
+
+# Reads a .tex files and create an identical file but only with
+# pages whose index is in pages_to_keep
+def filter_pages(source_path, destination_path, pages_to_keep):
+    source_file = open(source_path, "r")
+    destination_file = open(destination_path, "w")
+
+    page_index = 0
+    skip_page = False
+    for line in source_file:
+        # We found a new page
+        if line.startswith("\\begin{preview}"):
+            page_index += 1
+            # If the page index isn't in pages_to_keep we don't copy it
+            skip_page = page_index not in pages_to_keep
+
+        if not skip_page:
+            destination_file.write(line)
+
+        # End of a page, we reset the skip_page bool
+        if line.startswith("\\end{preview}"):
+            skip_page = False
+
+    destination_file.close()
+    source_file.close()
+
+# Joins two metrics list, that is a list of tuple (page_index, metric)
+# new_page_indexes contains the original page number of the pages in new_metrics
+# e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
+# original_bitmap and destination_bitmap are file name models used to rename the new files
+# e.g. image_new%d.png and image_%d.png
+def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
+    legacy_index = 0
+    for (index, metric) in new_metrics:
+        # If the file exists we rename it
+        if os.path.isfile(original_bitmap % (index)):
+            os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
+
+        # Extract the original page index
+        index = new_page_indexes[index-1]
+        # Goes through the array until the end is reached or the correct index is found
+        while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
+            legacy_index += 1
+
+        # Add or update the metric for this page
+        if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
+            original_metrics[legacy_index] = (index, metric)
+        else:
+            original_metrics.insert(legacy_index, (index, metric))