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