]> git.lyx.org Git - lyx.git/blob - src/support/Systemcall.cpp
Mingw-w64 build fixes for long long
[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 "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 &, 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 anon
234
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         LYXERR(Debug::INFO,"Running: " << what_ss);
243
244         string infile;
245         string outfile;
246         string errfile;
247         QString const cmd = QString::fromLocal8Bit(
248                         parsecmd(what_ss, infile, outfile, errfile).c_str());
249
250         SystemcallPrivate d(infile, outfile, errfile);
251
252 #ifdef Q_OS_WIN32
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());
262                 return 10;
263         }
264         if (how == DontWait) {
265                 d.releaseProcess();
266                 return 0;
267         }
268 #else
269         d.startProcess(cmd, path, lpath, how == DontWait);
270         if (how == DontWait && d.state == SystemcallPrivate::Running)
271                 return 0;
272
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());
277                 return 10;
278         }
279 #endif
280
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());
286                 return 20;
287         }
288
289         int const exit_code = d.exitCode();
290         if (exit_code) {
291                 LYXERR0("Systemcall: '" << cmd << "' finished with exit code " << exit_code);
292         }
293
294         return exit_code;
295 }
296
297
298 SystemcallPrivate::SystemcallPrivate(std::string const & sf,
299                                      std::string const & of,
300                                      std::string const & ef) :
301                                 process_(new QProcess), 
302                                 out_index_(0),
303                                 err_index_(0),
304                                 in_file_(sf),
305                                 out_file_(of), 
306                                 err_file_(ef), 
307                                 process_events_(false)
308 {
309         if (!in_file_.empty())
310                 process_->setStandardInputFile(QString::fromLocal8Bit(in_file_.c_str()));
311         if (!out_file_.empty()) {
312                 if (out_file_[0] == '&') {
313                         if (subst(out_file_, " ", "") == "&2"
314                             && err_file_[0] != '&') {
315                                 out_file_ = err_file_;
316                                 process_->setProcessChannelMode(
317                                                 QProcess::MergedChannels);
318                         } else {
319                                 if (err_file_[0] == '&') {
320                                         // Leave alone things such as
321                                         // "1>&2 2>&1". Should not be harmful,
322                                         // but let's give anyway a warning.
323                                         LYXERR0("Unsupported stdout/stderr redirect.");
324                                         err_file_.erase();
325                                 } else {
326                                         LYXERR0("Ambiguous stdout redirect: "
327                                                 << out_file_);
328                                 }
329                                 out_file_ = os::nulldev();
330                         }
331                 }
332                 // Check whether we have to set the output file.
333                 if (out_file_ != os::nulldev()) {
334                         process_->setStandardOutputFile(QString::fromLocal8Bit(
335                                                         out_file_.c_str()));
336                 }
337         }
338         if (!err_file_.empty()) {
339                 if (err_file_[0] == '&') {
340                         if (subst(err_file_, " ", "") == "&1"
341                             && out_file_[0] != '&') {
342                                 process_->setProcessChannelMode(
343                                                 QProcess::MergedChannels);
344                         } else {
345                                 LYXERR0("Ambiguous stderr redirect: "
346                                         << err_file_);
347                         }
348                         // In MergedChannels mode stderr goes to stdout.
349                         err_file_ = os::nulldev();
350                 }
351                 // Check whether we have to set the error file.
352                 if (err_file_ != os::nulldev()) {
353                         process_->setStandardErrorFile(QString::fromLocal8Bit(
354                                                         err_file_.c_str()));
355                 }
356         }
357
358         connect(process_, SIGNAL(readyReadStandardOutput()), SLOT(stdOut()));
359         connect(process_, SIGNAL(readyReadStandardError()), SLOT(stdErr()));
360 #if QT_VERSION >= 0x050600
361         connect(process_, SIGNAL(errorOccurred(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
362 #else
363         connect(process_, SIGNAL(error(QProcess::ProcessError)), SLOT(processError(QProcess::ProcessError)));
364 #endif
365         connect(process_, SIGNAL(started()), this, SLOT(processStarted()));
366         connect(process_, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(processFinished(int, QProcess::ExitStatus)));
367 }
368
369
370 void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
371                                      string const & lpath, bool detached)
372 {
373         cmd_ = cmd;
374         if (detached) {
375                 state = SystemcallPrivate::Running;
376                 if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_)) {
377                         state = SystemcallPrivate::Error;
378                         return;
379                 }
380                 QProcess* released = releaseProcess();
381                 delete released;
382         } else if (process_) {
383                 state = SystemcallPrivate::Starting;
384                 process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
385         }
386 }
387
388
389 void SystemcallPrivate::processEvents()
390 {
391         if (process_events_) {
392                 QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/);
393         }
394 }
395
396
397 void SystemcallPrivate::waitAndProcessEvents()
398 {
399         Sleep::millisec(100);
400         processEvents();
401 }
402
403
404 namespace {
405
406 bool queryStopCommand(QString const & cmd)
407 {
408         docstring text = bformat(_(
409                 "The command\n%1$s\nhas not yet completed.\n\n"
410                 "Do you want to stop it?"), qstring_to_ucs4(cmd));
411         return ProgressInterface::instance()->prompt(_("Stop command?"), text,
412                         1, 1, _("&Stop it"), _("Let it &run")) == 0;
413 }
414
415 }
416
417
418 bool SystemcallPrivate::waitWhile(State waitwhile, bool process_events, int timeout)
419 {
420         if (!process_)
421                 return false;
422
423         bool timedout = false;
424         process_events_ = process_events;
425
426         // Block GUI while waiting,
427         // relay on QProcess' wait functions
428         if (!process_events_) {
429                 if (waitwhile == Starting)
430                         return process_->waitForStarted(timeout);
431                 if (waitwhile == Running) {
432                         int bump = 2;
433                         while (!timedout) {
434                                 if (process_->waitForFinished(timeout))
435                                         return true;
436                                 bool stop = queryStopCommand(cmd_);
437                                 // The command may have finished in the meantime
438                                 if (process_->state() == QProcess::NotRunning)
439                                         return true;
440                                 if (stop) {
441                                         timedout = true;
442                                         process_->kill();
443                                 } else {
444                                         timeout *= bump;
445                                         bump = 3;
446                                 }
447                         }
448                 }
449                 return false;
450         }
451
452         // process events while waiting, no timeout
453         if (timeout == -1) {
454                 while (state == waitwhile && state != Error) {
455                         waitAndProcessEvents();
456                 }
457                 return state != Error;
458         } 
459
460         // process events while waiting with timeout
461         QTime timer;
462         timer.start();
463         while (state == waitwhile && state != Error && !timedout) {
464                 waitAndProcessEvents();
465                 if (timer.elapsed() > timeout) {
466                         bool stop = queryStopCommand(cmd_);
467                         // The command may have finished in the meantime
468                         if (process_->state() == QProcess::NotRunning)
469                                 break;
470                         if (stop) {
471                                 timedout = true;
472                                 process_->kill();
473                         } else
474                                 timeout *= 3;
475                 }
476         }
477         return (state != Error) && !timedout;
478 }
479
480
481 SystemcallPrivate::~SystemcallPrivate()
482 {
483         if (out_index_) {
484                 out_data_[out_index_] = '\0';
485                 out_index_ = 0;
486                 cout << out_data_;
487         }
488         cout.flush();
489         if (err_index_) {
490                 err_data_[err_index_] = '\0';
491                 err_index_ = 0;
492                 cerr << err_data_;
493         }
494         cerr.flush();
495
496         killProcess();
497 }
498
499
500 void SystemcallPrivate::stdOut()
501 {
502         if (process_) {
503                 char c;
504                 process_->setReadChannel(QProcess::StandardOutput);
505                 while (process_->getChar(&c)) {
506                         out_data_[out_index_++] = c;
507                         if (c == '\n' || out_index_ + 1 == buffer_size_) {
508                                 out_data_[out_index_] = '\0';
509                                 out_index_ = 0;
510                                 ProgressInterface::instance()->appendMessage(QString::fromLocal8Bit(out_data_));
511                                 cout << out_data_;
512                         }
513                 }
514         }
515 }
516
517
518 void SystemcallPrivate::stdErr()
519 {
520         if (process_) {
521                 char c;
522                 process_->setReadChannel(QProcess::StandardError);
523                 while (process_->getChar(&c)) {
524                         err_data_[err_index_++] = c;
525                         if (c == '\n' || err_index_ + 1 == buffer_size_) {
526                                 err_data_[err_index_] = '\0';
527                                 err_index_ = 0;
528                                 ProgressInterface::instance()->appendError(QString::fromLocal8Bit(err_data_));
529                                 cerr << err_data_;
530                         }
531                 }
532         }
533 }
534
535
536 void SystemcallPrivate::processStarted()
537 {
538         if (state != Running) {
539                 state = Running;
540                 ProgressInterface::instance()->processStarted(cmd_);
541         }
542 }
543
544
545 void SystemcallPrivate::processFinished(int, QProcess::ExitStatus)
546 {
547         if (state != Finished) {
548                 state = Finished;
549                 ProgressInterface::instance()->processFinished(cmd_);
550         }
551 }
552
553
554 void SystemcallPrivate::processError(QProcess::ProcessError)
555 {
556         state = Error;
557         ProgressInterface::instance()->appendError(errorMessage());
558 }
559
560
561 QString SystemcallPrivate::errorMessage() const 
562 {
563         if (!process_)
564                 return "No QProcess available";
565
566         QString message;
567         switch (process_->error()) {
568                 case QProcess::FailedToStart:
569                         message = "The process failed to start. Either the invoked program is missing, "
570                                       "or you may have insufficient permissions to invoke the program.";
571                         break;
572                 case QProcess::Crashed:
573                         message = "The process crashed some time after starting successfully.";
574                         break;
575                 case QProcess::Timedout:
576                         message = "The process timed out. It might be restarted automatically.";
577                         break;
578                 case QProcess::WriteError:
579                         message = "An error occurred when attempting to write to the process-> For example, "
580                                       "the process may not be running, or it may have closed its input channel.";
581                         break;
582                 case QProcess::ReadError:
583                         message = "An error occurred when attempting to read from the process-> For example, "
584                                       "the process may not be running.";
585                         break;
586                 case QProcess::UnknownError:
587                 default:
588                         message = "An unknown error occurred.";
589                         break;
590         }
591         return message;
592 }
593
594
595 QString SystemcallPrivate::exitStatusMessage() const
596 {
597         if (!process_)
598                 return "No QProcess available";
599
600         QString message;
601         switch (process_->exitStatus()) {
602                 case QProcess::NormalExit:
603                         message = "The process exited normally.";
604                         break;
605                 case QProcess::CrashExit:
606                         message = "The process crashed.";
607                         break;
608                 default:
609                         message = "Unknown exit state.";
610                         break;
611         }
612         return message;
613 }
614
615
616 int SystemcallPrivate::exitCode()
617 {
618         // From Qt's documentation, in regards to QProcess::exitCode(),
619         // "This value is not valid unless exitStatus() returns NormalExit"
620         if (!process_ || process_->exitStatus() != QProcess::NormalExit)
621                 return -1;
622
623         return process_->exitCode();
624 }
625
626
627 QProcess* SystemcallPrivate::releaseProcess()
628 {
629         QProcess* released = process_;
630         process_ = 0;
631         return released;
632 }
633
634
635 void SystemcallPrivate::killProcess()
636 {
637         killProcess(process_);
638 }
639
640
641 void SystemcallPrivate::killProcess(QProcess * p)
642 {
643         if (p) {
644                 p->disconnect();
645                 p->closeReadChannel(QProcess::StandardOutput);
646                 p->closeReadChannel(QProcess::StandardError);
647                 p->close();
648                 delete p;
649         }
650 }
651
652
653
654 #include "moc_SystemcallPrivate.cpp"
655 #endif
656
657 } // namespace support
658 } // namespace lyx