]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
OS/2 fix in setdrive.
[wxWidgets.git] / src / msw / utilsexc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
35 #endif
36
37 #include "wx/log.h"
38
39 #ifdef __WIN32__
40 #include "wx/stream.h"
41 #include "wx/process.h"
42 #endif
43
44 #include "wx/msw/private.h"
45
46 #include <ctype.h>
47
48 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
49 #include <direct.h>
50 #ifndef __MWERKS__
51 #include <dos.h>
52 #endif
53 #endif
54
55 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
56 #include <sys/unistd.h>
57 #include <sys/stat.h>
58 #endif
59
60 #if defined(__WIN32__) && !defined(__WXWINE__)
61 #include <io.h>
62
63 #ifndef __GNUWIN32__
64 #include <shellapi.h>
65 #endif
66 #endif
67
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #ifndef __WATCOMC__
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
73 #include <errno.h>
74 #endif
75 #endif
76 #include <stdarg.h>
77
78 #if wxUSE_IPC
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
80 #endif // wxUSE_IPC
81
82 // ----------------------------------------------------------------------------
83 // constants
84 // ----------------------------------------------------------------------------
85
86 // this message is sent when the process we're waiting for terminates
87 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
88
89 // ----------------------------------------------------------------------------
90 // this module globals
91 // ----------------------------------------------------------------------------
92
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;
97
98 // ----------------------------------------------------------------------------
99 // private types
100 // ----------------------------------------------------------------------------
101
102 // structure describing the process we're being waiting for
103 struct wxExecuteData
104 {
105 public:
106 ~wxExecuteData()
107 {
108 #ifndef __WIN16__
109 if ( !::CloseHandle(hProcess) )
110 {
111 wxLogLastError(wxT("CloseHandle(hProcess)"));
112 }
113 #endif
114 }
115
116 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
117 HANDLE hProcess; // handle of the process
118 DWORD dwProcessId; // pid of the process
119 wxProcess *handler;
120 DWORD dwExitCode; // the exit code of the process
121 bool state; // set to FALSE when the process finishes
122 };
123
124 #if defined(__WIN32__) && wxUSE_STREAMS
125
126 // ----------------------------------------------------------------------------
127 // wxPipeStreams
128 // ----------------------------------------------------------------------------
129
130 class wxPipeInputStream: public wxInputStream
131 {
132 public:
133 wxPipeInputStream(HANDLE hInput);
134 ~wxPipeInputStream();
135
136 virtual bool Eof() const;
137
138 protected:
139 size_t OnSysRead(void *buffer, size_t len);
140
141 protected:
142 HANDLE m_hInput;
143 };
144
145 class wxPipeOutputStream: public wxOutputStream
146 {
147 public:
148 wxPipeOutputStream(HANDLE hOutput);
149 ~wxPipeOutputStream();
150
151 protected:
152 size_t OnSysWrite(const void *buffer, size_t len);
153
154 protected:
155 HANDLE m_hOutput;
156 };
157
158 // ==================
159 // wxPipeInputStream
160 // ==================
161
162 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
163 {
164 m_hInput = hInput;
165 }
166
167 wxPipeInputStream::~wxPipeInputStream()
168 {
169 ::CloseHandle(m_hInput);
170 }
171
172 bool wxPipeInputStream::Eof() const
173 {
174 DWORD nAvailable;
175
176 // function name is misleading, it works with anon pipes as well
177 DWORD rc = ::PeekNamedPipe
178 (
179 m_hInput, // handle
180 NULL, 0, // ptr to buffer and its size
181 NULL, // [out] bytes read
182 &nAvailable, // [out] bytes available
183 NULL // [out] bytes left
184 );
185
186 if ( !rc )
187 {
188 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
189 {
190 // unexpected error
191 wxLogLastError(_T("PeekNamedPipe"));
192 }
193
194 // don't try to continue reading from a pipe if an error occured or if
195 // it had been closed
196 return TRUE;
197 }
198 else
199 {
200 return nAvailable == 0;
201 }
202 }
203
204 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
205 {
206 // reading from a pipe may block if there is no more data, always check for
207 // EOF first
208 m_lasterror = wxSTREAM_NOERROR;
209 if ( Eof() )
210 return 0;
211
212 DWORD bytesRead;
213 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
214 {
215 if ( ::GetLastError() == ERROR_BROKEN_PIPE )
216 m_lasterror = wxSTREAM_EOF;
217 else
218 m_lasterror = wxSTREAM_READ_ERROR;
219 }
220
221 return bytesRead;
222 }
223
224 // ==================
225 // wxPipeOutputStream
226 // ==================
227
228 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
229 {
230 m_hOutput = hOutput;
231 }
232
233 wxPipeOutputStream::~wxPipeOutputStream()
234 {
235 ::CloseHandle(m_hOutput);
236 }
237
238 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
239 {
240 DWORD bytesRead;
241
242 m_lasterror = wxSTREAM_NOERROR;
243 if ( !::WriteFile(m_hOutput, buffer, len, &bytesRead, NULL) )
244 {
245 if ( ::GetLastError() == ERROR_BROKEN_PIPE )
246 m_lasterror = wxSTREAM_EOF;
247 else
248 m_lasterror = wxSTREAM_READ_ERROR;
249 }
250
251 return bytesRead;
252 }
253
254 #endif // __WIN32__
255
256 // ============================================================================
257 // implementation
258 // ============================================================================
259
260 #ifdef __WIN32__
261
262 static DWORD wxExecuteThread(wxExecuteData *data)
263 {
264 WaitForSingleObject(data->hProcess, INFINITE);
265
266 // get the exit code
267 if ( !GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
268 {
269 wxLogLastError(wxT("GetExitCodeProcess"));
270 }
271
272 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
273 wxT("process should have terminated") );
274
275 // send a message indicating process termination to the window
276 SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
277
278 return 0;
279 }
280
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)
285 {
286 if ( message == wxWM_PROC_TERMINATED )
287 {
288 DestroyWindow(hWnd); // we don't need it any more
289
290 wxExecuteData *data = (wxExecuteData *)lParam;
291 if ( data->handler )
292 {
293 data->handler->OnTerminate((int)data->dwProcessId,
294 (int)data->dwExitCode);
295 }
296
297 if ( data->state )
298 {
299 // we're executing synchronously, tell the waiting thread
300 // that the process finished
301 data->state = 0;
302 }
303 else
304 {
305 // asynchronous execution - we should do the clean up
306 delete data;
307 }
308
309 return 0;
310 }
311 else
312 {
313 return DefWindowProc(hWnd, message, wParam, lParam);
314 }
315 }
316 #endif // Win32
317
318 long wxExecute(const wxString& cmd, bool sync, wxProcess *handler)
319 {
320 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
321
322 wxString command;
323
324 #if wxUSE_IPC
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#") )
336 {
337 const wxChar *p = cmd.c_str() + 7;
338 while ( *p && *p != _T('#') )
339 {
340 command += *p++;
341 }
342
343 if ( *p )
344 {
345 // skip '#'
346 p++;
347 }
348 else
349 {
350 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
351 }
352
353 while ( *p && *p != _T('#') )
354 {
355 ddeServer += *p++;
356 }
357
358 if ( *p )
359 {
360 // skip '#'
361 p++;
362 }
363 else
364 {
365 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
366 }
367
368 while ( *p && *p != _T('#') )
369 {
370 ddeTopic += *p++;
371 }
372
373 if ( *p )
374 {
375 // skip '#'
376 p++;
377 }
378 else
379 {
380 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
381 }
382
383 while ( *p )
384 {
385 ddeCommand += *p++;
386 }
387
388 // maybe we don't have to launch the DDE server at all - if it is
389 // already running, for example
390 wxDDEClient client;
391 wxLogNull nolog;
392 wxConnectionBase *conn = client.MakeConnection(_T(""),
393 ddeServer,
394 ddeTopic);
395 if ( conn )
396 {
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);
401
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;
406 }
407 //else: couldn't establish DDE conversation, now try launching the app
408 // and sending the DDE request again
409 }
410 else
411 #endif // wxUSE_IPC
412 {
413 // no DDE
414 command = cmd;
415 }
416
417 #if defined(__WIN32__) && !defined(__TWIN32__)
418
419 // the IO redirection is only supported with wxUSE_STREAMS
420 BOOL redirect = FALSE;
421 #if wxUSE_STREAMS
422 // the first elements are reading ends, the second are the writing ones
423 HANDLE hpipeStdin[2],
424 hpipeStdout[2],
425 hpipeStderr[2];
426 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
427
428 // open the pipes to which child process IO will be redirected if needed
429 if ( handler && handler->IsRedirected() )
430 {
431 // default secutiry attributes
432 SECURITY_ATTRIBUTES security;
433
434 security.nLength = sizeof(security);
435 security.lpSecurityDescriptor = NULL;
436 security.bInheritHandle = TRUE;
437
438 // create stdin pipe
439 if ( !::CreatePipe(&hpipeStdin[0], &hpipeStdin[1], &security, 0) )
440 {
441 wxLogSysError(_("Can't create the inter-process read pipe"));
442
443 // indicate failure in both cases
444 return sync ? -1 : 0;
445 }
446
447 // and a stdout one
448 if ( !::CreatePipe(&hpipeStdout[0], &hpipeStdout[1], &security, 0) )
449 {
450 ::CloseHandle(hpipeStdin[0]);
451 ::CloseHandle(hpipeStdin[1]);
452
453 wxLogSysError(_("Can't create the inter-process write pipe"));
454
455 return sync ? -1 : 0;
456 }
457
458 (void)::CreatePipe(&hpipeStderr[0], &hpipeStderr[1], &security, 0);
459
460 redirect = TRUE;
461 }
462 #endif // wxUSE_STREAMS
463
464 // create the process
465 STARTUPINFO si;
466 wxZeroMemory(si);
467 si.cb = sizeof(si);
468
469 #if wxUSE_STREAMS
470 if ( redirect )
471 {
472 // when the std IO is redirected, we don't show the (console) process
473 // window
474 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
475
476 si.hStdInput = hpipeStdin[0];
477 si.hStdOutput = hpipeStdout[1];
478 si.hStdError = hpipeStderr[1];
479
480 si.wShowWindow = SW_HIDE;
481
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
488 (
489 GetCurrentProcess(),
490 hpipeStdin[1],
491 GetCurrentProcess(),
492 &hpipeStdinWrite,
493 0, // desired access: unused here
494 FALSE, // not inherited
495 DUPLICATE_SAME_ACCESS // same access as for src handle
496 ) )
497 {
498 wxLogLastError(_T("DuplicateHandle"));
499 }
500
501 ::CloseHandle(hpipeStdin[1]);
502 }
503 #endif // wxUSE_STREAMS
504
505 PROCESS_INFORMATION pi;
506 DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;
507
508 bool ok = ::CreateProcess
509 (
510 NULL, // application name (use only cmd line)
511 (wxChar *)
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)
520 &pi // process info
521 ) != 0;
522
523 #if wxUSE_STREAMS
524 // we can close the pipe ends used by child anyhow
525 if ( redirect )
526 {
527 ::CloseHandle(hpipeStdin[0]);
528 ::CloseHandle(hpipeStdout[1]);
529 ::CloseHandle(hpipeStderr[1]);
530 }
531 #endif // wxUSE_STREAMS
532
533 if ( !ok )
534 {
535 #if wxUSE_STREAMS
536 // close the other handles too
537 if ( redirect )
538 {
539 ::CloseHandle(hpipeStdout[0]);
540 ::CloseHandle(hpipeStderr[0]);
541 }
542 #endif // wxUSE_STREAMS
543
544 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
545
546 return sync ? -1 : 0;
547 }
548
549 #if wxUSE_STREAMS
550 if ( redirect )
551 {
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);
556
557 handler->SetPipeStreams(inStream, outStream, errStream);
558 }
559 #endif // wxUSE_STREAMS
560
561 // register the class for the hidden window used for the notifications
562 if ( !gs_classForHiddenWindow )
563 {
564 gs_classForHiddenWindow = _T("wxHiddenWindow");
565
566 WNDCLASS wndclass;
567 wxZeroMemory(wndclass);
568 wndclass.lpfnWndProc = (WNDPROC)wxExecuteWindowCbk;
569 wndclass.hInstance = wxGetInstance();
570 wndclass.lpszClassName = gs_classForHiddenWindow;
571
572 if ( !::RegisterClass(&wndclass) )
573 {
574 wxLogLastError(wxT("RegisterClass(hidden window)"));
575 }
576 }
577
578 // create a hidden window to receive notification about process
579 // termination
580 HWND hwnd = ::CreateWindow(gs_classForHiddenWindow, NULL,
581 WS_OVERLAPPEDWINDOW,
582 0, 0, 0, 0, NULL,
583 (HMENU)NULL, wxGetInstance(), 0);
584 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
585
586 // Alloc data
587 wxExecuteData *data = new wxExecuteData;
588 data->hProcess = pi.hProcess;
589 data->dwProcessId = pi.dwProcessId;
590 data->hWnd = hwnd;
591 data->state = sync;
592 if ( sync )
593 {
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;
597 }
598 else
599 {
600 // may be NULL or not
601 data->handler = handler;
602 }
603
604 DWORD tid;
605 HANDLE hThread = ::CreateThread(NULL,
606 0,
607 (LPTHREAD_START_ROUTINE)wxExecuteThread,
608 (void *)data,
609 0,
610 &tid);
611
612 // resume process we created now - whether the thread creation succeeded or
613 // not
614 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
615 {
616 // ignore it - what can we do?
617 wxLogLastError(wxT("ResumeThread in wxExecute"));
618 }
619
620 // close unneeded handle
621 if ( !::CloseHandle(pi.hThread) )
622 wxLogLastError(wxT("CloseHandle(hThread)"));
623
624 if ( !hThread )
625 {
626 wxLogLastError(wxT("CreateThread in wxExecute"));
627
628 DestroyWindow(hwnd);
629 delete data;
630
631 // the process still started up successfully...
632 return pi.dwProcessId;
633 }
634
635 ::CloseHandle(hThread);
636
637 #if wxUSE_IPC
638 // second part of DDE hack: now establish the DDE conversation with the
639 // just launched process
640 if ( !!ddeServer )
641 {
642 wxDDEClient client;
643 wxConnectionBase *conn;
644
645 {
646 // try doing it the first time without error messages
647 wxLogNull nolog;
648
649 conn = client.MakeConnection(_T(""), ddeServer, ddeTopic);
650 }
651
652 if ( !conn )
653 {
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
658 ::Sleep(2000);
659
660 wxConnectionBase *conn = client.MakeConnection(_T(""),
661 ddeServer,
662 ddeTopic);
663 if ( !conn )
664 {
665 wxLogError(_("Couldn't launch DDE server '%s'."), command.c_str());
666 }
667 }
668
669 if ( conn )
670 {
671 // FIXME just as above we don't check Execute() return code
672 wxLogNull nolog;
673 (void)conn->Execute(ddeCommand);
674 }
675 }
676 #endif // wxUSE_IPC
677
678 if ( !sync )
679 {
680 // clean up will be done when the process terminates
681
682 // return the pid
683 return pi.dwProcessId;
684 }
685
686 // waiting until command executed (disable everything while doing it)
687 #if wxUSE_GUI
688 {
689 wxBusyCursor bc;
690
691 wxWindowDisabler wd;
692 #endif // wxUSE_GUI
693
694 while ( data->state )
695 wxYield();
696
697 #if wxUSE_GUI
698 }
699 #endif // wxUSE_GUI
700
701 DWORD dwExitCode = data->dwExitCode;
702 delete data;
703
704 // return the exit code
705 return dwExitCode;
706 #else // Win16
707 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
708 if (instanceID < 32) return(0);
709
710 if (sync) {
711 int running;
712 do {
713 wxYield();
714 running = GetModuleUsage((HINSTANCE)instanceID);
715 } while (running);
716 }
717
718 return(instanceID);
719 #endif // Win16/32
720 }
721
722 long wxExecute(char **argv, bool sync, wxProcess *handler)
723 {
724 wxString command;
725
726 while ( *argv != NULL )
727 {
728 command << *argv++ << ' ';
729 }
730
731 command.RemoveLast();
732
733 return wxExecute(command, sync, handler);
734 }
735
736 #if wxUSE_GUI
737
738 // ----------------------------------------------------------------------------
739 // Metafile helpers
740 // ----------------------------------------------------------------------------
741
742 extern void PixelToHIMETRIC(LONG *x, LONG *y)
743 {
744 ScreenHDC hdcRef;
745
746 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
747 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
748 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
749 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
750
751 *x *= (iWidthMM * 100);
752 *x /= iWidthPels;
753 *y *= (iHeightMM * 100);
754 *y /= iHeightPels;
755 }
756
757 extern void HIMETRICToPixel(LONG *x, LONG *y)
758 {
759 ScreenHDC hdcRef;
760
761 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
762 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
763 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
764 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
765
766 *x *= iWidthPels;
767 *x /= (iWidthMM * 100);
768 *y *= iHeightPels;
769 *y /= (iHeightMM * 100);
770 }
771
772 #endif // wxUSE_GUI