1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/init.cpp
3 // Purpose: initialisation for the library
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #include "wx/wxprec.h"
28 #include "wx/filefn.h"
31 #include "wx/module.h"
35 #include "wx/thread.h"
37 #include "wx/scopedptr.h"
38 #include "wx/except.h"
40 #if defined(__WXMSW__) && defined(__WXDEBUG__)
41 #include "wx/msw/msvcrt.h"
43 static struct EnableMemLeakChecking
45 EnableMemLeakChecking()
47 // do check for memory leaks on program exit (another useful flag
48 // is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free deallocated
49 // memory which may be used to simulate low-memory condition)
50 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
52 } gs_enableLeakChecks
;
53 #endif // __WXMSW__ && __WXDEBUG__
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // we need a dummy app object if the user doesn't want to create a real one
60 class wxDummyConsoleApp
: public wxAppConsole
63 wxDummyConsoleApp() { }
65 virtual int OnRun() { wxFAIL_MSG( _T("unreachable code") ); return 0; }
66 virtual bool DoYield(bool, long) { return true; }
68 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp
);
71 // we need a special kind of auto pointer to wxApp which not only deletes the
72 // pointer it holds in its dtor but also resets the global application pointer
73 wxDECLARE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
74 wxDEFINE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
76 class wxAppPtr
: public wxAppPtrBase
79 wxEXPLICIT
wxAppPtr(wxAppConsole
*ptr
= NULL
) : wxAppPtrBase(ptr
) { }
84 // the pointer is going to be deleted in the base class dtor, don't
85 // leave the dangling pointer!
86 wxApp::SetInstance(NULL
);
90 void Set(wxAppConsole
*ptr
)
94 wxApp::SetInstance(ptr
);
97 wxDECLARE_NO_COPY_CLASS(wxAppPtr
);
100 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
102 class wxCallAppCleanup
105 wxCallAppCleanup(wxAppConsole
*app
) : m_app(app
) { }
106 ~wxCallAppCleanup() { if ( m_app
) m_app
->CleanUp(); }
108 void Dismiss() { m_app
= NULL
; }
114 // another tiny class which simply exists to ensure that wxEntryCleanup is
116 class wxCleanupOnExit
119 ~wxCleanupOnExit() { wxEntryCleanup(); }
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 // suppress warnings about unused variables
127 static inline void Use(void *) { }
129 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
131 // ----------------------------------------------------------------------------
132 // initialization data
133 // ----------------------------------------------------------------------------
135 static struct InitData
143 // argv = NULL; -- not even really needed
144 #endif // wxUSE_UNICODE
147 // critical section protecting this struct
148 wxCRIT_SECT_DECLARE_MEMBER(csInit
);
150 // number of times wxInitialize() was called minus the number of times
151 // wxUninitialize() was
157 // if we receive the command line arguments as ASCII and have to convert
158 // them to Unicode ourselves (this is the case under Unix but not Windows,
159 // for example), we remember the converted argv here because we'll have to
160 // free it when doing cleanup to avoid memory leaks
162 #endif // wxUSE_UNICODE
164 wxDECLARE_NO_COPY_CLASS(InitData
);
167 // ============================================================================
169 // ============================================================================
171 // ----------------------------------------------------------------------------
172 // command line arguments ANSI -> Unicode conversion
173 // ----------------------------------------------------------------------------
177 static void ConvertArgsToUnicode(int argc
, char **argv
)
179 gs_initData
.argv
= new wchar_t *[argc
+ 1];
181 for ( int i
= 0; i
< argc
; i
++ )
184 wxWCharBuffer
buf(wxConvFileName
->cMB2WX(argv
[i
]));
186 wxWCharBuffer
buf(wxConvLocal
.cMB2WX(argv
[i
]));
190 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
195 gs_initData
.argv
[wargc
++] = wxStrdup(buf
);
199 gs_initData
.argc
= wargc
;
200 gs_initData
.argv
[wargc
] = NULL
;
203 static void FreeConvertedArgs()
205 if ( gs_initData
.argv
)
207 for ( int i
= 0; i
< gs_initData
.argc
; i
++ )
209 free(gs_initData
.argv
[i
]);
212 delete [] gs_initData
.argv
;
213 gs_initData
.argv
= NULL
;
214 gs_initData
.argc
= 0;
218 #endif // wxUSE_UNICODE
220 // ----------------------------------------------------------------------------
222 // ----------------------------------------------------------------------------
224 // initialization which is always done (not customizable) before wxApp creation
225 static bool DoCommonPreInit()
228 // Reset logging in case we were cleaned up and are being reinitialized.
229 wxLog::DoCreateOnDemand();
231 // install temporary log sink: we can't use wxLogGui before wxApp is
232 // constructed and if we use wxLogStderr, all messages during
233 // initialization simply disappear under Windows
235 // note that we will delete this log target below
236 delete wxLog::SetActiveTarget(new wxLogBuffer
);
242 // non customizable initialization done after wxApp creation and initialization
243 static bool DoCommonPostInit()
245 wxModule::RegisterModules();
247 if ( !wxModule::InitializeModules() )
249 wxLogError(_("Initialization failed in post init, aborting."));
253 #if defined(__WXDEBUG__)
254 // check if event classes implement Clone() correctly
255 // NOTE: the check is done against _all_ event classes which are linked to
256 // the executable currently running, which are not necessarily all
257 // wxWidgets event classes.
258 const wxClassInfo
*ci
= wxClassInfo::GetFirst();
259 for (; ci
; ci
= ci
->GetNext())
261 // is this class derived from wxEvent?
262 if (!ci
->IsKindOf(CLASSINFO(wxEvent
)) || wxString(ci
->GetClassName()) == "wxEvent")
265 if (!ci
->IsDynamic())
267 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
272 // yes; test if it implements Clone() correctly
273 wxEvent
* test
= wxDynamicCast(ci
->CreateObject(),wxEvent
);
276 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
281 wxEvent
* cloned
= test
->Clone();
282 if (!cloned
|| cloned
->GetClassInfo() != ci
)
283 wxLogWarning("The event class '%s' does not correctly implement Clone()!",
294 bool wxEntryStart(int& argc
, wxChar
**argv
)
296 // do minimal, always necessary, initialization
297 // --------------------------------------------
300 if ( !DoCommonPreInit() )
306 // first of all, we need an application object
307 // -------------------------------------------
309 // the user might have already created it himself somehow
310 wxAppPtr
app(wxTheApp
);
313 // if not, he might have used IMPLEMENT_APP() to give us a function to
315 wxAppInitializerFunction fnCreate
= wxApp::GetInitializerFunction();
319 // he did, try to create the custom wxApp object
320 app
.Set((*fnCreate
)());
326 // either IMPLEMENT_APP() was not used at all or it failed -- in any
327 // case we still need something
328 app
.Set(new wxDummyConsoleApp
);
332 // wxApp initialization: this can be customized
333 // --------------------------------------------
335 if ( !app
->Initialize(argc
, argv
) )
340 // remember, possibly modified (e.g. due to removal of toolkit-specific
341 // parameters), command line arguments in member variables
346 wxCallAppCleanup
callAppCleanup(app
.get());
348 // for compatibility call the old initialization function too
349 if ( !app
->OnInitGui() )
353 // common initialization after wxTheApp creation
354 // ---------------------------------------------
356 if ( !DoCommonPostInit() )
360 // prevent the smart pointer from destroying its contents
363 // and the cleanup object from doing cleanup
364 callAppCleanup
.Dismiss();
367 // now that we have a valid wxApp (wxLogGui would have crashed if we used
368 // it before now), we can delete the temporary sink we had created for the
369 // initialization messages -- the next time logging function is called, the
370 // sink will be recreated but this time wxAppTraits will be used
371 delete wxLog::SetActiveTarget(NULL
);
379 // we provide a wxEntryStart() wrapper taking "char *" pointer too
380 bool wxEntryStart(int& argc
, char **argv
)
382 ConvertArgsToUnicode(argc
, argv
);
384 if ( !wxEntryStart(gs_initData
.argc
, gs_initData
.argv
) )
394 #endif // wxUSE_UNICODE
396 // ----------------------------------------------------------------------------
398 // ----------------------------------------------------------------------------
400 // cleanup done before destroying wxTheApp
401 static void DoCommonPreCleanup()
404 // flush the logged messages if any and install a 'safer' log target: the
405 // default one (wxLogGui) can't be used after the resources are freed just
406 // below and the user supplied one might be even more unsafe (using any
407 // wxWidgets GUI function is unsafe starting from now)
408 wxLog::DontCreateOnDemand();
410 // this will flush the old messages if any
411 delete wxLog::SetActiveTarget(new wxLogStderr
);
415 // cleanup done after destroying wxTheApp
416 static void DoCommonPostCleanup()
418 wxModule::CleanUpModules();
420 // we can't do this in wxApp itself because it doesn't know if argv had
424 #endif // wxUSE_UNICODE
426 // use Set(NULL) and not Get() to avoid creating a message output object on
427 // demand when we just want to delete it
428 delete wxMessageOutput::Set(NULL
);
431 // and now delete the last logger as well
432 delete wxLog::SetActiveTarget(NULL
);
436 void wxEntryCleanup()
438 DoCommonPreCleanup();
441 // delete the application object
446 // reset the global pointer to it to NULL before destroying it as in
447 // some circumstances this can result in executing the code using
448 // wxTheApp and using half-destroyed object is no good
449 wxAppConsole
* const app
= wxApp::GetInstance();
450 wxApp::SetInstance(NULL
);
455 DoCommonPostCleanup();
458 // ----------------------------------------------------------------------------
460 // ----------------------------------------------------------------------------
462 // for MSW the real wxEntry is defined in msw/main.cpp
464 #define wxEntryReal wxEntry
467 int wxEntryReal(int& argc
, wxChar
**argv
)
469 // library initialization
470 if ( !wxEntryStart(argc
, argv
) )
473 // flush any log messages explaining why we failed
474 delete wxLog::SetActiveTarget(NULL
);
479 // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code
480 // below returns or throws
481 wxCleanupOnExit cleanupOnExit
;
483 WX_SUPPRESS_UNUSED_WARN(cleanupOnExit
);
488 // app initialization
489 if ( !wxTheApp
->CallOnInit() )
491 // don't call OnExit() if OnInit() failed
495 // ensure that OnExit() is called if OnInit() had succeeded
499 ~CallOnExit() { wxTheApp
->OnExit(); }
502 WX_SUPPRESS_UNUSED_WARN(callOnExit
);
505 return wxTheApp
->OnRun();
507 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); return -1; )
512 // as with wxEntryStart, we provide an ANSI wrapper
513 int wxEntry(int& argc
, char **argv
)
515 ConvertArgsToUnicode(argc
, argv
);
517 return wxEntry(gs_initData
.argc
, gs_initData
.argv
);
520 #endif // wxUSE_UNICODE
522 // ----------------------------------------------------------------------------
523 // wxInitialize/wxUninitialize
524 // ----------------------------------------------------------------------------
526 bool wxInitialize(int argc
, wxChar
**argv
)
528 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
530 if ( gs_initData
.nInitCount
++ )
532 // already initialized
536 return wxEntryStart(argc
, argv
);
539 void wxUninitialize()
541 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
543 if ( --gs_initData
.nInitCount
== 0 )