]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
trying to fix memory leak in wxListCtrl (attributes not deleted)
[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/process.h"
41 #endif
42
43 #include "wx/msw/private.h"
44
45 #include <ctype.h>
46
47 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__)
48 #include <direct.h>
49 #ifndef __MWERKS__
50 #include <dos.h>
51 #endif
52 #endif
53
54 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
55 #include <sys/unistd.h>
56 #include <sys/stat.h>
57 #endif
58
59 #if defined(__WIN32__) && !defined(__WXWINE__)
60 #include <io.h>
61
62 #ifndef __GNUWIN32__
63 #include <shellapi.h>
64 #endif
65 #endif
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #ifndef __WATCOMC__
71 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
72 #include <errno.h>
73 #endif
74 #endif
75 #include <stdarg.h>
76
77 #if wxUSE_IPC
78 #include "wx/dde.h" // for WX_DDE hack in wxExecute
79 #endif // wxUSE_IPC
80
81 // ----------------------------------------------------------------------------
82 // constants
83 // ----------------------------------------------------------------------------
84
85 // this message is sent when the process we're waiting for terminates
86 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
87
88 // ----------------------------------------------------------------------------
89 // this module globals
90 // ----------------------------------------------------------------------------
91
92 // we need to create a hidden window to receive the process termination
93 // notifications and for this we need a (Win) class name for it which we will
94 // register the first time it's needed
95 static const wxChar *gs_classForHiddenWindow = NULL;
96
97 // ----------------------------------------------------------------------------
98 // private types
99 // ----------------------------------------------------------------------------
100
101 // structure describing the process we're being waiting for
102 struct wxExecuteData
103 {
104 public:
105 ~wxExecuteData()
106 {
107 #ifndef __WIN16__
108 if ( !::CloseHandle(hProcess) )
109 {
110 wxLogLastError("CloseHandle(hProcess)");
111 }
112 #endif
113 }
114
115 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
116 HANDLE hProcess; // handle of the process
117 DWORD dwProcessId; // pid of the process
118 wxProcess *handler;
119 DWORD dwExitCode; // the exit code of the process
120 bool state; // set to FALSE when the process finishes
121 };
122
123 // ============================================================================
124 // implementation
125 // ============================================================================
126
127 #ifdef __WIN32__
128 static DWORD wxExecuteThread(wxExecuteData *data)
129 {
130 WaitForSingleObject(data->hProcess, INFINITE);
131
132 // get the exit code
133 if ( !GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
134 {
135 wxLogLastError("GetExitCodeProcess");
136 }
137
138 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
139 wxT("process should have terminated") );
140
141 // send a message indicating process termination to the window
142 SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
143
144 return 0;
145 }
146
147 // window procedure of a hidden window which is created just to receive
148 // the notification message when a process exits
149 LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
150 WPARAM wParam, LPARAM lParam)
151 {
152 if ( message == wxWM_PROC_TERMINATED )
153 {
154 DestroyWindow(hWnd); // we don't need it any more
155
156 wxExecuteData *data = (wxExecuteData *)lParam;
157 if ( data->handler )
158 {
159 data->handler->OnTerminate((int)data->dwProcessId,
160 (int)data->dwExitCode);
161 }
162
163 if ( data->state )
164 {
165 // we're executing synchronously, tell the waiting thread
166 // that the process finished
167 data->state = 0;
168 }
169 else
170 {
171 // asynchronous execution - we should do the clean up
172 delete data;
173 }
174
175 return 0;
176 }
177 else
178 {
179 return DefWindowProc(hWnd, message, wParam, lParam);
180 }
181 }
182 #endif // Win32
183
184 long wxExecute(const wxString& cmd, bool sync, wxProcess *handler)
185 {
186 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
187
188 wxString command;
189 #if wxUSE_IPC
190 // DDE hack: this is really not pretty, but we need to allow this for
191 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
192 // returns the command which should be run to view/open/... a file of the
193 // given type. Sometimes, however, this command just launches the server
194 // and an additional DDE request must be made to really open the file. To
195 // keep all this well hidden from the application, we allow a special form
196 // of command: WX_DDE:<command>:DDE_SERVER:DDE_TOPIC:DDE_COMMAND in which
197 // case we execute just <command> and process the rest below
198 wxString ddeServer, ddeTopic, ddeCommand;
199 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
200 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
201 {
202 const wxChar *p = cmd.c_str() + 7;
203 while ( *p && *p != _T('#') )
204 {
205 command += *p++;
206 }
207
208 if ( *p )
209 {
210 // skip '#'
211 p++;
212 }
213 else
214 {
215 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
216 }
217
218 while ( *p && *p != _T('#') )
219 {
220 ddeServer += *p++;
221 }
222
223 if ( *p )
224 {
225 // skip '#'
226 p++;
227 }
228 else
229 {
230 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
231 }
232
233 while ( *p && *p != _T('#') )
234 {
235 ddeTopic += *p++;
236 }
237
238 if ( *p )
239 {
240 // skip '#'
241 p++;
242 }
243 else
244 {
245 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
246 }
247
248 while ( *p )
249 {
250 ddeCommand += *p++;
251 }
252 }
253 else
254 #endif // wxUSE_IPC
255 {
256 // no DDE
257 command = cmd;
258 }
259
260 #if defined(__WIN32__) && !defined(__TWIN32__)
261 // the old code is disabled because we really need a process handle
262 // if we want to execute it asynchronously or even just get its
263 // return code and for this we must use CreateProcess() and not
264 // ShellExecute()
265 #if 0
266 // isolate command and arguments
267 wxString commandName;
268 bool insideQuotes = FALSE;
269 const char *pc;
270 for ( pc = command.c_str(); *pc != '\0'; pc++ )
271 {
272 switch ( *pc )
273 {
274 case ' ':
275 case '\t':
276 if ( !insideQuotes )
277 break;
278 // fall through
279
280 case '"':
281 insideQuotes = !insideQuotes;
282 // fall through
283
284 default:
285 commandName += *pc;
286 continue; // skip the next break
287 }
288
289 // only reached for space not inside quotes
290 break;
291 }
292
293 wxString commandArgs = pc;
294
295 wxWindow *winTop = wxTheApp->GetTopWindow();
296 HWND hwndTop = (HWND)(winTop ? winTop->GetHWND() : 0);
297
298 HANDLE result;
299 #ifdef __GNUWIN32__
300 result = ShellExecute(hwndTop,
301 (const wchar_t)"open",
302 (const wchar_t)commandName,
303 (const wchar_t)commandArgs,
304 (const wchar_t)NULL,
305 SW_SHOWNORMAL);
306 #else // !GNUWIN32
307 result = ShellExecute(hwndTop, "open", commandName,
308 commandArgs, NULL, SW_SHOWNORMAL);
309 #endif // GNUWIN32
310
311 if ( ((long)result) <= 32 )
312 wxLogSysError(_("Can't execute command '%s'"), command.c_str());
313
314 return result;
315 #else // 1
316
317 // create the process
318 STARTUPINFO si;
319 wxZeroMemory(si);
320
321 si.cb = sizeof(si);
322
323 PROCESS_INFORMATION pi;
324
325 if ( ::CreateProcess(
326 NULL, // application name (use only cmd line)
327 (wxChar *)command.c_str(), // full command line
328 NULL, // security attributes: defaults for both
329 NULL, // the process and its main thread
330 FALSE, // don't inherit handles
331 CREATE_DEFAULT_ERROR_MODE |
332 CREATE_SUSPENDED, // flags
333 NULL, // environment (use the same)
334 NULL, // current directory (use the same)
335 &si, // startup info (unused here)
336 &pi // process info
337 ) == 0 )
338 {
339 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
340
341 return 0;
342 }
343
344 // register the class for the hidden window used for the notifications
345 if ( !gs_classForHiddenWindow )
346 {
347 gs_classForHiddenWindow = _T("wxHiddenWindow");
348
349 WNDCLASS wndclass;
350 wxZeroMemory(wndclass);
351 wndclass.lpfnWndProc = (WNDPROC)wxExecuteWindowCbk;
352 wndclass.hInstance = wxGetInstance();
353 wndclass.lpszClassName = gs_classForHiddenWindow;
354
355 if ( !::RegisterClass(&wndclass) )
356 {
357 wxLogLastError("RegisterClass(hidden window)");
358 }
359 }
360
361 // create a hidden window to receive notification about process
362 // termination
363 HWND hwnd = ::CreateWindow(gs_classForHiddenWindow, NULL,
364 WS_OVERLAPPEDWINDOW,
365 0, 0, 0, 0, NULL,
366 (HMENU)NULL, wxGetInstance(), 0);
367 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
368
369 // Alloc data
370 wxExecuteData *data = new wxExecuteData;
371 data->hProcess = pi.hProcess;
372 data->dwProcessId = pi.dwProcessId;
373 data->hWnd = hwnd;
374 data->state = sync;
375 if ( sync )
376 {
377 wxASSERT_MSG( !handler, wxT("wxProcess param ignored for sync execution") );
378
379 data->handler = NULL;
380 }
381 else
382 {
383 // may be NULL or not
384 data->handler = handler;
385 }
386
387 DWORD tid;
388 HANDLE hThread = ::CreateThread(NULL,
389 0,
390 (LPTHREAD_START_ROUTINE)wxExecuteThread,
391 (void *)data,
392 0,
393 &tid);
394
395 // resume process we created now - whether the thread creation succeeded or
396 // not
397 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
398 {
399 // ignore it - what can we do?
400 wxLogLastError("ResumeThread in wxExecute");
401 }
402
403 // close unneeded handle
404 if ( !::CloseHandle(pi.hThread) )
405 wxLogLastError("CloseHandle(hThread)");
406
407 if ( !hThread )
408 {
409 wxLogLastError("CreateThread in wxExecute");
410
411 DestroyWindow(hwnd);
412 delete data;
413
414 // the process still started up successfully...
415 return pi.dwProcessId;
416 }
417
418 #if wxUSE_IPC
419 // second part of DDE hack: now establish the DDE conversation with the
420 // just launched process
421 if ( !!ddeServer )
422 {
423 wxDDEClient client;
424 wxConnectionBase *conn = client.MakeConnection(_T(""),
425 ddeServer,
426 ddeTopic);
427 if ( !conn || !conn->Execute(ddeCommand) )
428 {
429 wxLogError(_("Couldn't launch DDE server '%s'."), command.c_str());
430 }
431 }
432 #endif // wxUSE_IPC
433
434 if ( !sync )
435 {
436 // clean up will be done when the process terminates
437
438 // return the pid
439 return pi.dwProcessId;
440 }
441
442 // waiting until command executed (disable everything while doing it)
443 #if wxUSE_GUI
444 wxBeginBusyCursor();
445 wxEnableTopLevelWindows(FALSE);
446 #endif // wxUSE_GUI
447
448 while ( data->state )
449 wxYield();
450
451 #if wxUSE_GUI
452 wxEnableTopLevelWindows(TRUE);
453 wxEndBusyCursor();
454 #endif // wxUSE_GUI
455
456 DWORD dwExitCode = data->dwExitCode;
457 delete data;
458
459 // return the exit code
460 return dwExitCode;
461 #endif // 0/1
462 #else // Win16
463 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
464 if (instanceID < 32) return(0);
465
466 if (sync) {
467 int running;
468 do {
469 wxYield();
470 running = GetModuleUsage((HINSTANCE)instanceID);
471 } while (running);
472 }
473
474 return(instanceID);
475 #endif // Win16/32
476 }
477
478 long wxExecute(char **argv, bool sync, wxProcess *handler)
479 {
480 wxString command;
481
482 while ( *argv != NULL )
483 {
484 command << *argv++ << ' ';
485 }
486
487 command.RemoveLast();
488
489 return wxExecute(command, sync, handler);
490 }
491
492 // ----------------------------------------------------------------------------
493 // Metafile helpers
494 // ----------------------------------------------------------------------------
495
496 extern void PixelToHIMETRIC(LONG *x, LONG *y)
497 {
498 ScreenHDC hdcRef;
499
500 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
501 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
502 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
503 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
504
505 *x *= (iWidthMM * 100);
506 *x /= iWidthPels;
507 *y *= (iHeightMM * 100);
508 *y /= iHeightPels;
509 }
510
511 extern void HIMETRICToPixel(LONG *x, LONG *y)
512 {
513 ScreenHDC hdcRef;
514
515 int iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE),
516 iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE),
517 iWidthPels = GetDeviceCaps(hdcRef, HORZRES),
518 iHeightPels = GetDeviceCaps(hdcRef, VERTRES);
519
520 *x *= iWidthPels;
521 *x /= (iWidthMM * 100);
522 *y *= iHeightPels;
523 *y /= (iHeightMM * 100);
524 }