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