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"
35 #include <QCoreApplication>
41 struct Sleep : QThread
43 static void millisec(unsigned long ms)
45 QThread::usleep(ms * 1000);
58 class ProgressDummy : public ProgressInterface
63 void processStarted(QString const &) {}
64 void processFinished(QString const &) {}
65 void appendMessage(QString const &) {}
66 void appendError(QString const &) {}
67 void clearMessages() {}
70 void lyxerrConnect() {}
71 void lyxerrDisconnect() {}
73 void warning(QString const &, QString const &) {}
74 void toggleWarning(QString const &, QString const &, QString const &) {}
75 void error(QString const &, QString const &, QString const &) {}
76 void information(QString const &, QString const &) {}
77 int prompt(docstring const &, docstring const &, int default_but, int,
78 docstring const &, docstring const &) { return default_but; }
82 static ProgressInterface * progress_instance = 0;
84 void ProgressInterface::setInstance(ProgressInterface* p)
86 progress_instance = p;
90 ProgressInterface * ProgressInterface::instance()
92 if (!progress_instance) {
93 static ProgressDummy dummy;
96 return progress_instance;
104 int Systemcall::startscript(Starttype how, string const & what,
105 string const & path, string const & lpath,
106 bool /*process_events*/)
109 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
112 if (how == DontWait) {
113 switch (os::shell()) {
118 command = "start /min " + command;
121 } else if (os::shell() == os::CMD_EXE)
122 command = subst(command, "cmd /d /c ", "");
124 return ::system(command.c_str());
132 * This is a parser that (mostly) mimics the behavior of a posix shell as
133 * regards quoting, but its output is tailored for being processed by QProcess.
134 * Note that shell metacharacters are not parsed.
136 * The escape character is the backslash.
137 * A backslash that is not quoted preserves the literal value of the following
138 * character, with the exception of a double-quote '"'. If a double-quote
139 * follows a backslash, it will be replaced by three consecutive double-quotes
140 * (this is how the QProcess parser recognizes a '"' as a simple character
141 * instead of a quoting character). Thus, for example:
147 * Characters enclosed in single-quotes ('') have their literal value preserved.
148 * A single-quote cannot occur within single-quotes. Indeed, a backslash cannot
149 * be used to escape a single-quote in a single-quoted string. In other words,
150 * anything enclosed in single-quotes is passed as is, but the single-quotes
151 * themselves are eliminated. Thus, for example:
158 * Characters enclosed in double-quotes ("") have their literal value preserved,
159 * with the exception of the backslash. The backslash retains its special
160 * meaning as an escape character only when followed by a double-quote.
161 * Contrarily to the behavior of a posix shell, the double-quotes themselves
162 * are *not* eliminated. Thus, for example:
167 string const parsecmd(string const & incmd, string & infile, string & outfile,
170 bool in_single_quote = false;
171 bool in_double_quote = false;
172 bool escaped = false;
173 string const python_call = "python -tt";
174 vector<string> outcmd(4);
177 if (prefixIs(incmd, python_call)) {
178 outcmd[0] = os::python();
179 start = python_call.length();
182 for (size_t i = start, o = 0; i < incmd.length(); ++i) {
185 if (in_double_quote || escaped) {
186 if (in_double_quote && escaped)
190 in_single_quote = !in_single_quote;
194 if (in_single_quote) {
200 // Don't triple double-quotes for redirection
201 // files as these won't be parsed by QProcess
202 outcmd[o] += string(o ? "\"" : "\"\"\"");
206 in_double_quote = !in_double_quote;
208 } else if (c == '\\' && !escaped) {
210 } else if (c == '>' && !(in_double_quote || escaped)) {
211 if (suffixIs(outcmd[o], " 2")) {
212 outcmd[o] = rtrim(outcmd[o], "2");
215 if (suffixIs(outcmd[o], " 1"))
216 outcmd[o] = rtrim(outcmd[o], "1");
219 } else if (c == '<' && !(in_double_quote || escaped)) {
222 if (escaped && in_double_quote)
228 infile = trim(outcmd[3], " \"");
229 outfile = trim(outcmd[1], " \"");
230 errfile = trim(outcmd[2], " \"");
231 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);
243 lyxerr << "\nRunning: " << what_ss << endl;
245 LYXERR(Debug::INFO,"Running: " << what_ss);
250 QString const cmd = QString::fromLocal8Bit(
251 parsecmd(what_ss, infile, outfile, errfile).c_str());
253 SystemcallPrivate d(infile, outfile, errfile);
256 // QProcess::startDetached cannot provide environment variables. When the
257 // environment variables are set using the latexEnvCmdPrefix and the process
258 // is started with QProcess::startDetached, a console window is shown every
259 // time a viewer is started. To avoid this, we fall back on Windows to the
260 // original implementation that creates a QProcess object.
261 d.startProcess(cmd, path, lpath, false);
262 if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
263 LYXERR0("Systemcall: '" << cmd << "' did not start!");
264 LYXERR0("error " << d.errorMessage());
267 if (how == DontWait) {
272 d.startProcess(cmd, path, lpath, how == DontWait);
273 if (how == DontWait && d.state == SystemcallPrivate::Running)
276 if (d.state == SystemcallPrivate::Error
277 || !d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
278 LYXERR0("Systemcall: '" << cmd << "' did not start!");
279 LYXERR0("error " << d.errorMessage());
284 if (!d.waitWhile(SystemcallPrivate::Running, process_events,
285 os::timeout_min() * 60 * 1000)) {
286 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
287 LYXERR0("error " << d.errorMessage());
288 LYXERR0("status " << d.exitStatusMessage());
292 int const exit_code = d.exitCode();
294 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
301 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
302 std::string const & ef)
303 : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
304 in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
306 if (!in_file_.empty())
307 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
308 if (!out_file_.empty()) {
309 if (out_file_[0] == '&') {
310 if (subst(out_file_, " ", "") == "&2"
311 && err_file_[0] != '&') {
312 out_file_ = err_file_;
313 process_->setProcessChannelMode(
314 QProcess::MergedChannels);
316 if (err_file_[0] == '&') {
317 // Leave alone things such as
318 // "1>&2 2>&1". Should not be harmful,
319 // but let's give anyway a warning.
320 LYXERR0("Unsupported stdout/stderr redirect.");
323 LYXERR0("Ambiguous stdout redirect: "
326 out_file_ = os::nulldev();
329 // Check whether we have to set the output file.
330 if (out_file_ != os::nulldev()) {
331 process_->setStandardOutputFile(QString::fromLocal8Bit(
335 if (!err_file_.empty()) {
336 if (err_file_[0] == '&') {
337 if (subst(err_file_, " ", "") == "&1"
338 && out_file_[0] != '&') {
339 process_->setProcessChannelMode(
340 QProcess::MergedChannels);
342 LYXERR0("Ambiguous stderr redirect: "
345 // In MergedChannels mode stderr goes to stdout.
346 err_file_ = os::nulldev();
348 // Check whether we have to set the error file.
349 if (err_file_ != os::nulldev()) {
350 process_->setStandardErrorFile(QString::fromLocal8Bit(
355 connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
356 connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
357 #if QT_VERSION >= 0x050600
358 connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
360 connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
362 connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
363 connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
367 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
368 string const & lpath, bool detached)
372 state = SystemcallPrivate::Running;
373 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
374 state = SystemcallPrivate::Error;
377 QProcess* released = releaseProcess();
379 } else if (process_) {
380 state = SystemcallPrivate::Starting;
381 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
386 void SystemcallPrivate::processEvents()
388 if (process_events_) {
389 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
394 void SystemcallPrivate::waitAndProcessEvents()
396 Sleep::millisec(100);
403 bool queryStopCommand(QString const & cmd)
405 docstring text = bformat(_(
406 "The command\n%1$s\nhas not yet completed.\n\n"
407 "Do you want to stop it?"), qstring_to_ucs4(cmd));
408 return ProgressInterface::instance()->prompt(_("Stop command?"), text,
409 1, 1, _("&Stop it"), _("Let it &run")) == 0;
415 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
420 bool timedout = false;
421 process_events_ = process_events;
423 // Block GUI while waiting,
424 // relay on QProcess' wait functions
425 if (!process_events_) {
426 if (waitwhile == Starting)
427 return process_->waitForStarted(timeout);
428 if (waitwhile == Running) {
431 if (process_->waitForFinished(timeout))
433 bool stop = queryStopCommand(cmd_);
434 // The command may have finished in the meantime
435 if (process_->state() == QProcess::NotRunning)
449 // process events while waiting, no timeout
451 while (state == waitwhile && state != Error) {
452 waitAndProcessEvents();
454 return state != Error;
457 // process events while waiting with timeout
460 while (state == waitwhile && state != Error && !timedout) {
461 waitAndProcessEvents();
462 if (timer.elapsed() > timeout) {
463 bool stop = queryStopCommand(cmd_);
464 // The command may have finished in the meantime
465 if (process_->state() == QProcess::NotRunning)
474 return (state != Error) && !timedout;
478 SystemcallPrivate::~SystemcallPrivate()
481 out_data_[out_index_] = '\0';
487 err_data_[err_index_] = '\0';
497 void SystemcallPrivate::stdOut()
501 process_->setReadChannel(QProcess::StandardOutput);
502 while (process_->getChar(&c)) {
503 out_data_[out_index_++] = c;
504 if (c == '\n' || out_index_ + 1 == buffer_size_) {
505 out_data_[out_index_] = '\0';
507 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
515 void SystemcallPrivate::stdErr()
519 process_->setReadChannel(QProcess::StandardError);
520 while (process_->getChar(&c)) {
521 err_data_[err_index_++] = c;
522 if (c == '\n' || err_index_ + 1 == buffer_size_) {
523 err_data_[err_index_] = '\0';
525 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
533 void SystemcallPrivate::processStarted()
535 if (state != Running) {
537 ProgressInterface::instance()->processStarted(cmd_);
542 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
544 if (state != Finished) {
546 ProgressInterface::instance()->processFinished(cmd_);
551 void SystemcallPrivate::processError(QProcess::ProcessError)
554 ProgressInterface::instance()->appendError(errorMessage());
558 QString SystemcallPrivate::errorMessage() const
561 return "No QProcess available";
564 switch (process_->error()) {
565 case QProcess::FailedToStart:
566 message = "The process failed to start. Either the invoked program is missing, "
567 "or you may have insufficient permissions to invoke the program.";
569 case QProcess::Crashed:
570 message = "The process crashed some time after starting successfully.";
572 case QProcess::Timedout:
573 message = "The process timed out. It might be restarted automatically.";
575 case QProcess::WriteError:
576 message = "An error occurred when attempting to write to the process-> For example, "
577 "the process may not be running, or it may have closed its input channel.";
579 case QProcess::ReadError:
580 message = "An error occurred when attempting to read from the process-> For example, "
581 "the process may not be running.";
583 case QProcess::UnknownError:
585 message = "An unknown error occurred.";
592 QString SystemcallPrivate::exitStatusMessage() const
595 return "No QProcess available";
598 switch (process_->exitStatus()) {
599 case QProcess::NormalExit:
600 message = "The process exited normally.";
602 case QProcess::CrashExit:
603 message = "The process crashed.";
606 message = "Unknown exit state.";
613 int SystemcallPrivate::exitCode()
615 // From Qt's documentation, in regards to QProcess::exitCode(),
616 // "This value is not valid unless exitStatus() returns NormalExit"
617 if (!process_ || process_->exitStatus() != QProcess::NormalExit)
620 return process_->exitCode();
624 QProcess* SystemcallPrivate::releaseProcess()
626 QProcess* released = process_;
632 void SystemcallPrivate::killProcess()
634 killProcess(process_);
638 void SystemcallPrivate::killProcess(QProcess * p)
642 p->closeReadChannel(QProcess::StandardOutput);
643 p->closeReadChannel(QProcess::StandardError);
651 #include "moc_SystemcallPrivate.cpp"
654 } // namespace support