]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
warnings in wxCHeCK_MSG fixed
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
b568d04f 2// Name: msw/utilsexec.cpp
32592631
GL
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
3f4a0c5b 9// Licence: wxWindows license
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
32592631 20#ifdef __GNUG__
b568d04f 21 #pragma implementation
32592631
GL
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
b568d04f 28 #pragma hdrstop
32592631
GL
29#endif
30
31#ifndef WX_PRECOMP
b568d04f
VZ
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
32592631
GL
35#endif
36
3e64d4e1 37#include "wx/log.h"
1044a386
JS
38
39#ifdef __WIN32__
8b33ae2d 40 #include "wx/stream.h"
b568d04f 41 #include "wx/process.h"
1044a386 42#endif
dbeac4bd 43
32592631 44#include "wx/msw/private.h"
dbeac4bd 45
32592631
GL
46#include <ctype.h>
47
5ea105e0 48#if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
b568d04f 49 #include <direct.h>
17dff81c 50#ifndef __MWERKS__
b568d04f 51 #include <dos.h>
32592631 52#endif
17dff81c 53#endif
32592631 54
b568d04f
VZ
55#if defined(__GNUWIN32__) && !defined(__TWIN32__)
56 #include <sys/unistd.h>
57 #include <sys/stat.h>
57c208c5 58#endif
32592631 59
5ea105e0 60#if defined(__WIN32__) && !defined(__WXWINE__)
32592631
GL
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__
3f4a0c5b
VZ
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
73 #include <errno.h>
74 #endif
32592631
GL
75#endif
76#include <stdarg.h>
77
731dd422
VZ
78#if wxUSE_IPC
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
80#endif // wxUSE_IPC
5bd3a2da 81
b568d04f
VZ
82// ----------------------------------------------------------------------------
83// constants
84// ----------------------------------------------------------------------------
85
cb6827a8
VZ
86// this message is sent when the process we're waiting for terminates
87#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 88
b568d04f
VZ
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
96static const wxChar *gs_classForHiddenWindow = NULL;
97
98// ----------------------------------------------------------------------------
99// private types
100// ----------------------------------------------------------------------------
101
cb6827a8
VZ
102// structure describing the process we're being waiting for
103struct wxExecuteData
104{
105public:
106 ~wxExecuteData()
107 {
750b78ba 108#ifndef __WIN16__
cb6827a8
VZ
109 if ( !::CloseHandle(hProcess) )
110 {
111 wxLogLastError("CloseHandle(hProcess)");
112 }
750b78ba 113#endif
cb6827a8
VZ
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
32592631
GL
122};
123
8b33ae2d
GL
124
125#ifdef __WIN32__
126// ----------------------------------------------------------------------------
127// wxPipeStreams
128// ----------------------------------------------------------------------------
129
130class wxPipeInputStream: public wxInputStream {
131public:
132 wxPipeInputStream(HANDLE hInput);
133 ~wxPipeInputStream();
134
135protected:
136 size_t OnSysRead(void *buffer, size_t len);
137
138protected:
139 HANDLE m_hInput;
140};
141
142class wxPipeOutputStream: public wxOutputStream {
143public:
144 wxPipeOutputStream(HANDLE hOutput);
145 ~wxPipeOutputStream();
146
147protected:
148 size_t OnSysWrite(const void *buffer, size_t len);
149
150protected:
151 HANDLE m_hOutput;
152};
153
154// ==================
155// wxPipeInputStream
156// ==================
157
158wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
159{
160 m_hInput = hInput;
cd6ce4a9 161}
8b33ae2d
GL
162
163wxPipeInputStream::~wxPipeInputStream()
164{
165 ::CloseHandle(m_hInput);
166}
167
168size_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
186wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
187{
188 m_hOutput = hOutput;
cd6ce4a9 189}
8b33ae2d
GL
190
191wxPipeOutputStream::~wxPipeOutputStream()
192{
193 ::CloseHandle(m_hOutput);
194}
195
196size_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
b568d04f
VZ
212// ============================================================================
213// implementation
214// ============================================================================
5260b1c5
JS
215
216#ifdef __WIN32__
32592631
GL
217static DWORD wxExecuteThread(wxExecuteData *data)
218{
cb6827a8
VZ
219 WaitForSingleObject(data->hProcess, INFINITE);
220
221 // get the exit code
222 if ( !GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
223 {
224 wxLogLastError("GetExitCodeProcess");
225 }
32592631 226
cb6827a8 227 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
223d09f6 228 wxT("process should have terminated") );
32592631 229
cb6827a8
VZ
230 // send a message indicating process termination to the window
231 SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
e6045e08 232
cb6827a8 233 return 0;
32592631 234}
5260b1c5 235
cb6827a8
VZ
236// window procedure of a hidden window which is created just to receive
237// the notification message when a process exits
32592631
GL
238LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
239 WPARAM wParam, LPARAM lParam)
240{
cb6827a8
VZ
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 }
e6045e08 251
cb6827a8
VZ
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 }
cb6827a8 263
0d7ea902
VZ
264 return 0;
265 }
266 else
267 {
268 return DefWindowProc(hWnd, message, wParam, lParam);
269 }
32592631 270}
731dd422 271#endif // Win32
32592631 272
5bd3a2da 273long wxExecute(const wxString& cmd, bool sync, wxProcess *handler)
32592631 274{
5bd3a2da
VZ
275 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
276
039f62f4 277 wxString command;
731dd422 278#if wxUSE_IPC
5bd3a2da
VZ
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
039f62f4 287 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da
VZ
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
731dd422 343#endif // wxUSE_IPC
5bd3a2da
VZ
344 {
345 // no DDE
346 command = cmd;
347 }
32592631 348
57c208c5 349#if defined(__WIN32__) && !defined(__TWIN32__)
cb6827a8
VZ
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 }
cb6827a8
VZ
381 wxString commandArgs = pc;
382
383 wxWindow *winTop = wxTheApp->GetTopWindow();
384 HWND hwndTop = (HWND)(winTop ? winTop->GetHWND() : 0);
385
386 HANDLE result;
32592631 387#ifdef __GNUWIN32__
cb6827a8
VZ
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
e6045e08 398
cb6827a8
VZ
399 if ( ((long)result) <= 32 )
400 wxLogSysError(_("Can't execute command '%s'"), command.c_str());
401
402 return result;
403#else // 1
cd6ce4a9 404
5e1febfa
VZ
405 HANDLE hpipeRead[2];
406 HANDLE hpipeWrite[2];
407 HANDLE hStdIn = INVALID_HANDLE_VALUE;
408 HANDLE hStdOut = INVALID_HANDLE_VALUE;
409
410 // we need to inherit handles in the child process if we want to redirect
411 // its IO
412 BOOL inheritHandles = FALSE;
8b33ae2d 413
cd6ce4a9 414 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
415 if ( handler && handler->IsRedirected() )
416 {
8b33ae2d
GL
417 SECURITY_ATTRIBUTES security;
418
419 security.nLength = sizeof(security);
420 security.lpSecurityDescriptor = NULL;
421 security.bInheritHandle = TRUE;
422
5e1febfa 423 if ( !::CreatePipe(&hpipeRead[0], &hpipeRead[1], &security, 0) )
cd6ce4a9
VZ
424 {
425 wxLogSysError(_("Can't create the inter-process read pipe"));
8b33ae2d
GL
426
427 return 0;
428 }
429
5e1febfa 430 if ( !::CreatePipe(&hpipeWrite[0], &hpipeWrite[1], &security, 0) )
cd6ce4a9 431 {
5e1febfa
VZ
432 ::CloseHandle(hpipeRead[0]);
433 ::CloseHandle(hpipeRead[1]);
cd6ce4a9
VZ
434
435 wxLogSysError(_("Can't create the inter-process write pipe"));
8b33ae2d
GL
436
437 return 0;
438 }
439
440 // We need to save the old stdio handles to restore them after the call
441 // to CreateProcess
5e1febfa
VZ
442 hStdIn = ::GetStdHandle(STD_INPUT_HANDLE);
443 hStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
8b33ae2d 444
5e1febfa
VZ
445 if ( !::SetStdHandle(STD_INPUT_HANDLE, hpipeRead[0]) ||
446 !::SetStdHandle(STD_OUTPUT_HANDLE, hpipeWrite[1]) )
447 {
448 wxLogDebug(_T("Failed to change stdin/out handles"));
449 }
8b33ae2d
GL
450
451 inheritHandles = TRUE;
452 }
5bd3a2da 453
cb6827a8
VZ
454 // create the process
455 STARTUPINFO si;
11c7d5b6 456 wxZeroMemory(si);
cf0b3979 457
cb6827a8
VZ
458 si.cb = sizeof(si);
459
460 PROCESS_INFORMATION pi;
461
462 if ( ::CreateProcess(
463 NULL, // application name (use only cmd line)
837e5743 464 (wxChar *)command.c_str(), // full command line
cb6827a8
VZ
465 NULL, // security attributes: defaults for both
466 NULL, // the process and its main thread
8b33ae2d 467 inheritHandles, // inherit handles if we need pipes
0d7ea902
VZ
468 CREATE_DEFAULT_ERROR_MODE |
469 CREATE_SUSPENDED, // flags
cb6827a8
VZ
470 NULL, // environment (use the same)
471 NULL, // current directory (use the same)
472 &si, // startup info (unused here)
473 &pi // process info
474 ) == 0 )
475 {
cd6ce4a9
VZ
476 if ( inheritHandles )
477 {
5e1febfa
VZ
478 ::CloseHandle(hpipeWrite[0]);
479 ::CloseHandle(hpipeWrite[1]);
480 ::CloseHandle(hpipeRead[0]);
481 ::CloseHandle(hpipeRead[1]);
8b33ae2d 482 }
cd6ce4a9 483
cb6827a8
VZ
484 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
485
486 return 0;
487 }
488
8b33ae2d 489 // Restore the old stdio handles
5e1febfa
VZ
490 if ( inheritHandles )
491 {
492 if ( !::SetStdHandle(STD_INPUT_HANDLE, hStdIn) ||
493 !::SetStdHandle(STD_OUTPUT_HANDLE, hStdOut) )
494 {
495 wxLogDebug(_T("Failed to restore old stdin/out handles"));
496 }
497
498 // they're still opened in child process
499 ::CloseHandle(hpipeWrite[1]);
500 ::CloseHandle(hpipeRead[0]);
8b33ae2d 501
8b33ae2d 502 // We can now initialize the wxStreams
5e1febfa
VZ
503 wxInputStream *inStream = new wxPipeInputStream(hpipeWrite[0]);
504 wxOutputStream *outStream = new wxPipeOutputStream(hpipeRead[1]);
8b33ae2d 505
5e1febfa 506 handler->SetPipeStreams(inStream, outStream);
8b33ae2d
GL
507 }
508
0d7ea902 509 // register the class for the hidden window used for the notifications
b568d04f
VZ
510 if ( !gs_classForHiddenWindow )
511 {
512 gs_classForHiddenWindow = _T("wxHiddenWindow");
513
514 WNDCLASS wndclass;
515 wxZeroMemory(wndclass);
516 wndclass.lpfnWndProc = (WNDPROC)wxExecuteWindowCbk;
517 wndclass.hInstance = wxGetInstance();
518 wndclass.lpszClassName = gs_classForHiddenWindow;
519
520 if ( !::RegisterClass(&wndclass) )
521 {
522 wxLogLastError("RegisterClass(hidden window)");
b568d04f
VZ
523 }
524 }
525
cb6827a8
VZ
526 // create a hidden window to receive notification about process
527 // termination
b568d04f 528 HWND hwnd = ::CreateWindow(gs_classForHiddenWindow, NULL,
0d7ea902
VZ
529 WS_OVERLAPPEDWINDOW,
530 0, 0, 0, 0, NULL,
cb6827a8 531 (HMENU)NULL, wxGetInstance(), 0);
223d09f6 532 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 533
cb6827a8
VZ
534 // Alloc data
535 wxExecuteData *data = new wxExecuteData;
536 data->hProcess = pi.hProcess;
537 data->dwProcessId = pi.dwProcessId;
538 data->hWnd = hwnd;
539 data->state = sync;
e6045e08
VZ
540 if ( sync )
541 {
5e1febfa
VZ
542 // handler may be !NULL for capturing program output, but we don't use
543 // it wxExecuteData struct in this case
e6045e08
VZ
544 data->handler = NULL;
545 }
546 else
547 {
548 // may be NULL or not
549 data->handler = handler;
550 }
cb6827a8
VZ
551
552 DWORD tid;
553 HANDLE hThread = ::CreateThread(NULL,
554 0,
555 (LPTHREAD_START_ROUTINE)wxExecuteThread,
556 (void *)data,
557 0,
558 &tid);
559
0d7ea902
VZ
560 // resume process we created now - whether the thread creation succeeded or
561 // not
562 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
563 {
564 // ignore it - what can we do?
565 wxLogLastError("ResumeThread in wxExecute");
566 }
567
568 // close unneeded handle
569 if ( !::CloseHandle(pi.hThread) )
570 wxLogLastError("CloseHandle(hThread)");
571
cb6827a8
VZ
572 if ( !hThread )
573 {
574 wxLogLastError("CreateThread in wxExecute");
575
576 DestroyWindow(hwnd);
577 delete data;
578
579 // the process still started up successfully...
580 return pi.dwProcessId;
581 }
e6045e08 582
731dd422 583#if wxUSE_IPC
5bd3a2da
VZ
584 // second part of DDE hack: now establish the DDE conversation with the
585 // just launched process
586 if ( !!ddeServer )
587 {
588 wxDDEClient client;
589 wxConnectionBase *conn = client.MakeConnection(_T(""),
590 ddeServer,
591 ddeTopic);
592 if ( !conn || !conn->Execute(ddeCommand) )
593 {
594 wxLogError(_("Couldn't launch DDE server '%s'."), command.c_str());
595 }
596 }
731dd422 597#endif // wxUSE_IPC
5bd3a2da 598
cb6827a8
VZ
599 if ( !sync )
600 {
601 // clean up will be done when the process terminates
e6045e08
VZ
602
603 // return the pid
cb6827a8
VZ
604 return pi.dwProcessId;
605 }
e6045e08 606
0d7ea902
VZ
607 // waiting until command executed (disable everything while doing it)
608#if wxUSE_GUI
cd6ce4a9
VZ
609 {
610 wxBusyCursor bc;
611
612 wxWindowDisabler wd;
0d7ea902
VZ
613#endif // wxUSE_GUI
614
cb6827a8
VZ
615 while ( data->state )
616 wxYield();
e6045e08 617
0d7ea902 618#if wxUSE_GUI
cd6ce4a9 619 }
0d7ea902
VZ
620#endif // wxUSE_GUI
621
e6045e08 622 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
623 delete data;
624
e6045e08
VZ
625 // return the exit code
626 return dwExitCode;
cb6827a8
VZ
627#endif // 0/1
628#else // Win16
629 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
630 if (instanceID < 32) return(0);
e6045e08 631
cb6827a8
VZ
632 if (sync) {
633 int running;
634 do {
635 wxYield();
27a9bd48 636 running = GetModuleUsage((HINSTANCE)instanceID);
cb6827a8
VZ
637 } while (running);
638 }
639
640 return(instanceID);
641#endif // Win16/32
32592631 642}
c740f496
GL
643
644long wxExecute(char **argv, bool sync, wxProcess *handler)
645{
cb6827a8 646 wxString command;
e6045e08 647
cb6827a8
VZ
648 while ( *argv != NULL )
649 {
650 command << *argv++ << ' ';
651 }
652
653 command.RemoveLast();
654
655 return wxExecute(command, sync, handler);
c740f496 656}
006162a9 657
d9317fd4
VZ
658// ----------------------------------------------------------------------------
659// Metafile helpers
660// ----------------------------------------------------------------------------
661
662extern void PixelToHIMETRIC(LONG *x, LONG *y)
663{
664 ScreenHDC hdcRef;
665
666 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
667 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
668 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
669 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
670
671 *x *= (iWidthMM * 100);
672 *x /= iWidthPels;
673 *y *= (iHeightMM * 100);
674 *y /= iHeightPels;
675}
676
677extern void HIMETRICToPixel(LONG *x, LONG *y)
678{
679 ScreenHDC hdcRef;
680
681 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
682 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
683 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
684 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
685
686 *x *= iWidthPels;
687 *x /= (iWidthMM * 100);
688 *y *= iHeightPels;
689 *y /= (iHeightMM * 100);
690}