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