]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
1. wxProcess changes to make capturing subprocess output easier (and more
[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("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
125 #ifdef __WIN32__
126 // ----------------------------------------------------------------------------
127 // wxPipeStreams
128 // ----------------------------------------------------------------------------
129
130 class wxPipeInputStream: public wxInputStream {
131 public:
132 wxPipeInputStream(HANDLE hInput);
133 ~wxPipeInputStream();
134
135 protected:
136 size_t OnSysRead(void *buffer, size_t len);
137
138 protected:
139 HANDLE m_hInput;
140 };
141
142 class wxPipeOutputStream: public wxOutputStream {
143 public:
144 wxPipeOutputStream(HANDLE hOutput);
145 ~wxPipeOutputStream();
146
147 protected:
148 size_t OnSysWrite(const void *buffer, size_t len);
149
150 protected:
151 HANDLE m_hOutput;
152 };
153
154 // ==================
155 // wxPipeInputStream
156 // ==================
157
158 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
159 {
160 m_hInput = hInput;
161 }
162
163 wxPipeInputStream::~wxPipeInputStream()
164 {
165 ::CloseHandle(m_hInput);
166 }
167
168 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
169 {
170 DWORD bytesRead;
171
172 m_lasterror = wxSTREAM_NOERROR;
173 if (! ::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) ) {
174 if (GetLastError() == ERROR_BROKEN_PIPE)
175 m_lasterror = wxSTREAM_EOF;
176 else
177 m_lasterror = wxSTREAM_READ_ERROR;
178 }
179 return bytesRead;
180 }
181
182 // ==================
183 // wxPipeOutputStream
184 // ==================
185
186 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
187 {
188 m_hOutput = hOutput;
189 }
190
191 wxPipeOutputStream::~wxPipeOutputStream()
192 {
193 ::CloseHandle(m_hOutput);
194 }
195
196 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
197 {
198 DWORD bytesRead;
199
200 m_lasterror = wxSTREAM_NOERROR;
201 if (! ::WriteFile(m_hOutput, buffer, len, &bytesRead, NULL) ) {
202 if (GetLastError() == ERROR_BROKEN_PIPE)
203 m_lasterror = wxSTREAM_EOF;
204 else
205 m_lasterror = wxSTREAM_READ_ERROR;
206 }
207 return bytesRead;
208 }
209
210 #endif // __WIN32__
211
212 // ============================================================================
213 // implementation
214 // ============================================================================
215
216 #ifdef __WIN32__
217 static DWORD wxExecuteThread(wxExecuteData *data)
218 {
219 WaitForSingleObject(data->hProcess, INFINITE);
220
221 // get the exit code
222 if ( !GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
223 {
224 wxLogLastError("GetExitCodeProcess");
225 }
226
227 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
228 wxT("process should have terminated") );
229
230 // send a message indicating process termination to the window
231 SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
232
233 return 0;
234 }
235
236 // window procedure of a hidden window which is created just to receive
237 // the notification message when a process exits
238 LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
239 WPARAM wParam, LPARAM lParam)
240 {
241 if ( message == wxWM_PROC_TERMINATED )
242 {
243 DestroyWindow(hWnd); // we don't need it any more
244
245 wxExecuteData *data = (wxExecuteData *)lParam;
246 if ( data->handler )
247 {
248 data->handler->OnTerminate((int)data->dwProcessId,
249 (int)data->dwExitCode);
250 }
251
252 if ( data->state )
253 {
254 // we're executing synchronously, tell the waiting thread
255 // that the process finished
256 data->state = 0;
257 }
258 else
259 {
260 // asynchronous execution - we should do the clean up
261 delete data;
262 }
263
264 return 0;
265 }
266 else
267 {
268 return DefWindowProc(hWnd, message, wParam, lParam);
269 }
270 }
271 #endif // Win32
272
273 long wxExecute(const wxString& cmd, bool sync, wxProcess *handler)
274 {
275 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
276
277 wxString command;
278 #if wxUSE_IPC
279 // DDE hack: this is really not pretty, but we need to allow this for
280 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
281 // returns the command which should be run to view/open/... a file of the
282 // given type. Sometimes, however, this command just launches the server
283 // and an additional DDE request must be made to really open the file. To
284 // keep all this well hidden from the application, we allow a special form
285 // of command: WX_DDE:<command>:DDE_SERVER:DDE_TOPIC:DDE_COMMAND in which
286 // case we execute just <command> and process the rest below
287 wxString ddeServer, ddeTopic, ddeCommand;
288 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
289 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
290 {
291 const wxChar *p = cmd.c_str() + 7;
292 while ( *p && *p != _T('#') )
293 {
294 command += *p++;
295 }
296
297 if ( *p )
298 {
299 // skip '#'
300 p++;
301 }
302 else
303 {
304 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
305 }
306
307 while ( *p && *p != _T('#') )
308 {
309 ddeServer += *p++;
310 }
311
312 if ( *p )
313 {
314 // skip '#'
315 p++;
316 }
317 else
318 {
319 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
320 }
321
322 while ( *p && *p != _T('#') )
323 {
324 ddeTopic += *p++;
325 }
326
327 if ( *p )
328 {
329 // skip '#'
330 p++;
331 }
332 else
333 {
334 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
335 }
336
337 while ( *p )
338 {
339 ddeCommand += *p++;
340 }
341 }
342 else
343 #endif // wxUSE_IPC
344 {
345 // no DDE
346 command = cmd;
347 }
348
349 #if defined(__WIN32__) && !defined(__TWIN32__)
350 // the old code is disabled because we really need a process handle
351 // if we want to execute it asynchronously or even just get its
352 // return code and for this we must use CreateProcess() and not
353 // ShellExecute()
354 #if 0
355 // isolate command and arguments
356 wxString commandName;
357 bool insideQuotes = FALSE;
358 const char *pc;
359 for ( pc = command.c_str(); *pc != '\0'; pc++ )
360 {
361 switch ( *pc )
362 {
363 case ' ':
364 case '\t':
365 if ( !insideQuotes )
366 break;
367 // fall through
368
369 case '"':
370 insideQuotes = !insideQuotes;
371 // fall through
372
373 default:
374 commandName += *pc;
375 continue; // skip the next break
376 }
377
378 // only reached for space not inside quotes
379 break;
380 }
381 wxString commandArgs = pc;
382
383 wxWindow *winTop = wxTheApp->GetTopWindow();
384 HWND hwndTop = (HWND)(winTop ? winTop->GetHWND() : 0);
385
386 HANDLE result;
387 #ifdef __GNUWIN32__
388 result = ShellExecute(hwndTop,
389 (const wchar_t)"open",
390 (const wchar_t)commandName,
391 (const wchar_t)commandArgs,
392 (const wchar_t)NULL,
393 SW_SHOWNORMAL);
394 #else // !GNUWIN32
395 result = ShellExecute(hwndTop, "open", commandName,
396 commandArgs, NULL, SW_SHOWNORMAL);
397 #endif // GNUWIN32
398
399 if ( ((long)result) <= 32 )
400 wxLogSysError(_("Can't execute command '%s'"), command.c_str());
401
402 return result;
403 #else // 1
404
405 HANDLE h_readPipe[2];
406 HANDLE h_writePipe[2];
407 HANDLE h_oldreadPipe;
408 HANDLE h_oldwritePipe;
409 BOOL inheritHandles;
410
411 // open the pipes to which child process IO will be redirected if needed
412 inheritHandles = FALSE;
413 if ( handler && handler->IsRedirected() )
414 {
415 SECURITY_ATTRIBUTES security;
416
417 security.nLength = sizeof(security);
418 security.lpSecurityDescriptor = NULL;
419 security.bInheritHandle = TRUE;
420
421 if (! ::CreatePipe(&h_readPipe[0], &h_readPipe[1], &security, 0) )
422 {
423 wxLogSysError(_("Can't create the inter-process read pipe"));
424
425 return 0;
426 }
427
428 if (! ::CreatePipe(&h_writePipe[0], &h_writePipe[1], &security, 0) )
429 {
430 ::CloseHandle(h_readPipe[0]);
431 ::CloseHandle(h_readPipe[1]);
432
433 wxLogSysError(_("Can't create the inter-process write pipe"));
434
435 return 0;
436 }
437
438 // We need to save the old stdio handles to restore them after the call
439 // to CreateProcess
440 h_oldreadPipe = GetStdHandle(STD_INPUT_HANDLE);
441 h_oldwritePipe = GetStdHandle(STD_OUTPUT_HANDLE);
442
443 SetStdHandle(STD_INPUT_HANDLE, h_readPipe[0]);
444 SetStdHandle(STD_OUTPUT_HANDLE, h_writePipe[1]);
445
446 inheritHandles = TRUE;
447 }
448
449 // create the process
450 STARTUPINFO si;
451 wxZeroMemory(si);
452
453 si.cb = sizeof(si);
454
455 PROCESS_INFORMATION pi;
456
457 if ( ::CreateProcess(
458 NULL, // application name (use only cmd line)
459 (wxChar *)command.c_str(), // full command line
460 NULL, // security attributes: defaults for both
461 NULL, // the process and its main thread
462 inheritHandles, // inherit handles if we need pipes
463 CREATE_DEFAULT_ERROR_MODE |
464 CREATE_SUSPENDED, // flags
465 NULL, // environment (use the same)
466 NULL, // current directory (use the same)
467 &si, // startup info (unused here)
468 &pi // process info
469 ) == 0 )
470 {
471 if ( inheritHandles )
472 {
473 ::CloseHandle(h_writePipe[0]);
474 ::CloseHandle(h_writePipe[1]);
475 ::CloseHandle(h_readPipe[0]);
476 ::CloseHandle(h_readPipe[1]);
477 }
478
479 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
480
481 return 0;
482 }
483
484 // Restore the old stdio handles
485 if (inheritHandles) {
486 SetStdHandle(STD_INPUT_HANDLE, h_oldreadPipe);
487 SetStdHandle(STD_OUTPUT_HANDLE, h_oldwritePipe);
488
489 ::CloseHandle(h_writePipe[1]);
490 ::CloseHandle(h_readPipe[0]);
491 // We can now initialize the wxStreams
492 wxInputStream *processOutput = new wxPipeInputStream(h_writePipe[0]);
493 wxOutputStream *processInput = new wxPipeOutputStream(h_readPipe[1]);
494
495 handler->SetPipeStreams(processOutput, processInput);
496 }
497
498 // register the class for the hidden window used for the notifications
499 if ( !gs_classForHiddenWindow )
500 {
501 gs_classForHiddenWindow = _T("wxHiddenWindow");
502
503 WNDCLASS wndclass;
504 wxZeroMemory(wndclass);
505 wndclass.lpfnWndProc = (WNDPROC)wxExecuteWindowCbk;
506 wndclass.hInstance = wxGetInstance();
507 wndclass.lpszClassName = gs_classForHiddenWindow;
508
509 if ( !::RegisterClass(&wndclass) )
510 {
511 wxLogLastError("RegisterClass(hidden window)");
512 }
513 }
514
515 // create a hidden window to receive notification about process
516 // termination
517 HWND hwnd = ::CreateWindow(gs_classForHiddenWindow, NULL,
518 WS_OVERLAPPEDWINDOW,
519 0, 0, 0, 0, NULL,
520 (HMENU)NULL, wxGetInstance(), 0);
521 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
522
523 // Alloc data
524 wxExecuteData *data = new wxExecuteData;
525 data->hProcess = pi.hProcess;
526 data->dwProcessId = pi.dwProcessId;
527 data->hWnd = hwnd;
528 data->state = sync;
529 if ( sync )
530 {
531 wxASSERT_MSG( !handler, wxT("wxProcess param ignored for sync execution") );
532
533 data->handler = NULL;
534 }
535 else
536 {
537 // may be NULL or not
538 data->handler = handler;
539 }
540
541 DWORD tid;
542 HANDLE hThread = ::CreateThread(NULL,
543 0,
544 (LPTHREAD_START_ROUTINE)wxExecuteThread,
545 (void *)data,
546 0,
547 &tid);
548
549 // resume process we created now - whether the thread creation succeeded or
550 // not
551 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
552 {
553 // ignore it - what can we do?
554 wxLogLastError("ResumeThread in wxExecute");
555 }
556
557 // close unneeded handle
558 if ( !::CloseHandle(pi.hThread) )
559 wxLogLastError("CloseHandle(hThread)");
560
561 if ( !hThread )
562 {
563 wxLogLastError("CreateThread in wxExecute");
564
565 DestroyWindow(hwnd);
566 delete data;
567
568 // the process still started up successfully...
569 return pi.dwProcessId;
570 }
571
572 #if wxUSE_IPC
573 // second part of DDE hack: now establish the DDE conversation with the
574 // just launched process
575 if ( !!ddeServer )
576 {
577 wxDDEClient client;
578 wxConnectionBase *conn = client.MakeConnection(_T(""),
579 ddeServer,
580 ddeTopic);
581 if ( !conn || !conn->Execute(ddeCommand) )
582 {
583 wxLogError(_("Couldn't launch DDE server '%s'."), command.c_str());
584 }
585 }
586 #endif // wxUSE_IPC
587
588 if ( !sync )
589 {
590 // clean up will be done when the process terminates
591
592 // return the pid
593 return pi.dwProcessId;
594 }
595
596 // waiting until command executed (disable everything while doing it)
597 #if wxUSE_GUI
598 {
599 wxBusyCursor bc;
600
601 wxWindowDisabler wd;
602 #endif // wxUSE_GUI
603
604 while ( data->state )
605 wxYield();
606
607 #if wxUSE_GUI
608 }
609 #endif // wxUSE_GUI
610
611 DWORD dwExitCode = data->dwExitCode;
612 delete data;
613
614 // return the exit code
615 return dwExitCode;
616 #endif // 0/1
617 #else // Win16
618 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
619 if (instanceID < 32) return(0);
620
621 if (sync) {
622 int running;
623 do {
624 wxYield();
625 running = GetModuleUsage((HINSTANCE)instanceID);
626 } while (running);
627 }
628
629 return(instanceID);
630 #endif // Win16/32
631 }
632
633 long wxExecute(char **argv, bool sync, wxProcess *handler)
634 {
635 wxString command;
636
637 while ( *argv != NULL )
638 {
639 command << *argv++ << ' ';
640 }
641
642 command.RemoveLast();
643
644 return wxExecute(command, sync, handler);
645 }
646
647 // ----------------------------------------------------------------------------
648 // Metafile helpers
649 // ----------------------------------------------------------------------------
650
651 extern void PixelToHIMETRIC(LONG *x, LONG *y)
652 {
653 ScreenHDC hdcRef;
654
655 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
656 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
657 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
658 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
659
660 *x *= (iWidthMM * 100);
661 *x /= iWidthPels;
662 *y *= (iHeightMM * 100);
663 *y /= iHeightPels;
664 }
665
666 extern void HIMETRICToPixel(LONG *x, LONG *y)
667 {
668 ScreenHDC hdcRef;
669
670 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
671 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
672 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
673 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
674
675 *x *= iWidthPels;
676 *x /= (iWidthMM * 100);
677 *y *= iHeightPels;
678 *y /= (iHeightMM * 100);
679 }