1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
40 #include "wx/stream.h"
41 #include "wx/process.h"
44 #include "wx/msw/private.h"
48 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
55 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
56 #include <sys/unistd.h>
60 #if defined(__WIN32__) && !defined(__WXWINE__)
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
82 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
86 // this message is sent when the process we're waiting for terminates
87 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
89 // ----------------------------------------------------------------------------
90 // this module globals
91 // ----------------------------------------------------------------------------
93 // we need to create a hidden window to receive the process termination
94 // notifications and for this we need a (Win) class name for it which we will
95 // register the first time it's needed
96 static const wxChar
*gs_classForHiddenWindow
= NULL
;
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 // structure describing the process we're being waiting for
109 if ( !::CloseHandle(hProcess
) )
111 wxLogLastError(wxT("CloseHandle(hProcess)"));
116 HWND hWnd
; // window to send wxWM_PROC_TERMINATED to
117 HANDLE hProcess
; // handle of the process
118 DWORD dwProcessId
; // pid of the process
120 DWORD dwExitCode
; // the exit code of the process
121 bool state
; // set to FALSE when the process finishes
124 #if defined(__WIN32__) && wxUSE_STREAMS
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 class wxPipeInputStream
: public wxInputStream
133 wxPipeInputStream(HANDLE hInput
);
134 ~wxPipeInputStream();
136 virtual bool Eof() const;
139 size_t OnSysRead(void *buffer
, size_t len
);
145 class wxPipeOutputStream
: public wxOutputStream
148 wxPipeOutputStream(HANDLE hOutput
);
149 ~wxPipeOutputStream();
152 size_t OnSysWrite(const void *buffer
, size_t len
);
158 // ==================
160 // ==================
162 wxPipeInputStream::wxPipeInputStream(HANDLE hInput
)
167 wxPipeInputStream::~wxPipeInputStream()
169 ::CloseHandle(m_hInput
);
172 bool wxPipeInputStream::Eof() const
176 // function name is misleading, it works with anon pipes as well
177 DWORD rc
= ::PeekNamedPipe
180 NULL
, 0, // ptr to buffer and its size
181 NULL
, // [out] bytes read
182 &nAvailable
, // [out] bytes available
183 NULL
// [out] bytes left
188 if ( ::GetLastError() != ERROR_BROKEN_PIPE
)
191 wxLogLastError(_T("PeekNamedPipe"));
194 // don't try to continue reading from a pipe if an error occured or if
195 // it had been closed
200 return nAvailable
== 0;
204 size_t wxPipeInputStream::OnSysRead(void *buffer
, size_t len
)
206 // reading from a pipe may block if there is no more data, always check for
208 m_lasterror
= wxSTREAM_NOERROR
;
213 if ( !::ReadFile(m_hInput
, buffer
, len
, &bytesRead
, NULL
) )
215 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
216 m_lasterror
= wxSTREAM_EOF
;
218 m_lasterror
= wxSTREAM_READ_ERROR
;
224 // ==================
225 // wxPipeOutputStream
226 // ==================
228 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput
)
233 wxPipeOutputStream::~wxPipeOutputStream()
235 ::CloseHandle(m_hOutput
);
238 size_t wxPipeOutputStream::OnSysWrite(const void *buffer
, size_t len
)
242 m_lasterror
= wxSTREAM_NOERROR
;
243 if ( !::WriteFile(m_hOutput
, buffer
, len
, &bytesRead
, NULL
) )
245 if ( ::GetLastError() == ERROR_BROKEN_PIPE
)
246 m_lasterror
= wxSTREAM_EOF
;
248 m_lasterror
= wxSTREAM_READ_ERROR
;
256 // ============================================================================
258 // ============================================================================
262 static DWORD
wxExecuteThread(wxExecuteData
*data
)
264 WaitForSingleObject(data
->hProcess
, INFINITE
);
267 if ( !GetExitCodeProcess(data
->hProcess
, &data
->dwExitCode
) )
269 wxLogLastError(wxT("GetExitCodeProcess"));
272 wxASSERT_MSG( data
->dwExitCode
!= STILL_ACTIVE
,
273 wxT("process should have terminated") );
275 // send a message indicating process termination to the window
276 SendMessage(data
->hWnd
, wxWM_PROC_TERMINATED
, 0, (LPARAM
)data
);
281 // window procedure of a hidden window which is created just to receive
282 // the notification message when a process exits
283 LRESULT APIENTRY _EXPORT
wxExecuteWindowCbk(HWND hWnd
, UINT message
,
284 WPARAM wParam
, LPARAM lParam
)
286 if ( message
== wxWM_PROC_TERMINATED
)
288 DestroyWindow(hWnd
); // we don't need it any more
290 wxExecuteData
*data
= (wxExecuteData
*)lParam
;
293 data
->handler
->OnTerminate((int)data
->dwProcessId
,
294 (int)data
->dwExitCode
);
299 // we're executing synchronously, tell the waiting thread
300 // that the process finished
305 // asynchronous execution - we should do the clean up
313 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
318 long wxExecute(const wxString
& cmd
, bool sync
, wxProcess
*handler
)
320 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
325 // DDE hack: this is really not pretty, but we need to allow this for
326 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
327 // returns the command which should be run to view/open/... a file of the
328 // given type. Sometimes, however, this command just launches the server
329 // and an additional DDE request must be made to really open the file. To
330 // keep all this well hidden from the application, we allow a special form
331 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
332 // case we execute just <command> and process the rest below
333 wxString ddeServer
, ddeTopic
, ddeCommand
;
334 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
335 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
337 const wxChar
*p
= cmd
.c_str() + 7;
338 while ( *p
&& *p
!= _T('#') )
350 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
353 while ( *p
&& *p
!= _T('#') )
365 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
368 while ( *p
&& *p
!= _T('#') )
380 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
388 // maybe we don't have to launch the DDE server at all - if it is
389 // already running, for example
392 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
397 // FIXME we don't check the return code as for some strange reason
398 // it will sometimes be FALSE - it is probably a bug in our
399 // DDE code but I don't see anything wrong there
400 (void)conn
->Execute(ddeCommand
);
402 // ok, the command executed - return value indicating success,
403 // making it up for async case as we really don't have any way to
404 // get the real PID of the DDE server here
405 return sync
? 0 : -1;
407 //else: couldn't establish DDE conversation, now try launching the app
408 // and sending the DDE request again
417 #if defined(__WIN32__) && !defined(__TWIN32__)
419 // the IO redirection is only supported with wxUSE_STREAMS
420 BOOL redirect
= FALSE
;
422 // the first elements are reading ends, the second are the writing ones
423 HANDLE hpipeStdin
[2],
424 hpipeStdinWrite
= INVALID_HANDLE_VALUE
,
428 // open the pipes to which child process IO will be redirected if needed
429 if ( handler
&& handler
->IsRedirected() )
431 // default secutiry attributes
432 SECURITY_ATTRIBUTES security
;
434 security
.nLength
= sizeof(security
);
435 security
.lpSecurityDescriptor
= NULL
;
436 security
.bInheritHandle
= TRUE
;
439 if ( !::CreatePipe(&hpipeStdin
[0], &hpipeStdin
[1], &security
, 0) )
441 wxLogSysError(_("Can't create the inter-process read pipe"));
443 // indicate failure in both cases
444 return sync
? -1 : 0;
448 if ( !::CreatePipe(&hpipeStdout
[0], &hpipeStdout
[1], &security
, 0) )
450 ::CloseHandle(hpipeStdin
[0]);
451 ::CloseHandle(hpipeStdin
[1]);
453 wxLogSysError(_("Can't create the inter-process write pipe"));
455 return sync
? -1 : 0;
458 (void)::CreatePipe(&hpipeStderr
[0], &hpipeStderr
[1], &security
, 0);
462 #endif // wxUSE_STREAMS
464 // create the process
472 // when the std IO is redirected, we don't show the (console) process
474 si
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
476 si
.hStdInput
= hpipeStdin
[0];
477 si
.hStdOutput
= hpipeStdout
[1];
478 si
.hStdError
= hpipeStderr
[1];
480 si
.wShowWindow
= SW_HIDE
;
482 // we must duplicate the handle to the write side of stdin pipe to make
483 // it non inheritable: indeed, we must close hpipeStdin[1] before
484 // launching the child process as otherwise this handle will be
485 // inherited by the child which will never close it and so the pipe
486 // will never be closed and the child will be left stuck in ReadFile()
487 if ( !::DuplicateHandle
493 0, // desired access: unused here
494 FALSE
, // not inherited
495 DUPLICATE_SAME_ACCESS
// same access as for src handle
498 wxLogLastError(_T("DuplicateHandle"));
501 ::CloseHandle(hpipeStdin
[1]);
503 #endif // wxUSE_STREAMS
505 PROCESS_INFORMATION pi
;
506 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
508 bool ok
= ::CreateProcess
510 NULL
, // application name (use only cmd line)
512 command
.c_str(), // full command line
513 NULL
, // security attributes: defaults for both
514 NULL
, // the process and its main thread
515 redirect
, // inherit handles if we use pipes
516 dwFlags
, // process creation flags
517 NULL
, // environment (use the same)
518 NULL
, // current directory (use the same)
519 &si
, // startup info (unused here)
524 // we can close the pipe ends used by child anyhow
527 ::CloseHandle(hpipeStdin
[0]);
528 ::CloseHandle(hpipeStdout
[1]);
529 ::CloseHandle(hpipeStderr
[1]);
531 #endif // wxUSE_STREAMS
536 // close the other handles too
539 ::CloseHandle(hpipeStdout
[0]);
540 ::CloseHandle(hpipeStderr
[0]);
542 #endif // wxUSE_STREAMS
544 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
546 return sync
? -1 : 0;
552 // We can now initialize the wxStreams
553 wxInputStream
*inStream
= new wxPipeInputStream(hpipeStdout
[0]),
554 *errStream
= new wxPipeInputStream(hpipeStderr
[0]);
555 wxOutputStream
*outStream
= new wxPipeOutputStream(hpipeStdinWrite
);
557 handler
->SetPipeStreams(inStream
, outStream
, errStream
);
559 #endif // wxUSE_STREAMS
561 // register the class for the hidden window used for the notifications
562 if ( !gs_classForHiddenWindow
)
564 gs_classForHiddenWindow
= _T("wxHiddenWindow");
567 wxZeroMemory(wndclass
);
568 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
569 wndclass
.hInstance
= wxGetInstance();
570 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
572 if ( !::RegisterClass(&wndclass
) )
574 wxLogLastError(wxT("RegisterClass(hidden window)"));
578 // create a hidden window to receive notification about process
580 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
583 (HMENU
)NULL
, wxGetInstance(), 0);
584 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
587 wxExecuteData
*data
= new wxExecuteData
;
588 data
->hProcess
= pi
.hProcess
;
589 data
->dwProcessId
= pi
.dwProcessId
;
594 // handler may be !NULL for capturing program output, but we don't use
595 // it wxExecuteData struct in this case
596 data
->handler
= NULL
;
600 // may be NULL or not
601 data
->handler
= handler
;
605 HANDLE hThread
= ::CreateThread(NULL
,
607 (LPTHREAD_START_ROUTINE
)wxExecuteThread
,
612 // resume process we created now - whether the thread creation succeeded or
614 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
616 // ignore it - what can we do?
617 wxLogLastError(wxT("ResumeThread in wxExecute"));
620 // close unneeded handle
621 if ( !::CloseHandle(pi
.hThread
) )
622 wxLogLastError(wxT("CloseHandle(hThread)"));
626 wxLogLastError(wxT("CreateThread in wxExecute"));
631 // the process still started up successfully...
632 return pi
.dwProcessId
;
635 ::CloseHandle(hThread
);
638 // second part of DDE hack: now establish the DDE conversation with the
639 // just launched process
643 wxConnectionBase
*conn
;
646 // try doing it the first time without error messages
649 conn
= client
.MakeConnection(_T(""), ddeServer
, ddeTopic
);
654 // give the app some time to initialize itself: in fact, a common
655 // reason for failure is that we tried to open DDE conversation too
656 // soon (before the app had time to setup its DDE server), so wait
657 // a bit and try again
660 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
665 wxLogError(_("Couldn't launch DDE server '%s'."), command
.c_str());
671 // FIXME just as above we don't check Execute() return code
673 (void)conn
->Execute(ddeCommand
);
680 // clean up will be done when the process terminates
683 return pi
.dwProcessId
;
686 // waiting until command executed (disable everything while doing it)
694 while ( data
->state
)
701 DWORD dwExitCode
= data
->dwExitCode
;
704 // return the exit code
707 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
708 if (instanceID
< 32) return(0);
714 running
= GetModuleUsage((HINSTANCE
)instanceID
);
722 long wxExecute(char **argv
, bool sync
, wxProcess
*handler
)
726 while ( *argv
!= NULL
)
728 command
<< *argv
++ << ' ';
731 command
.RemoveLast();
733 return wxExecute(command
, sync
, handler
);
738 // ----------------------------------------------------------------------------
740 // ----------------------------------------------------------------------------
742 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
746 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
747 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
748 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
749 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
751 *x
*= (iWidthMM
* 100);
753 *y
*= (iHeightMM
* 100);
757 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
761 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
762 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
763 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
764 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
767 *x
/= (iWidthMM
* 100);
769 *y
/= (iHeightMM
* 100);