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