]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
Moved all the coordinate system calculation to wxDCBase
[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"
dbeac4bd 39
e2478fde
VZ
40#include "wx/apptrait.h"
41
eccd1992 42
32592631 43#include "wx/msw/private.h"
dbeac4bd 44
32592631
GL
45#include <ctype.h>
46
4676948b 47#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 48 #include <direct.h>
17dff81c 49#ifndef __MWERKS__
b568d04f 50 #include <dos.h>
32592631 51#endif
17dff81c 52#endif
32592631 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
eccd1992 83// implemented in utils.cpp
487f2d58 84extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
85wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
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
104// ----------------------------------------------------------------------------
105// private types
106// ----------------------------------------------------------------------------
107
cb6827a8
VZ
108// structure describing the process we're being waiting for
109struct wxExecuteData
110{
111public:
112 ~wxExecuteData()
113 {
114 if ( !::CloseHandle(hProcess) )
115 {
f6bcfd97 116 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8
VZ
117 }
118 }
119
120 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
121 HANDLE hProcess; // handle of the process
122 DWORD dwProcessId; // pid of the process
123 wxProcess *handler;
124 DWORD dwExitCode; // the exit code of the process
27d2dbbc 125 bool state; // set to false when the process finishes
32592631
GL
126};
127
eccd1992
VZ
128class wxExecuteModule : public wxModule
129{
130public:
131 virtual bool OnInit() { return true; }
132 virtual void OnExit()
133 {
134 if ( *gs_classForHiddenWindow )
135 {
136 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
137 {
138 wxLogLastError(_T("UnregisterClass(wxExecClass)"));
139 }
140
141 gs_classForHiddenWindow = NULL;
142 }
143 }
144
145private:
146 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
147};
148
149#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 150
8b33ae2d
GL
151// ----------------------------------------------------------------------------
152// wxPipeStreams
153// ----------------------------------------------------------------------------
154
f6bcfd97
BP
155class wxPipeInputStream: public wxInputStream
156{
8b33ae2d
GL
157public:
158 wxPipeInputStream(HANDLE hInput);
79066131 159 virtual ~wxPipeInputStream();
8b33ae2d 160
27d2dbbc 161 // returns true if the pipe is still opened
79066131
VZ
162 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
163
27d2dbbc 164 // returns true if there is any data to be read from the pipe
2b5f62a0 165 virtual bool CanRead() const;
f6bcfd97 166
8b33ae2d
GL
167protected:
168 size_t OnSysRead(void *buffer, size_t len);
169
170protected:
171 HANDLE m_hInput;
22f3361e
VZ
172
173 DECLARE_NO_COPY_CLASS(wxPipeInputStream)
8b33ae2d
GL
174};
175
f6bcfd97
BP
176class wxPipeOutputStream: public wxOutputStream
177{
8b33ae2d
GL
178public:
179 wxPipeOutputStream(HANDLE hOutput);
8f0ff178
RN
180 virtual ~wxPipeOutputStream() { Close(); }
181 bool Close();
8b33ae2d
GL
182
183protected:
184 size_t OnSysWrite(const void *buffer, size_t len);
185
186protected:
187 HANDLE m_hOutput;
22f3361e
VZ
188
189 DECLARE_NO_COPY_CLASS(wxPipeOutputStream)
8b33ae2d
GL
190};
191
79066131
VZ
192// define this to let wxexec.cpp know that we know what we're doing
193#define _WX_USED_BY_WXEXECUTE_
194#include "../common/execcmn.cpp"
195
196// ----------------------------------------------------------------------------
197// wxPipe represents a Win32 anonymous pipe
198// ----------------------------------------------------------------------------
199
200class wxPipe
201{
202public:
203 // the symbolic names for the pipe ends
204 enum Direction
205 {
206 Read,
207 Write
208 };
209
210 // default ctor doesn't do anything
211 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
212
27d2dbbc 213 // create the pipe, return true if ok, false on error
79066131
VZ
214 bool Create()
215 {
216 // default secutiry attributes
217 SECURITY_ATTRIBUTES security;
218
219 security.nLength = sizeof(security);
220 security.lpSecurityDescriptor = NULL;
221 security.bInheritHandle = TRUE; // to pass it to the child
222
223 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
224 {
225 wxLogSysError(_("Failed to create an anonymous pipe"));
226
27d2dbbc 227 return false;
79066131
VZ
228 }
229
27d2dbbc 230 return true;
79066131
VZ
231 }
232
27d2dbbc 233 // return true if we were created successfully
79066131
VZ
234 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
235
236 // return the descriptor for one of the pipe ends
82baa5e4 237 HANDLE operator[](Direction which) const { return m_handles[which]; }
79066131
VZ
238
239 // detach a descriptor, meaning that the pipe dtor won't close it, and
240 // return it
241 HANDLE Detach(Direction which)
242 {
79066131
VZ
243 HANDLE handle = m_handles[which];
244 m_handles[which] = INVALID_HANDLE_VALUE;
245
246 return handle;
247 }
248
249 // close the pipe descriptors
250 void Close()
251 {
252 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
253 {
254 if ( m_handles[n] != INVALID_HANDLE_VALUE )
255 {
256 ::CloseHandle(m_handles[n]);
257 m_handles[n] = INVALID_HANDLE_VALUE;
258 }
259 }
260 }
261
262 // dtor closes the pipe descriptors
263 ~wxPipe() { Close(); }
264
265private:
266 HANDLE m_handles[2];
267};
268
269#endif // wxUSE_STREAMS
270
271// ============================================================================
272// implementation
273// ============================================================================
274
79066131
VZ
275// ----------------------------------------------------------------------------
276// process termination detecting support
277// ----------------------------------------------------------------------------
278
279// thread function for the thread monitoring the process termination
280static DWORD __stdcall wxExecuteThread(void *arg)
281{
45d5a0c6 282 wxExecuteData * const data = (wxExecuteData *)arg;
79066131
VZ
283
284 if ( ::WaitForSingleObject(data->hProcess, INFINITE) != WAIT_OBJECT_0 )
285 {
286 wxLogDebug(_T("Waiting for the process termination failed!"));
287 }
288
289 // get the exit code
290 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
291 {
292 wxLogLastError(wxT("GetExitCodeProcess"));
293 }
294
295 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
296 wxT("process should have terminated") );
297
298 // send a message indicating process termination to the window
299 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
300
301 return 0;
302}
303
304// window procedure of a hidden window which is created just to receive
305// the notification message when a process exits
306LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
307 WPARAM wParam, LPARAM lParam)
308{
309 if ( message == wxWM_PROC_TERMINATED )
310 {
311 DestroyWindow(hWnd); // we don't need it any more
312
45d5a0c6 313 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
314 if ( data->handler )
315 {
316 data->handler->OnTerminate((int)data->dwProcessId,
317 (int)data->dwExitCode);
318 }
319
320 if ( data->state )
321 {
322 // we're executing synchronously, tell the waiting thread
323 // that the process finished
324 data->state = 0;
325 }
326 else
327 {
328 // asynchronous execution - we should do the clean up
329 delete data;
330 }
331
332 return 0;
333 }
334 else
335 {
45d5a0c6 336 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
337 }
338}
339
340// ============================================================================
341// implementation of IO redirection support classes
342// ============================================================================
343
4676948b 344#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
345
346// ----------------------------------------------------------------------------
347// wxPipeInputStreams
348// ----------------------------------------------------------------------------
8b33ae2d
GL
349
350wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
351{
352 m_hInput = hInput;
cd6ce4a9 353}
8b33ae2d
GL
354
355wxPipeInputStream::~wxPipeInputStream()
356{
79066131
VZ
357 if ( m_hInput != INVALID_HANDLE_VALUE )
358 ::CloseHandle(m_hInput);
8b33ae2d
GL
359}
360
2b5f62a0 361bool wxPipeInputStream::CanRead() const
8b33ae2d 362{
79066131 363 if ( !IsOpened() )
27d2dbbc 364 return false;
79066131 365
f6bcfd97
BP
366 DWORD nAvailable;
367
368 // function name is misleading, it works with anon pipes as well
369 DWORD rc = ::PeekNamedPipe
370 (
371 m_hInput, // handle
372 NULL, 0, // ptr to buffer and its size
373 NULL, // [out] bytes read
374 &nAvailable, // [out] bytes available
375 NULL // [out] bytes left
376 );
377
378 if ( !rc )
379 {
380 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
381 {
382 // unexpected error
383 wxLogLastError(_T("PeekNamedPipe"));
384 }
8b33ae2d 385
3103e8a9 386 // don't try to continue reading from a pipe if an error occurred or if
f6bcfd97 387 // it had been closed
79066131
VZ
388 ::CloseHandle(m_hInput);
389
2b5f62a0 390 wxPipeInputStream *self = wxConstCast(this, wxPipeInputStream);
79066131 391
2b5f62a0
VZ
392 self->m_hInput = INVALID_HANDLE_VALUE;
393 self->m_lasterror = wxSTREAM_EOF;
394
395 nAvailable = 0;
f6bcfd97 396 }
79066131
VZ
397
398 return nAvailable != 0;
f6bcfd97
BP
399}
400
401size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
402{
2b5f62a0 403 if ( !IsOpened() )
79066131
VZ
404 {
405 m_lasterror = wxSTREAM_EOF;
406
f6bcfd97 407 return 0;
79066131
VZ
408 }
409
f6bcfd97
BP
410 DWORD bytesRead;
411 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
412 {
2b5f62a0
VZ
413 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
414 ? wxSTREAM_EOF
415 : wxSTREAM_READ_ERROR;
8b33ae2d 416 }
f6bcfd97 417
3103e8a9 418 // bytesRead is set to 0, as desired, if an error occurred
8b33ae2d
GL
419 return bytesRead;
420}
421
79066131 422// ----------------------------------------------------------------------------
8b33ae2d 423// wxPipeOutputStream
79066131 424// ----------------------------------------------------------------------------
8b33ae2d
GL
425
426wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
427{
428 m_hOutput = hOutput;
3338a5bd
VZ
429
430 // unblock the pipe to prevent deadlocks when we're writing to the pipe
431 // from which the child process can't read because it is writing in its own
432 // end of it
433 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
434 if ( !::SetNamedPipeHandleState
435 (
436 m_hOutput,
437 &mode,
438 NULL, // collection count (we don't set it)
439 NULL // timeout (we don't set it neither)
440 ) )
441 {
442 wxLogLastError(_T("SetNamedPipeHandleState(PIPE_NOWAIT)"));
443 }
cd6ce4a9 444}
8b33ae2d 445
8f0ff178 446bool wxPipeOutputStream::Close()
8b33ae2d 447{
8f0ff178 448 return ::CloseHandle(m_hOutput) != 0;
8b33ae2d
GL
449}
450
8f0ff178 451
8b33ae2d
GL
452size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
453{
2b5f62a0 454 m_lasterror = wxSTREAM_NO_ERROR;
3338a5bd
VZ
455
456 DWORD totalWritten = 0;
457 while ( len > 0 )
f6bcfd97 458 {
3338a5bd
VZ
459 DWORD chunkWritten;
460 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
461 {
462 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
463 ? wxSTREAM_EOF
464 : wxSTREAM_WRITE_ERROR;
465 break;
466 }
467
468 if ( !chunkWritten )
469 break;
470
471 buffer = (char *)buffer + chunkWritten;
472 totalWritten += chunkWritten;
473 len -= chunkWritten;
8b33ae2d 474 }
f6bcfd97 475
3338a5bd 476 return totalWritten;
8b33ae2d
GL
477}
478
79066131
VZ
479#endif // wxUSE_STREAMS
480
b568d04f 481// ============================================================================
79066131 482// wxExecute functions family
b568d04f 483// ============================================================================
5260b1c5 484
ca289436
VZ
485#if wxUSE_IPC
486
487// connect to the given server via DDE and ask it to execute the command
42d0df00
VZ
488bool
489wxExecuteDDE(const wxString& ddeServer,
490 const wxString& ddeTopic,
491 const wxString& ddeCommand)
ca289436 492{
999836aa 493 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
494
495 wxDDEClient client;
42d0df00
VZ
496 wxConnectionBase *
497 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
ca289436
VZ
498 if ( !conn )
499 {
27d2dbbc 500 ok = false;
ca289436
VZ
501 }
502 else // connected to DDE server
503 {
4dd03db9
VZ
504 // the added complication here is that although most programs use
505 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
506 // and other MS stuff - use XTYP_REQUEST!
ca289436 507 //
4dd03db9
VZ
508 // moreover, anotheri mportant program (IE) understands both but
509 // returns an error from Execute() so we must try Request() first
510 // to avoid doing it twice
ca289436 511 {
4dd03db9 512 // we're prepared for this one to fail, so don't show errors
ca289436 513 wxLogNull noErrors;
4dd03db9
VZ
514
515 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
516 }
517
518 if ( !ok )
519 {
4dd03db9
VZ
520 // now try execute -- but show the errors
521 ok = conn->Execute(ddeCommand);
ca289436
VZ
522 }
523 }
524
525 return ok;
526}
527
528#endif // wxUSE_IPC
529
fbf456aa 530long wxExecute(const wxString& cmd, int flags, wxProcess *handler)
32592631 531{
c3fad64b 532 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
5bd3a2da 533
647b8e37
VZ
534#if wxUSE_THREADS
535 // for many reasons, the code below breaks down if it's called from another
536 // thread -- this could be fixed, but as Unix versions don't support this
537 // neither I don't want to waste time on this now
538 wxASSERT_MSG( wxThread::IsMain(),
539 _T("wxExecute() can be called only from the main thread") );
540#endif // wxUSE_THREADS
541
039f62f4 542 wxString command;
6ba63600 543
731dd422 544#if wxUSE_IPC
5bd3a2da
VZ
545 // DDE hack: this is really not pretty, but we need to allow this for
546 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
547 // returns the command which should be run to view/open/... a file of the
548 // given type. Sometimes, however, this command just launches the server
549 // and an additional DDE request must be made to really open the file. To
550 // keep all this well hidden from the application, we allow a special form
6ba63600 551 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 552 // case we execute just <command> and process the rest below
039f62f4 553 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da
VZ
554 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
555 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
556 {
ca289436
VZ
557 // speed up the concatenations below
558 ddeServer.reserve(256);
559 ddeTopic.reserve(256);
560 ddeCommand.reserve(256);
561
5bd3a2da
VZ
562 const wxChar *p = cmd.c_str() + 7;
563 while ( *p && *p != _T('#') )
564 {
565 command += *p++;
566 }
567
568 if ( *p )
569 {
570 // skip '#'
571 p++;
572 }
573 else
574 {
575 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
576 }
577
578 while ( *p && *p != _T('#') )
579 {
580 ddeServer += *p++;
581 }
582
583 if ( *p )
584 {
585 // skip '#'
586 p++;
587 }
588 else
589 {
590 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
591 }
592
593 while ( *p && *p != _T('#') )
594 {
595 ddeTopic += *p++;
596 }
597
598 if ( *p )
599 {
600 // skip '#'
601 p++;
602 }
603 else
604 {
605 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
606 }
607
608 while ( *p )
609 {
610 ddeCommand += *p++;
611 }
6ba63600 612
ca289436
VZ
613 // if we want to just launch the program and not wait for its
614 // termination, try to execute DDE command right now, it can succeed if
615 // the process is already running - but as it fails if it's not
616 // running, suppress any errors it might generate
fbf456aa 617 if ( !(flags & wxEXEC_SYNC) )
6ba63600 618 {
ca289436
VZ
619 wxLogNull noErrors;
620 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
621 {
622 // a dummy PID - this is a hack, of course, but it's well worth
623 // it as we don't open a new server each time we're called
624 // which would be quite bad
625 return -1;
626 }
6ba63600 627 }
5bd3a2da
VZ
628 }
629 else
731dd422 630#endif // wxUSE_IPC
5bd3a2da
VZ
631 {
632 // no DDE
633 command = cmd;
634 }
32592631 635
f6bcfd97
BP
636 // the IO redirection is only supported with wxUSE_STREAMS
637 BOOL redirect = FALSE;
79066131 638
4676948b 639#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
640 wxPipe pipeIn, pipeOut, pipeErr;
641
642 // we'll save here the copy of pipeIn[Write]
33ac7e6f 643 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 644
cd6ce4a9 645 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
646 if ( handler && handler->IsRedirected() )
647 {
79066131
VZ
648 // create pipes for redirecting stdin, stdout and stderr
649 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 650 {
79066131 651 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 652
fbf456aa
VZ
653 // indicate failure: we need to return different error code
654 // depending on the sync flag
655 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
656 }
657
f6bcfd97 658 redirect = TRUE;
8b33ae2d 659 }
f6bcfd97 660#endif // wxUSE_STREAMS
5bd3a2da 661
cb6827a8
VZ
662 // create the process
663 STARTUPINFO si;
11c7d5b6 664 wxZeroMemory(si);
cb6827a8
VZ
665 si.cb = sizeof(si);
666
4676948b 667#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 668 if ( redirect )
cb6827a8 669 {
fbf456aa 670 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 671
79066131
VZ
672 si.hStdInput = pipeIn[wxPipe::Read];
673 si.hStdOutput = pipeOut[wxPipe::Write];
674 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 675
fbf456aa
VZ
676 // when the std IO is redirected, we don't show the (console) process
677 // window by default, but this can be overridden by the caller by
678 // specifying wxEXEC_NOHIDE flag
679 if ( !(flags & wxEXEC_NOHIDE) )
680 {
681 si.dwFlags |= STARTF_USESHOWWINDOW;
682 si.wShowWindow = SW_HIDE;
683 }
f6bcfd97
BP
684
685 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
686 // it non inheritable: indeed, we must close the writing end of pipeIn
687 // before launching the child process as otherwise this handle will be
f6bcfd97
BP
688 // inherited by the child which will never close it and so the pipe
689 // will never be closed and the child will be left stuck in ReadFile()
79066131 690 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
691 if ( !::DuplicateHandle
692 (
79066131
VZ
693 ::GetCurrentProcess(),
694 pipeInWrite,
695 ::GetCurrentProcess(),
f6bcfd97
BP
696 &hpipeStdinWrite,
697 0, // desired access: unused here
698 FALSE, // not inherited
699 DUPLICATE_SAME_ACCESS // same access as for src handle
700 ) )
cd6ce4a9 701 {
f6bcfd97 702 wxLogLastError(_T("DuplicateHandle"));
8b33ae2d 703 }
cd6ce4a9 704
79066131 705 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
706 }
707#endif // wxUSE_STREAMS
cb6827a8 708
f6bcfd97 709 PROCESS_INFORMATION pi;
4676948b 710 DWORD dwFlags = CREATE_SUSPENDED;
78c743d8 711
4676948b
JS
712#ifndef __WXWINCE__
713 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
78c743d8 714#else
9cd03a43
WS
715 // we are assuming commands without spaces for now
716 wxString moduleName = command.BeforeFirst(wxT(' '));
717 wxString arguments = command.AfterFirst(wxT(' '));
4676948b 718#endif
f6bcfd97
BP
719
720 bool ok = ::CreateProcess
721 (
9cd03a43 722 // WinCE requires appname to be non null
78c743d8
JS
723 // Win32 allows for null
724#ifdef __WXWINCE__
725 (wxChar *)
c9f78968 726 moduleName.wx_str(),// application name
78c743d8 727 (wxChar *)
c9f78968 728 arguments.wx_str(), // arguments
78c743d8 729#else
9cd03a43 730 NULL, // application name (use only cmd line)
f6bcfd97 731 (wxChar *)
c9f78968 732 command.wx_str(), // full command line
78c743d8 733#endif
9cd03a43
WS
734 NULL, // security attributes: defaults for both
735 NULL, // the process and its main thread
736 redirect, // inherit handles if we use pipes
737 dwFlags, // process creation flags
738 NULL, // environment (use the same)
739 NULL, // current directory (use the same)
740 &si, // startup info (unused here)
741 &pi // process info
f6bcfd97
BP
742 ) != 0;
743
4676948b 744#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
745 // we can close the pipe ends used by child anyhow
746 if ( redirect )
747 {
79066131
VZ
748 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
749 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
750 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 751 }
f6bcfd97 752#endif // wxUSE_STREAMS
cb6827a8 753
f6bcfd97 754 if ( !ok )
5e1febfa 755 {
4676948b 756#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
757 // close the other handles too
758 if ( redirect )
5e1febfa 759 {
79066131
VZ
760 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
761 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 762 }
f6bcfd97 763#endif // wxUSE_STREAMS
5e1febfa 764
f6bcfd97
BP
765 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
766
fbf456aa 767 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 768 }
8b33ae2d 769
4676948b 770#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
771 // the input buffer bufOut is connected to stdout, this is why it is
772 // called bufOut and not bufIn
773 wxStreamTempInputBuffer bufOut,
774 bufErr;
775
f6bcfd97
BP
776 if ( redirect )
777 {
8b33ae2d 778 // We can now initialize the wxStreams
79066131
VZ
779 wxPipeInputStream *
780 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
781 wxPipeInputStream *
782 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
783 wxPipeOutputStream *
784 inStream = new wxPipeOutputStream(hpipeStdinWrite);
785
786 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 787
79066131
VZ
788 bufOut.Init(outStream);
789 bufErr.Init(errStream);
8b33ae2d 790 }
f6bcfd97 791#endif // wxUSE_STREAMS
8b33ae2d 792
cb6827a8
VZ
793 // create a hidden window to receive notification about process
794 // termination
eccd1992
VZ
795 HWND hwnd = wxCreateHiddenWindow
796 (
797 &gs_classForHiddenWindow,
798 wxMSWEXEC_WNDCLASSNAME,
799 (WNDPROC)wxExecuteWindowCbk
800 );
801
223d09f6 802 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 803
cb6827a8
VZ
804 // Alloc data
805 wxExecuteData *data = new wxExecuteData;
806 data->hProcess = pi.hProcess;
807 data->dwProcessId = pi.dwProcessId;
808 data->hWnd = hwnd;
fbf456aa
VZ
809 data->state = (flags & wxEXEC_SYNC) != 0;
810 if ( flags & wxEXEC_SYNC )
e6045e08 811 {
5e1febfa
VZ
812 // handler may be !NULL for capturing program output, but we don't use
813 // it wxExecuteData struct in this case
e6045e08
VZ
814 data->handler = NULL;
815 }
816 else
817 {
818 // may be NULL or not
819 data->handler = handler;
820 }
cb6827a8
VZ
821
822 DWORD tid;
823 HANDLE hThread = ::CreateThread(NULL,
824 0,
19193a2c 825 wxExecuteThread,
cb6827a8
VZ
826 (void *)data,
827 0,
828 &tid);
829
0d7ea902
VZ
830 // resume process we created now - whether the thread creation succeeded or
831 // not
832 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
833 {
834 // ignore it - what can we do?
f6bcfd97 835 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
836 }
837
838 // close unneeded handle
839 if ( !::CloseHandle(pi.hThread) )
f6bcfd97 840 wxLogLastError(wxT("CloseHandle(hThread)"));
0d7ea902 841
cb6827a8
VZ
842 if ( !hThread )
843 {
f6bcfd97 844 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
845
846 DestroyWindow(hwnd);
847 delete data;
848
849 // the process still started up successfully...
850 return pi.dwProcessId;
851 }
e6045e08 852
f6bcfd97
BP
853 ::CloseHandle(hThread);
854
4676948b 855#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
856 // second part of DDE hack: now establish the DDE conversation with the
857 // just launched process
ca289436 858 if ( !ddeServer.empty() )
5bd3a2da 859 {
ca289436
VZ
860 bool ok;
861
862 // give the process the time to init itself
863 //
864 // we use a very big timeout hoping that WaitForInputIdle() will return
865 // much sooner, but not INFINITE just in case the process hangs
866 // completely - like this we will regain control sooner or later
867 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
6ba63600 868 {
ca289436
VZ
869 default:
870 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
871 // fall through
6ba63600 872
ca289436
VZ
873 case -1:
874 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
6ba63600 875
ca289436
VZ
876 case WAIT_TIMEOUT:
877 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
878
27d2dbbc 879 ok = false;
ca289436
VZ
880 break;
881
882 case 0:
883 // ok, process ready to accept DDE requests
884 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 885 }
1b47bebc
VZ
886
887 if ( !ok )
888 {
889 wxLogDebug(_T("Failed to send DDE request to the process \"%s\"."),
890 cmd.c_str());
891 }
5bd3a2da 892 }
731dd422 893#endif // wxUSE_IPC
5bd3a2da 894
fbf456aa 895 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
896 {
897 // clean up will be done when the process terminates
e6045e08
VZ
898
899 // return the pid
cb6827a8
VZ
900 return pi.dwProcessId;
901 }
e6045e08 902
d60e2332
VZ
903 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
904 wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );
905
c3fad64b 906 void *cookie = NULL;
f38f6899
VZ
907 if ( !(flags & wxEXEC_NODISABLE) )
908 {
f38f6899
VZ
909 // disable all app windows while waiting for the child process to finish
910 cookie = traits->BeforeChildWaitLoop();
911 }
e2478fde
VZ
912
913 // wait until the child process terminates
914 while ( data->state )
915 {
4676948b 916#if wxUSE_STREAMS && !defined(__WXWINCE__)
e2478fde
VZ
917 bufOut.Update();
918 bufErr.Update();
79066131
VZ
919#endif // wxUSE_STREAMS
920
e2478fde
VZ
921 // don't eat 100% of the CPU -- ugly but anything else requires
922 // real async IO which we don't have for the moment
923 ::Sleep(50);
e6045e08 924
e2478fde
VZ
925 // we must process messages or we'd never get wxWM_PROC_TERMINATED
926 traits->AlwaysYield();
cd6ce4a9 927 }
068a7cfe 928
d60e2332
VZ
929 if ( !(flags & wxEXEC_NODISABLE) )
930 {
931 // reenable disabled windows back
f38f6899 932 traits->AfterChildWaitLoop(cookie);
d60e2332 933 }
0d7ea902 934
e6045e08 935 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
936 delete data;
937
e6045e08
VZ
938 // return the exit code
939 return dwExitCode;
32592631 940}
c740f496 941
0493ba13 942long wxExecute(wxChar **argv, int flags, wxProcess *handler)
c740f496 943{
cb6827a8 944 wxString command;
e6045e08 945
0493ba13 946 for ( ;; )
cb6827a8 947 {
0493ba13
VZ
948 command += *argv++;
949 if ( !*argv )
950 break;
cb6827a8 951
0493ba13
VZ
952 command += _T(' ');
953 }
cb6827a8 954
fbf456aa 955 return wxExecute(command, flags, handler);
c740f496 956}