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