]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
Recognize VC12 (a.k.a. MSVS 2013) and define __VISUALC12__ for it.
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
9cd03a43 2// Name: src/msw/utilsexc.cpp
79066131 3// Purpose: wxExecute implementation for MSW
32592631
GL
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
77ffb593 8// Copyright: (c) 1998-2002 wxWidgets dev team
65571936 9// Licence: wxWindows licence
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
32592631
GL
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
b568d04f 24 #pragma hdrstop
32592631
GL
25#endif
26
27#ifndef WX_PRECOMP
b568d04f
VZ
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
068a7cfe 31 #include "wx/log.h"
530ecef0
WS
32 #if wxUSE_STREAMS
33 #include "wx/stream.h"
34 #endif
02761f6c 35 #include "wx/module.h"
2ae8a353 36#endif
32592631 37
eccd1992 38#include "wx/process.h"
204abcd4 39#include "wx/thread.h"
e2478fde 40#include "wx/apptrait.h"
dbbcfbb6 41#include "wx/evtloop.h"
5a8561fc 42#include "wx/vector.h"
e2478fde 43
eccd1992 44
32592631 45#include "wx/msw/private.h"
dbeac4bd 46
32592631
GL
47#include <ctype.h>
48
f172cb82 49#if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 50 #include <direct.h>
b568d04f 51 #include <dos.h>
32592631
GL
52#endif
53
b39dbf34 54#if defined(__GNUWIN32__)
b568d04f
VZ
55 #include <sys/unistd.h>
56 #include <sys/stat.h>
57c208c5 57#endif
32592631 58
eccd1992
VZ
59#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
60 #ifndef __UNIX__
61 #include <io.h>
62 #endif
32592631 63
eccd1992
VZ
64 #ifndef __GNUWIN32__
65 #include <shellapi.h>
66 #endif
32592631
GL
67#endif
68
69#include <stdio.h>
70#include <stdlib.h>
71#include <string.h>
72#ifndef __WATCOMC__
3f4a0c5b
VZ
73 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
74 #include <errno.h>
75 #endif
32592631
GL
76#endif
77#include <stdarg.h>
78
731dd422
VZ
79#if wxUSE_IPC
80 #include "wx/dde.h" // for WX_DDE hack in wxExecute
81#endif // wxUSE_IPC
5bd3a2da 82
b481194f 83#include "wx/msw/private/hiddenwin.h"
eccd1992 84
ee6c519a
VZ
85// FIXME-VC6: These are not defined in VC6 SDK headers.
86#ifndef BELOW_NORMAL_PRIORITY_CLASS
87 #define BELOW_NORMAL_PRIORITY_CLASS 0x4000
88#endif
89
90#ifndef ABOVE_NORMAL_PRIORITY_CLASS
91 #define ABOVE_NORMAL_PRIORITY_CLASS 0x8000
92#endif
93
b568d04f
VZ
94// ----------------------------------------------------------------------------
95// constants
96// ----------------------------------------------------------------------------
97
cb6827a8
VZ
98// this message is sent when the process we're waiting for terminates
99#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 100
b568d04f
VZ
101// ----------------------------------------------------------------------------
102// this module globals
103// ----------------------------------------------------------------------------
104
105// we need to create a hidden window to receive the process termination
106// notifications and for this we need a (Win) class name for it which we will
107// register the first time it's needed
eccd1992 108static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
b568d04f
VZ
109static const wxChar *gs_classForHiddenWindow = NULL;
110
5a8561fc
VZ
111// event used to wake up threads waiting in wxExecuteThread
112static HANDLE gs_heventShutdown = NULL;
113
114// handles of all threads monitoring the execution of asynchronously running
115// processes
116static wxVector<HANDLE> gs_asyncThreads;
117
b568d04f
VZ
118// ----------------------------------------------------------------------------
119// private types
120// ----------------------------------------------------------------------------
121
cb6827a8
VZ
122// structure describing the process we're being waiting for
123struct wxExecuteData
124{
125public:
126 ~wxExecuteData()
127 {
128 if ( !::CloseHandle(hProcess) )
129 {
f6bcfd97 130 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8
VZ
131 }
132 }
133
134 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
135 HANDLE hProcess; // handle of the process
136 DWORD dwProcessId; // pid of the process
137 wxProcess *handler;
138 DWORD dwExitCode; // the exit code of the process
27d2dbbc 139 bool state; // set to false when the process finishes
32592631
GL
140};
141
eccd1992
VZ
142class wxExecuteModule : public wxModule
143{
144public:
145 virtual bool OnInit() { return true; }
146 virtual void OnExit()
147 {
5a8561fc
VZ
148 if ( gs_heventShutdown )
149 {
150 // stop any threads waiting for the termination of asynchronously
151 // running processes
152 if ( !::SetEvent(gs_heventShutdown) )
153 {
9a83f860 154 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
5a8561fc
VZ
155 }
156
157 ::CloseHandle(gs_heventShutdown);
158 gs_heventShutdown = NULL;
159
160 // now wait until they terminate
161 if ( !gs_asyncThreads.empty() )
162 {
163 const size_t numThreads = gs_asyncThreads.size();
164
165 if ( ::WaitForMultipleObjects
166 (
167 numThreads,
168 &gs_asyncThreads[0],
169 TRUE, // wait for all of them to become signalled
170 3000 // long but finite value
171 ) == WAIT_TIMEOUT )
172 {
9a83f860 173 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
5a8561fc
VZ
174 }
175
176 for ( size_t n = 0; n < numThreads; n++ )
177 {
178 ::CloseHandle(gs_asyncThreads[n]);
179 }
180
181 gs_asyncThreads.clear();
182 }
183 }
184
9978ac8e 185 if ( gs_classForHiddenWindow )
eccd1992
VZ
186 {
187 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
188 {
9a83f860 189 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
eccd1992
VZ
190 }
191
192 gs_classForHiddenWindow = NULL;
193 }
194 }
195
196private:
197 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
198};
199
5a8561fc
VZ
200IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
201
eccd1992 202#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 203
bfabc7f4 204#include "wx/private/pipestream.h"
9b70925d 205#include "wx/private/streamtempinput.h"
79066131
VZ
206
207// ----------------------------------------------------------------------------
208// wxPipe represents a Win32 anonymous pipe
209// ----------------------------------------------------------------------------
210
211class wxPipe
212{
213public:
214 // the symbolic names for the pipe ends
215 enum Direction
216 {
217 Read,
218 Write
219 };
220
221 // default ctor doesn't do anything
222 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
223
27d2dbbc 224 // create the pipe, return true if ok, false on error
79066131
VZ
225 bool Create()
226 {
227 // default secutiry attributes
228 SECURITY_ATTRIBUTES security;
229
230 security.nLength = sizeof(security);
231 security.lpSecurityDescriptor = NULL;
232 security.bInheritHandle = TRUE; // to pass it to the child
233
234 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
235 {
236 wxLogSysError(_("Failed to create an anonymous pipe"));
237
27d2dbbc 238 return false;
79066131
VZ
239 }
240
27d2dbbc 241 return true;
79066131
VZ
242 }
243
27d2dbbc 244 // return true if we were created successfully
79066131
VZ
245 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
246
247 // return the descriptor for one of the pipe ends
82baa5e4 248 HANDLE operator[](Direction which) const { return m_handles[which]; }
79066131
VZ
249
250 // detach a descriptor, meaning that the pipe dtor won't close it, and
251 // return it
252 HANDLE Detach(Direction which)
253 {
79066131
VZ
254 HANDLE handle = m_handles[which];
255 m_handles[which] = INVALID_HANDLE_VALUE;
256
257 return handle;
258 }
259
260 // close the pipe descriptors
261 void Close()
262 {
263 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
264 {
265 if ( m_handles[n] != INVALID_HANDLE_VALUE )
266 {
267 ::CloseHandle(m_handles[n]);
268 m_handles[n] = INVALID_HANDLE_VALUE;
269 }
270 }
271 }
272
273 // dtor closes the pipe descriptors
274 ~wxPipe() { Close(); }
275
276private:
277 HANDLE m_handles[2];
278};
279
280#endif // wxUSE_STREAMS
281
282// ============================================================================
283// implementation
284// ============================================================================
285
79066131
VZ
286// ----------------------------------------------------------------------------
287// process termination detecting support
288// ----------------------------------------------------------------------------
289
290// thread function for the thread monitoring the process termination
291static DWORD __stdcall wxExecuteThread(void *arg)
292{
45d5a0c6 293 wxExecuteData * const data = (wxExecuteData *)arg;
79066131 294
5a8561fc
VZ
295 // create the shutdown event if we're the first thread starting to wait
296 if ( !gs_heventShutdown )
79066131 297 {
5a8561fc
VZ
298 // create a manual initially non-signalled event object
299 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
300 if ( !gs_heventShutdown )
301 {
9a83f860 302 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
5a8561fc 303 }
79066131
VZ
304 }
305
5a8561fc
VZ
306 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
307 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
79066131 308 {
5a8561fc
VZ
309 case WAIT_OBJECT_0:
310 // process terminated, get its exit code
311 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
312 {
313 wxLogLastError(wxT("GetExitCodeProcess"));
314 }
315
316 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
317 wxT("process should have terminated") );
79066131 318
5a8561fc
VZ
319 // send a message indicating process termination to the window
320 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
321 break;
322
323 case WAIT_OBJECT_0 + 1:
324 // we're shutting down but the process is still running -- leave it
325 // run but clean up the associated data
326 if ( !data->state )
327 {
328 delete data;
329 }
330 //else: exiting while synchronously executing process is still
331 // running? this shouldn't happen...
332 break;
79066131 333
5a8561fc 334 default:
9a83f860 335 wxLogDebug(wxT("Waiting for the process termination failed!"));
5a8561fc 336 }
79066131
VZ
337
338 return 0;
339}
340
341// window procedure of a hidden window which is created just to receive
342// the notification message when a process exits
343LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
344 WPARAM wParam, LPARAM lParam)
345{
346 if ( message == wxWM_PROC_TERMINATED )
347 {
348 DestroyWindow(hWnd); // we don't need it any more
349
45d5a0c6 350 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
351 if ( data->handler )
352 {
353 data->handler->OnTerminate((int)data->dwProcessId,
354 (int)data->dwExitCode);
355 }
356
357 if ( data->state )
358 {
359 // we're executing synchronously, tell the waiting thread
360 // that the process finished
5a8561fc 361 data->state = false;
79066131
VZ
362 }
363 else
364 {
365 // asynchronous execution - we should do the clean up
366 delete data;
367 }
368
369 return 0;
370 }
371 else
372 {
45d5a0c6 373 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
374 }
375}
376
377// ============================================================================
378// implementation of IO redirection support classes
379// ============================================================================
380
4676948b 381#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
382
383// ----------------------------------------------------------------------------
384// wxPipeInputStreams
385// ----------------------------------------------------------------------------
8b33ae2d
GL
386
387wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
388{
389 m_hInput = hInput;
cd6ce4a9 390}
8b33ae2d
GL
391
392wxPipeInputStream::~wxPipeInputStream()
393{
79066131
VZ
394 if ( m_hInput != INVALID_HANDLE_VALUE )
395 ::CloseHandle(m_hInput);
8b33ae2d
GL
396}
397
2b5f62a0 398bool wxPipeInputStream::CanRead() const
8b33ae2d 399{
386a2898
VZ
400 // we can read if there's something in the put back buffer
401 // even pipe is closed
402 if ( m_wbacksize > m_wbackcur )
403 return true;
404
405 wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream);
406
79066131 407 if ( !IsOpened() )
386a2898
VZ
408 {
409 // set back to mark Eof as it may have been unset by Ungetch()
410 self->m_lasterror = wxSTREAM_EOF;
27d2dbbc 411 return false;
386a2898 412 }
79066131 413
f6bcfd97
BP
414 DWORD nAvailable;
415
416 // function name is misleading, it works with anon pipes as well
417 DWORD rc = ::PeekNamedPipe
418 (
419 m_hInput, // handle
420 NULL, 0, // ptr to buffer and its size
421 NULL, // [out] bytes read
422 &nAvailable, // [out] bytes available
423 NULL // [out] bytes left
424 );
425
426 if ( !rc )
427 {
428 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
429 {
430 // unexpected error
9a83f860 431 wxLogLastError(wxT("PeekNamedPipe"));
f6bcfd97 432 }
8b33ae2d 433
3103e8a9 434 // don't try to continue reading from a pipe if an error occurred or if
f6bcfd97 435 // it had been closed
79066131
VZ
436 ::CloseHandle(m_hInput);
437
2b5f62a0
VZ
438 self->m_hInput = INVALID_HANDLE_VALUE;
439 self->m_lasterror = wxSTREAM_EOF;
440
441 nAvailable = 0;
f6bcfd97 442 }
79066131
VZ
443
444 return nAvailable != 0;
f6bcfd97
BP
445}
446
447size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
448{
2b5f62a0 449 if ( !IsOpened() )
79066131
VZ
450 {
451 m_lasterror = wxSTREAM_EOF;
452
f6bcfd97 453 return 0;
79066131
VZ
454 }
455
f6bcfd97
BP
456 DWORD bytesRead;
457 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
458 {
2b5f62a0
VZ
459 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
460 ? wxSTREAM_EOF
461 : wxSTREAM_READ_ERROR;
8b33ae2d 462 }
f6bcfd97 463
3103e8a9 464 // bytesRead is set to 0, as desired, if an error occurred
8b33ae2d
GL
465 return bytesRead;
466}
467
79066131 468// ----------------------------------------------------------------------------
8b33ae2d 469// wxPipeOutputStream
79066131 470// ----------------------------------------------------------------------------
8b33ae2d
GL
471
472wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
473{
474 m_hOutput = hOutput;
3338a5bd
VZ
475
476 // unblock the pipe to prevent deadlocks when we're writing to the pipe
477 // from which the child process can't read because it is writing in its own
478 // end of it
479 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
480 if ( !::SetNamedPipeHandleState
481 (
482 m_hOutput,
483 &mode,
484 NULL, // collection count (we don't set it)
485 NULL // timeout (we don't set it neither)
486 ) )
487 {
9a83f860 488 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
3338a5bd 489 }
cd6ce4a9 490}
8b33ae2d 491
8f0ff178 492bool wxPipeOutputStream::Close()
8b33ae2d 493{
8f0ff178 494 return ::CloseHandle(m_hOutput) != 0;
8b33ae2d
GL
495}
496
8f0ff178 497
8b33ae2d
GL
498size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
499{
2b5f62a0 500 m_lasterror = wxSTREAM_NO_ERROR;
3338a5bd
VZ
501
502 DWORD totalWritten = 0;
503 while ( len > 0 )
f6bcfd97 504 {
3338a5bd
VZ
505 DWORD chunkWritten;
506 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
507 {
508 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
509 ? wxSTREAM_EOF
510 : wxSTREAM_WRITE_ERROR;
511 break;
512 }
513
514 if ( !chunkWritten )
515 break;
516
517 buffer = (char *)buffer + chunkWritten;
518 totalWritten += chunkWritten;
519 len -= chunkWritten;
8b33ae2d 520 }
f6bcfd97 521
3338a5bd 522 return totalWritten;
8b33ae2d
GL
523}
524
79066131
VZ
525#endif // wxUSE_STREAMS
526
b568d04f 527// ============================================================================
79066131 528// wxExecute functions family
b568d04f 529// ============================================================================
5260b1c5 530
ca289436
VZ
531#if wxUSE_IPC
532
533// connect to the given server via DDE and ask it to execute the command
42d0df00
VZ
534bool
535wxExecuteDDE(const wxString& ddeServer,
536 const wxString& ddeTopic,
537 const wxString& ddeCommand)
ca289436 538{
999836aa 539 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
540
541 wxDDEClient client;
42d0df00
VZ
542 wxConnectionBase *
543 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
ca289436
VZ
544 if ( !conn )
545 {
27d2dbbc 546 ok = false;
ca289436
VZ
547 }
548 else // connected to DDE server
549 {
4dd03db9
VZ
550 // the added complication here is that although most programs use
551 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
552 // and other MS stuff - use XTYP_REQUEST!
ca289436 553 //
4dd03db9
VZ
554 // moreover, anotheri mportant program (IE) understands both but
555 // returns an error from Execute() so we must try Request() first
556 // to avoid doing it twice
ca289436 557 {
4dd03db9 558 // we're prepared for this one to fail, so don't show errors
ca289436 559 wxLogNull noErrors;
4dd03db9
VZ
560
561 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
562 }
563
564 if ( !ok )
565 {
4dd03db9
VZ
566 // now try execute -- but show the errors
567 ok = conn->Execute(ddeCommand);
ca289436
VZ
568 }
569 }
570
571 return ok;
572}
573
574#endif // wxUSE_IPC
575
164db92c
VZ
576long wxExecute(const wxString& cmd, int flags, wxProcess *handler,
577 const wxExecuteEnv *env)
32592631 578{
c3fad64b 579 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
5bd3a2da 580
647b8e37
VZ
581#if wxUSE_THREADS
582 // for many reasons, the code below breaks down if it's called from another
583 // thread -- this could be fixed, but as Unix versions don't support this
584 // neither I don't want to waste time on this now
585 wxASSERT_MSG( wxThread::IsMain(),
9a83f860 586 wxT("wxExecute() can be called only from the main thread") );
647b8e37
VZ
587#endif // wxUSE_THREADS
588
039f62f4 589 wxString command;
6ba63600 590
731dd422 591#if wxUSE_IPC
5bd3a2da
VZ
592 // DDE hack: this is really not pretty, but we need to allow this for
593 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
594 // returns the command which should be run to view/open/... a file of the
595 // given type. Sometimes, however, this command just launches the server
596 // and an additional DDE request must be made to really open the file. To
597 // keep all this well hidden from the application, we allow a special form
6ba63600 598 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 599 // case we execute just <command> and process the rest below
039f62f4 600 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da 601 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
9a83f860 602 if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") )
5bd3a2da 603 {
ca289436
VZ
604 // speed up the concatenations below
605 ddeServer.reserve(256);
606 ddeTopic.reserve(256);
607 ddeCommand.reserve(256);
608
5bd3a2da 609 const wxChar *p = cmd.c_str() + 7;
9a83f860 610 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
611 {
612 command += *p++;
613 }
614
615 if ( *p )
616 {
617 // skip '#'
618 p++;
619 }
620 else
621 {
9a83f860 622 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
623 }
624
9a83f860 625 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
626 {
627 ddeServer += *p++;
628 }
629
630 if ( *p )
631 {
632 // skip '#'
633 p++;
634 }
635 else
636 {
9a83f860 637 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
638 }
639
9a83f860 640 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
641 {
642 ddeTopic += *p++;
643 }
644
645 if ( *p )
646 {
647 // skip '#'
648 p++;
649 }
650 else
651 {
9a83f860 652 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
653 }
654
655 while ( *p )
656 {
657 ddeCommand += *p++;
658 }
6ba63600 659
ca289436
VZ
660 // if we want to just launch the program and not wait for its
661 // termination, try to execute DDE command right now, it can succeed if
662 // the process is already running - but as it fails if it's not
663 // running, suppress any errors it might generate
fbf456aa 664 if ( !(flags & wxEXEC_SYNC) )
6ba63600 665 {
ca289436
VZ
666 wxLogNull noErrors;
667 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
668 {
669 // a dummy PID - this is a hack, of course, but it's well worth
670 // it as we don't open a new server each time we're called
671 // which would be quite bad
672 return -1;
673 }
6ba63600 674 }
5bd3a2da
VZ
675 }
676 else
731dd422 677#endif // wxUSE_IPC
5bd3a2da
VZ
678 {
679 // no DDE
680 command = cmd;
681 }
32592631 682
f6bcfd97
BP
683 // the IO redirection is only supported with wxUSE_STREAMS
684 BOOL redirect = FALSE;
79066131 685
4676948b 686#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
687 wxPipe pipeIn, pipeOut, pipeErr;
688
689 // we'll save here the copy of pipeIn[Write]
33ac7e6f 690 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 691
cd6ce4a9 692 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
693 if ( handler && handler->IsRedirected() )
694 {
79066131
VZ
695 // create pipes for redirecting stdin, stdout and stderr
696 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 697 {
79066131 698 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 699
fbf456aa
VZ
700 // indicate failure: we need to return different error code
701 // depending on the sync flag
702 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
703 }
704
f6bcfd97 705 redirect = TRUE;
8b33ae2d 706 }
f6bcfd97 707#endif // wxUSE_STREAMS
5bd3a2da 708
cb6827a8
VZ
709 // create the process
710 STARTUPINFO si;
11c7d5b6 711 wxZeroMemory(si);
cb6827a8
VZ
712 si.cb = sizeof(si);
713
4676948b 714#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 715 if ( redirect )
cb6827a8 716 {
fbf456aa 717 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 718
79066131
VZ
719 si.hStdInput = pipeIn[wxPipe::Read];
720 si.hStdOutput = pipeOut[wxPipe::Write];
721 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 722
f6bcfd97 723 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
724 // it non inheritable: indeed, we must close the writing end of pipeIn
725 // before launching the child process as otherwise this handle will be
f6bcfd97
BP
726 // inherited by the child which will never close it and so the pipe
727 // will never be closed and the child will be left stuck in ReadFile()
79066131 728 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
729 if ( !::DuplicateHandle
730 (
79066131
VZ
731 ::GetCurrentProcess(),
732 pipeInWrite,
733 ::GetCurrentProcess(),
f6bcfd97
BP
734 &hpipeStdinWrite,
735 0, // desired access: unused here
736 FALSE, // not inherited
737 DUPLICATE_SAME_ACCESS // same access as for src handle
738 ) )
cd6ce4a9 739 {
9a83f860 740 wxLogLastError(wxT("DuplicateHandle"));
8b33ae2d 741 }
cd6ce4a9 742
79066131 743 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
744 }
745#endif // wxUSE_STREAMS
cb6827a8 746
4fe4a7c5
VZ
747 // The default logic for showing the console is to show it only if the IO
748 // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be
749 // explicitly specified to change it.
750 if ( (flags & wxEXEC_HIDE_CONSOLE) ||
751 (redirect && !(flags & wxEXEC_SHOW_CONSOLE)) )
752 {
753 si.dwFlags |= STARTF_USESHOWWINDOW;
754 si.wShowWindow = SW_HIDE;
755 }
756
757
f6bcfd97 758 PROCESS_INFORMATION pi;
4676948b 759 DWORD dwFlags = CREATE_SUSPENDED;
78c743d8 760
4676948b 761#ifndef __WXWINCE__
ee4d4380
VZ
762 if ( (flags & wxEXEC_MAKE_GROUP_LEADER) &&
763 (wxGetOsVersion() == wxOS_WINDOWS_NT) )
764 dwFlags |= CREATE_NEW_PROCESS_GROUP;
765
4676948b 766 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
78c743d8 767#else
9cd03a43
WS
768 // we are assuming commands without spaces for now
769 wxString moduleName = command.BeforeFirst(wxT(' '));
770 wxString arguments = command.AfterFirst(wxT(' '));
4676948b 771#endif
f6bcfd97 772
164db92c
VZ
773 wxWxCharBuffer envBuffer;
774 bool useCwd = false;
775 if ( env )
776 {
777 useCwd = !env->cwd.empty();
778
779 // Translate environment variable map into NUL-terminated list of
780 // NUL-terminated strings.
781 if ( !env->env.empty() )
782 {
783#if wxUSE_UNICODE
784 // Environment variables can contain non-ASCII characters. We could
785 // check for it and not use this flag if everything is really ASCII
786 // only but there doesn't seem to be any reason to do it so just
787 // assume Unicode by default.
788 dwFlags |= CREATE_UNICODE_ENVIRONMENT;
789#endif // wxUSE_UNICODE
790
791 wxEnvVariableHashMap::const_iterator it;
792
793 size_t envSz = 1; // ending '\0'
794 for ( it = env->env.begin(); it != env->env.end(); ++it )
795 {
796 // Add size of env variable name and value, and '=' char and
797 // ending '\0'
798 envSz += it->first.length() + it->second.length() + 2;
799 }
800
801 envBuffer.extend(envSz);
802
803 wxChar *p = envBuffer.data();
804 for ( it = env->env.begin(); it != env->env.end(); ++it )
805 {
806 const wxString line = it->first + wxS("=") + it->second;
807
808 // Include the trailing NUL which will always terminate the
809 // buffer returned by t_str().
810 const size_t len = line.length() + 1;
811
812 wxTmemcpy(p, line.t_str(), len);
813
814 p += len;
815 }
816
817 // And another NUL to terminate the list of NUL-terminated strings.
818 *p = 0;
819 }
820 }
821
eaf4bde6 822 // Translate wxWidgets priority to Windows conventions.
b640fa17 823 if ( handler )
eaf4bde6 824 {
b640fa17
VZ
825 unsigned prio = handler->GetPriority();
826 if ( prio <= 20 )
827 dwFlags |= IDLE_PRIORITY_CLASS;
828 else if ( prio <= 40 )
829 dwFlags |= BELOW_NORMAL_PRIORITY_CLASS;
830 else if ( prio <= 60 )
831 dwFlags |= NORMAL_PRIORITY_CLASS;
832 else if ( prio <= 80 )
833 dwFlags |= ABOVE_NORMAL_PRIORITY_CLASS;
834 else if ( prio <= 99 )
835 dwFlags |= HIGH_PRIORITY_CLASS;
836 else if ( prio <= 100 )
837 dwFlags |= REALTIME_PRIORITY_CLASS;
838 else
839 {
840 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
841 dwFlags |= NORMAL_PRIORITY_CLASS;
842 }
eaf4bde6
VZ
843 }
844
f6bcfd97
BP
845 bool ok = ::CreateProcess
846 (
9cd03a43 847 // WinCE requires appname to be non null
78c743d8
JS
848 // Win32 allows for null
849#ifdef __WXWINCE__
125afca0
VZ
850 moduleName.t_str(), // application name
851 wxMSW_CONV_LPTSTR(arguments), // arguments
78c743d8 852#else
9cd03a43 853 NULL, // application name (use only cmd line)
125afca0 854 wxMSW_CONV_LPTSTR(command), // full command line
78c743d8 855#endif
9cd03a43
WS
856 NULL, // security attributes: defaults for both
857 NULL, // the process and its main thread
858 redirect, // inherit handles if we use pipes
859 dwFlags, // process creation flags
164db92c
VZ
860 envBuffer.data(), // environment (may be NULL which is fine)
861 useCwd // initial working directory
125afca0 862 ? wxMSW_CONV_LPTSTR(env->cwd)
164db92c 863 : NULL, // (or use the same)
9cd03a43
WS
864 &si, // startup info (unused here)
865 &pi // process info
f6bcfd97
BP
866 ) != 0;
867
4676948b 868#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
869 // we can close the pipe ends used by child anyhow
870 if ( redirect )
871 {
79066131
VZ
872 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
873 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
874 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 875 }
f6bcfd97 876#endif // wxUSE_STREAMS
cb6827a8 877
f6bcfd97 878 if ( !ok )
5e1febfa 879 {
4676948b 880#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
881 // close the other handles too
882 if ( redirect )
5e1febfa 883 {
79066131
VZ
884 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
885 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 886 }
f6bcfd97 887#endif // wxUSE_STREAMS
5e1febfa 888
f6bcfd97
BP
889 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
890
fbf456aa 891 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 892 }
8b33ae2d 893
4676948b 894#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
895 // the input buffer bufOut is connected to stdout, this is why it is
896 // called bufOut and not bufIn
897 wxStreamTempInputBuffer bufOut,
898 bufErr;
899
f6bcfd97
BP
900 if ( redirect )
901 {
8b33ae2d 902 // We can now initialize the wxStreams
79066131
VZ
903 wxPipeInputStream *
904 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
905 wxPipeInputStream *
906 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
907 wxPipeOutputStream *
908 inStream = new wxPipeOutputStream(hpipeStdinWrite);
909
910 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 911
79066131
VZ
912 bufOut.Init(outStream);
913 bufErr.Init(errStream);
8b33ae2d 914 }
f6bcfd97 915#endif // wxUSE_STREAMS
8b33ae2d 916
cb6827a8
VZ
917 // create a hidden window to receive notification about process
918 // termination
eccd1992
VZ
919 HWND hwnd = wxCreateHiddenWindow
920 (
921 &gs_classForHiddenWindow,
922 wxMSWEXEC_WNDCLASSNAME,
923 (WNDPROC)wxExecuteWindowCbk
924 );
925
223d09f6 926 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 927
cb6827a8
VZ
928 // Alloc data
929 wxExecuteData *data = new wxExecuteData;
930 data->hProcess = pi.hProcess;
931 data->dwProcessId = pi.dwProcessId;
932 data->hWnd = hwnd;
fbf456aa
VZ
933 data->state = (flags & wxEXEC_SYNC) != 0;
934 if ( flags & wxEXEC_SYNC )
e6045e08 935 {
5e1febfa
VZ
936 // handler may be !NULL for capturing program output, but we don't use
937 // it wxExecuteData struct in this case
e6045e08
VZ
938 data->handler = NULL;
939 }
940 else
941 {
942 // may be NULL or not
943 data->handler = handler;
ca5016d4
FM
944
945 if (handler)
946 handler->SetPid(pi.dwProcessId);
e6045e08 947 }
cb6827a8
VZ
948
949 DWORD tid;
950 HANDLE hThread = ::CreateThread(NULL,
951 0,
19193a2c 952 wxExecuteThread,
cb6827a8
VZ
953 (void *)data,
954 0,
955 &tid);
956
0d7ea902
VZ
957 // resume process we created now - whether the thread creation succeeded or
958 // not
959 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
960 {
961 // ignore it - what can we do?
f6bcfd97 962 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
963 }
964
965 // close unneeded handle
966 if ( !::CloseHandle(pi.hThread) )
43b2d5e7 967 {
f6bcfd97 968 wxLogLastError(wxT("CloseHandle(hThread)"));
43b2d5e7 969 }
0d7ea902 970
cb6827a8
VZ
971 if ( !hThread )
972 {
f6bcfd97 973 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
974
975 DestroyWindow(hwnd);
976 delete data;
977
978 // the process still started up successfully...
979 return pi.dwProcessId;
980 }
e6045e08 981
5a8561fc 982 gs_asyncThreads.push_back(hThread);
f6bcfd97 983
4676948b 984#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
985 // second part of DDE hack: now establish the DDE conversation with the
986 // just launched process
ca289436 987 if ( !ddeServer.empty() )
5bd3a2da 988 {
daa35097 989 bool ddeOK;
ca289436
VZ
990
991 // give the process the time to init itself
992 //
993 // we use a very big timeout hoping that WaitForInputIdle() will return
994 // much sooner, but not INFINITE just in case the process hangs
995 // completely - like this we will regain control sooner or later
996 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
6ba63600 997 {
ca289436 998 default:
9a83f860 999 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
ca289436 1000 // fall through
6ba63600 1001
53d7ab95 1002 case WAIT_FAILED:
9a83f860 1003 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
6ba63600 1004
ca289436 1005 case WAIT_TIMEOUT:
9a83f860 1006 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
ca289436 1007
daa35097 1008 ddeOK = false;
ca289436
VZ
1009 break;
1010
1011 case 0:
1012 // ok, process ready to accept DDE requests
daa35097 1013 ddeOK = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 1014 }
1b47bebc 1015
daa35097 1016 if ( !ddeOK )
1b47bebc 1017 {
9a83f860 1018 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1b47bebc
VZ
1019 cmd.c_str());
1020 }
5bd3a2da 1021 }
731dd422 1022#endif // wxUSE_IPC
5bd3a2da 1023
fbf456aa 1024 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
1025 {
1026 // clean up will be done when the process terminates
e6045e08
VZ
1027
1028 // return the pid
cb6827a8
VZ
1029 return pi.dwProcessId;
1030 }
e6045e08 1031
d60e2332 1032 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
9a83f860 1033 wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") );
d60e2332 1034
c3fad64b 1035 void *cookie = NULL;
f38f6899
VZ
1036 if ( !(flags & wxEXEC_NODISABLE) )
1037 {
f38f6899
VZ
1038 // disable all app windows while waiting for the child process to finish
1039 cookie = traits->BeforeChildWaitLoop();
1040 }
e2478fde
VZ
1041
1042 // wait until the child process terminates
1043 while ( data->state )
1044 {
4676948b 1045#if wxUSE_STREAMS && !defined(__WXWINCE__)
4d425dee 1046 if ( !bufOut.Update() && !bufErr.Update() )
79066131 1047#endif // wxUSE_STREAMS
4d425dee
VZ
1048 {
1049 // don't eat 100% of the CPU -- ugly but anything else requires
1050 // real async IO which we don't have for the moment
1051 ::Sleep(50);
1052 }
e6045e08 1053
dbbcfbb6
VZ
1054 // we must always process messages for our hidden window or we'd never
1055 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1056 MSG msg;
1057 ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE);
1058
1059 // we may also need to process messages for all the other application
1060 // windows
1061 if ( !(flags & wxEXEC_NOEVENTS) )
1062 {
1063 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1064 if ( loop )
1065 loop->Yield();
1066 }
cd6ce4a9 1067 }
068a7cfe 1068
d60e2332
VZ
1069 if ( !(flags & wxEXEC_NODISABLE) )
1070 {
1071 // reenable disabled windows back
f38f6899 1072 traits->AfterChildWaitLoop(cookie);
d60e2332 1073 }
0d7ea902 1074
e6045e08 1075 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
1076 delete data;
1077
e6045e08
VZ
1078 // return the exit code
1079 return dwExitCode;
32592631 1080}
c740f496 1081
05718a98 1082template <typename CharType>
164db92c
VZ
1083long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler,
1084 const wxExecuteEnv *env)
c740f496 1085{
cb6827a8 1086 wxString command;
05718a98 1087 command.reserve(1024);
e6045e08 1088
3cdd564f 1089 wxString arg;
0493ba13 1090 for ( ;; )
cb6827a8 1091 {
3cdd564f
VZ
1092 arg = *argv++;
1093
a6eac99d
VZ
1094 bool quote;
1095 if ( arg.empty() )
1096 {
1097 // we need to quote empty arguments, otherwise they'd just
1098 // disappear
1099 quote = true;
1100 }
1101 else // non-empty
1102 {
1103 // escape any quotes present in the string to avoid interfering
1104 // with the command line parsing in the child process
1105 arg.Replace("\"", "\\\"", true /* replace all */);
3cdd564f 1106
a6eac99d
VZ
1107 // and quote any arguments containing the spaces to prevent them from
1108 // being broken down
1109 quote = arg.find_first_of(" \t") != wxString::npos;
1110 }
1111
1112 if ( quote )
3cdd564f 1113 command += '\"' + arg + '\"';
a6eac99d
VZ
1114 else
1115 command += arg;
3cdd564f 1116
0493ba13
VZ
1117 if ( !*argv )
1118 break;
cb6827a8 1119
05718a98 1120 command += ' ';
0493ba13 1121 }
cb6827a8 1122
164db92c 1123 return wxExecute(command, flags, handler, env);
c740f496 1124}
05718a98 1125
164db92c
VZ
1126long wxExecute(char **argv, int flags, wxProcess *handler,
1127 const wxExecuteEnv *env)
05718a98 1128{
164db92c 1129 return wxExecuteImpl(argv, flags, handler, env);
05718a98
VZ
1130}
1131
d7ef641d
VZ
1132#if wxUSE_UNICODE
1133
164db92c
VZ
1134long wxExecute(wchar_t **argv, int flags, wxProcess *handler,
1135 const wxExecuteEnv *env)
05718a98 1136{
164db92c 1137 return wxExecuteImpl(argv, flags, handler, env);
05718a98 1138}
d7ef641d
VZ
1139
1140#endif // wxUSE_UNICODE