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