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
);
320 // connect to the given server via DDE and ask it to execute the command
321 static bool wxExecuteDDE(const wxString
& ddeServer
,
322 const wxString
& ddeTopic
,
323 const wxString
& ddeCommand
)
328 wxConnectionBase
*conn
= client
.MakeConnection(_T(""),
335 else // connected to DDE server
337 // the added complication here is that although most
338 // programs use XTYP_EXECUTE for their DDE API, some
339 // important ones - like IE and other MS stuff - use
342 // so we try it first and then the other one if it
346 ok
= conn
->Request(ddeCommand
) != NULL
;
351 // now try execute - but show the errors
352 ok
= conn
->Execute(ddeCommand
);
361 long wxExecute(const wxString
& cmd
, bool sync
, wxProcess
*handler
)
363 wxCHECK_MSG( !!cmd
, 0, wxT("empty command in wxExecute") );
368 // DDE hack: this is really not pretty, but we need to allow this for
369 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
370 // returns the command which should be run to view/open/... a file of the
371 // given type. Sometimes, however, this command just launches the server
372 // and an additional DDE request must be made to really open the file. To
373 // keep all this well hidden from the application, we allow a special form
374 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
375 // case we execute just <command> and process the rest below
376 wxString ddeServer
, ddeTopic
, ddeCommand
;
377 static const size_t lenDdePrefix
= 7; // strlen("WX_DDE:")
378 if ( cmd
.Left(lenDdePrefix
) == _T("WX_DDE#") )
380 // speed up the concatenations below
381 ddeServer
.reserve(256);
382 ddeTopic
.reserve(256);
383 ddeCommand
.reserve(256);
385 const wxChar
*p
= cmd
.c_str() + 7;
386 while ( *p
&& *p
!= _T('#') )
398 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
401 while ( *p
&& *p
!= _T('#') )
413 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
416 while ( *p
&& *p
!= _T('#') )
428 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
436 // if we want to just launch the program and not wait for its
437 // termination, try to execute DDE command right now, it can succeed if
438 // the process is already running - but as it fails if it's not
439 // running, suppress any errors it might generate
443 if ( wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
) )
445 // a dummy PID - this is a hack, of course, but it's well worth
446 // it as we don't open a new server each time we're called
447 // which would be quite bad
459 #if defined(__WIN32__) && !defined(__TWIN32__)
461 // the IO redirection is only supported with wxUSE_STREAMS
462 BOOL redirect
= FALSE
;
464 // the first elements are reading ends, the second are the writing ones
465 HANDLE hpipeStdin
[2],
468 HANDLE hpipeStdinWrite
= INVALID_HANDLE_VALUE
;
470 // open the pipes to which child process IO will be redirected if needed
471 if ( handler
&& handler
->IsRedirected() )
473 // default secutiry attributes
474 SECURITY_ATTRIBUTES security
;
476 security
.nLength
= sizeof(security
);
477 security
.lpSecurityDescriptor
= NULL
;
478 security
.bInheritHandle
= TRUE
;
481 if ( !::CreatePipe(&hpipeStdin
[0], &hpipeStdin
[1], &security
, 0) )
483 wxLogSysError(_("Can't create the inter-process read pipe"));
485 // indicate failure in both cases
486 return sync
? -1 : 0;
490 if ( !::CreatePipe(&hpipeStdout
[0], &hpipeStdout
[1], &security
, 0) )
492 ::CloseHandle(hpipeStdin
[0]);
493 ::CloseHandle(hpipeStdin
[1]);
495 wxLogSysError(_("Can't create the inter-process write pipe"));
497 return sync
? -1 : 0;
500 (void)::CreatePipe(&hpipeStderr
[0], &hpipeStderr
[1], &security
, 0);
504 #endif // wxUSE_STREAMS
506 // create the process
514 // when the std IO is redirected, we don't show the (console) process
516 si
.dwFlags
= STARTF_USESTDHANDLES
| STARTF_USESHOWWINDOW
;
518 si
.hStdInput
= hpipeStdin
[0];
519 si
.hStdOutput
= hpipeStdout
[1];
520 si
.hStdError
= hpipeStderr
[1];
522 si
.wShowWindow
= SW_HIDE
;
524 // we must duplicate the handle to the write side of stdin pipe to make
525 // it non inheritable: indeed, we must close hpipeStdin[1] before
526 // launching the child process as otherwise this handle will be
527 // inherited by the child which will never close it and so the pipe
528 // will never be closed and the child will be left stuck in ReadFile()
529 if ( !::DuplicateHandle
535 0, // desired access: unused here
536 FALSE
, // not inherited
537 DUPLICATE_SAME_ACCESS
// same access as for src handle
540 wxLogLastError(_T("DuplicateHandle"));
543 ::CloseHandle(hpipeStdin
[1]);
545 #endif // wxUSE_STREAMS
547 PROCESS_INFORMATION pi
;
548 DWORD dwFlags
= CREATE_DEFAULT_ERROR_MODE
| CREATE_SUSPENDED
;
550 bool ok
= ::CreateProcess
552 NULL
, // application name (use only cmd line)
554 command
.c_str(), // full command line
555 NULL
, // security attributes: defaults for both
556 NULL
, // the process and its main thread
557 redirect
, // inherit handles if we use pipes
558 dwFlags
, // process creation flags
559 NULL
, // environment (use the same)
560 NULL
, // current directory (use the same)
561 &si
, // startup info (unused here)
566 // we can close the pipe ends used by child anyhow
569 ::CloseHandle(hpipeStdin
[0]);
570 ::CloseHandle(hpipeStdout
[1]);
571 ::CloseHandle(hpipeStderr
[1]);
573 #endif // wxUSE_STREAMS
578 // close the other handles too
581 ::CloseHandle(hpipeStdout
[0]);
582 ::CloseHandle(hpipeStderr
[0]);
584 #endif // wxUSE_STREAMS
586 wxLogSysError(_("Execution of command '%s' failed"), command
.c_str());
588 return sync
? -1 : 0;
594 // We can now initialize the wxStreams
595 wxInputStream
*inStream
= new wxPipeInputStream(hpipeStdout
[0]),
596 *errStream
= new wxPipeInputStream(hpipeStderr
[0]);
597 wxOutputStream
*outStream
= new wxPipeOutputStream(hpipeStdinWrite
);
599 handler
->SetPipeStreams(inStream
, outStream
, errStream
);
601 #endif // wxUSE_STREAMS
603 // register the class for the hidden window used for the notifications
604 if ( !gs_classForHiddenWindow
)
606 gs_classForHiddenWindow
= _T("wxHiddenWindow");
609 wxZeroMemory(wndclass
);
610 wndclass
.lpfnWndProc
= (WNDPROC
)wxExecuteWindowCbk
;
611 wndclass
.hInstance
= wxGetInstance();
612 wndclass
.lpszClassName
= gs_classForHiddenWindow
;
614 if ( !::RegisterClass(&wndclass
) )
616 wxLogLastError(wxT("RegisterClass(hidden window)"));
620 // create a hidden window to receive notification about process
622 HWND hwnd
= ::CreateWindow(gs_classForHiddenWindow
, NULL
,
625 (HMENU
)NULL
, wxGetInstance(), 0);
626 wxASSERT_MSG( hwnd
, wxT("can't create a hidden window for wxExecute") );
629 wxExecuteData
*data
= new wxExecuteData
;
630 data
->hProcess
= pi
.hProcess
;
631 data
->dwProcessId
= pi
.dwProcessId
;
636 // handler may be !NULL for capturing program output, but we don't use
637 // it wxExecuteData struct in this case
638 data
->handler
= NULL
;
642 // may be NULL or not
643 data
->handler
= handler
;
647 HANDLE hThread
= ::CreateThread(NULL
,
649 (LPTHREAD_START_ROUTINE
)wxExecuteThread
,
654 // resume process we created now - whether the thread creation succeeded or
656 if ( ::ResumeThread(pi
.hThread
) == (DWORD
)-1 )
658 // ignore it - what can we do?
659 wxLogLastError(wxT("ResumeThread in wxExecute"));
662 // close unneeded handle
663 if ( !::CloseHandle(pi
.hThread
) )
664 wxLogLastError(wxT("CloseHandle(hThread)"));
668 wxLogLastError(wxT("CreateThread in wxExecute"));
673 // the process still started up successfully...
674 return pi
.dwProcessId
;
677 ::CloseHandle(hThread
);
680 // second part of DDE hack: now establish the DDE conversation with the
681 // just launched process
682 if ( !ddeServer
.empty() )
686 // give the process the time to init itself
688 // we use a very big timeout hoping that WaitForInputIdle() will return
689 // much sooner, but not INFINITE just in case the process hangs
690 // completely - like this we will regain control sooner or later
691 switch ( ::WaitForInputIdle(pi
.hProcess
, 10000 /* 10 seconds */) )
694 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
698 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
701 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
707 // ok, process ready to accept DDE requests
708 ok
= wxExecuteDDE(ddeServer
, ddeTopic
, ddeCommand
);
715 // clean up will be done when the process terminates
718 return pi
.dwProcessId
;
721 // waiting until command executed (disable everything while doing it)
729 while ( data
->state
)
736 DWORD dwExitCode
= data
->dwExitCode
;
739 // return the exit code
742 long instanceID
= WinExec((LPCSTR
) WXSTRINGCAST command
, SW_SHOW
);
743 if (instanceID
< 32) return(0);
749 running
= GetModuleUsage((HINSTANCE
)instanceID
);
757 long wxExecute(char **argv
, bool sync
, wxProcess
*handler
)
761 while ( *argv
!= NULL
)
763 command
<< *argv
++ << ' ';
766 command
.RemoveLast();
768 return wxExecute(command
, sync
, handler
);
773 // ----------------------------------------------------------------------------
775 // ----------------------------------------------------------------------------
777 extern void PixelToHIMETRIC(LONG
*x
, LONG
*y
)
781 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
782 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
783 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
784 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
786 *x
*= (iWidthMM
* 100);
788 *y
*= (iHeightMM
* 100);
792 extern void HIMETRICToPixel(LONG
*x
, LONG
*y
)
796 int iWidthMM
= GetDeviceCaps(hdcRef
, HORZSIZE
),
797 iHeightMM
= GetDeviceCaps(hdcRef
, VERTSIZE
),
798 iWidthPels
= GetDeviceCaps(hdcRef
, HORZRES
),
799 iHeightPels
= GetDeviceCaps(hdcRef
, VERTRES
);
802 *x
/= (iWidthMM
* 100);
804 *y
/= (iHeightMM
* 100);