]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
fdb3f8ef878f83d4ea24398a2cb79e7debbb1a90
[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 process_events = false;
109
110         d.startProcess(cmd);
111         if (!d.waitWhile(SystemcallPrivate::Starting, process_events, 3000)) {
112                 LYXERR0("QProcess " << cmd << " did not start!");
113                 LYXERR0("error " << d.errorMessage());
114                 return 10;
115         }
116
117         if (how == DontWait) {
118                 QProcess* released = d.releaseProcess();
119                 (void) released; // TODO who deletes it?
120                 return 0;
121         }
122
123         if (!d.waitWhile(SystemcallPrivate::Running, process_events, 180000)) {
124                 LYXERR0("QProcess " << cmd << " did not finished!");
125                 LYXERR0("error " << d.errorMessage());
126                 LYXERR0("status " << d.exitStatusMessage());
127                 return 20;
128         }
129
130         int const exit_code = d.exitCode();
131         if (exit_code) {
132                 LYXERR0("QProcess " << cmd << " finished!");
133                 LYXERR0("error " << exit_code << ": " << d.errorMessage()); 
134         }
135
136         return exit_code;
137 }
138
139
140 SystemcallPrivate::SystemcallPrivate(const std::string& of) : 
141                                 proc_(new QProcess), outindex_(0), 
142                                 errindex_(0), showout_(false), showerr_(false), outfile(of)
143 {
144         if (!outfile.empty()) {
145                 // Check whether we have to simply throw away the output.
146                 if (outfile != os::nulldev())
147                         proc_->setStandardOutputFile(toqstr(outfile));
148         } else if (os::is_terminal(os::STDOUT))
149                 showout();
150         if (os::is_terminal(os::STDERR))
151                 showerr();
152
153         connect(proc_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
154         connect(proc_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
155         connect(proc_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
156         connect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
157         connect(proc_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
158 }
159
160
161
162 void SystemcallPrivate::startProcess(const QString& cmd)
163 {
164         if (proc_) {
165                 state = SystemcallPrivate::Starting;
166                 proc_->start(cmd);
167         }
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 process_events, int timeout)
179 {
180         if (!proc_)
181                 return false;
182
183         // Block GUI while waiting,
184         // relay on QProcess' wait functions
185         if (!process_events) {
186                 if (waitwhile == Starting)
187                         return proc_->waitForStarted(timeout);
188                 if (waitwhile == Running)
189                         return proc_->waitForFinished(timeout);
190                 return false;
191         }
192
193         // process events while waiting, no timeout
194         if (timeout == -1) {
195                 while (state == waitwhile && state != Error) {
196                         waitAndProcessEvents();
197                 }
198                 return state != Error;
199         } 
200
201         // process events while waiting whith timeout
202         QTime timer;
203         timer.start();
204         while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
205                 waitAndProcessEvents();
206         }
207         return (state != Error) && (timer.elapsed() < timeout);
208 }
209
210
211
212 SystemcallPrivate::~SystemcallPrivate()
213 {
214         flush();
215
216         if (outindex_) {
217                 outdata_[outindex_] = '\0';
218                 outindex_ = 0;
219                 cout << outdata_;
220         }
221         cout.flush();
222         if (errindex_) {
223                 errdata_[errindex_] = '\0';
224                 errindex_ = 0;
225                 cerr << errdata_;
226         }
227         cerr.flush();
228
229         killProcess();
230 }
231
232
233 void SystemcallPrivate::flush()
234 {
235         if (proc_) {
236                 // If the output has been redirected, we write it all at once.
237                 // Even if we are not running in a terminal, the output could go
238                 // to some log file, for example ~/.xsession-errors on *nix.
239                 if (!os::is_terminal(os::STDOUT) && outfile.empty())
240                         cout << fromqstr(QString::fromLocal8Bit(
241                                                 proc_->readAllStandardOutput().data()));
242                 if (!os::is_terminal(os::STDERR))
243                         cerr << fromqstr(QString::fromLocal8Bit(
244                                                 proc_->readAllStandardError().data()));
245         }
246 }
247
248 void SystemcallPrivate::stdOut()
249 {
250         if (proc_ && showout_) {
251                 char c;
252                 proc_->setReadChannel(QProcess::StandardOutput);
253                 while (proc_->getChar(&c)) {
254                         outdata_[outindex_++] = c;
255                         if (c == '\n' || outindex_ + 1 == bufsize_) {
256                                 outdata_[outindex_] = '\0';
257                                 outindex_ = 0;
258                                 cout << outdata_;
259                         }
260                 }
261         }
262 }
263
264
265 void SystemcallPrivate::stdErr()
266 {
267         if (proc_ && showerr_) {
268                 char c;
269                 proc_->setReadChannel(QProcess::StandardError);
270                 while (proc_->getChar(&c)) {
271                         errdata_[errindex_++] = c;
272                         if (c == '\n' || errindex_ + 1 == bufsize_) {
273                                 errdata_[errindex_] = '\0';
274                                 errindex_ = 0;
275                                 cerr << errdata_;
276                         }
277                 }
278         }
279 }
280
281
282 void SystemcallPrivate::processError(QProcess::ProcessError err)
283 {
284         state = Error;
285 }
286
287
288 QString SystemcallPrivate::errorMessage() const 
289 {
290         if (!proc_)
291                 return "No QProcess available";
292
293         QString message;
294         switch (proc_->error()) {
295                 case QProcess::FailedToStart:
296                         message = "The process failed to start. Either the invoked program is missing, "
297                                       "or you may have insufficient permissions to invoke the program.";
298                         break;
299                 case QProcess::Crashed:
300                         message = "The process crashed some time after starting successfully.";
301                         break;
302                 case QProcess::Timedout:
303                         message = "The process timed out. It might be restarted automatically.";
304                         break;
305                 case QProcess::WriteError:
306                         message = "An error occurred when attempting to write to the process-> For example, "
307                                       "the process may not be running, or it may have closed its input channel.";
308                         break;
309                 case QProcess::ReadError:
310                         message = "An error occurred when attempting to read from the process-> For example, "
311                                       "the process may not be running.";
312                         break;
313                 case QProcess::UnknownError:
314                 default:
315                         message = "An unknown error occured.";
316                         break;
317         }
318         return message;
319 }
320
321
322 void SystemcallPrivate::processStarted()
323 {
324         state = Running;
325         // why do we get two started signals?
326         //disconnect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
327 }
328
329
330 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus status)
331 {
332         state = Finished;
333 }
334
335
336 QString SystemcallPrivate::exitStatusMessage() const
337 {
338         if (!proc_)
339                 return "No QProcess available";
340
341         QString message;
342         switch (proc_->exitStatus()) {
343                 case QProcess::NormalExit:
344                         message = "The process exited normally.";
345                         break;
346                 case QProcess::CrashExit:
347                         message = "The process crashed.";
348                         break;
349                 default:
350                         message = "Unknown exit state.";
351                         break;
352         }
353         return message;
354 }
355
356 int SystemcallPrivate::exitCode()
357 {
358         if (!proc_)
359                 return -1;
360
361         return proc_->exitCode();
362 }
363
364
365 QProcess* SystemcallPrivate::releaseProcess()
366 {
367         QProcess* released = proc_;
368         proc_ = 0;
369         return released;
370 }
371
372
373 void SystemcallPrivate::killProcess()
374 {
375         killProcess(proc_);
376 }
377
378 void SystemcallPrivate::killProcess(QProcess * p)
379 {
380         if (p) {
381                 p->disconnect();
382                 p->closeReadChannel(QProcess::StandardOutput);
383                 p->closeReadChannel(QProcess::StandardError);
384                 p->close();
385                 delete p;
386         }
387 }
388
389
390
391 #include "moc_SystemcallPrivate.cpp"
392 #endif
393
394 } // namespace support
395 } // namespace lyx