]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Use more informative descriptions fro Springer layouts
[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/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"
25
26 #include "LyX.h"
27
28 #include <cstdlib>
29 #include <iostream>
30
31 #include <QProcess>
32 #include <QTime>
33 #include <QThread>
34 #include <QCoreApplication>
35 #include <QDebug>
36
37 #define USE_QPROCESS
38
39
40 struct Sleep : QThread
41 {
42         static void millisec(unsigned long ms)
43         {
44                 QThread::usleep(ms * 1000);
45         }
46 };
47
48
49
50
51 using namespace std;
52
53 namespace lyx {
54 namespace support {
55
56
57 class ProgressDummy : public ProgressInterface
58 {
59 public:
60         ProgressDummy() {}
61
62         void processStarted(QString const &) {}
63         void processFinished(QString const &) {}
64         void appendMessage(QString const &) {}
65         void appendError(QString const &) {}
66         void clearMessages() {}
67         void lyxerrFlush() {}
68
69         void lyxerrConnect() {}
70         void lyxerrDisconnect() {}
71
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; }
78 };
79
80
81 static ProgressInterface * progress_instance = 0;
82
83 void ProgressInterface::setInstance(ProgressInterface* p)
84 {
85         progress_instance = p;
86 }
87
88
89 ProgressInterface * ProgressInterface::instance()
90 {
91         if (!progress_instance) {
92                 static ProgressDummy dummy;
93                 return &dummy;
94         }
95         return progress_instance;
96 }
97
98
99
100
101 // Reuse of instance
102 #ifndef USE_QPROCESS
103 int Systemcall::startscript(Starttype how, string const & what,
104                             string const & path, string const & lpath,
105                             bool /*process_events*/)
106 {
107         string command =
108                 to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
109                        + commandPrep(what);
110
111         if (how == DontWait) {
112                 switch (os::shell()) {
113                 case os::UNIX:
114                         command += " &";
115                         break;
116                 case os::CMD_EXE:
117                         command = "start /min " + command;
118                         break;
119                 }
120         } else if (os::shell() == os::CMD_EXE)
121                 command = subst(command, "cmd /d /c ", "");
122
123         return ::system(command.c_str());
124 }
125
126 #else
127
128 namespace {
129
130 /*
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.
134  *
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:
141  *     \\  ->  \
142  *     \a  ->  a
143  *     \"  ->  """
144  *
145  * Single-quotes.
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:
151  *    '\'    ->  \
152  *    '\\'   ->  \\
153  *    '\a'   ->  \a
154  *    'a\"b' ->  a\"b
155  *
156  * Double-quotes.
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:
162  *    "\\"   ->  "\\"
163  *    "\a"   ->  "\a"
164  *    "a\"b" ->  "a"""b"
165  */
166 string const parsecmd(string const & incmd, string & infile, string & outfile,
167                      string & errfile)
168 {
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);
174         size_t start = 0;
175
176         if (prefixIs(incmd, python_call)) {
177                 outcmd[0] = os::python();
178                 start = python_call.length();
179         }
180
181         for (size_t i = start, o = 0; i < incmd.length(); ++i) {
182                 char c = incmd[i];
183                 if (c == '\'') {
184                         if (in_double_quote || escaped) {
185                                 if (in_double_quote && escaped)
186                                         outcmd[o] += '\\';
187                                 outcmd[o] += c;
188                         } else
189                                 in_single_quote = !in_single_quote;
190                         escaped = false;
191                         continue;
192                 }
193                 if (in_single_quote) {
194                         outcmd[o] += c;
195                         continue;
196                 }
197                 if (c == '"') {
198                         if (escaped) {
199                                 // Don't triple double-quotes for redirection
200                                 // files as these won't be parsed by QProcess
201                                 outcmd[o] += string(o ? "\"" : "\"\"\"");
202                                 escaped = false;
203                         } else {
204                                 outcmd[o] += c;
205                                 in_double_quote = !in_double_quote;
206                         }
207                 } else if (c == '\\' && !escaped) {
208                         escaped = !escaped;
209                 } else if (c == '>' && !(in_double_quote || escaped)) {
210                         if (suffixIs(outcmd[o], " 2")) {
211                                 outcmd[o] = rtrim(outcmd[o], "2");
212                                 o = 2;
213                         } else {
214                                 if (suffixIs(outcmd[o], " 1"))
215                                         outcmd[o] = rtrim(outcmd[o], "1");
216                                 o = 1;
217                         }
218                 } else if (c == '<' && !(in_double_quote || escaped)) {
219                         o = 3;
220                 } else {
221                         if (escaped && in_double_quote)
222                                 outcmd[o] += '\\';
223                         outcmd[o] += c;
224                         escaped = false;
225                 }
226         }
227         infile  = trim(outcmd[3], " \"");
228         outfile = trim(outcmd[1], " \"");
229         errfile = trim(outcmd[2], " \"");
230         return trim(outcmd[0]);
231 }
232
233 } // namespace
234
235
236 void Systemcall::killscript()
237 {
238         SystemcallPrivate::kill_script = true;
239 }
240
241
242 int Systemcall::startscript(Starttype how, string const & what,
243                             string const & path, string const & lpath,
244                             bool process_events)
245 {
246         string const what_ss = commandPrep(what);
247         if (verbose)
248                 lyxerr << "\nRunning: " << what_ss << endl;
249         else
250                 LYXERR(Debug::INFO,"Running: " << what_ss);
251
252         string infile;
253         string outfile;
254         string errfile;
255         QString const cmd = QString::fromLocal8Bit(
256                         parsecmd(what_ss, infile, outfile, errfile).c_str());
257
258         SystemcallPrivate d(infile, outfile, errfile);
259         bool do_events = process_events || how == WaitLoop;
260
261 #ifdef Q_OS_WIN32
262         // QProcess::startDetached cannot provide environment variables. When the
263         // environment variables are set using the latexEnvCmdPrefix and the process
264         // is started with QProcess::startDetached, a console window is shown every
265         // time a viewer is started. To avoid this, we fall back on Windows to the
266         // original implementation that creates a QProcess object.
267         d.startProcess(cmd, path, lpath, false);
268         if (!d.waitWhile(SystemcallPrivate::Starting, do_events, -1)) {
269                 if (d.state == SystemcallPrivate::Error) {
270                         LYXERR0("Systemcall: '" << cmd << "' did not start!");
271                         LYXERR0("error " << d.errorMessage());
272                         return NOSTART;
273                 } else if (d.state == SystemcallPrivate::Killed) {
274                         LYXERR0("Killed: " << cmd);
275                         return KILLED;
276                 }
277         }
278         if (how == DontWait) {
279                 d.releaseProcess();
280                 return OK;
281         }
282 #else
283         d.startProcess(cmd, path, lpath, how == DontWait);
284         if (how == DontWait && d.state == SystemcallPrivate::Running)
285                 return OK;
286
287         if (d.state == SystemcallPrivate::Error
288                         || !d.waitWhile(SystemcallPrivate::Starting, do_events, -1)) {
289                 if (d.state == SystemcallPrivate::Error) {
290                         LYXERR0("Systemcall: '" << cmd << "' did not start!");
291                         LYXERR0("error " << d.errorMessage());
292                         return NOSTART;
293                 } else if (d.state == SystemcallPrivate::Killed) {
294                         LYXERR0("Killed: " << cmd);
295                         return KILLED;
296                 }
297         }
298 #endif
299
300         if (!d.waitWhile(SystemcallPrivate::Running, do_events,
301                          os::timeout_min() * 60 * 1000)) {
302                 if (d.state == SystemcallPrivate::Killed) {
303                         LYXERR0("Killed: " << cmd);
304                         return KILLED;
305                 }
306                 LYXERR0("Systemcall: '" << cmd << "' did not finish!");
307                 LYXERR0("error " << d.errorMessage());
308                 LYXERR0("status " << d.exitStatusMessage());
309                 return TIMEOUT;
310         }
311
312         int const exit_code = d.exitCode();
313         if (exit_code) {
314                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
315         }
316
317         return exit_code;
318 }
319
320
321 bool SystemcallPrivate::kill_script = false;
322
323
324 SystemcallPrivate::SystemcallPrivate(std::string const & sf, std::string const & of,
325                                      std::string const & ef)
326         : state(Error), process_(new QProcess), out_index_(0), err_index_(0),
327           in_file_(sf), out_file_(of), err_file_(ef), process_events_(false)
328 {
329         if (!in_file_.empty())
330                 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
331         if (!out_file_.empty()) {
332                 if (out_file_[0] == '&') {
333                         if (subst(out_file_, " ", "") == "&2"
334                             && err_file_[0] != '&') {
335                                 out_file_ = err_file_;
336                                 process_->setProcessChannelMode(
337                                                 QProcess::MergedChannels);
338                         } else {
339                                 if (err_file_[0] == '&') {
340                                         // Leave alone things such as
341                                         // "1>&2 2>&1". Should not be harmful,
342                                         // but let's give anyway a warning.
343                                         LYXERR0("Unsupported stdout/stderr redirect.");
344                                         err_file_.erase();
345                                 } else {
346                                         LYXERR0("Ambiguous stdout redirect: "
347                                                 << out_file_);
348                                 }
349                                 out_file_ = os::nulldev();
350                         }
351                 }
352                 // Check whether we have to set the output file.
353                 if (out_file_ != os::nulldev()) {
354                         process_->setStandardOutputFile(QString::fromLocal8Bit(
355                                                         out_file_.c_str()));
356                 }
357         }
358         if (!err_file_.empty()) {
359                 if (err_file_[0] == '&') {
360                         if (subst(err_file_, " ", "") == "&1"
361                             && out_file_[0] != '&') {
362                                 process_->setProcessChannelMode(
363                                                 QProcess::MergedChannels);
364                         } else {
365                                 LYXERR0("Ambiguous stderr redirect: "
366                                         << err_file_);
367                         }
368                         // In MergedChannels mode stderr goes to stdout.
369                         err_file_ = os::nulldev();
370                 }
371                 // Check whether we have to set the error file.
372                 if (err_file_ != os::nulldev()) {
373                         process_->setStandardErrorFile(QString::fromLocal8Bit(
374                                                         err_file_.c_str()));
375                 }
376         }
377
378         connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
379         connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
380 #if QT_VERSION >= 0x050600
381         connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
382 #else
383         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
384 #endif
385         connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
386         connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
387 }
388
389
390 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
391                                      string const & lpath, bool detached)
392 {
393         cmd_ = cmd;
394         if (detached) {
395                 state = SystemcallPrivate::Running;
396                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
397                         state = SystemcallPrivate::Error;
398                         return;
399                 }
400                 QProcess* released = releaseProcess();
401                 delete released;
402         } else if (process_) {
403                 state = SystemcallPrivate::Starting;
404                 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
405         }
406 }
407
408
409 bool SystemcallPrivate::waitAndCheck()
410 {
411         Sleep::millisec(100);
412         if (kill_script) {
413                 // is there a better place to reset this?
414                 process_->kill();
415                 state = Killed;
416                 kill_script = false;
417                 LYXERR0("Export Canceled!!");
418                 return false;
419         }
420         QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
421         return true;
422 }
423
424
425 namespace {
426
427 bool queryStopCommand(QString const & cmd)
428 {
429         docstring text = bformat(_(
430                 "The command\n%1$s\nhas not yet completed.\n\n"
431                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
432         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
433                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
434 }
435
436 } // namespace
437
438
439 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
440 {
441         if (!process_)
442                 return false;
443
444         bool timedout = false;
445         process_events_ = process_events;
446
447         // Block GUI while waiting,
448         // relay on QProcess' wait functions
449         if (!process_events_) {
450                 if (waitwhile == Starting)
451                         return process_->waitForStarted(timeout);
452                 if (waitwhile == Running) {
453                         int bump = 2;
454                         while (!timedout) {
455                                 if (process_->waitForFinished(timeout))
456                                         return true;
457                                 bool stop = queryStopCommand(cmd_);
458                                 // The command may have finished in the meantime
459                                 if (process_->state() == QProcess::NotRunning)
460                                         return true;
461                                 if (stop) {
462                                         timedout = true;
463                                         process_->kill();
464                                 } else {
465                                         timeout *= bump;
466                                         bump = 3;
467                                 }
468                         }
469                 }
470                 return false;
471         }
472
473         // process events while waiting, no timeout
474         if (timeout == -1) {
475                 while (state == waitwhile && state != Error) {
476                         // check for cancellation of background process
477                         if (!waitAndCheck())
478                                 return false;
479                 }
480                 return state != Error;
481         }
482
483         // process events while waiting with timeout
484         QTime timer;
485         timer.start();
486         while (state == waitwhile && state != Error && !timedout) {
487                 // check for cancellation of background process
488                 if (!waitAndCheck())
489                         return false;
490
491                 if (timer.elapsed() > timeout) {
492                         bool stop = queryStopCommand(cmd_);
493                         // The command may have finished in the meantime
494                         if (process_->state() == QProcess::NotRunning)
495                                 break;
496                         if (stop) {
497                                 timedout = true;
498                                 process_->kill();
499                         } else
500                                 timeout *= 3;
501                 }
502         }
503         return (state != Error) && !timedout;
504 }
505
506
507 SystemcallPrivate::~SystemcallPrivate()
508 {
509         if (out_index_) {
510                 out_data_[out_index_] = '\0';
511                 out_index_ = 0;
512                 cout << out_data_;
513         }
514         cout.flush();
515         if (err_index_) {
516                 err_data_[err_index_] = '\0';
517                 err_index_ = 0;
518                 cerr << err_data_;
519         }
520         cerr.flush();
521
522         killProcess();
523 }
524
525
526 void SystemcallPrivate::stdOut()
527 {
528         if (process_) {
529                 char c;
530                 process_->setReadChannel(QProcess::StandardOutput);
531                 while (process_->getChar(&c)) {
532                         out_data_[out_index_++] = c;
533                         if (c == '\n' || out_index_ + 1 == buffer_size_) {
534                                 out_data_[out_index_] = '\0';
535                                 out_index_ = 0;
536                                 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
537                                 cout << out_data_;
538                         }
539                 }
540         }
541 }
542
543
544 void SystemcallPrivate::stdErr()
545 {
546         if (process_) {
547                 char c;
548                 process_->setReadChannel(QProcess::StandardError);
549                 while (process_->getChar(&c)) {
550                         err_data_[err_index_++] = c;
551                         if (c == '\n' || err_index_ + 1 == buffer_size_) {
552                                 err_data_[err_index_] = '\0';
553                                 err_index_ = 0;
554                                 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
555                                 cerr << err_data_;
556                         }
557                 }
558         }
559 }
560
561
562 void SystemcallPrivate::processStarted()
563 {
564         if (state != Running) {
565                 state = Running;
566                 ProgressInterface::instance()->processStarted(cmd_);
567         }
568 }
569
570
571 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
572 {
573         if (state != Finished) {
574                 state = Finished;
575                 ProgressInterface::instance()->processFinished(cmd_);
576         }
577 }
578
579
580 void SystemcallPrivate::processError(QProcess::ProcessError)
581 {
582         state = Error;
583         ProgressInterface::instance()->appendError(errorMessage());
584 }
585
586
587 QString SystemcallPrivate::errorMessage() const
588 {
589         if (!process_)
590                 return "No QProcess available";
591
592         QString message;
593         switch (process_->error()) {
594                 case QProcess::FailedToStart:
595                         message = "The process failed to start. Either the invoked program is missing, "
596                                       "or you may have insufficient permissions to invoke the program.";
597                         break;
598                 case QProcess::Crashed:
599                         message = "The process crashed some time after starting successfully.";
600                         break;
601                 case QProcess::Timedout:
602                         message = "The process timed out. It might be restarted automatically.";
603                         break;
604                 case QProcess::WriteError:
605                         message = "An error occurred when attempting to write to the process-> For example, "
606                                       "the process may not be running, or it may have closed its input channel.";
607                         break;
608                 case QProcess::ReadError:
609                         message = "An error occurred when attempting to read from the process-> For example, "
610                                       "the process may not be running.";
611                         break;
612                 case QProcess::UnknownError:
613                 default:
614                         message = "An unknown error occurred.";
615                         break;
616         }
617         return message;
618 }
619
620
621 QString SystemcallPrivate::exitStatusMessage() const
622 {
623         if (!process_)
624                 return "No QProcess available";
625
626         QString message;
627         switch (process_->exitStatus()) {
628                 case QProcess::NormalExit:
629                         message = "The process exited normally.";
630                         break;
631                 case QProcess::CrashExit:
632                         message = "The process crashed.";
633                         break;
634                 default:
635                         message = "Unknown exit state.";
636                         break;
637         }
638         return message;
639 }
640
641
642 int SystemcallPrivate::exitCode()
643 {
644         // From Qt's documentation, in regards to QProcess::exitCode(),
645         // "This value is not valid unless exitStatus() returns NormalExit"
646         if (!process_ || process_->exitStatus() != QProcess::NormalExit)
647                 return -1;
648
649         return process_->exitCode();
650 }
651
652
653 QProcess* SystemcallPrivate::releaseProcess()
654 {
655         QProcess* released = process_;
656         process_ = 0;
657         return released;
658 }
659
660
661 void SystemcallPrivate::killProcess()
662 {
663         killProcess(process_);
664 }
665
666
667 void SystemcallPrivate::killProcess(QProcess * p)
668 {
669         if (p) {
670                 p->disconnect();
671                 p->closeReadChannel(QProcess::StandardOutput);
672                 p->closeReadChannel(QProcess::StandardError);
673                 p->close();
674                 delete p;
675         }
676 }
677
678
679
680 #include "moc_SystemcallPrivate.cpp"
681 #endif
682
683 } // namespace support
684 } // namespace lyx