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