]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
7d22b6514a1273f7f68df9b88f6ed709b3b53537
[lyx.git] / lib / scripts / lyxpreview_tools.py
1 #! /usr/bin/env python
2
3 # file lyxpreview_tools.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 # Full author contact details are available in file CREDITS
9
10 # and with much help testing the code under Windows from
11 #   Paul A. Rubin, rubin@msu.edu.
12
13 # A repository of the following functions, used by the lyxpreview2xyz scripts.
14 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
15 # run_command, warning
16
17 import os, re, string, sys, tempfile
18
19 use_win32_modules = 0
20 if os.name == "nt":
21     use_win32_modules = 1
22     try:
23         import pywintypes
24         import win32con
25         import win32event
26         import win32file
27         import win32pipe
28         import win32process
29         import win32security
30         import winerror
31     except:
32         sys.stderr.write("Consider installing the PyWin extension modules "\
33                          "if you're irritated by windows appearing briefly.\n")
34         use_win32_modules = 0
35
36
37 def warning(message):
38     sys.stderr.write(message + '\n')
39
40
41 def error(message):
42     sys.stderr.write(message + '\n')
43     sys.exit(1)
44
45
46 def make_texcolor(hexcolor, graphics):
47     # Test that the input string contains 6 hexadecimal chars.
48     hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
49     if not hexcolor_re.match(hexcolor):
50         error("Cannot convert color '%s'" % hexcolor)
51
52     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
53     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
54     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
55
56     if graphics:
57         return "%f,%f,%f" % (red, green, blue)
58     else:
59         return "rgb %f %f %f" % (red, green, blue)
60
61
62 def find_exe(candidates, path):
63     extlist = ['']
64     if os.environ.has_key("PATHEXT"):
65         extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
66
67     for prog in candidates:
68         for directory in path:
69             for ext in extlist:
70                 full_path = os.path.join(directory, prog + ext)
71                 if os.access(full_path, os.X_OK):
72                     # The thing is in the PATH already (or we wouldn't
73                     # have found it). Return just the basename to avoid
74                     # problems when the path to the executable contains
75                     # spaces.
76                     return os.path.basename(full_path)
77
78     return None
79
80
81 def find_exe_or_terminate(candidates, path):
82     exe = find_exe(candidates, path)
83     if exe == None:
84         error("Unable to find executable from '%s'" % string.join(candidates))
85
86     return exe
87
88
89 def run_command_popen(cmd):
90     handle = os.popen(cmd, 'r')
91     cmd_stdout = handle.read()
92     cmd_status = handle.close()
93
94     return cmd_status, cmd_stdout
95
96
97 def run_command_win32(cmd):
98     sa = win32security.SECURITY_ATTRIBUTES()
99     sa.bInheritHandle = True
100     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
101
102     si = win32process.STARTUPINFO()
103     si.dwFlags = (win32process.STARTF_USESTDHANDLES
104                   | win32process.STARTF_USESHOWWINDOW)
105     si.wShowWindow = win32con.SW_HIDE
106     si.hStdOutput = stdout_w
107
108     process, thread, pid, tid = \
109              win32process.CreateProcess(None, cmd, None, None, True,
110                                         0, None, None, si)
111     if process == None:
112         return -1, ""
113
114     # Must close the write handle in this process, or ReadFile will hang.
115     stdout_w.Close()
116
117     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
118     # which is okay because it happens when child process ends).
119     data = ""
120     error = 0
121     while 1:
122         try:
123             hr, buffer = win32file.ReadFile(stdout_r, 4096)
124             if hr != winerror.ERROR_IO_PENDING:
125                 data = data + buffer
126
127         except pywintypes.error, e:
128             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
129                 error = 1
130             break
131
132     if error:
133         return -2, ""
134
135     # Everything is okay --- the called process has closed the pipe.
136     # For safety, check that the process ended, then pick up its exit code.
137     win32event.WaitForSingleObject(process, win32event.INFINITE)
138     if win32process.GetExitCodeProcess(process):
139         return -3, ""
140
141     return None, data
142
143
144 def run_command(cmd):
145     if use_win32_modules:
146         return run_command_win32(cmd)
147     else:
148         return run_command_popen(cmd)
149
150
151 def get_version_info():
152     version_re = re.compile("([0-9])\.([0-9])")
153
154     match = version_re.match(sys.version)
155     if match == None:
156         error("Unable to extract version info from 'sys.version'")
157
158     return string.atoi(match.group(1)), string.atoi(match.group(2))
159
160
161 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
162     """copy data from file-like object fsrc to file-like object fdst"""
163     if rewind:
164         fsrc.flush()
165         fsrc.seek(0)
166
167     while 1:
168         buf = fsrc.read(length)
169         if not buf:
170             break
171         fdst.write(buf)
172
173
174 class TempFile:
175     """clone of tempfile.TemporaryFile to use with python < 2.0."""
176     # Cache the unlinker so we don't get spurious errors at shutdown
177     # when the module-level "os" is None'd out.  Note that this must
178     # be referenced as self.unlink, because the name TempFile
179     # may also get None'd out before __del__ is called.
180     unlink = os.unlink
181
182     def __init__(self):
183         self.filename = tempfile.mktemp()
184         self.file = open(self.filename,"w+b")
185         self.close_called = 0
186
187     def close(self):
188         if not self.close_called:
189             self.close_called = 1
190             self.file.close()
191             self.unlink(self.filename)
192
193     def __del__(self):
194         self.close()
195
196     def read(self, size = -1):
197         return self.file.read(size)
198
199     def write(self, line):
200         return self.file.write(line)
201
202     def seek(self, offset):
203         return self.file.seek(offset)
204
205     def flush(self):
206         return self.file.flush()
207
208
209 def mkstemp():
210     """create a secure temporary file and return its object-like file"""
211     major, minor = get_version_info()
212
213     if major >= 2 and minor >= 0:
214         return tempfile.TemporaryFile()
215     else:
216         return TempFile()
217
218 def write_metrics_info(metrics_info, metrics_file):
219     metrics = open(metrics_file, 'w')
220     for metric in metrics_info:
221         metrics.write("Snippet %s %f\n" % metric)
222     metrics.close()