]> git.lyx.org Git - features.git/blob - src/support/Systemcall.cpp
also process user input, trigger more processEvents
[features.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 #include <QDebug>
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), process_events(false),
142                                 errindex_(0), outfile(of), showout_(false), showerr_(false)
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 void SystemcallPrivate::processEvents()
171 {
172         if(process_events) {
173                 //static int count = 0; qDebug() << count++ << ": waitAndProcessEvents";
174                 QCoreApplication::processEvents(QEventLoop::AllEvents);
175         }
176 }
177
178 void SystemcallPrivate::waitAndProcessEvents()
179 {
180         Sleep::millisec(100);
181         processEvents();
182 }
183
184
185 bool SystemcallPrivate::waitWhile(State waitwhile, bool proc_events, int timeout)
186 {
187         if (!proc_)
188                 return false;
189
190         process_events = proc_events;
191
192         // Block GUI while waiting,
193         // relay on QProcess' wait functions
194         if (!process_events) {
195                 if (waitwhile == Starting)
196                         return proc_->waitForStarted(timeout);
197                 if (waitwhile == Running)
198                         return proc_->waitForFinished(timeout);
199                 return false;
200         }
201
202         // process events while waiting, no timeout
203         if (timeout == -1) {
204                 while (state == waitwhile && state != Error) {
205                         waitAndProcessEvents();
206                 }
207                 return state != Error;
208         } 
209
210         // process events while waiting whith timeout
211         QTime timer;
212         timer.start();
213         while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
214                 waitAndProcessEvents();
215         }
216         return (state != Error) && (timer.elapsed() < timeout);
217 }
218
219
220
221 SystemcallPrivate::~SystemcallPrivate()
222 {
223         flush();
224
225         if (outindex_) {
226                 outdata_[outindex_] = '\0';
227                 outindex_ = 0;
228                 cout << outdata_;
229         }
230         cout.flush();
231         if (errindex_) {
232                 errdata_[errindex_] = '\0';
233                 errindex_ = 0;
234                 cerr << errdata_;
235         }
236         cerr.flush();
237
238         killProcess();
239 }
240
241
242 void SystemcallPrivate::flush()
243 {
244         if (proc_) {
245                 // If the output has been redirected, we write it all at once.
246                 // Even if we are not running in a terminal, the output could go
247                 // to some log file, for example ~/.xsession-errors on *nix.
248                 if (!os::is_terminal(os::STDOUT) && outfile.empty())
249                         cout << fromqstr(QString::fromLocal8Bit(
250                                                 proc_->readAllStandardOutput().data()));
251                 if (!os::is_terminal(os::STDERR))
252                         cerr << fromqstr(QString::fromLocal8Bit(
253                                                 proc_->readAllStandardError().data()));
254         }
255 }
256
257 void SystemcallPrivate::stdOut()
258 {
259         if (proc_ && showout_) {
260                 char c;
261                 proc_->setReadChannel(QProcess::StandardOutput);
262                 while (proc_->getChar(&c)) {
263                         outdata_[outindex_++] = c;
264                         if (c == '\n' || outindex_ + 1 == bufsize_) {
265                                 outdata_[outindex_] = '\0';
266                                 outindex_ = 0;
267                                 cout << outdata_;
268                         }
269                 }
270         }
271         processEvents();
272 }
273
274
275 void SystemcallPrivate::stdErr()
276 {
277         if (proc_ && showerr_) {
278                 char c;
279                 proc_->setReadChannel(QProcess::StandardError);
280                 while (proc_->getChar(&c)) {
281                         errdata_[errindex_++] = c;
282                         if (c == '\n' || errindex_ + 1 == bufsize_) {
283                                 errdata_[errindex_] = '\0';
284                                 errindex_ = 0;
285                                 cerr << errdata_;
286                         }
287                 }
288         }
289         processEvents();
290 }
291
292
293 void SystemcallPrivate::processStarted()
294 {
295         state = Running;
296         // why do we get two started signals?
297         //disconnect(proc_, SIGNAL(started()), this, SLOT(processStarted()));
298 }
299
300
301 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus status)
302 {
303         state = Finished;
304 }
305
306
307 void SystemcallPrivate::processError(QProcess::ProcessError err)
308 {
309         state = Error;
310 }
311
312
313 QString SystemcallPrivate::errorMessage() const 
314 {
315         if (!proc_)
316                 return "No QProcess available";
317
318         QString message;
319         switch (proc_->error()) {
320                 case QProcess::FailedToStart:
321                         message = "The process failed to start. Either the invoked program is missing, "
322                                       "or you may have insufficient permissions to invoke the program.";
323                         break;
324                 case QProcess::Crashed:
325                         message = "The process crashed some time after starting successfully.";
326                         break;
327                 case QProcess::Timedout:
328                         message = "The process timed out. It might be restarted automatically.";
329                         break;
330                 case QProcess::WriteError:
331                         message = "An error occurred when attempting to write to the process-> For example, "
332                                       "the process may not be running, or it may have closed its input channel.";
333                         break;
334                 case QProcess::ReadError:
335                         message = "An error occurred when attempting to read from the process-> For example, "
336                                       "the process may not be running.";
337                         break;
338                 case QProcess::UnknownError:
339                 default:
340                         message = "An unknown error occured.";
341                         break;
342         }
343         return message;
344 }
345
346
347 QString SystemcallPrivate::exitStatusMessage() const
348 {
349         if (!proc_)
350                 return "No QProcess available";
351
352         QString message;
353         switch (proc_->exitStatus()) {
354                 case QProcess::NormalExit:
355                         message = "The process exited normally.";
356                         break;
357                 case QProcess::CrashExit:
358                         message = "The process crashed.";
359                         break;
360                 default:
361                         message = "Unknown exit state.";
362                         break;
363         }
364         return message;
365 }
366
367 int SystemcallPrivate::exitCode()
368 {
369         if (!proc_)
370                 return -1;
371
372         return proc_->exitCode();
373 }
374
375
376 QProcess* SystemcallPrivate::releaseProcess()
377 {
378         QProcess* released = proc_;
379         proc_ = 0;
380         return released;
381 }
382
383
384 void SystemcallPrivate::killProcess()
385 {
386         killProcess(proc_);
387 }
388
389 void SystemcallPrivate::killProcess(QProcess * p)
390 {
391         if (p) {
392                 p->disconnect();
393                 p->closeReadChannel(QProcess::StandardOutput);
394                 p->closeReadChannel(QProcess::StandardError);
395                 p->close();
396                 delete p;
397         }
398 }
399
400
401
402 #include "moc_SystemcallPrivate.cpp"
403 #endif
404
405 } // namespace support
406 } // namespace lyx