]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
054be5f949e529cec1c8c667eeb8e427e46f91be
[lyx.git] / src / support / Systemcall.cpp
1 /**
2  * \file Systemcall.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Angus Leeming
8  * \author Enrico Forestieri
9  * \author Peter Kuemmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "support/debug.h"
17 #include "support/lstrings.h"
18 #include "support/qstring_helpers.h"
19 #include "support/Systemcall.h"
20 #include "support/SystemcallPrivate.h"
21 #include "support/os.h"
22
23
24 #include <cstdlib>
25 #include <iostream>
26
27 #include <QProcess>
28 #include <QTime>
29 #include <QThread>
30 #include <QCoreApplication>
31
32
33 #define USE_QPROCESS
34
35
36 struct Sleep : QThread
37 {
38         static void millisec(unsigned long ms) 
39         {
40                 QThread::usleep(ms * 1000);
41         }
42 };
43
44
45
46 using namespace std;
47
48 namespace lyx {
49 namespace support {
50
51
52
53 // Reuse of instance
54 #ifndef USE_QPROCESS
55 int Systemcall::startscript(Starttype how, string const & what)
56 {
57         string command = what;
58
59         if (how == DontWait) {
60                 switch (os::shell()) {
61                 case os::UNIX:
62                         command += " &";
63                         break;
64                 case os::CMD_EXE:
65                         command = "start /min " + command;
66                         break;
67                 }
68         }
69
70         return ::system(command.c_str());
71 }
72
73 #else
74
75 namespace {
76
77 string const parsecmd(string const & cmd, string & outfile)
78 {
79         bool inquote = false;
80         bool escaped = false;
81
82         for (size_t i = 0; i < cmd.length(); ++i) {
83                 char c = cmd[i];
84                 if (c == '"' && !escaped)
85                         inquote = !inquote;
86                 else if (c == '\\' && !escaped)
87                         escaped = !escaped;
88                 else if (c == '>' && !(inquote || escaped)) {
89                         outfile = trim(cmd.substr(i + 1), " \"");
90                         return trim(cmd.substr(0, i));
91                 } else
92                         escaped = false;
93         }
94         outfile.erase();
95         return cmd;
96 }
97
98 } // namespace anon
99
100
101
102 int Systemcall::startscript(Starttype how, string const & what)
103 {
104         string outfile;
105         QString cmd = toqstr(parsecmd(what, outfile));
106         SystemcallPrivate d(outfile);
107
108         bool processEvents = false;
109
110         d.startProcess(cmd);
111         if (!d.waitWhile(SystemcallPrivate::Starting, processEvents, 3000)) {
112                 LYXERR0("QProcess " << cmd << " did not start!");
113                 LYXERR0("error " << d.errorMessage());
114                 return 10;
115         }
116
117         if (how == DontWait) {
118                 // TODO delete process later
119                 return 0;
120         }
121
122         if (!d.waitWhile(SystemcallPrivate::Running, processEvents, 180000)) {
123                 LYXERR0("QProcess " << cmd << " did not finished!");
124                 LYXERR0("error " << d.errorMessage());
125                 LYXERR0("status " << d.exitStatusMessage());
126                 return 20;
127         }
128
129         int const exit_code = d.exitCode();
130         if (exit_code) {
131                 LYXERR0("QProcess " << cmd << " finished!");
132                 LYXERR0("error " << exit_code << ": " << d.errorMessage()); 
133         }
134
135         d.flush();
136         d.killProcess();
137
138         return exit_code;
139 }
140
141
142 SystemcallPrivate::SystemcallPrivate(const std::string& of) : 
143                                 proc_(new QProcess), outindex_(0), 
144                                 errindex_(0), showout_(false), showerr_(false), outfile(of)
145 {
146         if (!outfile.empty()) {
147                 // Check whether we have to simply throw away the output.
148                 if (outfile != os::nulldev())
149                         proc_->setStandardOutputFile(toqstr(outfile));
150         } else if (os::is_terminal(os::STDOUT))
151                 showout();
152         if (os::is_terminal(os::STDERR))
153                 showerr();
154
155         connect(proc_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
156         connect(proc_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
157         connect(proc_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
158         connect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
159         connect(proc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
160 }
161
162
163
164 void SystemcallPrivate::startProcess(const QString& cmd)
165 {
166         state = SystemcallPrivate::Starting;
167         proc_->start(cmd);
168 }
169
170
171 void SystemcallPrivate::waitAndProcessEvents()
172 {
173         Sleep::millisec(100);
174         QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
175 }
176
177
178 bool SystemcallPrivate::waitWhile(State waitwhile, bool processEvents, int timeout)
179 {
180         // Block GUI while waiting,
181         // relay on QProcess' wait functions
182         if (!processEvents) {
183                 if (waitwhile == Starting)
184                         return proc_->waitForStarted(timeout);
185                 if (waitwhile == Running)
186                         return proc_->waitForFinished(timeout);
187                 return false;
188         }
189
190         // process events while waiting, no timeout
191         if (timeout == -1) {
192                 while (state == waitwhile && state != Error) {
193                         waitAndProcessEvents();
194                 }
195                 return state != Error;
196         } 
197
198         // process events while waiting whith timeout
199         QTime timer;
200         timer.start();
201         while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
202                 waitAndProcessEvents();
203         }
204         return (state != Error) && (timer.elapsed() < timeout);
205 }
206
207
208
209 SystemcallPrivate::~SystemcallPrivate()
210 {
211         if (outindex_) {
212                 outdata_[outindex_] = '\0';
213                 outindex_ = 0;
214                 cout << outdata_;
215         }
216         cout.flush();
217         if (errindex_) {
218                 errdata_[errindex_] = '\0';
219                 errindex_ = 0;
220                 cerr << errdata_;
221         }
222         cerr.flush();
223 }
224
225
226 void SystemcallPrivate::flush()
227 {
228         // If the output has been redirected, we write it all at once.
229         // Even if we are not running in a terminal, the output could go
230         // to some log file, for example ~/.xsession-errors on *nix.
231         if (!os::is_terminal(os::STDOUT) && outfile.empty())
232                 cout << fromqstr(QString::fromLocal8Bit(
233                             proc_->readAllStandardOutput().data()));
234         if (!os::is_terminal(os::STDERR))
235                 cerr << fromqstr(QString::fromLocal8Bit(
236                             proc_->readAllStandardError().data()));
237 }
238
239 void SystemcallPrivate::stdOut()
240 {
241         if (showout_) {
242                 char c;
243                 proc_->setReadChannel(QProcess::StandardOutput);
244                 while (proc_->getChar(&c)) {
245                         outdata_[outindex_++] = c;
246                         if (c == '\n' || outindex_ + 1 == bufsize_) {
247                                 outdata_[outindex_] = '\0';
248                                 outindex_ = 0;
249                                 cout << outdata_;
250                         }
251                 }
252         }
253 }
254
255
256 void SystemcallPrivate::stdErr()
257 {
258         if (showerr_) {
259                 char c;
260                 proc_->setReadChannel(QProcess::StandardError);
261                 while (proc_->getChar(&c)) {
262                         errdata_[errindex_++] = c;
263                         if (c == '\n' || errindex_ + 1 == bufsize_) {
264                                 errdata_[errindex_] = '\0';
265                                 errindex_ = 0;
266                                 cerr << errdata_;
267                         }
268                 }
269         }
270 }
271
272
273 void SystemcallPrivate::processError(QProcess::ProcessError err)
274 {
275         state = Error;
276 }
277
278
279 QString SystemcallPrivate::errorMessage() const 
280 {
281         QString message;
282         switch (proc_->error()) {
283                 case QProcess::FailedToStart:
284                         message = "The process failed to start. Either the invoked program is missing, "
285                                       "or you may have insufficient permissions to invoke the program.";
286                         break;
287                 case QProcess::Crashed:
288                         message = "The process crashed some time after starting successfully.";
289                         break;
290                 case QProcess::Timedout:
291                         message = "The process timed out. It might be restarted automatically.";
292                         break;
293                 case QProcess::WriteError:
294                         message = "An error occurred when attempting to write to the process-> For example, "
295                                       "the process may not be running, or it may have closed its input channel.";
296                         break;
297                 case QProcess::ReadError:
298                         message = "An error occurred when attempting to read from the process-> For example, "
299                                       "the process may not be running.";
300                         break;
301                 case QProcess::UnknownError:
302                 default:
303                         message = "An unknown error occured.";
304                         break;
305         }
306         return message;
307 }
308
309
310 void SystemcallPrivate::processStarted()
311 {
312         state = Running;
313         // why do we get two started signals?
314         //disconnect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
315 }
316
317
318 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus status)
319 {
320         state = Finished;
321 }
322
323
324 QString SystemcallPrivate::exitStatusMessage() const
325 {
326         QString message;
327         switch (proc_->exitStatus()) {
328                 case QProcess::NormalExit:
329                         message = "The process exited normally.";
330                         break;
331                 case QProcess::CrashExit:
332                         message = "The process crashed.";
333                         break;
334                 default:
335                         message = "Unknown exit state.";
336                         break;
337         }
338         return message;
339 }
340
341 int SystemcallPrivate::exitCode()
342 {
343         return proc_->exitCode();
344 }
345
346
347 void SystemcallPrivate::killProcess()
348 {
349         killProcess(proc_);
350 }
351
352 void SystemcallPrivate::killProcess(QProcess * p)
353 {
354         p->disconnect();
355         p->closeReadChannel(QProcess::StandardOutput);
356         p->closeReadChannel(QProcess::StandardError);
357         p->close();
358         delete p;
359 }
360
361
362
363 #include "moc_SystemcallPrivate.cpp"
364 #endif
365
366 } // namespace support
367 } // namespace lyx