w32api 2.0 will have shlwapi.h
[wxWidgets.git] / src / msw / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
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 "app.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #if defined(__BORLANDC__)
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/frame.h"
33 #include "wx/app.h"
34 #include "wx/utils.h"
35 #include "wx/gdicmn.h"
36 #include "wx/pen.h"
37 #include "wx/brush.h"
38 #include "wx/cursor.h"
39 #include "wx/icon.h"
40 #include "wx/palette.h"
41 #include "wx/dc.h"
42 #include "wx/dialog.h"
43 #include "wx/msgdlg.h"
44 #include "wx/intl.h"
45 #include "wx/dynarray.h"
46 #include "wx/wxchar.h"
47 #include "wx/icon.h"
48 #include "wx/log.h"
49 #endif
50
51 #include "wx/cmdline.h"
52 #include "wx/filename.h"
53 #include "wx/module.h"
54
55 #include "wx/msw/private.h"
56
57 #if wxUSE_THREADS
58 #include "wx/thread.h"
59
60 // define the array of MSG strutures
61 WX_DECLARE_OBJARRAY(MSG, wxMsgArray);
62
63 #include "wx/arrimpl.cpp"
64
65 WX_DEFINE_OBJARRAY(wxMsgArray);
66 #endif // wxUSE_THREADS
67
68 #if wxUSE_WX_RESOURCES
69 #include "wx/resource.h"
70 #endif
71
72 #if wxUSE_TOOLTIPS
73 #include "wx/tooltip.h"
74 #endif // wxUSE_TOOLTIPS
75
76 // OLE is used for drag-and-drop, clipboard, OLE Automation..., but some
77 // compilers don't support it (missing headers, libs, ...)
78 #if defined(__GNUWIN32_OLD__) || defined(__SC__) || defined(__SALFORDC__)
79 #undef wxUSE_OLE
80
81 #define wxUSE_OLE 0
82 #endif // broken compilers
83
84 #if wxUSE_OLE
85 #include <ole2.h>
86 #endif
87
88 #include <string.h>
89 #include <ctype.h>
90
91 #if defined(__WIN95__) && !((defined(__GNUWIN32_OLD__) || defined(__TWIN32__) || defined(__WXMICROWIN__)) && !defined(__CYGWIN10__))
92 #include <commctrl.h>
93 #endif
94
95 #ifndef __WXMICROWIN__
96 #include "wx/msw/msvcrt.h"
97 #endif
98
99 // ----------------------------------------------------------------------------
100 // conditional compilation
101 // ----------------------------------------------------------------------------
102
103 // The macro _WIN32_IE is defined by commctrl.h (unless it had already been
104 // defined before) and shows us what common control features are available
105 // during the compile time (it doesn't mean that they will be available during
106 // the run-time, use GetComCtl32Version() to test for them!). The possible
107 // values are:
108 //
109 // 0x0200 for comctl32.dll 4.00 shipped with Win95/NT 4.0
110 // 0x0300 4.70 IE 3.x
111 // 0x0400 4.71 IE 4.0
112 // 0x0401 4.72 IE 4.01 and Win98
113 // 0x0500 5.00 IE 5.x and NT 5.0 (Win2000)
114
115 #ifndef _WIN32_IE
116 // minimal set of features by default
117 #define _WIN32_IE 0x0200
118 #endif
119
120 #if _WIN32_IE >= 0x0300 && \
121 (!defined(__MINGW32__) || wxCHECK_W32API_VERSION( 2, 0 ))
122 #include <shlwapi.h>
123 #endif
124
125 // ---------------------------------------------------------------------------
126 // global variables
127 // ---------------------------------------------------------------------------
128
129 extern wxChar *wxBuffer;
130 extern wxList WXDLLEXPORT wxPendingDelete;
131 #ifndef __WXMICROWIN__
132 extern void wxSetKeyboardHook(bool doIt);
133 #endif
134
135 MSG s_currentMsg;
136 wxApp *wxTheApp = NULL;
137
138 // NB: all "NoRedraw" classes must have the same names as the "normal" classes
139 // with NR suffix - wxWindow::MSWCreate() supposes this
140 const wxChar *wxCanvasClassName = wxT("wxWindowClass");
141 const wxChar *wxCanvasClassNameNR = wxT("wxWindowClassNR");
142 const wxChar *wxMDIFrameClassName = wxT("wxMDIFrameClass");
143 const wxChar *wxMDIFrameClassNameNoRedraw = wxT("wxMDIFrameClassNR");
144 const wxChar *wxMDIChildFrameClassName = wxT("wxMDIChildFrameClass");
145 const wxChar *wxMDIChildFrameClassNameNoRedraw = wxT("wxMDIChildFrameClassNR");
146
147 HICON wxSTD_FRAME_ICON = (HICON) NULL;
148 HICON wxSTD_MDICHILDFRAME_ICON = (HICON) NULL;
149 HICON wxSTD_MDIPARENTFRAME_ICON = (HICON) NULL;
150
151 HICON wxDEFAULT_FRAME_ICON = (HICON) NULL;
152 HICON wxDEFAULT_MDICHILDFRAME_ICON = (HICON) NULL;
153 HICON wxDEFAULT_MDIPARENTFRAME_ICON = (HICON) NULL;
154
155 HBRUSH wxDisableButtonBrush = (HBRUSH) 0;
156
157 LRESULT WXDLLEXPORT APIENTRY wxWndProc(HWND, UINT, WPARAM, LPARAM);
158
159 // FIXME wxUSE_ON_FATAL_EXCEPTION is only supported for VC++ now because it
160 // needs compiler support for Win32 SEH. Others (especially Borland)
161 // probably have it too, but I'm not sure about how it works
162 // JACS: get 'Cannot use __try in functions that require unwinding
163 // in Unicode mode, so disabling.
164 #if !defined(__VISUALC__) || defined(__WIN16__) || defined(UNICODE)
165 #undef wxUSE_ON_FATAL_EXCEPTION
166 #define wxUSE_ON_FATAL_EXCEPTION 0
167 #endif // VC++
168
169 #if wxUSE_ON_FATAL_EXCEPTION
170 static bool gs_handleExceptions = FALSE;
171 #endif
172
173 // ===========================================================================
174 // implementation
175 // ===========================================================================
176
177 // ---------------------------------------------------------------------------
178 // wxApp
179 // ---------------------------------------------------------------------------
180
181 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
182
183 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
184 EVT_IDLE(wxApp::OnIdle)
185 EVT_END_SESSION(wxApp::OnEndSession)
186 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
187 END_EVENT_TABLE()
188
189 //// Initialize
190 bool wxApp::Initialize()
191 {
192 // the first thing to do is to check if we're trying to run an Unicode
193 // program under Win9x w/o MSLU emulation layer - if so, abort right now
194 // as it has no chance to work
195 #if wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
196 if ( wxGetOsVersion() != wxWINDOWS_NT )
197 {
198 // note that we can use MessageBoxW() as it's implemented even under
199 // Win9x - OTOH, we can't use wxGetTranslation() because the file APIs
200 // used by wxLocale are not
201 ::MessageBox
202 (
203 NULL,
204 _T("This program uses Unicode and requires Windows NT/2000/XP.\nProgram aborted."),
205 _T("wxWindows Fatal Error"),
206 MB_ICONERROR | MB_OK
207 );
208
209 return FALSE;
210 }
211 #endif // wxUSE_UNICODE && !wxUSE_UNICODE_MSLU
212
213 wxBuffer = new wxChar[1500]; // FIXME
214
215 wxClassInfo::InitializeClasses();
216
217 #if wxUSE_THREADS
218 wxPendingEventsLocker = new wxCriticalSection;
219 #endif
220
221 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
222 wxTheColourDatabase->Initialize();
223
224 wxInitializeStockLists();
225 wxInitializeStockObjects();
226
227 #if wxUSE_WX_RESOURCES
228 wxInitializeResourceSystem();
229 #endif
230
231 wxBitmap::InitStandardHandlers();
232
233 #if defined(__WIN95__) && !defined(__WXMICROWIN__)
234 InitCommonControls();
235 #endif // __WIN95__
236
237 #if wxUSE_OLE || wxUSE_DRAG_AND_DROP
238
239 #ifdef __WIN16__
240 // for OLE, enlarge message queue to be as large as possible
241 int iMsg = 96;
242 while (!SetMessageQueue(iMsg) && (iMsg -= 8))
243 ;
244 #endif // Win16
245
246 #if wxUSE_OLE
247 // we need to initialize OLE library
248 if ( FAILED(::OleInitialize(NULL)) )
249 wxLogError(_("Cannot initialize OLE"));
250 #endif
251
252 #endif // wxUSE_OLE
253
254 #if wxUSE_CTL3D
255 if (!Ctl3dRegister(wxhInstance))
256 wxLogError(wxT("Cannot register CTL3D"));
257
258 Ctl3dAutoSubclass(wxhInstance);
259 #endif // wxUSE_CTL3D
260
261 // VZ: these icons are not in wx.rc anyhow (but should they?)!
262 #if 0
263 wxSTD_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_FRAME"));
264 wxSTD_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDIPARENTFRAME"));
265 wxSTD_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxSTD_MDICHILDFRAME"));
266
267 wxDEFAULT_FRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_FRAME"));
268 wxDEFAULT_MDIPARENTFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDIPARENTFRAME"));
269 wxDEFAULT_MDICHILDFRAME_ICON = LoadIcon(wxhInstance, wxT("wxDEFAULT_MDICHILDFRAME"));
270 #endif // 0
271
272 RegisterWindowClasses();
273
274 #ifndef __WXMICROWIN__
275 // Create the brush for disabling bitmap buttons
276
277 LOGBRUSH lb;
278 lb.lbStyle = BS_PATTERN;
279 lb.lbColor = 0;
280 lb.lbHatch = (int)LoadBitmap( wxhInstance, wxT("wxDISABLE_BUTTON_BITMAP") );
281 if ( lb.lbHatch )
282 {
283 wxDisableButtonBrush = ::CreateBrushIndirect( & lb );
284 ::DeleteObject( (HGDIOBJ)lb.lbHatch );
285 }
286 //else: wxWindows resources are probably not linked in
287 #endif
288
289 #if wxUSE_PENWINDOWS
290 wxRegisterPenWin();
291 #endif
292
293 wxWinHandleHash = new wxWinHashTable(wxKEY_INTEGER, 100);
294
295 // This is to foil optimizations in Visual C++ that throw out dummy.obj.
296 // PLEASE DO NOT ALTER THIS.
297 #if defined(__VISUALC__) && defined(__WIN16__) && !defined(WXMAKINGDLL)
298 extern char wxDummyChar;
299 if (wxDummyChar) wxDummyChar++;
300 #endif
301
302 #ifndef __WXMICROWIN__
303 wxSetKeyboardHook(TRUE);
304 #endif
305
306 wxModule::RegisterModules();
307 if (!wxModule::InitializeModules())
308 return FALSE;
309 return TRUE;
310 }
311
312 // ---------------------------------------------------------------------------
313 // RegisterWindowClasses
314 // ---------------------------------------------------------------------------
315
316 // TODO we should only register classes really used by the app. For this it
317 // would be enough to just delay the class registration until an attempt
318 // to create a window of this class is made.
319 bool wxApp::RegisterWindowClasses()
320 {
321 WNDCLASS wndclass;
322 wxZeroMemory(wndclass);
323
324 // for each class we register one with CS_(V|H)REDRAW style and one
325 // without for windows created with wxNO_FULL_REDRAW_ON_REPAINT flag
326 static const long styleNormal = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
327 static const long styleNoRedraw = CS_DBLCLKS;
328
329 // the fields which are common to all classes
330 wndclass.lpfnWndProc = (WNDPROC)wxWndProc;
331 wndclass.hInstance = wxhInstance;
332 wndclass.hCursor = ::LoadCursor((HINSTANCE)NULL, IDC_ARROW);
333
334 // Register the frame window class.
335 wndclass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE + 1);
336 wndclass.lpszClassName = wxCanvasClassName;
337 wndclass.style = styleNormal;
338
339 if ( !RegisterClass(&wndclass) )
340 {
341 wxLogLastError(wxT("RegisterClass(frame)"));
342 }
343
344 // "no redraw" frame
345 wndclass.lpszClassName = wxCanvasClassNameNR;
346 wndclass.style = styleNoRedraw;
347
348 if ( !RegisterClass(&wndclass) )
349 {
350 wxLogLastError(wxT("RegisterClass(no redraw frame)"));
351 }
352
353 // Register the MDI frame window class.
354 wndclass.hbrBackground = (HBRUSH)NULL; // paint MDI frame ourselves
355 wndclass.lpszClassName = wxMDIFrameClassName;
356 wndclass.style = styleNormal;
357
358 if ( !RegisterClass(&wndclass) )
359 {
360 wxLogLastError(wxT("RegisterClass(MDI parent)"));
361 }
362
363 // "no redraw" MDI frame
364 wndclass.lpszClassName = wxMDIFrameClassNameNoRedraw;
365 wndclass.style = styleNoRedraw;
366
367 if ( !RegisterClass(&wndclass) )
368 {
369 wxLogLastError(wxT("RegisterClass(no redraw MDI parent frame)"));
370 }
371
372 // Register the MDI child frame window class.
373 wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
374 wndclass.lpszClassName = wxMDIChildFrameClassName;
375 wndclass.style = styleNormal;
376
377 if ( !RegisterClass(&wndclass) )
378 {
379 wxLogLastError(wxT("RegisterClass(MDI child)"));
380 }
381
382 // "no redraw" MDI child frame
383 wndclass.lpszClassName = wxMDIChildFrameClassNameNoRedraw;
384 wndclass.style = styleNoRedraw;
385
386 if ( !RegisterClass(&wndclass) )
387 {
388 wxLogLastError(wxT("RegisterClass(no redraw MDI child)"));
389 }
390
391 return TRUE;
392 }
393
394 // ---------------------------------------------------------------------------
395 // UnregisterWindowClasses
396 // ---------------------------------------------------------------------------
397
398 bool wxApp::UnregisterWindowClasses()
399 {
400 bool retval = TRUE;
401
402 #ifndef __WXMICROWIN__
403 // MDI frame window class.
404 if ( !::UnregisterClass(wxMDIFrameClassName, wxhInstance) )
405 {
406 wxLogLastError(wxT("UnregisterClass(MDI parent)"));
407
408 retval = FALSE;
409 }
410
411 // "no redraw" MDI frame
412 if ( !::UnregisterClass(wxMDIFrameClassNameNoRedraw, wxhInstance) )
413 {
414 wxLogLastError(wxT("UnregisterClass(no redraw MDI parent frame)"));
415
416 retval = FALSE;
417 }
418
419 // MDI child frame window class.
420 if ( !::UnregisterClass(wxMDIChildFrameClassName, wxhInstance) )
421 {
422 wxLogLastError(wxT("UnregisterClass(MDI child)"));
423
424 retval = FALSE;
425 }
426
427 // "no redraw" MDI child frame
428 if ( !::UnregisterClass(wxMDIChildFrameClassNameNoRedraw, wxhInstance) )
429 {
430 wxLogLastError(wxT("UnregisterClass(no redraw MDI child)"));
431
432 retval = FALSE;
433 }
434
435 // canvas class name
436 if ( !::UnregisterClass(wxCanvasClassName, wxhInstance) )
437 {
438 wxLogLastError(wxT("UnregisterClass(canvas)"));
439
440 retval = FALSE;
441 }
442
443 if ( !::UnregisterClass(wxCanvasClassNameNR, wxhInstance) )
444 {
445 wxLogLastError(wxT("UnregisterClass(no redraw canvas)"));
446
447 retval = FALSE;
448 }
449 #endif // __WXMICROWIN__
450
451 return retval;
452 }
453
454 // ---------------------------------------------------------------------------
455 // Convert Windows to argc, argv style
456 // ---------------------------------------------------------------------------
457
458 void wxApp::ConvertToStandardCommandArgs(const char* lpCmdLine)
459 {
460 // break the command line in words
461 wxArrayString args =
462 wxCmdLineParser::ConvertStringToArgs(wxConvertMB2WX(lpCmdLine));
463
464 // +1 here for the program name
465 argc = args.GetCount() + 1;
466
467 // and +1 here for the terminating NULL
468 argv = new wxChar *[argc + 1];
469
470 argv[0] = new wxChar[260]; // 260 is MAX_PATH value from windef.h
471 ::GetModuleFileName(wxhInstance, argv[0], 260);
472
473 // also set the app name from argv[0]
474 wxString name;
475 wxFileName::SplitPath(argv[0], NULL, &name, NULL);
476
477 SetAppName(name);
478
479 // copy all the other arguments to wxApp::argv[]
480 for ( int i = 1; i < argc; i++ )
481 {
482 argv[i] = copystring(args[i - 1]);
483 }
484
485 // argv[] must be NULL-terminated
486 argv[argc] = NULL;
487 }
488
489 //// Cleans up any wxWindows internal structures left lying around
490
491 void wxApp::CleanUp()
492 {
493 //// COMMON CLEANUP
494
495 #if wxUSE_LOG
496 // flush the logged messages if any and install a 'safer' log target: the
497 // default one (wxLogGui) can't be used after the resources are freed just
498 // below and the user suppliedo ne might be even more unsafe (using any
499 // wxWindows GUI function is unsafe starting from now)
500 wxLog::DontCreateOnDemand();
501
502 // this will flush the old messages if any
503 delete wxLog::SetActiveTarget(new wxLogStderr);
504 #endif // wxUSE_LOG
505
506 // One last chance for pending objects to be cleaned up
507 wxTheApp->DeletePendingObjects();
508
509 wxModule::CleanUpModules();
510
511 #if wxUSE_WX_RESOURCES
512 wxCleanUpResourceSystem();
513
514 // wxDefaultResourceTable->ClearTable();
515 #endif
516
517 wxDeleteStockObjects();
518
519 // Destroy all GDI lists, etc.
520 wxDeleteStockLists();
521
522 delete wxTheColourDatabase;
523 wxTheColourDatabase = NULL;
524
525 wxBitmap::CleanUpHandlers();
526
527 delete[] wxBuffer;
528 wxBuffer = NULL;
529
530 //// WINDOWS-SPECIFIC CLEANUP
531
532 #ifndef __WXMICROWIN__
533 wxSetKeyboardHook(FALSE);
534 #endif
535
536 #if wxUSE_PENWINDOWS
537 wxCleanUpPenWin();
538 #endif
539
540 if (wxSTD_FRAME_ICON)
541 DestroyIcon(wxSTD_FRAME_ICON);
542 if (wxSTD_MDICHILDFRAME_ICON)
543 DestroyIcon(wxSTD_MDICHILDFRAME_ICON);
544 if (wxSTD_MDIPARENTFRAME_ICON)
545 DestroyIcon(wxSTD_MDIPARENTFRAME_ICON);
546
547 if (wxDEFAULT_FRAME_ICON)
548 DestroyIcon(wxDEFAULT_FRAME_ICON);
549 if (wxDEFAULT_MDICHILDFRAME_ICON)
550 DestroyIcon(wxDEFAULT_MDICHILDFRAME_ICON);
551 if (wxDEFAULT_MDIPARENTFRAME_ICON)
552 DestroyIcon(wxDEFAULT_MDIPARENTFRAME_ICON);
553
554 if ( wxDisableButtonBrush )
555 ::DeleteObject( wxDisableButtonBrush );
556
557 #if wxUSE_OLE
558 ::OleUninitialize();
559 #endif
560
561 #ifdef WXMAKINGDLL
562 // for an EXE the classes are unregistered when it terminates but DLL may
563 // be loaded several times (load/unload/load) into the same process in
564 // which case the registration will fail after the first time if we don't
565 // unregister the classes now
566 UnregisterWindowClasses();
567 #endif // WXMAKINGDLL
568
569 #if wxUSE_CTL3D
570 Ctl3dUnregister(wxhInstance);
571 #endif
572
573 delete wxWinHandleHash;
574
575 // GL: I'm annoyed ... I don't know where to put this and I don't want to
576 // create a module for that as it's part of the core.
577 delete wxPendingEvents;
578
579 #if wxUSE_THREADS
580 delete wxPendingEventsLocker;
581 // If we don't do the following, we get an apparent memory leak
582 #if wxUSE_VALIDATORS
583 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
584 #endif // wxUSE_VALIDATORS
585 #endif // wxUSE_THREADS
586
587 wxClassInfo::CleanUpClasses();
588
589 delete wxTheApp;
590 wxTheApp = NULL;
591
592 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
593 // At this point we want to check if there are any memory
594 // blocks that aren't part of the wxDebugContext itself,
595 // as a special case. Then when dumping we need to ignore
596 // wxDebugContext, too.
597 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
598 {
599 wxLogMessage(wxT("There were memory leaks."));
600 wxDebugContext::Dump();
601 wxDebugContext::PrintStatistics();
602 }
603 // wxDebugContext::SetStream(NULL, NULL);
604 #endif
605
606 #if wxUSE_LOG
607 // do it as the very last thing because everything else can log messages
608 delete wxLog::SetActiveTarget(NULL);
609 #endif // wxUSE_LOG
610 }
611
612 //----------------------------------------------------------------------
613 // Entry point helpers, used by wxPython
614 //----------------------------------------------------------------------
615
616 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char** WXUNUSED(argv) )
617 {
618 return wxApp::Initialize();
619 }
620
621 int WXDLLEXPORT wxEntryInitGui()
622 {
623 return wxTheApp->OnInitGui();
624 }
625
626 void WXDLLEXPORT wxEntryCleanup()
627 {
628 wxApp::CleanUp();
629 }
630
631
632 #if !defined(_WINDLL) || (defined(_WINDLL) && defined(WXMAKINGDLL))
633
634 // temporarily disable this warning which would be generated in release builds
635 // because of __try
636 #ifdef __VISUALC__
637 #pragma warning(disable: 4715) // not all control paths return a value
638 #endif // Visual C++
639
640 //----------------------------------------------------------------------
641 // Main wxWindows entry point
642 //----------------------------------------------------------------------
643 int wxEntry(WXHINSTANCE hInstance,
644 WXHINSTANCE WXUNUSED(hPrevInstance),
645 char *lpCmdLine,
646 int nCmdShow,
647 bool enterLoop)
648 {
649 // do check for memory leaks on program exit
650 // (another useful flag is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free
651 // deallocated memory which may be used to simulate low-memory condition)
652 #ifndef __WXMICROWIN__
653 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
654 #endif
655
656 #ifdef __MWERKS__
657 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
658 // This seems to be necessary since there are 'rogue'
659 // objects present at this point (perhaps global objects?)
660 // Setting a checkpoint will ignore them as far as the
661 // memory checking facility is concerned.
662 // Of course you may argue that memory allocated in globals should be
663 // checked, but this is a reasonable compromise.
664 wxDebugContext::SetCheckpoint();
665 #endif
666 #endif
667
668 // take everything into a try-except block to be able to call
669 // OnFatalException() if necessary
670 #if wxUSE_ON_FATAL_EXCEPTION
671 __try {
672 #endif
673 wxhInstance = (HINSTANCE) hInstance;
674
675 if (!wxEntryStart(0,0))
676 return 0;
677
678 // create the application object or ensure that one already exists
679 if (!wxTheApp)
680 {
681 // The app may have declared a global application object, but we recommend
682 // the IMPLEMENT_APP macro is used instead, which sets an initializer
683 // function for delayed, dynamic app object construction.
684 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
685 wxT("No initializer - use IMPLEMENT_APP macro.") );
686
687 wxTheApp = (wxApp*) (*wxApp::GetInitializerFunction()) ();
688 }
689
690 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
691
692 // save the WinMain() parameters
693 if (lpCmdLine) // MicroWindows passes NULL
694 wxTheApp->ConvertToStandardCommandArgs(lpCmdLine);
695 wxTheApp->m_nCmdShow = nCmdShow;
696
697 // We really don't want timestamps by default, because it means
698 // we can't simply double-click on the error message and get to that
699 // line in the source. So VC++ at least, let's have a sensible default.
700 #ifdef __VISUALC__
701 wxLog::SetTimestamp(NULL);
702 #endif
703
704 int retValue = 0;
705
706 // it is common to create a modal dialog in OnInit() (to ask/notify the
707 // user about something) but it wouldn't work if we don't change the
708 // "exit on delete last frame" flag here as when this dialog is
709 // deleted, the app would terminate (it was the last top level window
710 // as the main frame wasn't created yet!), so disable this behaviour
711 // temproarily
712 bool exitOnLastFrameDelete = wxTheApp->GetExitOnFrameDelete();
713 wxTheApp->SetExitOnFrameDelete(FALSE);
714
715 // init the app
716 retValue = wxEntryInitGui() && wxTheApp->OnInit() ? 0 : -1;
717
718 // restore the old flag value
719 wxTheApp->SetExitOnFrameDelete(exitOnLastFrameDelete);
720
721 if ( retValue == 0 )
722 {
723 if ( enterLoop )
724 {
725 // run the main loop
726 retValue = wxTheApp->OnRun();
727 }
728 else
729 {
730 // we want to initialize, but not run or exit immediately.
731 return 1;
732 }
733 }
734 //else: app initialization failed, so we skipped OnRun()
735
736 wxWindow *topWindow = wxTheApp->GetTopWindow();
737 if ( topWindow )
738 {
739 // Forcibly delete the window.
740 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
741 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
742 {
743 topWindow->Close(TRUE);
744 wxTheApp->DeletePendingObjects();
745 }
746 else
747 {
748 delete topWindow;
749 wxTheApp->SetTopWindow(NULL);
750 }
751 }
752
753 wxTheApp->OnExit();
754
755 wxEntryCleanup();
756
757 return retValue;
758
759 #if wxUSE_ON_FATAL_EXCEPTION
760 }
761 __except ( gs_handleExceptions ? EXCEPTION_EXECUTE_HANDLER
762 : EXCEPTION_CONTINUE_SEARCH ) {
763 if ( wxTheApp )
764 {
765 // give the user a chance to do something special about this
766 wxTheApp->OnFatalException();
767 }
768
769 ::ExitProcess(3); // the same exit code as abort()
770
771 // NOTREACHED
772 }
773 #endif // wxUSE_ON_FATAL_EXCEPTION
774 }
775
776 // restore warning state
777 #ifdef __VISUALC__
778 #pragma warning(default: 4715) // not all control paths return a value
779 #endif // Visual C++
780
781 #else /* _WINDLL */
782
783 //----------------------------------------------------------------------
784 // Entry point for wxWindows + the App in a DLL
785 //----------------------------------------------------------------------
786
787 int wxEntry(WXHINSTANCE hInstance)
788 {
789 wxhInstance = (HINSTANCE) hInstance;
790 wxEntryStart(0, 0);
791
792 // The app may have declared a global application object, but we recommend
793 // the IMPLEMENT_APP macro is used instead, which sets an initializer function
794 // for delayed, dynamic app object construction.
795 if (!wxTheApp)
796 {
797 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
798 "No initializer - use IMPLEMENT_APP macro." );
799
800 wxTheApp = (* wxApp::GetInitializerFunction()) ();
801 }
802
803 wxCHECK_MSG( wxTheApp, 0, "You have to define an instance of wxApp!" );
804
805 wxTheApp->argc = 0;
806 wxTheApp->argv = NULL;
807
808 wxEntryInitGui();
809
810 wxTheApp->OnInit();
811
812 wxWindow *topWindow = wxTheApp->GetTopWindow();
813 if ( topWindow && topWindow->GetHWND())
814 {
815 topWindow->Show(TRUE);
816 }
817
818 return 1;
819 }
820 #endif // _WINDLL
821
822 //// Static member initialization
823
824 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
825
826 wxApp::wxApp()
827 {
828 argc = 0;
829 argv = NULL;
830 m_printMode = wxPRINT_WINDOWS;
831 m_auto3D = TRUE;
832 }
833
834 wxApp::~wxApp()
835 {
836 // Delete command-line args
837 int i;
838 for (i = 0; i < argc; i++)
839 {
840 delete[] argv[i];
841 }
842 delete[] argv;
843 }
844
845 bool wxApp::Initialized()
846 {
847 #ifndef _WINDLL
848 if (GetTopWindow())
849 return TRUE;
850 else
851 return FALSE;
852 #else // Assume initialized if DLL (no way of telling)
853 return TRUE;
854 #endif
855 }
856
857 /*
858 * Get and process a message, returning FALSE if WM_QUIT
859 * received (and also set the flag telling the app to exit the main loop)
860 *
861 */
862 bool wxApp::DoMessage()
863 {
864 BOOL rc = ::GetMessage(&s_currentMsg, (HWND) NULL, 0, 0);
865 if ( rc == 0 )
866 {
867 // got WM_QUIT
868 m_keepGoing = FALSE;
869
870 return FALSE;
871 }
872 else if ( rc == -1 )
873 {
874 // should never happen, but let's test for it nevertheless
875 wxLogLastError(wxT("GetMessage"));
876 }
877 else
878 {
879 #if wxUSE_THREADS
880 wxASSERT_MSG( wxThread::IsMain(),
881 wxT("only the main thread can process Windows messages") );
882
883 static bool s_hadGuiLock = TRUE;
884 static wxMsgArray s_aSavedMessages;
885
886 // if a secondary thread owns is doing GUI calls, save all messages for
887 // later processing - we can't process them right now because it will
888 // lead to recursive library calls (and we're not reentrant)
889 if ( !wxGuiOwnedByMainThread() )
890 {
891 s_hadGuiLock = FALSE;
892
893 // leave out WM_COMMAND messages: too dangerous, sometimes
894 // the message will be processed twice
895 if ( !wxIsWaitingForThread() ||
896 s_currentMsg.message != WM_COMMAND )
897 {
898 s_aSavedMessages.Add(s_currentMsg);
899 }
900
901 return TRUE;
902 }
903 else
904 {
905 // have we just regained the GUI lock? if so, post all of the saved
906 // messages
907 //
908 // FIXME of course, it's not _exactly_ the same as processing the
909 // messages normally - expect some things to break...
910 if ( !s_hadGuiLock )
911 {
912 s_hadGuiLock = TRUE;
913
914 size_t count = s_aSavedMessages.GetCount();
915 for ( size_t n = 0; n < count; n++ )
916 {
917 MSG& msg = s_aSavedMessages[n];
918
919 DoMessage((WXMSG *)&msg);
920 }
921
922 s_aSavedMessages.Empty();
923 }
924 }
925 #endif // wxUSE_THREADS
926
927 // Process the message
928 DoMessage((WXMSG *)&s_currentMsg);
929 }
930
931 return TRUE;
932 }
933
934 void wxApp::DoMessage(WXMSG *pMsg)
935 {
936 if ( !ProcessMessage(pMsg) )
937 {
938 ::TranslateMessage((MSG *)pMsg);
939 ::DispatchMessage((MSG *)pMsg);
940 }
941 }
942
943 /*
944 * Keep trying to process messages until WM_QUIT
945 * received.
946 *
947 * If there are messages to be processed, they will all be
948 * processed and OnIdle will not be called.
949 * When there are no more messages, OnIdle is called.
950 * If OnIdle requests more time,
951 * it will be repeatedly called so long as there are no pending messages.
952 * A 'feature' of this is that once OnIdle has decided that no more processing
953 * is required, then it won't get processing time until further messages
954 * are processed (it'll sit in DoMessage).
955 */
956
957 int wxApp::MainLoop()
958 {
959 m_keepGoing = TRUE;
960
961 while ( m_keepGoing )
962 {
963 #if wxUSE_THREADS
964 wxMutexGuiLeaveOrEnter();
965 #endif // wxUSE_THREADS
966
967 while ( !Pending() && ProcessIdle() )
968 ;
969
970 // a message came or no more idle processing to do
971 DoMessage();
972 }
973
974 return s_currentMsg.wParam;
975 }
976
977 // Returns TRUE if more time is needed.
978 bool wxApp::ProcessIdle()
979 {
980 wxIdleEvent event;
981 event.SetEventObject(this);
982 ProcessEvent(event);
983
984 return event.MoreRequested();
985 }
986
987 void wxApp::ExitMainLoop()
988 {
989 // VZ: why not ::PostQuitMessage()?
990 m_keepGoing = FALSE;
991 }
992
993 bool wxApp::Pending()
994 {
995 return ::PeekMessage(&s_currentMsg, 0, 0, 0, PM_NOREMOVE) != 0;
996 }
997
998 void wxApp::Dispatch()
999 {
1000 DoMessage();
1001 }
1002
1003 /*
1004 * Give all windows a chance to preprocess
1005 * the message. Some may have accelerator tables, or have
1006 * MDI complications.
1007 */
1008
1009 bool wxApp::ProcessMessage(WXMSG *wxmsg)
1010 {
1011 MSG *msg = (MSG *)wxmsg;
1012 HWND hwnd = msg->hwnd;
1013 wxWindow *wndThis = wxGetWindowFromHWND((WXHWND)hwnd);
1014
1015 // this may happen if the event occured in a standard modeless dialog (the
1016 // only example of which I know of is the find/replace dialog) - then call
1017 // IsDialogMessage() to make TAB navigation in it work
1018 if ( !wndThis )
1019 {
1020 // we need to find the dialog containing this control as
1021 // IsDialogMessage() just eats all the messages (i.e. returns TRUE for
1022 // them) if we call it for the control itself
1023 while ( hwnd && ::GetWindowLong(hwnd, GWL_STYLE) & WS_CHILD )
1024 {
1025 hwnd = ::GetParent(hwnd);
1026 }
1027
1028 return hwnd && ::IsDialogMessage(hwnd, msg) != 0;
1029 }
1030
1031 #if wxUSE_TOOLTIPS
1032 // we must relay WM_MOUSEMOVE events to the tooltip ctrl if we want it to
1033 // popup the tooltip bubbles
1034 if ( (msg->message == WM_MOUSEMOVE) )
1035 {
1036 wxToolTip *tt = wndThis->GetToolTip();
1037 if ( tt )
1038 {
1039 tt->RelayEvent(wxmsg);
1040 }
1041 }
1042 #endif // wxUSE_TOOLTIPS
1043
1044 // allow the window to prevent certain messages from being
1045 // translated/processed (this is currently used by wxTextCtrl to always
1046 // grab Ctrl-C/V/X, even if they are also accelerators in some parent)
1047 if ( !wndThis->MSWShouldPreProcessMessage(wxmsg) )
1048 {
1049 return FALSE;
1050 }
1051
1052 // try translations first: the accelerators override everything
1053 wxWindow *wnd;
1054
1055 for ( wnd = wndThis; wnd; wnd = wnd->GetParent() )
1056 {
1057 if ( wnd->MSWTranslateMessage(wxmsg))
1058 return TRUE;
1059
1060 // stop at first top level window, i.e. don't try to process the key
1061 // strokes originating in a dialog using the accelerators of the parent
1062 // frame - this doesn't make much sense
1063 if ( wnd->IsTopLevel() )
1064 break;
1065 }
1066
1067 // now try the other hooks (kbd navigation is handled here): we start from
1068 // wndThis->GetParent() because wndThis->MSWProcessMessage() was already
1069 // called above
1070 for ( wnd = wndThis->GetParent(); wnd; wnd = wnd->GetParent() )
1071 {
1072 if ( wnd->MSWProcessMessage(wxmsg) )
1073 return TRUE;
1074 }
1075
1076 // no special preprocessing for this message, dispatch it normally
1077 return FALSE;
1078 }
1079
1080 void wxApp::OnIdle(wxIdleEvent& event)
1081 {
1082 static bool s_inOnIdle = FALSE;
1083
1084 // Avoid recursion (via ProcessEvent default case)
1085 if ( s_inOnIdle )
1086 return;
1087
1088 s_inOnIdle = TRUE;
1089
1090 // If there are pending events, we must process them: pending events
1091 // are either events to the threads other than main or events posted
1092 // with wxPostEvent() functions
1093 // GRG: I have moved this here so that all pending events are processed
1094 // before starting to delete any objects. This behaves better (in
1095 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
1096 // behaviour. Changed Feb/2000 before 2.1.14
1097 ProcessPendingEvents();
1098
1099 // 'Garbage' collection of windows deleted with Close().
1100 DeletePendingObjects();
1101
1102 #if wxUSE_LOG
1103 // flush the logged messages if any
1104 wxLog::FlushActive();
1105 #endif // wxUSE_LOG
1106
1107 #if wxUSE_DC_CACHEING
1108 // automated DC cache management: clear the cached DCs and bitmap
1109 // if it's likely that the app has finished with them, that is, we
1110 // get an idle event and we're not dragging anything.
1111 if (!::GetKeyState(MK_LBUTTON) && !::GetKeyState(MK_MBUTTON) && !::GetKeyState(MK_RBUTTON))
1112 wxDC::ClearCache();
1113 #endif // wxUSE_DC_CACHEING
1114
1115 // Send OnIdle events to all windows
1116 if ( SendIdleEvents() )
1117 {
1118 // SendIdleEvents() returns TRUE if at least one window requested more
1119 // idle events
1120 event.RequestMore(TRUE);
1121 }
1122
1123 s_inOnIdle = FALSE;
1124 }
1125
1126 // Send idle event to all top-level windows
1127 bool wxApp::SendIdleEvents()
1128 {
1129 bool needMore = FALSE;
1130
1131 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
1132 while (node)
1133 {
1134 wxWindow* win = node->GetData();
1135 if (SendIdleEvents(win))
1136 needMore = TRUE;
1137 node = node->GetNext();
1138 }
1139
1140 return needMore;
1141 }
1142
1143 // Send idle event to window and all subwindows
1144 bool wxApp::SendIdleEvents(wxWindow* win)
1145 {
1146 bool needMore = FALSE;
1147
1148 wxIdleEvent event;
1149 event.SetEventObject(win);
1150 win->GetEventHandler()->ProcessEvent(event);
1151
1152 if (event.MoreRequested())
1153 needMore = TRUE;
1154
1155 wxNode* node = win->GetChildren().First();
1156 while (node)
1157 {
1158 wxWindow* win = (wxWindow*) node->Data();
1159 if (SendIdleEvents(win))
1160 needMore = TRUE;
1161
1162 node = node->Next();
1163 }
1164 return needMore;
1165 }
1166
1167 void wxApp::DeletePendingObjects()
1168 {
1169 wxNode *node = wxPendingDelete.First();
1170 while (node)
1171 {
1172 wxObject *obj = (wxObject *)node->Data();
1173
1174 delete obj;
1175
1176 if (wxPendingDelete.Member(obj))
1177 delete node;
1178
1179 // Deleting one object may have deleted other pending
1180 // objects, so start from beginning of list again.
1181 node = wxPendingDelete.First();
1182 }
1183 }
1184
1185 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
1186 {
1187 if (GetTopWindow())
1188 GetTopWindow()->Close(TRUE);
1189 }
1190
1191 // Default behaviour: close the application with prompts. The
1192 // user can veto the close, and therefore the end session.
1193 void wxApp::OnQueryEndSession(wxCloseEvent& event)
1194 {
1195 if (GetTopWindow())
1196 {
1197 if (!GetTopWindow()->Close(!event.CanVeto()))
1198 event.Veto(TRUE);
1199 }
1200 }
1201
1202 /* static */
1203 int wxApp::GetComCtl32Version()
1204 {
1205 #ifdef __WXMICROWIN__
1206 return 0;
1207 #else
1208 // cache the result
1209 static int s_verComCtl32 = -1;
1210
1211 wxCRIT_SECT_DECLARE(csComCtl32);
1212 wxCRIT_SECT_LOCKER(lock, csComCtl32);
1213
1214 if ( s_verComCtl32 == -1 )
1215 {
1216 // initally assume no comctl32.dll at all
1217 s_verComCtl32 = 0;
1218
1219 // do we have it?
1220 HMODULE hModuleComCtl32 = ::GetModuleHandle(wxT("COMCTL32"));
1221
1222 // if so, then we can check for the version
1223 if ( hModuleComCtl32 )
1224 {
1225 // try to use DllGetVersion() if available in _headers_
1226 #ifdef DLLVER_PLATFORM_WINDOWS // defined in shlwapi.h
1227 DLLGETVERSIONPROC pfnDllGetVersion = (DLLGETVERSIONPROC)
1228 ::GetProcAddress(hModuleComCtl32, "DllGetVersion");
1229 if ( pfnDllGetVersion )
1230 {
1231 DLLVERSIONINFO dvi;
1232 dvi.cbSize = sizeof(dvi);
1233
1234 HRESULT hr = (*pfnDllGetVersion)(&dvi);
1235 if ( FAILED(hr) )
1236 {
1237 wxLogApiError(_T("DllGetVersion"), hr);
1238 }
1239 else
1240 {
1241 // this is incompatible with _WIN32_IE values, but
1242 // compatible with the other values returned by
1243 // GetComCtl32Version()
1244 s_verComCtl32 = 100*dvi.dwMajorVersion +
1245 dvi.dwMinorVersion;
1246 }
1247 }
1248 #endif
1249 // DllGetVersion() unavailable either during compile or
1250 // run-time, try to guess the version otherwise
1251 if ( !s_verComCtl32 )
1252 {
1253 // InitCommonControlsEx is unique to 4.70 and later
1254 FARPROC theProc = ::GetProcAddress
1255 (
1256 hModuleComCtl32,
1257 "InitCommonControlsEx"
1258 );
1259
1260 if ( !theProc )
1261 {
1262 // not found, must be 4.00
1263 s_verComCtl32 = 400;
1264 }
1265 else
1266 {
1267 // many symbols appeared in comctl32 4.71, could use
1268 // any of them except may be DllInstall
1269 theProc = ::GetProcAddress
1270 (
1271 hModuleComCtl32,
1272 "InitializeFlatSB"
1273 );
1274 if ( !theProc )
1275 {
1276 // not found, must be 4.70
1277 s_verComCtl32 = 470;
1278 }
1279 else
1280 {
1281 // found, must be 4.71
1282 s_verComCtl32 = 471;
1283 }
1284 }
1285 }
1286 }
1287 }
1288
1289 return s_verComCtl32;
1290 #endif
1291 }
1292
1293 void wxExit()
1294 {
1295 wxLogError(_("Fatal error: exiting"));
1296
1297 wxApp::CleanUp();
1298 exit(0);
1299 }
1300
1301 // Yield to incoming messages
1302
1303 bool wxApp::Yield(bool onlyIfNeeded)
1304 {
1305 // MT-FIXME
1306 static bool s_inYield = FALSE;
1307
1308 // disable log flushing from here because a call to wxYield() shouldn't
1309 // normally result in message boxes popping up &c
1310 wxLog::Suspend();
1311
1312 if ( s_inYield )
1313 {
1314 if ( !onlyIfNeeded )
1315 {
1316 wxFAIL_MSG( wxT("wxYield called recursively" ) );
1317 }
1318
1319 return FALSE;
1320 }
1321
1322 s_inYield = TRUE;
1323
1324 // we don't want to process WM_QUIT from here - it should be processed in
1325 // the main event loop in order to stop it
1326 MSG msg;
1327 while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
1328 msg.message != WM_QUIT )
1329 {
1330 #if wxUSE_THREADS
1331 wxMutexGuiLeaveOrEnter();
1332 #endif // wxUSE_THREADS
1333
1334 if ( !wxTheApp->DoMessage() )
1335 break;
1336 }
1337
1338 // if there are pending events, we must process them.
1339 ProcessPendingEvents();
1340
1341 // let the logs be flashed again
1342 wxLog::Resume();
1343
1344 s_inYield = FALSE;
1345
1346 return TRUE;
1347 }
1348
1349 bool wxHandleFatalExceptions(bool doit)
1350 {
1351 #if wxUSE_ON_FATAL_EXCEPTION
1352 // assume this can only be called from the main thread
1353 gs_handleExceptions = doit;
1354
1355 return TRUE;
1356 #else
1357 wxFAIL_MSG(_T("set wxUSE_ON_FATAL_EXCEPTION to 1 to use this function"));
1358
1359 (void)doit;
1360 return FALSE;
1361 #endif
1362 }
1363
1364 //-----------------------------------------------------------------------------
1365 // wxWakeUpIdle
1366 //-----------------------------------------------------------------------------
1367
1368 void wxWakeUpIdle()
1369 {
1370 // Send the top window a dummy message so idle handler processing will
1371 // start up again. Doing it this way ensures that the idle handler
1372 // wakes up in the right thread (see also wxWakeUpMainThread() which does
1373 // the same for the main app thread only)
1374 wxWindow *topWindow = wxTheApp->GetTopWindow();
1375 if ( topWindow )
1376 {
1377 if ( !::PostMessage(GetHwndOf(topWindow), WM_NULL, 0, 0) )
1378 {
1379 // should never happen
1380 wxLogLastError(wxT("PostMessage(WM_NULL)"));
1381 }
1382 }
1383 }
1384
1385 //-----------------------------------------------------------------------------
1386
1387 // For some reason, with MSVC++ 1.5, WinMain isn't linked in properly
1388 // if in a separate file. So include it here to ensure it's linked.
1389 #if (defined(__VISUALC__) && !defined(__WIN32__)) || (defined(__GNUWIN32__) && !defined(__TWIN32__) && !defined(WXMAKINGDLL))
1390 #include "main.cpp"
1391 #endif