| 1 |
#include "ChildProcess.h" |
| 2 |
|
| 3 |
#include "cl_exception.h" |
| 4 |
#include "file_logger.h" |
| 5 |
#include "fileutils.h" |
| 6 |
#include "processreaderthread.h" |
| 7 |
|
| 8 |
#include <asyncprocess.h> |
| 9 |
|
| 10 |
#if !USE_IPROCESS |
| 11 |
#include "UnixProcess.h" |
| 12 |
#endif |
| 13 |
|
| 14 |
ChildProcess::ChildProcess() {} |
| 15 |
|
| 16 |
ChildProcess::~ChildProcess() |
| 17 |
{ |
| 18 |
#if USE_IPROCESS |
| 19 |
if(m_process) { |
| 20 |
m_process->Detach(); |
| 21 |
} |
| 22 |
wxDELETE(m_process); |
| 23 |
#else |
| 24 |
if(m_childProcess) { |
| 25 |
m_childProcess->Detach(); |
| 26 |
} |
| 27 |
wxDELETE(m_childProcess); |
| 28 |
#endif |
| 29 |
} |
| 30 |
|
| 31 |
namespace |
| 32 |
{ |
| 33 |
wxString& wrap_with_quotes(wxString& str) |
| 34 |
{ |
| 35 |
if(!str.empty() && str.Contains(" ") && !str.StartsWith("\"") && !str.EndsWith("\"")) { |
| 36 |
str.Prepend("\"").Append("\""); |
| 37 |
} |
| 38 |
return str; |
| 39 |
} |
| 40 |
} // namespace |
| 41 |
|
| 42 |
void ChildProcess::Start(const wxArrayString& args) |
| 43 |
{ |
| 44 |
if(args.IsEmpty()) { |
| 45 |
return; |
| 46 |
} |
| 47 |
#if USE_IPROCESS |
| 48 |
// Build command line from the array |
| 49 |
wxString command; |
| 50 |
command << args[0]; |
| 51 |
|
| 52 |
wrap_with_quotes(command); |
| 53 |
for(size_t i = 1; i < args.size(); ++i) { |
| 54 |
wxString argument = args[i]; |
| 55 |
wrap_with_quotes(argument); |
| 56 |
command << " " << argument; |
| 57 |
} |
| 58 |
|
| 59 |
// Launch the process |
| 60 |
m_process = ::CreateAsyncProcess(this, command, IProcessCreateDefault | IProcessStderrEvent); |
| 61 |
if(!m_process) { |
| 62 |
throw clException(wxString() << "Failed to execute process: " << command); |
| 63 |
}; |
| 64 |
#else |
| 65 |
m_childProcess = new UnixProcess(this, args); |
| 66 |
#endif |
| 67 |
} |
| 68 |
|
| 69 |
void ChildProcess::Write(const wxString& message) { Write(FileUtils::ToStdString(message)); } |
| 70 |
|
| 71 |
void ChildProcess::Write(const std::string& message) |
| 72 |
{ |
| 73 |
if(!IsOk()) { |
| 74 |
return; |
| 75 |
} |
| 76 |
#if USE_IPROCESS |
| 77 |
m_process->WriteRaw(message); |
| 78 |
#else |
| 79 |
m_childProcess->Write(message); |
| 80 |
#endif |
| 81 |
} |
| 82 |
|
| 83 |
bool ChildProcess::IsOk() const |
| 84 |
{ |
| 85 |
#if USE_IPROCESS |
| 86 |
return m_process != nullptr; |
| 87 |
#else |
| 88 |
return m_childProcess != nullptr; |
| 89 |
#endif |
| 90 |
} |