]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
use "new" Lexer interface...
[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, 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 find_exe(candidates, path):
47     for prog in candidates:
48         for directory in path:
49             if os.name == "nt":
50                 full_path = os.path.join(directory, prog + ".exe")
51             else:
52                 full_path = os.path.join(directory, prog)
53
54             if os.access(full_path, os.X_OK):
55                 # The thing is in the PATH already (or we wouldn't
56                 # have found it). Return just the basename to avoid
57                 # problems when the path to the executable contains
58                 # spaces.
59                 return os.path.basename(full_path)
60
61     return None
62
63
64 def find_exe_or_terminate(candidates, path):
65     exe = find_exe(candidates, path)
66     if exe == None:
67         error("Unable to find executable from '%s'" % string.join(candidates))
68
69     return exe
70
71
72 def run_command_popen(cmd):
73     handle = os.popen(cmd, 'r')
74     cmd_stdout = handle.read()
75     cmd_status = handle.close()
76
77     return cmd_status, cmd_stdout
78
79
80 def run_command_win32(cmd):
81     sa = win32security.SECURITY_ATTRIBUTES()
82     sa.bInheritHandle = True
83     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
84
85     si = win32process.STARTUPINFO()
86     si.dwFlags = (win32process.STARTF_USESTDHANDLES
87                   | win32process.STARTF_USESHOWWINDOW)
88     si.wShowWindow = win32con.SW_HIDE
89     si.hStdOutput = stdout_w
90
91     process, thread, pid, tid = \
92              win32process.CreateProcess(None, cmd, None, None, True,
93                                         0, None, None, si)
94     if process == None:
95         return -1, ""
96
97     # Must close the write handle in this process, or ReadFile will hang.
98     stdout_w.Close()
99
100     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
101     # which is okay because it happens when child process ends).
102     data = ""
103     error = 0
104     while 1:
105         try:
106             hr, buffer = win32file.ReadFile(stdout_r, 4096)
107             if hr != winerror.ERROR_IO_PENDING:
108                 data = data + buffer
109
110         except pywintypes.error, e:
111             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
112                 error = 1
113             break
114
115     if error:
116         return -2, ""
117
118     # Everything is okay --- the called process has closed the pipe.
119     # For safety, check that the process ended, then pick up its exit code.
120     win32event.WaitForSingleObject(process, win32event.INFINITE)
121     if win32process.GetExitCodeProcess(process):
122         return -3, ""
123
124     return None, data
125
126
127 def run_command(cmd):
128     if use_win32_modules:
129         return run_command_win32(cmd)
130     else:
131         return run_command_popen(cmd)
132
133
134 def get_version_info():
135     version_re = re.compile("([0-9])\.([0-9])")
136
137     match = version_re.match(sys.version)
138     if match == None:
139         error("Unable to extract version info from 'sys.version'")
140
141     return string.atoi(match.group(1)), string.atoi(match.group(2))
142
143
144 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
145     """copy data from file-like object fsrc to file-like object fdst"""
146     if rewind:
147         fsrc.flush()
148         fsrc.seek(0)
149
150     while 1:
151         buf = fsrc.read(length)
152         if not buf:
153             break
154         fdst.write(buf)
155
156
157 class TempFile:
158     """clone of tempfile.TemporaryFile to use with python < 2.0."""
159     # Cache the unlinker so we don't get spurious errors at shutdown
160     # when the module-level "os" is None'd out.  Note that this must
161     # be referenced as self.unlink, because the name TempFile
162     # may also get None'd out before __del__ is called.
163     unlink = os.unlink
164
165     def __init__(self):
166         self.filename = tempfile.mktemp()
167         self.file = open(self.filename,"w+b")
168         self.close_called = 0
169
170     def close(self):
171         if not self.close_called:
172             self.close_called = 1
173             self.file.close()
174             self.unlink(self.filename)
175
176     def __del__(self):
177         self.close()
178
179     def read(self, size = -1):
180         return self.file.read(size)
181
182     def write(self, line):
183         return self.file.write(line)
184
185     def seek(self, offset):
186         return self.file.seek(offset)
187
188     def flush(self):
189         return self.file.flush()
190
191
192 def mkstemp():
193     """create a secure temporary file and return its object-like file"""
194     major, minor = get_version_info()
195
196     if major >= 2 and minor >= 0:
197         return tempfile.TemporaryFile()
198     else:
199         return TempFile()