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") );
324 // DDE hack: this is really not pretty, but we need to allow this for
325 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
326 // returns the command which should be run to view/open/... a file of the
327 // given type. Sometimes, however, this command just launches the server
328 // and an additional DDE request must be made to really open the file. To
329 // keep all this well hidden from the application, we allow a special form
330 // of command: WX_DDE:<command>:DDE_SERVER:DDE_TOPIC:DDE_COMMAND in which
331 // case we execute just <command> and process the rest below
332 wxString ddeServer
, ddeTopic
, ddeCommand
;
333 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
334 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
336 const wxChar
*p
= cmd
.c_str() + 7;
337 while ( *p
&& *p
!= _T('#') )
349 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
352 while ( *p
&& *p
!= _T('#') )
364 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
367 while ( *p
&& *p
!= _T('#') )
379 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
394 #if defined(__WIN32__) && !defined(__TWIN32__)
396 // the IO redirection is only supported with wxUSE_STREAMS
397 BOOL redirect
= FALSE
;
399 // the first elements are reading ends, the second are the writing ones
400 HANDLE hpipeStdin
[2],
401 hpipeStdinWrite
= INVALID_HANDLE_VALUE
,
405 // open the pipes to which child process IO will be redirected if needed
406 if ( handler
&& handler
->IsRedirected() )
408 // default secutiry attributes
409 SECURITY_ATTRIBUTES security
;
411 security
.nLength
= sizeof(security
);
412 security
.lpSecurityDescriptor
= NULL
;
413 security
.bInheritHandle
= TRUE
;
416 if ( !::CreatePipe(&hpipeStdin
[0], &hpipeStdin
[1], &security
, 0) )
418 wxLogSysError(_("Can't create the inter-process read pipe"));
420 // indicate failure in both cases
421 return sync
? -1 : 0;
425 if ( !::CreatePipe(&hpipeStdout
[0], &hpipeStdout
[1], &security
, 0) )
427 ::CloseHandle(hpipeStdin
[0]);
428 ::CloseHandle(hpipeStdin
[1]);
430 wxLogSysError(_("Can't create the inter-process write pipe"));
432 return sync
? -1 : 0;
435 (void)::CreatePipe(&hpipeStderr
[0], &hpipeStderr
[1], &security
, 0);
439 #endif // wxUSE_STREAMS
441 // create the process
449 // when the std IO is redirected, we don't show the (console) process
451 si
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
453 si
.hStdInput
= hpipeStdin
[0];
454 si
.hStdOutput
= hpipeStdout
[1];
455 si
.hStdError
= hpipeStderr
[1];
457 si
.wShowWindow
= SW_HIDE
;
459 // we must duplicate the handle to the write side of stdin pipe to make
460 // it non inheritable: indeed, we must close hpipeStdin[1] before
461 // launching the child process as otherwise this handle will be
462 // inherited by the child which will never close it and so the pipe
463 // will never be closed and the child will be left stuck in ReadFile()
464 if ( !::DuplicateHandle
470 0, // desired access: unused here
471 FALSE
, // not inherited
472 DUPLICATE_SAME_ACCESS
// same access as for src handle
475 wxLogLastError(_T("DuplicateHandle"));
478 ::CloseHandle(hpipeStdin
[1]);
480 #endif // wxUSE_STREAMS
482 PROCESS_INFORMATION pi
;
483 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
485 bool ok
= ::CreateProcess
487 NULL
, // application name (use only cmd line)
489 command
.c_str(), // full command line
490 NULL
, // security attributes: defaults for both
491 NULL
, // the process and its main thread
492 redirect
, // inherit handles if we use pipes
493 dwFlags
, // process creation flags
494 NULL
, // environment (use the same)
495 NULL
, // current directory (use the same)
496 &si
, // startup info (unused here)
501 // we can close the pipe ends used by child anyhow
504 ::CloseHandle(hpipeStdin
[0]);
505 ::CloseHandle(hpipeStdout
[1]);
506 ::CloseHandle(hpipeStderr
[1]);
508 #endif // wxUSE_STREAMS
513 // close the other handles too
516 ::CloseHandle(hpipeStdout
[0]);
517 ::CloseHandle(hpipeStderr
[0]);
519 #endif // wxUSE_STREAMS
521 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
523 return sync
? -1 : 0;
529 // We can now initialize the wxStreams
530 wxInputStream
*inStream
= new wxPipeInputStream(hpipeStdout
[0]),
531 *errStream
= new wxPipeInputStream(hpipeStderr
[0]);
532 wxOutputStream
*outStream
= new wxPipeOutputStream(hpipeStdinWrite
);
534 handler
->SetPipeStreams(inStream
, outStream
, errStream
);
536 #endif // wxUSE_STREAMS
538 // register the class for the hidden window used for the notifications
539 if ( !gs_classForHiddenWindow
)
541 gs_classForHiddenWindow
= _T("wxHiddenWindow");
544 wxZeroMemory(wndclass
);
545 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
546 wndclass
.hInstance
= wxGetInstance();
547 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
549 if ( !::RegisterClass(&wndclass
) )
551 wxLogLastError(wxT("RegisterClass(hidden window)"));
555 // create a hidden window to receive notification about process
557 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
560 (HMENU
)NULL
, wxGetInstance(), 0);
561 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
564 wxExecuteData
*data
= new wxExecuteData
;
565 data
->hProcess
= pi
.hProcess
;
566 data
->dwProcessId
= pi
.dwProcessId
;
571 // handler may be !NULL for capturing program output, but we don't use
572 // it wxExecuteData struct in this case
573 data
->handler
= NULL
;
577 // may be NULL or not
578 data
->handler
= handler
;
582 HANDLE hThread
= ::CreateThread(NULL
,
584 (LPTHREAD_START_ROUTINE
)wxExecuteThread
,
589 // resume process we created now - whether the thread creation succeeded or
591 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
593 // ignore it - what can we do?
594 wxLogLastError(wxT("ResumeThread in wxExecute"));
597 // close unneeded handle
598 if ( !::CloseHandle(pi
.hThread
) )
599 wxLogLastError(wxT("CloseHandle(hThread)"));
603 wxLogLastError(wxT("CreateThread in wxExecute"));
608 // the process still started up successfully...
609 return pi
.dwProcessId
;
612 ::CloseHandle(hThread
);
615 // second part of DDE hack: now establish the DDE conversation with the
616 // just launched process
620 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
623 if ( !conn
|| !conn
->Execute(ddeCommand
) )
625 wxLogError(_("Couldn't launch DDE server '%s'."), command
.c_str());
632 // clean up will be done when the process terminates
635 return pi
.dwProcessId
;
638 // waiting until command executed (disable everything while doing it)
646 while ( data
->state
)
653 DWORD dwExitCode
= data
->dwExitCode
;
656 // return the exit code
659 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
660 if (instanceID
< 32) return(0);
666 running
= GetModuleUsage((HINSTANCE
)instanceID
);
674 long wxExecute(char **argv
, bool sync
, wxProcess
*handler
)
678 while ( *argv
!= NULL
)
680 command
<< *argv
++ << ' ';
683 command
.RemoveLast();
685 return wxExecute(command
, sync
, handler
);
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
694 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
698 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
699 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
700 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
701 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
703 *x
*= (iWidthMM
* 100);
705 *y
*= (iHeightMM
* 100);
709 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
713 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
714 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
715 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
716 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
719 *x
/= (iWidthMM
* 100);
721 *y
/= (iHeightMM
* 100);