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/environment.h"
18 #include "support/filetools.h"
19 #include "support/lstrings.h"
20 #include "support/qstring_helpers.h"
21 #include "support/Systemcall.h"
22 #include "support/SystemcallPrivate.h"
23 #include "support/os.h"
24 #include "support/ProgressInterface.h"
34 #include <QCoreApplication>
40 struct Sleep : QThread
42 static void millisec(unsigned long ms)
44 QThread::usleep(ms * 1000);
57 class ProgressDummy : public ProgressInterface
62 void processStarted(QString const &) {}
63 void processFinished(QString const &) {}
64 void appendMessage(QString const &) {}
65 void appendError(QString const &) {}
66 void clearMessages() {}
69 void lyxerrConnect() {}
70 void lyxerrDisconnect() {}
72 void warning(QString const &, QString const &) {}
73 void toggleWarning(QString const &, QString const &, QString const &) {}
74 void error(QString const &, QString const &) {}
75 void information(QString const &, QString const &) {}
79 static ProgressInterface* progress_instance = 0;
81 void ProgressInterface::setInstance(ProgressInterface* p)
83 progress_instance = p;
87 ProgressInterface* ProgressInterface::instance()
89 if (!progress_instance) {
90 static ProgressDummy dummy;
93 return progress_instance;
101 int Systemcall::startscript(Starttype how, string const & what,
102 std::string const & path, bool /*process_events*/)
105 string const texinputs = os::latex_path_list(
106 replaceCurdirPath(path, lyxrc.texinputs_prefix));
107 string const sep = string(1, os::path_separator(os::TEXENGINE));
108 string const env = getEnv("TEXINPUTS");
110 switch (os::shell()) {
112 command = path.empty() || lyxrc.texinputs_prefix.empty() ? what
113 : "env TEXINPUTS='." + sep + texinputs
114 + sep + env + "' " + what;
117 command = path.empty() || lyxrc.texinputs_prefix.empty() ? what
118 : "set TEXINPUTS=." + sep + texinputs
119 + sep + env + " & " + what;
123 if (how == DontWait) {
124 switch (os::shell()) {
129 command = "start /min " + command;
134 return ::system(command.c_str());
142 * This is a parser that (mostly) mimics the behavior of a posix shell but
143 * its output is tailored for being processed by QProcess.
145 * The escape character is the backslash.
146 * A backslash that is not quoted preserves the literal value of the following
147 * character, with the exception of a double-quote '"'. If a double-quote
148 * follows a backslash, it will be replaced by three consecutive double-quotes
149 * (this is how the QProcess parser recognizes a '"' as a simple character
150 * instead of a quoting character). Thus, for example:
156 * Characters enclosed in single-quotes ('') have their literal value preserved.
157 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
158 * be used to escape a single-quote in a single-quoted string. In other words,
159 * anything enclosed in single-quotes is passed as is, but the single-quotes
160 * themselves are eliminated. Thus, for example:
167 * Characters enclosed in double-quotes ("") have their literal value preserved,
168 * with the exception of the backslash. The backslash retains its special
169 * meaning as an escape character only when followed by a double-quote.
170 * Contrarily to the behavior of a posix shell, the double-quotes themselves
171 * are *not* eliminated. Thus, for example:
176 string const parsecmd(string const & inputcmd, string & outfile)
178 bool in_single_quote = false;
179 bool in_double_quote = false;
180 bool escaped = false;
183 for (size_t i = 0; i < inputcmd.length(); ++i) {
184 char c = inputcmd[i];
186 if (in_double_quote || escaped) {
187 if (in_double_quote && escaped)
191 in_single_quote = !in_single_quote;
195 if (in_single_quote) {
205 in_double_quote = !in_double_quote;
207 } else if (c == '\\' && !escaped) {
209 } else if (c == '>' && !(in_double_quote || escaped)) {
210 outfile = trim(inputcmd.substr(i + 1), " \"");
213 if (escaped && in_double_quote)
227 int Systemcall::startscript(Starttype how, string const & what,
228 string const & path, bool process_events)
231 QString cmd = toqstr(parsecmd(what, outfile));
233 SystemcallPrivate d(outfile);
236 d.startProcess(cmd, path);
237 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
238 LYXERR0("Systemcall: '" << cmd << "' did not start!");
239 LYXERR0("error " << d.errorMessage());
243 if (how == DontWait) {
244 QProcess* released = d.releaseProcess();
245 (void) released; // TODO who deletes it?
249 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
250 os::timeout_min() * 60 * 1000)) {
251 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
252 LYXERR0("error " << d.errorMessage());
253 LYXERR0("status " << d.exitStatusMessage());
257 int const exit_code = d.exitCode();
259 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
266 SystemcallPrivate::SystemcallPrivate(const std::string& of) :
267 process_(new QProcess),
271 texinputs_(getEnv("TEXINPUTS")),
272 process_events_(false)
274 if (!out_file_.empty()) {
275 // Check whether we have to simply throw away the output.
276 if (out_file_ != os::nulldev())
277 process_->setStandardOutputFile(toqstr(out_file_));
280 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
281 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
282 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
283 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
284 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
289 void SystemcallPrivate::startProcess(QString const & cmd, string const & path)
293 if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
294 string const texinputs = os::latex_path_list(
295 replaceCurdirPath(path, lyxrc.texinputs_prefix));
296 string const sep = string(1,
297 os::path_separator(os::TEXENGINE));
298 string const prefix = "." + sep + texinputs + sep;
299 if (prefixIs(texinputs_, prefix))
302 setEnv("TEXINPUTS", prefix + texinputs_);
304 state = SystemcallPrivate::Starting;
305 process_->start(cmd_);
310 void SystemcallPrivate::processEvents()
312 if(process_events_) {
313 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
318 void SystemcallPrivate::waitAndProcessEvents()
320 Sleep::millisec(100);
325 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
330 process_events_ = process_events;
332 // Block GUI while waiting,
333 // relay on QProcess' wait functions
334 if (!process_events_) {
335 if (waitwhile == Starting)
336 return process_->waitForStarted(timeout);
337 if (waitwhile == Running)
338 return process_->waitForFinished(timeout);
342 // process events while waiting, no timeout
344 while (state == waitwhile && state != Error) {
345 waitAndProcessEvents();
347 return state != Error;
350 // process events while waiting whith timeout
353 while (state == waitwhile && state != Error && timer.elapsed() < timeout) {
354 waitAndProcessEvents();
356 return (state != Error) && (timer.elapsed() < timeout);
360 SystemcallPrivate::~SystemcallPrivate()
362 if (!texinputs_.empty())
363 setEnv("TEXINPUTS", texinputs_);
366 out_data_[out_index_] = '\0';
372 err_data_[err_index_] = '\0';
382 void SystemcallPrivate::stdOut()
386 process_->setReadChannel(QProcess::StandardOutput);
387 while (process_->getChar(&c)) {
388 out_data_[out_index_++] = c;
389 if (c == '\n' || out_index_ + 1 == buffer_size_) {
390 out_data_[out_index_] = '\0';
392 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
400 void SystemcallPrivate::stdErr()
404 process_->setReadChannel(QProcess::StandardError);
405 while (process_->getChar(&c)) {
406 err_data_[err_index_++] = c;
407 if (c == '\n' || err_index_ + 1 == buffer_size_) {
408 err_data_[err_index_] = '\0';
410 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
418 void SystemcallPrivate::processStarted()
420 if (state != Running) {
422 ProgressInterface::instance()->processStarted(cmd_);
427 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
429 if (state != Finished) {
431 ProgressInterface::instance()->processFinished(cmd_);
436 void SystemcallPrivate::processError(QProcess::ProcessError)
439 ProgressInterface::instance()->appendError(errorMessage());
443 QString SystemcallPrivate::errorMessage() const
446 return "No QProcess available";
449 switch (process_->error()) {
450 case QProcess::FailedToStart:
451 message = "The process failed to start. Either the invoked program is missing, "
452 "or you may have insufficient permissions to invoke the program.";
454 case QProcess::Crashed:
455 message = "The process crashed some time after starting successfully.";
457 case QProcess::Timedout:
458 message = "The process timed out. It might be restarted automatically.";
460 case QProcess::WriteError:
461 message = "An error occurred when attempting to write to the process-> For example, "
462 "the process may not be running, or it may have closed its input channel.";
464 case QProcess::ReadError:
465 message = "An error occurred when attempting to read from the process-> For example, "
466 "the process may not be running.";
468 case QProcess::UnknownError:
470 message = "An unknown error occured.";
477 QString SystemcallPrivate::exitStatusMessage() const
480 return "No QProcess available";
483 switch (process_->exitStatus()) {
484 case QProcess::NormalExit:
485 message = "The process exited normally.";
487 case QProcess::CrashExit:
488 message = "The process crashed.";
491 message = "Unknown exit state.";
498 int SystemcallPrivate::exitCode()
503 return process_->exitCode();
507 QProcess* SystemcallPrivate::releaseProcess()
509 QProcess* released = process_;
515 void SystemcallPrivate::killProcess()
517 killProcess(process_);
521 void SystemcallPrivate::killProcess(QProcess * p)
525 p->closeReadChannel(QProcess::StandardOutput);
526 p->closeReadChannel(QProcess::StandardError);
534 #include "moc_SystemcallPrivate.cpp"
537 } // namespace support