]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
Remove double buffering from wxWebViewIE as this is handled by the web browser contro...
[wxWidgets.git] / src / msw / utilsexc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/utilsexc.cpp
3 // Purpose: wxExecute implementation for MSW
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998-2002 wxWidgets dev team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
31 #include "wx/log.h"
32 #if wxUSE_STREAMS
33 #include "wx/stream.h"
34 #endif
35 #include "wx/module.h"
36 #endif
37
38 #include "wx/process.h"
39 #include "wx/thread.h"
40 #include "wx/apptrait.h"
41 #include "wx/evtloop.h"
42 #include "wx/vector.h"
43
44
45 #include "wx/msw/private.h"
46
47 #include <ctype.h>
48
49 #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
50 #include <direct.h>
51 #ifndef __MWERKS__
52 #include <dos.h>
53 #endif
54 #endif
55
56 #if defined(__GNUWIN32__)
57 #include <sys/unistd.h>
58 #include <sys/stat.h>
59 #endif
60
61 #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
62 #ifndef __UNIX__
63 #include <io.h>
64 #endif
65
66 #ifndef __GNUWIN32__
67 #include <shellapi.h>
68 #endif
69 #endif
70
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #ifndef __WATCOMC__
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
76 #include <errno.h>
77 #endif
78 #endif
79 #include <stdarg.h>
80
81 #if wxUSE_IPC
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
83 #endif // wxUSE_IPC
84
85 #include "wx/msw/private/hiddenwin.h"
86
87 // ----------------------------------------------------------------------------
88 // constants
89 // ----------------------------------------------------------------------------
90
91 // this message is sent when the process we're waiting for terminates
92 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
93
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
101 static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
102 static const wxChar *gs_classForHiddenWindow = NULL;
103
104 // event used to wake up threads waiting in wxExecuteThread
105 static HANDLE gs_heventShutdown = NULL;
106
107 // handles of all threads monitoring the execution of asynchronously running
108 // processes
109 static wxVector<HANDLE> gs_asyncThreads;
110
111 // ----------------------------------------------------------------------------
112 // private types
113 // ----------------------------------------------------------------------------
114
115 // structure describing the process we're being waiting for
116 struct wxExecuteData
117 {
118 public:
119 ~wxExecuteData()
120 {
121 if ( !::CloseHandle(hProcess) )
122 {
123 wxLogLastError(wxT("CloseHandle(hProcess)"));
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
132 bool state; // set to false when the process finishes
133 };
134
135 class wxExecuteModule : public wxModule
136 {
137 public:
138 virtual bool OnInit() { return true; }
139 virtual void OnExit()
140 {
141 if ( gs_heventShutdown )
142 {
143 // stop any threads waiting for the termination of asynchronously
144 // running processes
145 if ( !::SetEvent(gs_heventShutdown) )
146 {
147 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
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 {
166 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
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
178 if ( gs_classForHiddenWindow )
179 {
180 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
181 {
182 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
183 }
184
185 gs_classForHiddenWindow = NULL;
186 }
187 }
188
189 private:
190 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
191 };
192
193 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
194
195 #if wxUSE_STREAMS && !defined(__WXWINCE__)
196
197 // ----------------------------------------------------------------------------
198 // wxPipeStreams
199 // ----------------------------------------------------------------------------
200
201 class wxPipeInputStream: public wxInputStream
202 {
203 public:
204 wxPipeInputStream(HANDLE hInput);
205 virtual ~wxPipeInputStream();
206
207 // returns true if the pipe is still opened
208 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
209
210 // returns true if there is any data to be read from the pipe
211 virtual bool CanRead() const;
212
213 protected:
214 size_t OnSysRead(void *buffer, size_t len);
215
216 protected:
217 HANDLE m_hInput;
218
219 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream);
220 };
221
222 class wxPipeOutputStream: public wxOutputStream
223 {
224 public:
225 wxPipeOutputStream(HANDLE hOutput);
226 virtual ~wxPipeOutputStream() { Close(); }
227 bool Close();
228
229 protected:
230 size_t OnSysWrite(const void *buffer, size_t len);
231
232 protected:
233 HANDLE m_hOutput;
234
235 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream);
236 };
237
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
246 class wxPipe
247 {
248 public:
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
259 // create the pipe, return true if ok, false on error
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
273 return false;
274 }
275
276 return true;
277 }
278
279 // return true if we were created successfully
280 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
281
282 // return the descriptor for one of the pipe ends
283 HANDLE operator[](Direction which) const { return m_handles[which]; }
284
285 // detach a descriptor, meaning that the pipe dtor won't close it, and
286 // return it
287 HANDLE Detach(Direction which)
288 {
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
311 private:
312 HANDLE m_handles[2];
313 };
314
315 #endif // wxUSE_STREAMS
316
317 // ============================================================================
318 // implementation
319 // ============================================================================
320
321 // ----------------------------------------------------------------------------
322 // process termination detecting support
323 // ----------------------------------------------------------------------------
324
325 // thread function for the thread monitoring the process termination
326 static DWORD __stdcall wxExecuteThread(void *arg)
327 {
328 wxExecuteData * const data = (wxExecuteData *)arg;
329
330 // create the shutdown event if we're the first thread starting to wait
331 if ( !gs_heventShutdown )
332 {
333 // create a manual initially non-signalled event object
334 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
335 if ( !gs_heventShutdown )
336 {
337 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
338 }
339 }
340
341 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
342 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
343 {
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") );
353
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;
368
369 default:
370 wxLogDebug(wxT("Waiting for the process termination failed!"));
371 }
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
378 LRESULT 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
385 wxExecuteData * const data = (wxExecuteData *)lParam;
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
396 data->state = false;
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 {
408 return ::DefWindowProc(hWnd, message, wParam, lParam);
409 }
410 }
411
412 // ============================================================================
413 // implementation of IO redirection support classes
414 // ============================================================================
415
416 #if wxUSE_STREAMS && !defined(__WXWINCE__)
417
418 // ----------------------------------------------------------------------------
419 // wxPipeInputStreams
420 // ----------------------------------------------------------------------------
421
422 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
423 {
424 m_hInput = hInput;
425 }
426
427 wxPipeInputStream::~wxPipeInputStream()
428 {
429 if ( m_hInput != INVALID_HANDLE_VALUE )
430 ::CloseHandle(m_hInput);
431 }
432
433 bool wxPipeInputStream::CanRead() const
434 {
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
442 if ( !IsOpened() )
443 {
444 // set back to mark Eof as it may have been unset by Ungetch()
445 self->m_lasterror = wxSTREAM_EOF;
446 return false;
447 }
448
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
466 wxLogLastError(wxT("PeekNamedPipe"));
467 }
468
469 // don't try to continue reading from a pipe if an error occurred or if
470 // it had been closed
471 ::CloseHandle(m_hInput);
472
473 self->m_hInput = INVALID_HANDLE_VALUE;
474 self->m_lasterror = wxSTREAM_EOF;
475
476 nAvailable = 0;
477 }
478
479 return nAvailable != 0;
480 }
481
482 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
483 {
484 if ( !IsOpened() )
485 {
486 m_lasterror = wxSTREAM_EOF;
487
488 return 0;
489 }
490
491 DWORD bytesRead;
492 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
493 {
494 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
495 ? wxSTREAM_EOF
496 : wxSTREAM_READ_ERROR;
497 }
498
499 // bytesRead is set to 0, as desired, if an error occurred
500 return bytesRead;
501 }
502
503 // ----------------------------------------------------------------------------
504 // wxPipeOutputStream
505 // ----------------------------------------------------------------------------
506
507 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
508 {
509 m_hOutput = hOutput;
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 {
523 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
524 }
525 }
526
527 bool wxPipeOutputStream::Close()
528 {
529 return ::CloseHandle(m_hOutput) != 0;
530 }
531
532
533 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
534 {
535 m_lasterror = wxSTREAM_NO_ERROR;
536
537 DWORD totalWritten = 0;
538 while ( len > 0 )
539 {
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;
555 }
556
557 return totalWritten;
558 }
559
560 #endif // wxUSE_STREAMS
561
562 // ============================================================================
563 // wxExecute functions family
564 // ============================================================================
565
566 #if wxUSE_IPC
567
568 // connect to the given server via DDE and ask it to execute the command
569 bool
570 wxExecuteDDE(const wxString& ddeServer,
571 const wxString& ddeTopic,
572 const wxString& ddeCommand)
573 {
574 bool ok wxDUMMY_INITIALIZE(false);
575
576 wxDDEClient client;
577 wxConnectionBase *
578 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
579 if ( !conn )
580 {
581 ok = false;
582 }
583 else // connected to DDE server
584 {
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!
588 //
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
592 {
593 // we're prepared for this one to fail, so don't show errors
594 wxLogNull noErrors;
595
596 ok = conn->Request(ddeCommand) != NULL;
597 }
598
599 if ( !ok )
600 {
601 // now try execute -- but show the errors
602 ok = conn->Execute(ddeCommand);
603 }
604 }
605
606 return ok;
607 }
608
609 #endif // wxUSE_IPC
610
611 long wxExecute(const wxString& cmd, int flags, wxProcess *handler,
612 const wxExecuteEnv *env)
613 {
614 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
615
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(),
621 wxT("wxExecute() can be called only from the main thread") );
622 #endif // wxUSE_THREADS
623
624 wxString command;
625
626 #if wxUSE_IPC
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
633 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
634 // case we execute just <command> and process the rest below
635 wxString ddeServer, ddeTopic, ddeCommand;
636 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
637 if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") )
638 {
639 // speed up the concatenations below
640 ddeServer.reserve(256);
641 ddeTopic.reserve(256);
642 ddeCommand.reserve(256);
643
644 const wxChar *p = cmd.c_str() + 7;
645 while ( *p && *p != wxT('#') )
646 {
647 command += *p++;
648 }
649
650 if ( *p )
651 {
652 // skip '#'
653 p++;
654 }
655 else
656 {
657 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
658 }
659
660 while ( *p && *p != wxT('#') )
661 {
662 ddeServer += *p++;
663 }
664
665 if ( *p )
666 {
667 // skip '#'
668 p++;
669 }
670 else
671 {
672 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
673 }
674
675 while ( *p && *p != wxT('#') )
676 {
677 ddeTopic += *p++;
678 }
679
680 if ( *p )
681 {
682 // skip '#'
683 p++;
684 }
685 else
686 {
687 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
688 }
689
690 while ( *p )
691 {
692 ddeCommand += *p++;
693 }
694
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
699 if ( !(flags & wxEXEC_SYNC) )
700 {
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 }
709 }
710 }
711 else
712 #endif // wxUSE_IPC
713 {
714 // no DDE
715 command = cmd;
716 }
717
718 // the IO redirection is only supported with wxUSE_STREAMS
719 BOOL redirect = FALSE;
720
721 #if wxUSE_STREAMS && !defined(__WXWINCE__)
722 wxPipe pipeIn, pipeOut, pipeErr;
723
724 // we'll save here the copy of pipeIn[Write]
725 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
726
727 // open the pipes to which child process IO will be redirected if needed
728 if ( handler && handler->IsRedirected() )
729 {
730 // create pipes for redirecting stdin, stdout and stderr
731 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
732 {
733 wxLogSysError(_("Failed to redirect the child process IO"));
734
735 // indicate failure: we need to return different error code
736 // depending on the sync flag
737 return flags & wxEXEC_SYNC ? -1 : 0;
738 }
739
740 redirect = TRUE;
741 }
742 #endif // wxUSE_STREAMS
743
744 // create the process
745 STARTUPINFO si;
746 wxZeroMemory(si);
747 si.cb = sizeof(si);
748
749 #if wxUSE_STREAMS && !defined(__WXWINCE__)
750 if ( redirect )
751 {
752 si.dwFlags = STARTF_USESTDHANDLES;
753
754 si.hStdInput = pipeIn[wxPipe::Read];
755 si.hStdOutput = pipeOut[wxPipe::Write];
756 si.hStdError = pipeErr[wxPipe::Write];
757
758 // when the std IO is redirected, we don't show the (console) process
759 // window by default, but this can be overridden by the caller by
760 // specifying wxEXEC_NOHIDE flag
761 if ( !(flags & wxEXEC_NOHIDE) )
762 {
763 si.dwFlags |= STARTF_USESHOWWINDOW;
764 si.wShowWindow = SW_HIDE;
765 }
766
767 // we must duplicate the handle to the write side of stdin pipe to make
768 // it non inheritable: indeed, we must close the writing end of pipeIn
769 // before launching the child process as otherwise this handle will be
770 // inherited by the child which will never close it and so the pipe
771 // will never be closed and the child will be left stuck in ReadFile()
772 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
773 if ( !::DuplicateHandle
774 (
775 ::GetCurrentProcess(),
776 pipeInWrite,
777 ::GetCurrentProcess(),
778 &hpipeStdinWrite,
779 0, // desired access: unused here
780 FALSE, // not inherited
781 DUPLICATE_SAME_ACCESS // same access as for src handle
782 ) )
783 {
784 wxLogLastError(wxT("DuplicateHandle"));
785 }
786
787 ::CloseHandle(pipeInWrite);
788 }
789 #endif // wxUSE_STREAMS
790
791 PROCESS_INFORMATION pi;
792 DWORD dwFlags = CREATE_SUSPENDED;
793
794 #ifndef __WXWINCE__
795 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
796 #else
797 // we are assuming commands without spaces for now
798 wxString moduleName = command.BeforeFirst(wxT(' '));
799 wxString arguments = command.AfterFirst(wxT(' '));
800 #endif
801
802 wxWxCharBuffer envBuffer;
803 bool useCwd = false;
804 if ( env )
805 {
806 useCwd = !env->cwd.empty();
807
808 // Translate environment variable map into NUL-terminated list of
809 // NUL-terminated strings.
810 if ( !env->env.empty() )
811 {
812 #if wxUSE_UNICODE
813 // Environment variables can contain non-ASCII characters. We could
814 // check for it and not use this flag if everything is really ASCII
815 // only but there doesn't seem to be any reason to do it so just
816 // assume Unicode by default.
817 dwFlags |= CREATE_UNICODE_ENVIRONMENT;
818 #endif // wxUSE_UNICODE
819
820 wxEnvVariableHashMap::const_iterator it;
821
822 size_t envSz = 1; // ending '\0'
823 for ( it = env->env.begin(); it != env->env.end(); ++it )
824 {
825 // Add size of env variable name and value, and '=' char and
826 // ending '\0'
827 envSz += it->first.length() + it->second.length() + 2;
828 }
829
830 envBuffer.extend(envSz);
831
832 wxChar *p = envBuffer.data();
833 for ( it = env->env.begin(); it != env->env.end(); ++it )
834 {
835 const wxString line = it->first + wxS("=") + it->second;
836
837 // Include the trailing NUL which will always terminate the
838 // buffer returned by t_str().
839 const size_t len = line.length() + 1;
840
841 wxTmemcpy(p, line.t_str(), len);
842
843 p += len;
844 }
845
846 // And another NUL to terminate the list of NUL-terminated strings.
847 *p = 0;
848 }
849 }
850
851 bool ok = ::CreateProcess
852 (
853 // WinCE requires appname to be non null
854 // Win32 allows for null
855 #ifdef __WXWINCE__
856 (wxChar *)
857 moduleName.wx_str(),// application name
858 (wxChar *)
859 arguments.wx_str(), // arguments
860 #else
861 NULL, // application name (use only cmd line)
862 (wxChar *)
863 command.wx_str(), // full command line
864 #endif
865 NULL, // security attributes: defaults for both
866 NULL, // the process and its main thread
867 redirect, // inherit handles if we use pipes
868 dwFlags, // process creation flags
869 envBuffer.data(), // environment (may be NULL which is fine)
870 useCwd // initial working directory
871 ? const_cast<wxChar *>(env->cwd.wx_str())
872 : NULL, // (or use the same)
873 &si, // startup info (unused here)
874 &pi // process info
875 ) != 0;
876
877 #if wxUSE_STREAMS && !defined(__WXWINCE__)
878 // we can close the pipe ends used by child anyhow
879 if ( redirect )
880 {
881 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
882 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
883 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
884 }
885 #endif // wxUSE_STREAMS
886
887 if ( !ok )
888 {
889 #if wxUSE_STREAMS && !defined(__WXWINCE__)
890 // close the other handles too
891 if ( redirect )
892 {
893 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
894 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
895 }
896 #endif // wxUSE_STREAMS
897
898 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
899
900 return flags & wxEXEC_SYNC ? -1 : 0;
901 }
902
903 #if wxUSE_STREAMS && !defined(__WXWINCE__)
904 // the input buffer bufOut is connected to stdout, this is why it is
905 // called bufOut and not bufIn
906 wxStreamTempInputBuffer bufOut,
907 bufErr;
908
909 if ( redirect )
910 {
911 // We can now initialize the wxStreams
912 wxPipeInputStream *
913 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
914 wxPipeInputStream *
915 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
916 wxPipeOutputStream *
917 inStream = new wxPipeOutputStream(hpipeStdinWrite);
918
919 handler->SetPipeStreams(outStream, inStream, errStream);
920
921 bufOut.Init(outStream);
922 bufErr.Init(errStream);
923 }
924 #endif // wxUSE_STREAMS
925
926 // create a hidden window to receive notification about process
927 // termination
928 HWND hwnd = wxCreateHiddenWindow
929 (
930 &gs_classForHiddenWindow,
931 wxMSWEXEC_WNDCLASSNAME,
932 (WNDPROC)wxExecuteWindowCbk
933 );
934
935 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
936
937 // Alloc data
938 wxExecuteData *data = new wxExecuteData;
939 data->hProcess = pi.hProcess;
940 data->dwProcessId = pi.dwProcessId;
941 data->hWnd = hwnd;
942 data->state = (flags & wxEXEC_SYNC) != 0;
943 if ( flags & wxEXEC_SYNC )
944 {
945 // handler may be !NULL for capturing program output, but we don't use
946 // it wxExecuteData struct in this case
947 data->handler = NULL;
948 }
949 else
950 {
951 // may be NULL or not
952 data->handler = handler;
953
954 if (handler)
955 handler->SetPid(pi.dwProcessId);
956 }
957
958 DWORD tid;
959 HANDLE hThread = ::CreateThread(NULL,
960 0,
961 wxExecuteThread,
962 (void *)data,
963 0,
964 &tid);
965
966 // resume process we created now - whether the thread creation succeeded or
967 // not
968 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
969 {
970 // ignore it - what can we do?
971 wxLogLastError(wxT("ResumeThread in wxExecute"));
972 }
973
974 // close unneeded handle
975 if ( !::CloseHandle(pi.hThread) )
976 {
977 wxLogLastError(wxT("CloseHandle(hThread)"));
978 }
979
980 if ( !hThread )
981 {
982 wxLogLastError(wxT("CreateThread in wxExecute"));
983
984 DestroyWindow(hwnd);
985 delete data;
986
987 // the process still started up successfully...
988 return pi.dwProcessId;
989 }
990
991 gs_asyncThreads.push_back(hThread);
992
993 #if wxUSE_IPC && !defined(__WXWINCE__)
994 // second part of DDE hack: now establish the DDE conversation with the
995 // just launched process
996 if ( !ddeServer.empty() )
997 {
998 bool ok;
999
1000 // give the process the time to init itself
1001 //
1002 // we use a very big timeout hoping that WaitForInputIdle() will return
1003 // much sooner, but not INFINITE just in case the process hangs
1004 // completely - like this we will regain control sooner or later
1005 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
1006 {
1007 default:
1008 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1009 // fall through
1010
1011 case WAIT_FAILED:
1012 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1013
1014 case WAIT_TIMEOUT:
1015 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1016
1017 ok = false;
1018 break;
1019
1020 case 0:
1021 // ok, process ready to accept DDE requests
1022 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
1023 }
1024
1025 if ( !ok )
1026 {
1027 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1028 cmd.c_str());
1029 }
1030 }
1031 #endif // wxUSE_IPC
1032
1033 if ( !(flags & wxEXEC_SYNC) )
1034 {
1035 // clean up will be done when the process terminates
1036
1037 // return the pid
1038 return pi.dwProcessId;
1039 }
1040
1041 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
1042 wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") );
1043
1044 void *cookie = NULL;
1045 if ( !(flags & wxEXEC_NODISABLE) )
1046 {
1047 // disable all app windows while waiting for the child process to finish
1048 cookie = traits->BeforeChildWaitLoop();
1049 }
1050
1051 // wait until the child process terminates
1052 while ( data->state )
1053 {
1054 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1055 if ( !bufOut.Update() && !bufErr.Update() )
1056 #endif // wxUSE_STREAMS
1057 {
1058 // don't eat 100% of the CPU -- ugly but anything else requires
1059 // real async IO which we don't have for the moment
1060 ::Sleep(50);
1061 }
1062
1063 // we must always process messages for our hidden window or we'd never
1064 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1065 MSG msg;
1066 ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE);
1067
1068 // we may also need to process messages for all the other application
1069 // windows
1070 if ( !(flags & wxEXEC_NOEVENTS) )
1071 {
1072 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1073 if ( loop )
1074 loop->Yield();
1075 }
1076 }
1077
1078 if ( !(flags & wxEXEC_NODISABLE) )
1079 {
1080 // reenable disabled windows back
1081 traits->AfterChildWaitLoop(cookie);
1082 }
1083
1084 DWORD dwExitCode = data->dwExitCode;
1085 delete data;
1086
1087 // return the exit code
1088 return dwExitCode;
1089 }
1090
1091 template <typename CharType>
1092 long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler,
1093 const wxExecuteEnv *env)
1094 {
1095 wxString command;
1096 command.reserve(1024);
1097
1098 wxString arg;
1099 for ( ;; )
1100 {
1101 arg = *argv++;
1102
1103 bool quote;
1104 if ( arg.empty() )
1105 {
1106 // we need to quote empty arguments, otherwise they'd just
1107 // disappear
1108 quote = true;
1109 }
1110 else // non-empty
1111 {
1112 // escape any quotes present in the string to avoid interfering
1113 // with the command line parsing in the child process
1114 arg.Replace("\"", "\\\"", true /* replace all */);
1115
1116 // and quote any arguments containing the spaces to prevent them from
1117 // being broken down
1118 quote = arg.find_first_of(" \t") != wxString::npos;
1119 }
1120
1121 if ( quote )
1122 command += '\"' + arg + '\"';
1123 else
1124 command += arg;
1125
1126 if ( !*argv )
1127 break;
1128
1129 command += ' ';
1130 }
1131
1132 return wxExecute(command, flags, handler, env);
1133 }
1134
1135 long wxExecute(char **argv, int flags, wxProcess *handler,
1136 const wxExecuteEnv *env)
1137 {
1138 return wxExecuteImpl(argv, flags, handler, env);
1139 }
1140
1141 #if wxUSE_UNICODE
1142
1143 long wxExecute(wchar_t **argv, int flags, wxProcess *handler,
1144 const wxExecuteEnv *env)
1145 {
1146 return wxExecuteImpl(argv, flags, handler, env);
1147 }
1148
1149 #endif // wxUSE_UNICODE