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__)
41 #include "wx/msw/msvcrt.h"
43 #ifdef wxCrtSetDbgFlag
44 static struct EnableMemLeakChecking
46 EnableMemLeakChecking()
48 // check for memory leaks on program exit (another useful flag
49 // is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free deallocated
50 // memory which may be used to simulate low-memory condition)
51 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
53 } gs_enableLeakChecks
;
54 #endif // wxCrtSetDbgFlag
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
61 // we need a dummy app object if the user doesn't want to create a real one
62 class wxDummyConsoleApp
: public wxAppConsole
65 wxDummyConsoleApp() { }
67 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
68 virtual bool DoYield(bool, long) { return true; }
70 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp
);
73 // we need a special kind of auto pointer to wxApp which not only deletes the
74 // pointer it holds in its dtor but also resets the global application pointer
75 wxDECLARE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
76 wxDEFINE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
78 class wxAppPtr
: public wxAppPtrBase
81 wxEXPLICIT
wxAppPtr(wxAppConsole
*ptr
= NULL
) : wxAppPtrBase(ptr
) { }
86 // the pointer is going to be deleted in the base class dtor, don't
87 // leave the dangling pointer!
88 wxApp::SetInstance(NULL
);
92 void Set(wxAppConsole
*ptr
)
96 wxApp::SetInstance(ptr
);
99 wxDECLARE_NO_COPY_CLASS(wxAppPtr
);
102 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
104 class wxCallAppCleanup
107 wxCallAppCleanup(wxAppConsole
*app
) : m_app(app
) { }
108 ~wxCallAppCleanup() { if ( m_app
) m_app
->CleanUp(); }
110 void Dismiss() { m_app
= NULL
; }
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 // suppress warnings about unused variables
121 static inline void Use(void *) { }
123 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
125 // ----------------------------------------------------------------------------
126 // initialization data
127 // ----------------------------------------------------------------------------
129 static struct InitData
137 // argv = NULL; -- not even really needed
138 #endif // wxUSE_UNICODE
141 // critical section protecting this struct
142 wxCRIT_SECT_DECLARE_MEMBER(csInit
);
144 // number of times wxInitialize() was called minus the number of times
145 // wxUninitialize() was
151 // if we receive the command line arguments as ASCII and have to convert
152 // them to Unicode ourselves (this is the case under Unix but not Windows,
153 // for example), we remember the converted argv here because we'll have to
154 // free it when doing cleanup to avoid memory leaks
156 #endif // wxUSE_UNICODE
158 wxDECLARE_NO_COPY_CLASS(InitData
);
161 // ============================================================================
163 // ============================================================================
165 // ----------------------------------------------------------------------------
166 // command line arguments ANSI -> Unicode conversion
167 // ----------------------------------------------------------------------------
171 static void ConvertArgsToUnicode(int argc
, char **argv
)
173 gs_initData
.argv
= new wchar_t *[argc
+ 1];
175 for ( int i
= 0; i
< argc
; i
++ )
178 wxWCharBuffer
buf(wxConvFileName
->cMB2WX(argv
[i
]));
180 wxWCharBuffer
buf(wxConvLocal
.cMB2WX(argv
[i
]));
184 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
189 gs_initData
.argv
[wargc
++] = wxStrdup(buf
);
193 gs_initData
.argc
= wargc
;
194 gs_initData
.argv
[wargc
] = NULL
;
197 static void FreeConvertedArgs()
199 if ( gs_initData
.argv
)
201 for ( int i
= 0; i
< gs_initData
.argc
; i
++ )
203 free(gs_initData
.argv
[i
]);
206 delete [] gs_initData
.argv
;
207 gs_initData
.argv
= NULL
;
208 gs_initData
.argc
= 0;
212 #endif // wxUSE_UNICODE
214 // ----------------------------------------------------------------------------
216 // ----------------------------------------------------------------------------
218 // initialization which is always done (not customizable) before wxApp creation
219 static bool DoCommonPreInit()
222 // Reset logging in case we were cleaned up and are being reinitialized.
223 wxLog::DoCreateOnDemand();
229 // non customizable initialization done after wxApp creation and initialization
230 static bool DoCommonPostInit()
232 wxModule::RegisterModules();
234 if ( !wxModule::InitializeModules() )
236 wxLogError(_("Initialization failed in post init, aborting."));
243 bool wxEntryStart(int& argc
, wxChar
**argv
)
245 // do minimal, always necessary, initialization
246 // --------------------------------------------
249 if ( !DoCommonPreInit() )
253 // first of all, we need an application object
254 // -------------------------------------------
256 // the user might have already created it himself somehow
257 wxAppPtr
app(wxTheApp
);
260 // if not, he might have used IMPLEMENT_APP() to give us a function to
262 wxAppInitializerFunction fnCreate
= wxApp::GetInitializerFunction();
266 // he did, try to create the custom wxApp object
267 app
.Set((*fnCreate
)());
273 // either IMPLEMENT_APP() was not used at all or it failed -- in any
274 // case we still need something
275 app
.Set(new wxDummyConsoleApp
);
279 // wxApp initialization: this can be customized
280 // --------------------------------------------
282 if ( !app
->Initialize(argc
, argv
) )
285 // remember, possibly modified (e.g. due to removal of toolkit-specific
286 // parameters), command line arguments in member variables
290 wxCallAppCleanup
callAppCleanup(app
.get());
293 // common initialization after wxTheApp creation
294 // ---------------------------------------------
296 if ( !DoCommonPostInit() )
300 // prevent the smart pointer from destroying its contents
303 // and the cleanup object from doing cleanup
304 callAppCleanup
.Dismiss();
307 // now that we have a valid wxApp (wxLogGui would have crashed if we used
308 // it before now), we can delete the temporary sink we had created for the
309 // initialization messages -- the next time logging function is called, the
310 // sink will be recreated but this time wxAppTraits will be used
311 delete wxLog::SetActiveTarget(NULL
);
319 // we provide a wxEntryStart() wrapper taking "char *" pointer too
320 bool wxEntryStart(int& argc
, char **argv
)
322 ConvertArgsToUnicode(argc
, argv
);
324 if ( !wxEntryStart(gs_initData
.argc
, gs_initData
.argv
) )
334 #endif // wxUSE_UNICODE
336 // ----------------------------------------------------------------------------
338 // ----------------------------------------------------------------------------
340 // cleanup done before destroying wxTheApp
341 static void DoCommonPreCleanup()
344 // flush the logged messages if any and don't use the current probably
345 // unsafe log target any more: the default one (wxLogGui) can't be used
346 // after the resources are freed which happens when we return and the user
347 // supplied one might be even more unsafe (using any wxWidgets GUI function
348 // is unsafe starting from now)
350 // notice that wxLog will still recreate a default log target if any
351 // messages are logged but that one will be safe to use until the very end
352 delete wxLog::SetActiveTarget(NULL
);
356 // cleanup done after destroying wxTheApp
357 static void DoCommonPostCleanup()
359 wxModule::CleanUpModules();
361 // we can't do this in wxApp itself because it doesn't know if argv had
365 #endif // wxUSE_UNICODE
367 // use Set(NULL) and not Get() to avoid creating a message output object on
368 // demand when we just want to delete it
369 delete wxMessageOutput::Set(NULL
);
372 // and now delete the last logger as well
374 // we still don't disable log target auto-vivification even if any log
375 // objects created now will result in memory leaks because it seems better
376 // to leak memory which doesn't matter much considering the application is
377 // exiting anyhow than to not show messages which could still be logged
378 // from the user code (e.g. static dtors and such)
379 delete wxLog::SetActiveTarget(NULL
);
383 void wxEntryCleanup()
385 DoCommonPreCleanup();
388 // delete the application object
393 // reset the global pointer to it to NULL before destroying it as in
394 // some circumstances this can result in executing the code using
395 // wxTheApp and using half-destroyed object is no good
396 wxAppConsole
* const app
= wxApp::GetInstance();
397 wxApp::SetInstance(NULL
);
402 DoCommonPostCleanup();
405 // ----------------------------------------------------------------------------
407 // ----------------------------------------------------------------------------
409 // for MSW the real wxEntry is defined in msw/main.cpp
411 #define wxEntryReal wxEntry
414 int wxEntryReal(int& argc
, wxChar
**argv
)
416 // library initialization
417 wxInitializer
initializer(argc
, argv
);
419 if ( !initializer
.IsOk() )
422 // flush any log messages explaining why we failed
423 delete wxLog::SetActiveTarget(NULL
);
430 // app initialization
431 if ( !wxTheApp
->CallOnInit() )
433 // don't call OnExit() if OnInit() failed
437 // ensure that OnExit() is called if OnInit() had succeeded
441 ~CallOnExit() { wxTheApp
->OnExit(); }
444 WX_SUPPRESS_UNUSED_WARN(callOnExit
);
447 return wxTheApp
->OnRun();
449 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); return -1; )
454 // as with wxEntryStart, we provide an ANSI wrapper
455 int wxEntry(int& argc
, char **argv
)
457 ConvertArgsToUnicode(argc
, argv
);
459 return wxEntry(gs_initData
.argc
, gs_initData
.argv
);
462 #endif // wxUSE_UNICODE
464 // ----------------------------------------------------------------------------
465 // wxInitialize/wxUninitialize
466 // ----------------------------------------------------------------------------
470 return wxInitialize(0, (wxChar
**)NULL
);
473 bool wxInitialize(int argc
, wxChar
**argv
)
475 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
477 if ( gs_initData
.nInitCount
++ )
479 // already initialized
483 return wxEntryStart(argc
, argv
);
487 bool wxInitialize(int argc
, char **argv
)
489 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
491 if ( gs_initData
.nInitCount
++ )
493 // already initialized
497 return wxEntryStart(argc
, argv
);
499 #endif // wxUSE_UNICODE
501 void wxUninitialize()
503 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
505 if ( --gs_initData
.nInitCount
== 0 )