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();
225 // force wxLog to create a log target now: we do it because wxTheApp
226 // doesn't exist yet so wxLog will create a special log target which is
227 // safe to use even when the GUI is not available while without this call
228 // we could create wxApp in wxEntryStart() below, then log an error about
229 // e.g. failure to establish connection to the X server and wxLog would
230 // send it to wxLogGui (because wxTheApp does exist already) which, of
231 // course, can't be used in this case
233 // notice also that this does nothing if the user had set up a custom log
234 // target before -- which is fine as we want to give him this possibility
235 // (as it's impossible to override logging by overriding wxAppTraits::
236 // CreateLogTarget() before wxApp is created) and we just assume he knows
238 wxLog::GetActiveTarget();
244 // non customizable initialization done after wxApp creation and initialization
245 static bool DoCommonPostInit()
247 wxModule::RegisterModules();
249 if ( !wxModule::InitializeModules() )
251 wxLogError(_("Initialization failed in post init, aborting."));
258 bool wxEntryStart(int& argc
, wxChar
**argv
)
260 // do minimal, always necessary, initialization
261 // --------------------------------------------
264 if ( !DoCommonPreInit() )
268 // first of all, we need an application object
269 // -------------------------------------------
271 // the user might have already created it himself somehow
272 wxAppPtr
app(wxTheApp
);
275 // if not, he might have used IMPLEMENT_APP() to give us a function to
277 wxAppInitializerFunction fnCreate
= wxApp::GetInitializerFunction();
281 // he did, try to create the custom wxApp object
282 app
.Set((*fnCreate
)());
288 // either IMPLEMENT_APP() was not used at all or it failed -- in any
289 // case we still need something
290 app
.Set(new wxDummyConsoleApp
);
294 // wxApp initialization: this can be customized
295 // --------------------------------------------
297 if ( !app
->Initialize(argc
, argv
) )
300 // remember, possibly modified (e.g. due to removal of toolkit-specific
301 // parameters), command line arguments in member variables
305 wxCallAppCleanup
callAppCleanup(app
.get());
308 // common initialization after wxTheApp creation
309 // ---------------------------------------------
311 if ( !DoCommonPostInit() )
315 // prevent the smart pointer from destroying its contents
318 // and the cleanup object from doing cleanup
319 callAppCleanup
.Dismiss();
322 // now that we have a valid wxApp (wxLogGui would have crashed if we used
323 // it before now), we can delete the temporary sink we had created for the
324 // initialization messages -- the next time logging function is called, the
325 // sink will be recreated but this time wxAppTraits will be used
326 delete wxLog::SetActiveTarget(NULL
);
334 // we provide a wxEntryStart() wrapper taking "char *" pointer too
335 bool wxEntryStart(int& argc
, char **argv
)
337 ConvertArgsToUnicode(argc
, argv
);
339 if ( !wxEntryStart(gs_initData
.argc
, gs_initData
.argv
) )
349 #endif // wxUSE_UNICODE
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
355 // cleanup done before destroying wxTheApp
356 static void DoCommonPreCleanup()
359 // flush the logged messages if any and don't use the current probably
360 // unsafe log target any more: the default one (wxLogGui) can't be used
361 // after the resources are freed which happens when we return and the user
362 // supplied one might be even more unsafe (using any wxWidgets GUI function
363 // is unsafe starting from now)
365 // notice that wxLog will still recreate a default log target if any
366 // messages are logged but that one will be safe to use until the very end
367 delete wxLog::SetActiveTarget(NULL
);
371 // cleanup done after destroying wxTheApp
372 static void DoCommonPostCleanup()
374 wxModule::CleanUpModules();
376 // we can't do this in wxApp itself because it doesn't know if argv had
380 #endif // wxUSE_UNICODE
382 // use Set(NULL) and not Get() to avoid creating a message output object on
383 // demand when we just want to delete it
384 delete wxMessageOutput::Set(NULL
);
387 // and now delete the last logger as well
389 // we still don't disable log target auto-vivification even if any log
390 // objects created now will result in memory leaks because it seems better
391 // to leak memory which doesn't matter much considering the application is
392 // exiting anyhow than to not show messages which could still be logged
393 // from the user code (e.g. static dtors and such)
394 delete wxLog::SetActiveTarget(NULL
);
398 void wxEntryCleanup()
400 DoCommonPreCleanup();
403 // delete the application object
408 // reset the global pointer to it to NULL before destroying it as in
409 // some circumstances this can result in executing the code using
410 // wxTheApp and using half-destroyed object is no good
411 wxAppConsole
* const app
= wxApp::GetInstance();
412 wxApp::SetInstance(NULL
);
417 DoCommonPostCleanup();
420 // ----------------------------------------------------------------------------
422 // ----------------------------------------------------------------------------
424 // for MSW the real wxEntry is defined in msw/main.cpp
426 #define wxEntryReal wxEntry
429 int wxEntryReal(int& argc
, wxChar
**argv
)
431 // library initialization
432 wxInitializer
initializer(argc
, argv
);
434 if ( !initializer
.IsOk() )
437 // flush any log messages explaining why we failed
438 delete wxLog::SetActiveTarget(NULL
);
445 // app initialization
446 if ( !wxTheApp
->CallOnInit() )
448 // don't call OnExit() if OnInit() failed
452 // ensure that OnExit() is called if OnInit() had succeeded
456 ~CallOnExit() { wxTheApp
->OnExit(); }
459 WX_SUPPRESS_UNUSED_WARN(callOnExit
);
462 return wxTheApp
->OnRun();
464 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); return -1; )
469 // as with wxEntryStart, we provide an ANSI wrapper
470 int wxEntry(int& argc
, char **argv
)
472 ConvertArgsToUnicode(argc
, argv
);
474 return wxEntry(gs_initData
.argc
, gs_initData
.argv
);
477 #endif // wxUSE_UNICODE
479 // ----------------------------------------------------------------------------
480 // wxInitialize/wxUninitialize
481 // ----------------------------------------------------------------------------
485 return wxInitialize(0, (wxChar
**)NULL
);
488 bool wxInitialize(int argc
, wxChar
**argv
)
490 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
492 if ( gs_initData
.nInitCount
++ )
494 // already initialized
498 return wxEntryStart(argc
, argv
);
502 bool wxInitialize(int argc
, char **argv
)
504 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
506 if ( gs_initData
.nInitCount
++ )
508 // already initialized
512 return wxEntryStart(argc
, argv
);
514 #endif // wxUSE_UNICODE
516 void wxUninitialize()
518 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
520 if ( --gs_initData
.nInitCount
== 0 )