]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
routing the tab, return events for single line fields back to standard wx handler...
[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 // implemented in utils.cpp
86 extern "C" WXDLLIMPEXP_BASE HWND
87 wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
88
89 // ----------------------------------------------------------------------------
90 // constants
91 // ----------------------------------------------------------------------------
92
93 // this message is sent when the process we're waiting for terminates
94 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
95
96 // ----------------------------------------------------------------------------
97 // this module globals
98 // ----------------------------------------------------------------------------
99
100 // we need to create a hidden window to receive the process termination
101 // notifications and for this we need a (Win) class name for it which we will
102 // register the first time it's needed
103 static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
104 static const wxChar *gs_classForHiddenWindow = NULL;
105
106 // event used to wake up threads waiting in wxExecuteThread
107 static HANDLE gs_heventShutdown = NULL;
108
109 // handles of all threads monitoring the execution of asynchronously running
110 // processes
111 static wxVector<HANDLE> gs_asyncThreads;
112
113 // ----------------------------------------------------------------------------
114 // private types
115 // ----------------------------------------------------------------------------
116
117 // structure describing the process we're being waiting for
118 struct wxExecuteData
119 {
120 public:
121 ~wxExecuteData()
122 {
123 if ( !::CloseHandle(hProcess) )
124 {
125 wxLogLastError(wxT("CloseHandle(hProcess)"));
126 }
127 }
128
129 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
130 HANDLE hProcess; // handle of the process
131 DWORD dwProcessId; // pid of the process
132 wxProcess *handler;
133 DWORD dwExitCode; // the exit code of the process
134 bool state; // set to false when the process finishes
135 };
136
137 class wxExecuteModule : public wxModule
138 {
139 public:
140 virtual bool OnInit() { return true; }
141 virtual void OnExit()
142 {
143 if ( gs_heventShutdown )
144 {
145 // stop any threads waiting for the termination of asynchronously
146 // running processes
147 if ( !::SetEvent(gs_heventShutdown) )
148 {
149 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
150 }
151
152 ::CloseHandle(gs_heventShutdown);
153 gs_heventShutdown = NULL;
154
155 // now wait until they terminate
156 if ( !gs_asyncThreads.empty() )
157 {
158 const size_t numThreads = gs_asyncThreads.size();
159
160 if ( ::WaitForMultipleObjects
161 (
162 numThreads,
163 &gs_asyncThreads[0],
164 TRUE, // wait for all of them to become signalled
165 3000 // long but finite value
166 ) == WAIT_TIMEOUT )
167 {
168 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
169 }
170
171 for ( size_t n = 0; n < numThreads; n++ )
172 {
173 ::CloseHandle(gs_asyncThreads[n]);
174 }
175
176 gs_asyncThreads.clear();
177 }
178 }
179
180 if ( gs_classForHiddenWindow )
181 {
182 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
183 {
184 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
185 }
186
187 gs_classForHiddenWindow = NULL;
188 }
189 }
190
191 private:
192 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
193 };
194
195 IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
196
197 #if wxUSE_STREAMS && !defined(__WXWINCE__)
198
199 // ----------------------------------------------------------------------------
200 // wxPipeStreams
201 // ----------------------------------------------------------------------------
202
203 class wxPipeInputStream: public wxInputStream
204 {
205 public:
206 wxPipeInputStream(HANDLE hInput);
207 virtual ~wxPipeInputStream();
208
209 // returns true if the pipe is still opened
210 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
211
212 // returns true if there is any data to be read from the pipe
213 virtual bool CanRead() const;
214
215 protected:
216 size_t OnSysRead(void *buffer, size_t len);
217
218 protected:
219 HANDLE m_hInput;
220
221 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream);
222 };
223
224 class wxPipeOutputStream: public wxOutputStream
225 {
226 public:
227 wxPipeOutputStream(HANDLE hOutput);
228 virtual ~wxPipeOutputStream() { Close(); }
229 bool Close();
230
231 protected:
232 size_t OnSysWrite(const void *buffer, size_t len);
233
234 protected:
235 HANDLE m_hOutput;
236
237 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream);
238 };
239
240 // define this to let wxexec.cpp know that we know what we're doing
241 #define _WX_USED_BY_WXEXECUTE_
242 #include "../common/execcmn.cpp"
243
244 // ----------------------------------------------------------------------------
245 // wxPipe represents a Win32 anonymous pipe
246 // ----------------------------------------------------------------------------
247
248 class wxPipe
249 {
250 public:
251 // the symbolic names for the pipe ends
252 enum Direction
253 {
254 Read,
255 Write
256 };
257
258 // default ctor doesn't do anything
259 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
260
261 // create the pipe, return true if ok, false on error
262 bool Create()
263 {
264 // default secutiry attributes
265 SECURITY_ATTRIBUTES security;
266
267 security.nLength = sizeof(security);
268 security.lpSecurityDescriptor = NULL;
269 security.bInheritHandle = TRUE; // to pass it to the child
270
271 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
272 {
273 wxLogSysError(_("Failed to create an anonymous pipe"));
274
275 return false;
276 }
277
278 return true;
279 }
280
281 // return true if we were created successfully
282 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
283
284 // return the descriptor for one of the pipe ends
285 HANDLE operator[](Direction which) const { return m_handles[which]; }
286
287 // detach a descriptor, meaning that the pipe dtor won't close it, and
288 // return it
289 HANDLE Detach(Direction which)
290 {
291 HANDLE handle = m_handles[which];
292 m_handles[which] = INVALID_HANDLE_VALUE;
293
294 return handle;
295 }
296
297 // close the pipe descriptors
298 void Close()
299 {
300 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
301 {
302 if ( m_handles[n] != INVALID_HANDLE_VALUE )
303 {
304 ::CloseHandle(m_handles[n]);
305 m_handles[n] = INVALID_HANDLE_VALUE;
306 }
307 }
308 }
309
310 // dtor closes the pipe descriptors
311 ~wxPipe() { Close(); }
312
313 private:
314 HANDLE m_handles[2];
315 };
316
317 #endif // wxUSE_STREAMS
318
319 // ============================================================================
320 // implementation
321 // ============================================================================
322
323 // ----------------------------------------------------------------------------
324 // process termination detecting support
325 // ----------------------------------------------------------------------------
326
327 // thread function for the thread monitoring the process termination
328 static DWORD __stdcall wxExecuteThread(void *arg)
329 {
330 wxExecuteData * const data = (wxExecuteData *)arg;
331
332 // create the shutdown event if we're the first thread starting to wait
333 if ( !gs_heventShutdown )
334 {
335 // create a manual initially non-signalled event object
336 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
337 if ( !gs_heventShutdown )
338 {
339 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
340 }
341 }
342
343 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
344 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
345 {
346 case WAIT_OBJECT_0:
347 // process terminated, get its exit code
348 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
349 {
350 wxLogLastError(wxT("GetExitCodeProcess"));
351 }
352
353 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
354 wxT("process should have terminated") );
355
356 // send a message indicating process termination to the window
357 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
358 break;
359
360 case WAIT_OBJECT_0 + 1:
361 // we're shutting down but the process is still running -- leave it
362 // run but clean up the associated data
363 if ( !data->state )
364 {
365 delete data;
366 }
367 //else: exiting while synchronously executing process is still
368 // running? this shouldn't happen...
369 break;
370
371 default:
372 wxLogDebug(wxT("Waiting for the process termination failed!"));
373 }
374
375 return 0;
376 }
377
378 // window procedure of a hidden window which is created just to receive
379 // the notification message when a process exits
380 LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
381 WPARAM wParam, LPARAM lParam)
382 {
383 if ( message == wxWM_PROC_TERMINATED )
384 {
385 DestroyWindow(hWnd); // we don't need it any more
386
387 wxExecuteData * const data = (wxExecuteData *)lParam;
388 if ( data->handler )
389 {
390 data->handler->OnTerminate((int)data->dwProcessId,
391 (int)data->dwExitCode);
392 }
393
394 if ( data->state )
395 {
396 // we're executing synchronously, tell the waiting thread
397 // that the process finished
398 data->state = false;
399 }
400 else
401 {
402 // asynchronous execution - we should do the clean up
403 delete data;
404 }
405
406 return 0;
407 }
408 else
409 {
410 return ::DefWindowProc(hWnd, message, wParam, lParam);
411 }
412 }
413
414 // ============================================================================
415 // implementation of IO redirection support classes
416 // ============================================================================
417
418 #if wxUSE_STREAMS && !defined(__WXWINCE__)
419
420 // ----------------------------------------------------------------------------
421 // wxPipeInputStreams
422 // ----------------------------------------------------------------------------
423
424 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
425 {
426 m_hInput = hInput;
427 }
428
429 wxPipeInputStream::~wxPipeInputStream()
430 {
431 if ( m_hInput != INVALID_HANDLE_VALUE )
432 ::CloseHandle(m_hInput);
433 }
434
435 bool wxPipeInputStream::CanRead() const
436 {
437 // we can read if there's something in the put back buffer
438 // even pipe is closed
439 if ( m_wbacksize > m_wbackcur )
440 return true;
441
442 wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream);
443
444 if ( !IsOpened() )
445 {
446 // set back to mark Eof as it may have been unset by Ungetch()
447 self->m_lasterror = wxSTREAM_EOF;
448 return false;
449 }
450
451 DWORD nAvailable;
452
453 // function name is misleading, it works with anon pipes as well
454 DWORD rc = ::PeekNamedPipe
455 (
456 m_hInput, // handle
457 NULL, 0, // ptr to buffer and its size
458 NULL, // [out] bytes read
459 &nAvailable, // [out] bytes available
460 NULL // [out] bytes left
461 );
462
463 if ( !rc )
464 {
465 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
466 {
467 // unexpected error
468 wxLogLastError(wxT("PeekNamedPipe"));
469 }
470
471 // don't try to continue reading from a pipe if an error occurred or if
472 // it had been closed
473 ::CloseHandle(m_hInput);
474
475 self->m_hInput = INVALID_HANDLE_VALUE;
476 self->m_lasterror = wxSTREAM_EOF;
477
478 nAvailable = 0;
479 }
480
481 return nAvailable != 0;
482 }
483
484 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
485 {
486 if ( !IsOpened() )
487 {
488 m_lasterror = wxSTREAM_EOF;
489
490 return 0;
491 }
492
493 DWORD bytesRead;
494 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
495 {
496 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
497 ? wxSTREAM_EOF
498 : wxSTREAM_READ_ERROR;
499 }
500
501 // bytesRead is set to 0, as desired, if an error occurred
502 return bytesRead;
503 }
504
505 // ----------------------------------------------------------------------------
506 // wxPipeOutputStream
507 // ----------------------------------------------------------------------------
508
509 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
510 {
511 m_hOutput = hOutput;
512
513 // unblock the pipe to prevent deadlocks when we're writing to the pipe
514 // from which the child process can't read because it is writing in its own
515 // end of it
516 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
517 if ( !::SetNamedPipeHandleState
518 (
519 m_hOutput,
520 &mode,
521 NULL, // collection count (we don't set it)
522 NULL // timeout (we don't set it neither)
523 ) )
524 {
525 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
526 }
527 }
528
529 bool wxPipeOutputStream::Close()
530 {
531 return ::CloseHandle(m_hOutput) != 0;
532 }
533
534
535 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
536 {
537 m_lasterror = wxSTREAM_NO_ERROR;
538
539 DWORD totalWritten = 0;
540 while ( len > 0 )
541 {
542 DWORD chunkWritten;
543 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
544 {
545 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
546 ? wxSTREAM_EOF
547 : wxSTREAM_WRITE_ERROR;
548 break;
549 }
550
551 if ( !chunkWritten )
552 break;
553
554 buffer = (char *)buffer + chunkWritten;
555 totalWritten += chunkWritten;
556 len -= chunkWritten;
557 }
558
559 return totalWritten;
560 }
561
562 #endif // wxUSE_STREAMS
563
564 // ============================================================================
565 // wxExecute functions family
566 // ============================================================================
567
568 #if wxUSE_IPC
569
570 // connect to the given server via DDE and ask it to execute the command
571 bool
572 wxExecuteDDE(const wxString& ddeServer,
573 const wxString& ddeTopic,
574 const wxString& ddeCommand)
575 {
576 bool ok wxDUMMY_INITIALIZE(false);
577
578 wxDDEClient client;
579 wxConnectionBase *
580 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
581 if ( !conn )
582 {
583 ok = false;
584 }
585 else // connected to DDE server
586 {
587 // the added complication here is that although most programs use
588 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
589 // and other MS stuff - use XTYP_REQUEST!
590 //
591 // moreover, anotheri mportant program (IE) understands both but
592 // returns an error from Execute() so we must try Request() first
593 // to avoid doing it twice
594 {
595 // we're prepared for this one to fail, so don't show errors
596 wxLogNull noErrors;
597
598 ok = conn->Request(ddeCommand) != NULL;
599 }
600
601 if ( !ok )
602 {
603 // now try execute -- but show the errors
604 ok = conn->Execute(ddeCommand);
605 }
606 }
607
608 return ok;
609 }
610
611 #endif // wxUSE_IPC
612
613 long wxExecute(const wxString& cmd, int flags, wxProcess *handler,
614 const wxExecuteEnv *env)
615 {
616 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
617
618 #if wxUSE_THREADS
619 // for many reasons, the code below breaks down if it's called from another
620 // thread -- this could be fixed, but as Unix versions don't support this
621 // neither I don't want to waste time on this now
622 wxASSERT_MSG( wxThread::IsMain(),
623 wxT("wxExecute() can be called only from the main thread") );
624 #endif // wxUSE_THREADS
625
626 wxString command;
627
628 #if wxUSE_IPC
629 // DDE hack: this is really not pretty, but we need to allow this for
630 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
631 // returns the command which should be run to view/open/... a file of the
632 // given type. Sometimes, however, this command just launches the server
633 // and an additional DDE request must be made to really open the file. To
634 // keep all this well hidden from the application, we allow a special form
635 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
636 // case we execute just <command> and process the rest below
637 wxString ddeServer, ddeTopic, ddeCommand;
638 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
639 if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") )
640 {
641 // speed up the concatenations below
642 ddeServer.reserve(256);
643 ddeTopic.reserve(256);
644 ddeCommand.reserve(256);
645
646 const wxChar *p = cmd.c_str() + 7;
647 while ( *p && *p != wxT('#') )
648 {
649 command += *p++;
650 }
651
652 if ( *p )
653 {
654 // skip '#'
655 p++;
656 }
657 else
658 {
659 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
660 }
661
662 while ( *p && *p != wxT('#') )
663 {
664 ddeServer += *p++;
665 }
666
667 if ( *p )
668 {
669 // skip '#'
670 p++;
671 }
672 else
673 {
674 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
675 }
676
677 while ( *p && *p != wxT('#') )
678 {
679 ddeTopic += *p++;
680 }
681
682 if ( *p )
683 {
684 // skip '#'
685 p++;
686 }
687 else
688 {
689 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
690 }
691
692 while ( *p )
693 {
694 ddeCommand += *p++;
695 }
696
697 // if we want to just launch the program and not wait for its
698 // termination, try to execute DDE command right now, it can succeed if
699 // the process is already running - but as it fails if it's not
700 // running, suppress any errors it might generate
701 if ( !(flags & wxEXEC_SYNC) )
702 {
703 wxLogNull noErrors;
704 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
705 {
706 // a dummy PID - this is a hack, of course, but it's well worth
707 // it as we don't open a new server each time we're called
708 // which would be quite bad
709 return -1;
710 }
711 }
712 }
713 else
714 #endif // wxUSE_IPC
715 {
716 // no DDE
717 command = cmd;
718 }
719
720 // the IO redirection is only supported with wxUSE_STREAMS
721 BOOL redirect = FALSE;
722
723 #if wxUSE_STREAMS && !defined(__WXWINCE__)
724 wxPipe pipeIn, pipeOut, pipeErr;
725
726 // we'll save here the copy of pipeIn[Write]
727 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
728
729 // open the pipes to which child process IO will be redirected if needed
730 if ( handler && handler->IsRedirected() )
731 {
732 // create pipes for redirecting stdin, stdout and stderr
733 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
734 {
735 wxLogSysError(_("Failed to redirect the child process IO"));
736
737 // indicate failure: we need to return different error code
738 // depending on the sync flag
739 return flags & wxEXEC_SYNC ? -1 : 0;
740 }
741
742 redirect = TRUE;
743 }
744 #endif // wxUSE_STREAMS
745
746 // create the process
747 STARTUPINFO si;
748 wxZeroMemory(si);
749 si.cb = sizeof(si);
750
751 #if wxUSE_STREAMS && !defined(__WXWINCE__)
752 if ( redirect )
753 {
754 si.dwFlags = STARTF_USESTDHANDLES;
755
756 si.hStdInput = pipeIn[wxPipe::Read];
757 si.hStdOutput = pipeOut[wxPipe::Write];
758 si.hStdError = pipeErr[wxPipe::Write];
759
760 // when the std IO is redirected, we don't show the (console) process
761 // window by default, but this can be overridden by the caller by
762 // specifying wxEXEC_NOHIDE flag
763 if ( !(flags & wxEXEC_NOHIDE) )
764 {
765 si.dwFlags |= STARTF_USESHOWWINDOW;
766 si.wShowWindow = SW_HIDE;
767 }
768
769 // we must duplicate the handle to the write side of stdin pipe to make
770 // it non inheritable: indeed, we must close the writing end of pipeIn
771 // before launching the child process as otherwise this handle will be
772 // inherited by the child which will never close it and so the pipe
773 // will never be closed and the child will be left stuck in ReadFile()
774 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
775 if ( !::DuplicateHandle
776 (
777 ::GetCurrentProcess(),
778 pipeInWrite,
779 ::GetCurrentProcess(),
780 &hpipeStdinWrite,
781 0, // desired access: unused here
782 FALSE, // not inherited
783 DUPLICATE_SAME_ACCESS // same access as for src handle
784 ) )
785 {
786 wxLogLastError(wxT("DuplicateHandle"));
787 }
788
789 ::CloseHandle(pipeInWrite);
790 }
791 #endif // wxUSE_STREAMS
792
793 PROCESS_INFORMATION pi;
794 DWORD dwFlags = CREATE_SUSPENDED;
795
796 #ifndef __WXWINCE__
797 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
798 #else
799 // we are assuming commands without spaces for now
800 wxString moduleName = command.BeforeFirst(wxT(' '));
801 wxString arguments = command.AfterFirst(wxT(' '));
802 #endif
803
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
853 bool ok = ::CreateProcess
854 (
855 // WinCE requires appname to be non null
856 // Win32 allows for null
857 #ifdef __WXWINCE__
858 (wxChar *)
859 moduleName.wx_str(),// application name
860 (wxChar *)
861 arguments.wx_str(), // arguments
862 #else
863 NULL, // application name (use only cmd line)
864 (wxChar *)
865 command.wx_str(), // full command line
866 #endif
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
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)
875 &si, // startup info (unused here)
876 &pi // process info
877 ) != 0;
878
879 #if wxUSE_STREAMS && !defined(__WXWINCE__)
880 // we can close the pipe ends used by child anyhow
881 if ( redirect )
882 {
883 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
884 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
885 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
886 }
887 #endif // wxUSE_STREAMS
888
889 if ( !ok )
890 {
891 #if wxUSE_STREAMS && !defined(__WXWINCE__)
892 // close the other handles too
893 if ( redirect )
894 {
895 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
896 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
897 }
898 #endif // wxUSE_STREAMS
899
900 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
901
902 return flags & wxEXEC_SYNC ? -1 : 0;
903 }
904
905 #if wxUSE_STREAMS && !defined(__WXWINCE__)
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
911 if ( redirect )
912 {
913 // We can now initialize the wxStreams
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);
922
923 bufOut.Init(outStream);
924 bufErr.Init(errStream);
925 }
926 #endif // wxUSE_STREAMS
927
928 // create a hidden window to receive notification about process
929 // termination
930 HWND hwnd = wxCreateHiddenWindow
931 (
932 &gs_classForHiddenWindow,
933 wxMSWEXEC_WNDCLASSNAME,
934 (WNDPROC)wxExecuteWindowCbk
935 );
936
937 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
938
939 // Alloc data
940 wxExecuteData *data = new wxExecuteData;
941 data->hProcess = pi.hProcess;
942 data->dwProcessId = pi.dwProcessId;
943 data->hWnd = hwnd;
944 data->state = (flags & wxEXEC_SYNC) != 0;
945 if ( flags & wxEXEC_SYNC )
946 {
947 // handler may be !NULL for capturing program output, but we don't use
948 // it wxExecuteData struct in this case
949 data->handler = NULL;
950 }
951 else
952 {
953 // may be NULL or not
954 data->handler = handler;
955
956 if (handler)
957 handler->SetPid(pi.dwProcessId);
958 }
959
960 DWORD tid;
961 HANDLE hThread = ::CreateThread(NULL,
962 0,
963 wxExecuteThread,
964 (void *)data,
965 0,
966 &tid);
967
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?
973 wxLogLastError(wxT("ResumeThread in wxExecute"));
974 }
975
976 // close unneeded handle
977 if ( !::CloseHandle(pi.hThread) )
978 {
979 wxLogLastError(wxT("CloseHandle(hThread)"));
980 }
981
982 if ( !hThread )
983 {
984 wxLogLastError(wxT("CreateThread in wxExecute"));
985
986 DestroyWindow(hwnd);
987 delete data;
988
989 // the process still started up successfully...
990 return pi.dwProcessId;
991 }
992
993 gs_asyncThreads.push_back(hThread);
994
995 #if wxUSE_IPC && !defined(__WXWINCE__)
996 // second part of DDE hack: now establish the DDE conversation with the
997 // just launched process
998 if ( !ddeServer.empty() )
999 {
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 */) )
1008 {
1009 default:
1010 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
1011 // fall through
1012
1013 case -1:
1014 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
1015
1016 case WAIT_TIMEOUT:
1017 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
1018
1019 ok = false;
1020 break;
1021
1022 case 0:
1023 // ok, process ready to accept DDE requests
1024 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
1025 }
1026
1027 if ( !ok )
1028 {
1029 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1030 cmd.c_str());
1031 }
1032 }
1033 #endif // wxUSE_IPC
1034
1035 if ( !(flags & wxEXEC_SYNC) )
1036 {
1037 // clean up will be done when the process terminates
1038
1039 // return the pid
1040 return pi.dwProcessId;
1041 }
1042
1043 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
1044 wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") );
1045
1046 void *cookie = NULL;
1047 if ( !(flags & wxEXEC_NODISABLE) )
1048 {
1049 // disable all app windows while waiting for the child process to finish
1050 cookie = traits->BeforeChildWaitLoop();
1051 }
1052
1053 // wait until the child process terminates
1054 while ( data->state )
1055 {
1056 #if wxUSE_STREAMS && !defined(__WXWINCE__)
1057 if ( !bufOut.Update() && !bufErr.Update() )
1058 #endif // wxUSE_STREAMS
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 }
1064
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 }
1078 }
1079
1080 if ( !(flags & wxEXEC_NODISABLE) )
1081 {
1082 // reenable disabled windows back
1083 traits->AfterChildWaitLoop(cookie);
1084 }
1085
1086 DWORD dwExitCode = data->dwExitCode;
1087 delete data;
1088
1089 // return the exit code
1090 return dwExitCode;
1091 }
1092
1093 template <typename CharType>
1094 long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler,
1095 const wxExecuteEnv *env)
1096 {
1097 wxString command;
1098 command.reserve(1024);
1099
1100 wxString arg;
1101 for ( ;; )
1102 {
1103 arg = *argv++;
1104
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 */);
1117
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 )
1124 command += '\"' + arg + '\"';
1125 else
1126 command += arg;
1127
1128 if ( !*argv )
1129 break;
1130
1131 command += ' ';
1132 }
1133
1134 return wxExecute(command, flags, handler, env);
1135 }
1136
1137 long wxExecute(char **argv, int flags, wxProcess *handler,
1138 const wxExecuteEnv *env)
1139 {
1140 return wxExecuteImpl(argv, flags, handler, env);
1141 }
1142
1143 #if wxUSE_UNICODE
1144
1145 long wxExecute(wchar_t **argv, int flags, wxProcess *handler,
1146 const wxExecuteEnv *env)
1147 {
1148 return wxExecuteImpl(argv, flags, handler, env);
1149 }
1150
1151 #endif // wxUSE_UNICODE