3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Angus Leeming
8 * \author Enrico Forestieri
9 * \author Peter Kuemmel
11 * Full author contact details are available in file CREDITS.
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/qstring_helpers.h"
20 #include "support/Systemcall.h"
21 #include "support/SystemcallPrivate.h"
22 #include "support/os.h"
23 #include "support/ProgressInterface.h"
33 #include <QCoreApplication>
39 struct Sleep : QThread
41 static void millisec(unsigned long ms)
43 QThread::usleep(ms * 1000);
56 class ProgressDummy : public ProgressInterface
61 void processStarted(QString const &) {}
62 void processFinished(QString const &) {}
63 void appendMessage(QString const &) {}
64 void appendError(QString const &) {}
65 void clearMessages() {}
68 void lyxerrConnect() {}
69 void lyxerrDisconnect() {}
71 void warning(QString const &, QString const &) {}
72 void toggleWarning(QString const &, QString const &, QString const &) {}
73 void error(QString const &, QString const &) {}
74 void information(QString const &, QString const &) {}
78 static ProgressInterface* progress_instance = 0;
80 void ProgressInterface::setInstance(ProgressInterface* p)
82 progress_instance = p;
86 ProgressInterface* ProgressInterface::instance()
88 if (!progress_instance) {
89 static ProgressDummy dummy;
92 return progress_instance;
100 int Systemcall::startscript(Starttype how, string const & what,
101 std::string const & path, bool /*process_events*/)
104 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path))) + what;
106 if (how == DontWait) {
107 switch (os::shell()) {
112 command = "start /min " + command;
115 } else if (os::shell() == os::CMD_EXE)
116 command = subst(command, "cmd /d /c ", "");
118 return ::system(command.c_str());
126 * This is a parser that (mostly) mimics the behavior of a posix shell but
127 * its output is tailored for being processed by QProcess.
129 * The escape character is the backslash.
130 * A backslash that is not quoted preserves the literal value of the following
131 * character, with the exception of a double-quote '"'. If a double-quote
132 * follows a backslash, it will be replaced by three consecutive double-quotes
133 * (this is how the QProcess parser recognizes a '"' as a simple character
134 * instead of a quoting character). Thus, for example:
140 * Characters enclosed in single-quotes ('') have their literal value preserved.
141 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
142 * be used to escape a single-quote in a single-quoted string. In other words,
143 * anything enclosed in single-quotes is passed as is, but the single-quotes
144 * themselves are eliminated. Thus, for example:
151 * Characters enclosed in double-quotes ("") have their literal value preserved,
152 * with the exception of the backslash. The backslash retains its special
153 * meaning as an escape character only when followed by a double-quote.
154 * Contrarily to the behavior of a posix shell, the double-quotes themselves
155 * are *not* eliminated. Thus, for example:
160 string const parsecmd(string const & inputcmd, string & outfile)
162 bool in_single_quote = false;
163 bool in_double_quote = false;
164 bool escaped = false;
167 for (size_t i = 0; i < inputcmd.length(); ++i) {
168 char c = inputcmd[i];
170 if (in_double_quote || escaped) {
171 if (in_double_quote && escaped)
175 in_single_quote = !in_single_quote;
179 if (in_single_quote) {
189 in_double_quote = !in_double_quote;
191 } else if (c == '\\' && !escaped) {
193 } else if (c == '>' && !(in_double_quote || escaped)) {
194 outfile = trim(inputcmd.substr(i + 1), " \"");
197 if (escaped && in_double_quote)
211 int Systemcall::startscript(Starttype how, string const & what,
212 string const & path, bool process_events)
215 QString cmd = QString::fromLocal8Bit(parsecmd(what, outfile).c_str());
217 SystemcallPrivate d(outfile);
220 d.startProcess(cmd, path);
221 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
222 LYXERR0("Systemcall: '" << cmd << "' did not start!");
223 LYXERR0("error " << d.errorMessage());
227 if (how == DontWait) {
228 QProcess* released = d.releaseProcess();
229 (void) released; // TODO who deletes it?
233 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
234 os::timeout_min() * 60 * 1000)) {
235 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
236 LYXERR0("error " << d.errorMessage());
237 LYXERR0("status " << d.exitStatusMessage());
241 int const exit_code = d.exitCode();
243 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
250 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
251 process_(new QProcess),
255 process_events_(false)
257 if (!out_file_.empty()) {
258 // Check whether we have to simply throw away the output.
259 if (out_file_ != os::nulldev())
260 process_->setStandardOutputFile(QString::fromLocal8Bit(out_file_.c_str()));
263 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
264 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
265 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
266 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
267 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
271 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
275 state = SystemcallPrivate::Starting;
276 process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
281 void SystemcallPrivate::processEvents()
283 if(process_events_) {
284 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
289 void SystemcallPrivate::waitAndProcessEvents()
291 Sleep::millisec(100);
296 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
301 process_events_ = process_events;
303 // Block GUI while waiting,
304 // relay on QProcess' wait functions
305 if (!process_events_) {
306 if (waitwhile == Starting)
307 return process_->waitForStarted(timeout);
308 if (waitwhile == Running)
309 return process_->waitForFinished(timeout);
313 // process events while waiting, no timeout
315 while (state == waitwhile && state != Error) {
316 waitAndProcessEvents();
318 return state != Error;
321 // process events while waiting whith timeout
324 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
325 waitAndProcessEvents();
327 return (state != Error) && (timer.elapsed() < timeout);
331 SystemcallPrivate::~SystemcallPrivate()
334 out_data_[out_index_] = '\0';
340 err_data_[err_index_] = '\0';
350 void SystemcallPrivate::stdOut()
354 process_->setReadChannel(QProcess::StandardOutput);
355 while (process_->getChar(&c)) {
356 out_data_[out_index_++] = c;
357 if (c == '\n' || out_index_ + 1 == buffer_size_) {
358 out_data_[out_index_] = '\0';
360 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
368 void SystemcallPrivate::stdErr()
372 process_->setReadChannel(QProcess::StandardError);
373 while (process_->getChar(&c)) {
374 err_data_[err_index_++] = c;
375 if (c == '\n' || err_index_ + 1 == buffer_size_) {
376 err_data_[err_index_] = '\0';
378 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
386 void SystemcallPrivate::processStarted()
388 if (state != Running) {
390 ProgressInterface::instance()->processStarted(cmd_);
395 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
397 if (state != Finished) {
399 ProgressInterface::instance()->processFinished(cmd_);
404 void SystemcallPrivate::processError(QProcess::ProcessError)
407 ProgressInterface::instance()->appendError(errorMessage());
411 QString SystemcallPrivate::errorMessage() const
414 return "No QProcess available";
417 switch (process_->error()) {
418 case QProcess::FailedToStart:
419 message = "The process failed to start. Either the invoked program is missing, "
420 "or you may have insufficient permissions to invoke the program.";
422 case QProcess::Crashed:
423 message = "The process crashed some time after starting successfully.";
425 case QProcess::Timedout:
426 message = "The process timed out. It might be restarted automatically.";
428 case QProcess::WriteError:
429 message = "An error occurred when attempting to write to the process-> For example, "
430 "the process may not be running, or it may have closed its input channel.";
432 case QProcess::ReadError:
433 message = "An error occurred when attempting to read from the process-> For example, "
434 "the process may not be running.";
436 case QProcess::UnknownError:
438 message = "An unknown error occured.";
445 QString SystemcallPrivate::exitStatusMessage() const
448 return "No QProcess available";
451 switch (process_->exitStatus()) {
452 case QProcess::NormalExit:
453 message = "The process exited normally.";
455 case QProcess::CrashExit:
456 message = "The process crashed.";
459 message = "Unknown exit state.";
466 int SystemcallPrivate::exitCode()
471 return process_->exitCode();
475 QProcess* SystemcallPrivate::releaseProcess()
477 QProcess* released = process_;
483 void SystemcallPrivate::killProcess()
485 killProcess(process_);
489 void SystemcallPrivate::killProcess(QProcess * p)
493 p->closeReadChannel(QProcess::StandardOutput);
494 p->closeReadChannel(QProcess::StandardError);
502 #include "moc_SystemcallPrivate.cpp"
505 } // namespace support