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/gettext.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 &, QString const &) {}
75 void information(QString const &, QString const &) {}
76 int prompt(docstring const &, docstring const &, int default_but, int,
77 docstring const &, docstring const &) { return default_but; }
81 static ProgressInterface * progress_instance = 0;
83 void ProgressInterface::setInstance(ProgressInterface* p)
85 progress_instance = p;
89 ProgressInterface * ProgressInterface::instance()
91 if (!progress_instance) {
92 static ProgressDummy dummy;
95 return progress_instance;
103 int Systemcall::startscript(Starttype how, string const & what,
104 string const & path, string const & lpath,
105 bool /*process_events*/)
108 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
111 if (how == DontWait) {
112 switch (os::shell()) {
117 command = "start /min " + command;
120 } else if (os::shell() == os::CMD_EXE)
121 command = subst(command, "cmd /d /c ", "");
123 return ::system(command.c_str());
131 * This is a parser that (mostly) mimics the behavior of a posix shell as
132 * regards quoting, but its output is tailored for being processed by QProcess.
133 * Note that shell metacharacters are not parsed.
135 * The escape character is the backslash.
136 * A backslash that is not quoted preserves the literal value of the following
137 * character, with the exception of a double-quote '"'. If a double-quote
138 * follows a backslash, it will be replaced by three consecutive double-quotes
139 * (this is how the QProcess parser recognizes a '"' as a simple character
140 * instead of a quoting character). Thus, for example:
146 * Characters enclosed in single-quotes ('') have their literal value preserved.
147 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
148 * be used to escape a single-quote in a single-quoted string. In other words,
149 * anything enclosed in single-quotes is passed as is, but the single-quotes
150 * themselves are eliminated. Thus, for example:
157 * Characters enclosed in double-quotes ("") have their literal value preserved,
158 * with the exception of the backslash. The backslash retains its special
159 * meaning as an escape character only when followed by a double-quote.
160 * Contrarily to the behavior of a posix shell, the double-quotes themselves
161 * are *not* eliminated. Thus, for example:
166 string const parsecmd(string const & incmd, string & infile, string & outfile,
169 bool in_single_quote = false;
170 bool in_double_quote = false;
171 bool escaped = false;
172 string const python_call = "python -tt";
173 vector<string> outcmd(4);
176 if (prefixIs(incmd, python_call)) {
177 outcmd[0] = os::python();
178 start = python_call.length();
181 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
184 if (in_double_quote || escaped) {
185 if (in_double_quote && escaped)
189 in_single_quote = !in_single_quote;
193 if (in_single_quote) {
199 // Don't triple double-quotes for redirection
200 // files as these won't be parsed by QProcess
201 outcmd[o] += string(o ? "\"" : "\"\"\"");
205 in_double_quote = !in_double_quote;
207 } else if (c == '\\' && !escaped) {
209 } else if (c == '>' && !(in_double_quote || escaped)) {
210 if (suffixIs(outcmd[o], " 2")) {
211 outcmd[o] = rtrim(outcmd[o], "2");
214 if (suffixIs(outcmd[o], " 1"))
215 outcmd[o] = rtrim(outcmd[o], "1");
218 } else if (c == '<' && !(in_double_quote || escaped)) {
221 if (escaped && in_double_quote)
227 infile = trim(outcmd[3], " \"");
228 outfile = trim(outcmd[1], " \"");
229 errfile = trim(outcmd[2], " \"");
230 return trim(outcmd[0]);
237 int Systemcall::startscript(Starttype how, string const & what,
238 string const & path, string const & lpath,
241 string const what_ss = commandPrep(what);
242 LYXERR(Debug::INFO,"Running: " << what_ss);
247 QString const cmd = QString::fromLocal8Bit(
248 parsecmd(what_ss, infile, outfile, errfile).c_str());
250 SystemcallPrivate d(infile, outfile, errfile);
253 // QProcess::startDetached cannot provide environment variables. When the
254 // environment variables are set using the latexEnvCmdPrefix and the process
255 // is started with QProcess::startDetached, a console window is shown every
256 // time a viewer is started. To avoid this, we fall back on Windows to the
257 // original implementation that creates a QProcess object.
258 d.startProcess(cmd, path, lpath, false);
259 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
260 LYXERR0("Systemcall: '" << cmd << "' did not start!");
261 LYXERR0("error " << d.errorMessage());
264 if (how == DontWait) {
269 d.startProcess(cmd, path, lpath, how == DontWait);
270 if (how == DontWait && d.state == SystemcallPrivate::Running)
273 if (d.state == SystemcallPrivate::Error
274 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
275 LYXERR0("Systemcall: '" << cmd << "' did not start!");
276 LYXERR0("error " << d.errorMessage());
281 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
282 os::timeout_min() * 60 * 1000)) {
283 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
284 LYXERR0("error " << d.errorMessage());
285 LYXERR0("status " << d.exitStatusMessage());
289 int const exit_code = d.exitCode();
291 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
298 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
299 std::string const & ef)
300 : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
301 in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
303 if (!in_file_.empty())
304 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
305 if (!out_file_.empty()) {
306 if (out_file_[0] == '&') {
307 if (subst(out_file_, " ", "") == "&2"
308 && err_file_[0] != '&') {
309 out_file_ = err_file_;
310 process_->setProcessChannelMode(
311 QProcess::MergedChannels);
313 if (err_file_[0] == '&') {
314 // Leave alone things such as
315 // "1>&2 2>&1". Should not be harmful,
316 // but let's give anyway a warning.
317 LYXERR0("Unsupported stdout/stderr redirect.");
320 LYXERR0("Ambiguous stdout redirect: "
323 out_file_ = os::nulldev();
326 // Check whether we have to set the output file.
327 if (out_file_ != os::nulldev()) {
328 process_->setStandardOutputFile(QString::fromLocal8Bit(
332 if (!err_file_.empty()) {
333 if (err_file_[0] == '&') {
334 if (subst(err_file_, " ", "") == "&1"
335 && out_file_[0] != '&') {
336 process_->setProcessChannelMode(
337 QProcess::MergedChannels);
339 LYXERR0("Ambiguous stderr redirect: "
342 // In MergedChannels mode stderr goes to stdout.
343 err_file_ = os::nulldev();
345 // Check whether we have to set the error file.
346 if (err_file_ != os::nulldev()) {
347 process_->setStandardErrorFile(QString::fromLocal8Bit(
352 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
353 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
354 #if QT_VERSION >= 0x050600
355 connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
357 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
359 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
360 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
364 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
365 string const & lpath, bool detached)
369 state = SystemcallPrivate::Running;
370 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
371 state = SystemcallPrivate::Error;
374 QProcess* released = releaseProcess();
376 } else if (process_) {
377 state = SystemcallPrivate::Starting;
378 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
383 void SystemcallPrivate::processEvents()
385 if (process_events_) {
386 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
391 void SystemcallPrivate::waitAndProcessEvents()
393 Sleep::millisec(100);
400 bool queryStopCommand(QString const & cmd)
402 docstring text = bformat(_(
403 "The command\n%1$s\nhas not yet completed.\n\n"
404 "Do you want to stop it?"), qstring_to_ucs4(cmd));
405 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
406 1, 1, _("&Stop it"), _("Let it &run")) == 0;
412 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
417 bool timedout = false;
418 process_events_ = process_events;
420 // Block GUI while waiting,
421 // relay on QProcess' wait functions
422 if (!process_events_) {
423 if (waitwhile == Starting)
424 return process_->waitForStarted(timeout);
425 if (waitwhile == Running) {
428 if (process_->waitForFinished(timeout))
430 bool stop = queryStopCommand(cmd_);
431 // The command may have finished in the meantime
432 if (process_->state() == QProcess::NotRunning)
446 // process events while waiting, no timeout
448 while (state == waitwhile && state != Error) {
449 waitAndProcessEvents();
451 return state != Error;
454 // process events while waiting with timeout
457 while (state == waitwhile && state != Error && !timedout) {
458 waitAndProcessEvents();
459 if (timer.elapsed() > timeout) {
460 bool stop = queryStopCommand(cmd_);
461 // The command may have finished in the meantime
462 if (process_->state() == QProcess::NotRunning)
471 return (state != Error) && !timedout;
475 SystemcallPrivate::~SystemcallPrivate()
478 out_data_[out_index_] = '\0';
484 err_data_[err_index_] = '\0';
494 void SystemcallPrivate::stdOut()
498 process_->setReadChannel(QProcess::StandardOutput);
499 while (process_->getChar(&c)) {
500 out_data_[out_index_++] = c;
501 if (c == '\n' || out_index_ + 1 == buffer_size_) {
502 out_data_[out_index_] = '\0';
504 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
512 void SystemcallPrivate::stdErr()
516 process_->setReadChannel(QProcess::StandardError);
517 while (process_->getChar(&c)) {
518 err_data_[err_index_++] = c;
519 if (c == '\n' || err_index_ + 1 == buffer_size_) {
520 err_data_[err_index_] = '\0';
522 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
530 void SystemcallPrivate::processStarted()
532 if (state != Running) {
534 ProgressInterface::instance()->processStarted(cmd_);
539 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
541 if (state != Finished) {
543 ProgressInterface::instance()->processFinished(cmd_);
548 void SystemcallPrivate::processError(QProcess::ProcessError)
551 ProgressInterface::instance()->appendError(errorMessage());
555 QString SystemcallPrivate::errorMessage() const
558 return "No QProcess available";
561 switch (process_->error()) {
562 case QProcess::FailedToStart:
563 message = "The process failed to start. Either the invoked program is missing, "
564 "or you may have insufficient permissions to invoke the program.";
566 case QProcess::Crashed:
567 message = "The process crashed some time after starting successfully.";
569 case QProcess::Timedout:
570 message = "The process timed out. It might be restarted automatically.";
572 case QProcess::WriteError:
573 message = "An error occurred when attempting to write to the process-> For example, "
574 "the process may not be running, or it may have closed its input channel.";
576 case QProcess::ReadError:
577 message = "An error occurred when attempting to read from the process-> For example, "
578 "the process may not be running.";
580 case QProcess::UnknownError:
582 message = "An unknown error occurred.";
589 QString SystemcallPrivate::exitStatusMessage() const
592 return "No QProcess available";
595 switch (process_->exitStatus()) {
596 case QProcess::NormalExit:
597 message = "The process exited normally.";
599 case QProcess::CrashExit:
600 message = "The process crashed.";
603 message = "Unknown exit state.";
610 int SystemcallPrivate::exitCode()
612 // From Qt's documentation, in regards to QProcess::exitCode(),
613 // "This value is not valid unless exitStatus() returns NormalExit"
614 if (!process_ || process_->exitStatus() != QProcess::NormalExit)
617 return process_->exitCode();
621 QProcess* SystemcallPrivate::releaseProcess()
623 QProcess* released = process_;
629 void SystemcallPrivate::killProcess()
631 killProcess(process_);
635 void SystemcallPrivate::killProcess(QProcess * p)
639 p->closeReadChannel(QProcess::StandardOutput);
640 p->closeReadChannel(QProcess::StandardError);
648 #include "moc_SystemcallPrivate.cpp"
651 } // namespace support