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(__WINDOWS__)
41 #include "wx/msw/private.h"
42 #include "wx/msw/msvcrt.h"
44 #ifdef wxCrtSetDbgFlag
45 static struct EnableMemLeakChecking
47 EnableMemLeakChecking()
49 // check for memory leaks on program exit (another useful flag
50 // is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free deallocated
51 // memory which may be used to simulate low-memory condition)
52 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF
);
54 } gs_enableLeakChecks
;
55 #endif // wxCrtSetDbgFlag
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 // we need a dummy app object if the user doesn't want to create a real one
63 class wxDummyConsoleApp
: public wxAppConsole
66 wxDummyConsoleApp() { }
68 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
69 virtual bool DoYield(bool, long) { return true; }
71 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp
);
74 // we need a special kind of auto pointer to wxApp which not only deletes the
75 // pointer it holds in its dtor but also resets the global application pointer
76 wxDECLARE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
77 wxDEFINE_SCOPED_PTR(wxAppConsole
, wxAppPtrBase
)
79 class wxAppPtr
: public wxAppPtrBase
82 wxEXPLICIT
wxAppPtr(wxAppConsole
*ptr
= NULL
) : wxAppPtrBase(ptr
) { }
87 // the pointer is going to be deleted in the base class dtor, don't
88 // leave the dangling pointer!
89 wxApp::SetInstance(NULL
);
93 void Set(wxAppConsole
*ptr
)
97 wxApp::SetInstance(ptr
);
100 wxDECLARE_NO_COPY_CLASS(wxAppPtr
);
103 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
105 class wxCallAppCleanup
108 wxCallAppCleanup(wxAppConsole
*app
) : m_app(app
) { }
109 ~wxCallAppCleanup() { if ( m_app
) m_app
->CleanUp(); }
111 void Dismiss() { m_app
= NULL
; }
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 // suppress warnings about unused variables
122 static inline void Use(void *) { }
124 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
126 // ----------------------------------------------------------------------------
127 // initialization data
128 // ----------------------------------------------------------------------------
130 static struct InitData
138 // argv = NULL; -- not even really needed
139 #endif // wxUSE_UNICODE
142 // critical section protecting this struct
143 wxCRIT_SECT_DECLARE_MEMBER(csInit
);
145 // number of times wxInitialize() was called minus the number of times
146 // wxUninitialize() was
152 // if we receive the command line arguments as ASCII and have to convert
153 // them to Unicode ourselves (this is the case under Unix but not Windows,
154 // for example), we remember the converted argv here because we'll have to
155 // free it when doing cleanup to avoid memory leaks
157 #endif // wxUSE_UNICODE
159 wxDECLARE_NO_COPY_CLASS(InitData
);
162 // ============================================================================
164 // ============================================================================
166 // ----------------------------------------------------------------------------
167 // command line arguments ANSI -> Unicode conversion
168 // ----------------------------------------------------------------------------
172 static void ConvertArgsToUnicode(int argc
, char **argv
)
174 gs_initData
.argv
= new wchar_t *[argc
+ 1];
176 for ( int i
= 0; i
< argc
; i
++ )
179 wxWCharBuffer
buf(wxConvFileName
->cMB2WX(argv
[i
]));
181 wxWCharBuffer
buf(wxConvLocal
.cMB2WX(argv
[i
]));
185 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
190 gs_initData
.argv
[wargc
++] = wxStrdup(buf
);
194 gs_initData
.argc
= wargc
;
195 gs_initData
.argv
[wargc
] = NULL
;
198 static void FreeConvertedArgs()
200 if ( gs_initData
.argv
)
202 for ( int i
= 0; i
< gs_initData
.argc
; i
++ )
204 free(gs_initData
.argv
[i
]);
207 wxDELETEA(gs_initData
.argv
);
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()
221 #if wxUSE_UNICODE && defined(__WXOSX__)
222 // In OS X and iOS, wchar_t CRT functions convert to char* and fail under
223 // some locales. The safest fix is to set LC_CTYPE to UTF-8 to ensure that
224 // they can handle any input.
226 // Note that this must be done for any app, Cocoa or console, whether or
227 // not it uses wxLocale.
229 // See http://stackoverflow.com/questions/11713745/why-does-the-printf-family-of-functions-care-about-locale
230 setlocale(LC_CTYPE
, "UTF-8");
231 #endif // wxUSE_UNICODE && defined(__WXOSX__)
234 // Reset logging in case we were cleaned up and are being reinitialized.
235 wxLog::DoCreateOnDemand();
237 // force wxLog to create a log target now: we do it because wxTheApp
238 // doesn't exist yet so wxLog will create a special log target which is
239 // safe to use even when the GUI is not available while without this call
240 // we could create wxApp in wxEntryStart() below, then log an error about
241 // e.g. failure to establish connection to the X server and wxLog would
242 // send it to wxLogGui (because wxTheApp does exist already) which, of
243 // course, can't be used in this case
245 // notice also that this does nothing if the user had set up a custom log
246 // target before -- which is fine as we want to give him this possibility
247 // (as it's impossible to override logging by overriding wxAppTraits::
248 // CreateLogTarget() before wxApp is created) and we just assume he knows
250 wxLog::GetActiveTarget();
254 // GUI applications obtain HINSTANCE in their WinMain() but we also need to
255 // initialize the global wxhInstance variable for the console programs as
256 // they may need it too, so set it here if it wasn't done yet
257 if ( !wxGetInstance() )
259 wxSetInstance(::GetModuleHandle(NULL
));
261 #endif // __WINDOWS__
266 // non customizable initialization done after wxApp creation and initialization
267 static bool DoCommonPostInit()
269 wxModule::RegisterModules();
271 if ( !wxModule::InitializeModules() )
273 wxLogError(_("Initialization failed in post init, aborting."));
280 bool wxEntryStart(int& argc
, wxChar
**argv
)
282 // do minimal, always necessary, initialization
283 // --------------------------------------------
286 if ( !DoCommonPreInit() )
290 // first of all, we need an application object
291 // -------------------------------------------
293 // the user might have already created it himself somehow
294 wxAppPtr
app(wxTheApp
);
297 // if not, he might have used IMPLEMENT_APP() to give us a function to
299 wxAppInitializerFunction fnCreate
= wxApp::GetInitializerFunction();
303 // he did, try to create the custom wxApp object
304 app
.Set((*fnCreate
)());
310 // either IMPLEMENT_APP() was not used at all or it failed -- in any
311 // case we still need something
312 app
.Set(new wxDummyConsoleApp
);
316 // wxApp initialization: this can be customized
317 // --------------------------------------------
319 if ( !app
->Initialize(argc
, argv
) )
322 // remember, possibly modified (e.g. due to removal of toolkit-specific
323 // parameters), command line arguments in member variables
327 wxCallAppCleanup
callAppCleanup(app
.get());
330 // common initialization after wxTheApp creation
331 // ---------------------------------------------
333 if ( !DoCommonPostInit() )
337 // prevent the smart pointer from destroying its contents
340 // and the cleanup object from doing cleanup
341 callAppCleanup
.Dismiss();
344 // now that we have a valid wxApp (wxLogGui would have crashed if we used
345 // it before now), we can delete the temporary sink we had created for the
346 // initialization messages -- the next time logging function is called, the
347 // sink will be recreated but this time wxAppTraits will be used
348 delete wxLog::SetActiveTarget(NULL
);
356 // we provide a wxEntryStart() wrapper taking "char *" pointer too
357 bool wxEntryStart(int& argc
, char **argv
)
359 ConvertArgsToUnicode(argc
, argv
);
361 if ( !wxEntryStart(gs_initData
.argc
, gs_initData
.argv
) )
371 #endif // wxUSE_UNICODE
373 // ----------------------------------------------------------------------------
375 // ----------------------------------------------------------------------------
377 // cleanup done before destroying wxTheApp
378 static void DoCommonPreCleanup()
381 // flush the logged messages if any and don't use the current probably
382 // unsafe log target any more: the default one (wxLogGui) can't be used
383 // after the resources are freed which happens when we return and the user
384 // supplied one might be even more unsafe (using any wxWidgets GUI function
385 // is unsafe starting from now)
387 // notice that wxLog will still recreate a default log target if any
388 // messages are logged but that one will be safe to use until the very end
389 delete wxLog::SetActiveTarget(NULL
);
393 // cleanup done after destroying wxTheApp
394 static void DoCommonPostCleanup()
396 wxModule::CleanUpModules();
398 // we can't do this in wxApp itself because it doesn't know if argv had
402 #endif // wxUSE_UNICODE
404 // use Set(NULL) and not Get() to avoid creating a message output object on
405 // demand when we just want to delete it
406 delete wxMessageOutput::Set(NULL
);
409 // and now delete the last logger as well
411 // we still don't disable log target auto-vivification even if any log
412 // objects created now will result in memory leaks because it seems better
413 // to leak memory which doesn't matter much considering the application is
414 // exiting anyhow than to not show messages which could still be logged
415 // from the user code (e.g. static dtors and such)
416 delete wxLog::SetActiveTarget(NULL
);
420 void wxEntryCleanup()
422 DoCommonPreCleanup();
425 // delete the application object
430 // reset the global pointer to it to NULL before destroying it as in
431 // some circumstances this can result in executing the code using
432 // wxTheApp and using half-destroyed object is no good
433 wxAppConsole
* const app
= wxApp::GetInstance();
434 wxApp::SetInstance(NULL
);
439 DoCommonPostCleanup();
442 // ----------------------------------------------------------------------------
444 // ----------------------------------------------------------------------------
446 // for MSW the real wxEntry is defined in msw/main.cpp
448 #define wxEntryReal wxEntry
449 #endif // !__WINDOWS__
451 int wxEntryReal(int& argc
, wxChar
**argv
)
453 // library initialization
454 wxInitializer
initializer(argc
, argv
);
456 if ( !initializer
.IsOk() )
459 // flush any log messages explaining why we failed
460 delete wxLog::SetActiveTarget(NULL
);
467 // app initialization
468 if ( !wxTheApp
->CallOnInit() )
470 // don't call OnExit() if OnInit() failed
474 // ensure that OnExit() is called if OnInit() had succeeded
478 ~CallOnExit() { wxTheApp
->OnExit(); }
481 WX_SUPPRESS_UNUSED_WARN(callOnExit
);
484 return wxTheApp
->OnRun();
486 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); return -1; )
491 // as with wxEntryStart, we provide an ANSI wrapper
492 int wxEntry(int& argc
, char **argv
)
494 ConvertArgsToUnicode(argc
, argv
);
496 return wxEntry(gs_initData
.argc
, gs_initData
.argv
);
499 #endif // wxUSE_UNICODE
501 // ----------------------------------------------------------------------------
502 // wxInitialize/wxUninitialize
503 // ----------------------------------------------------------------------------
507 return wxInitialize(0, (wxChar
**)NULL
);
510 bool wxInitialize(int argc
, wxChar
**argv
)
512 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
514 if ( gs_initData
.nInitCount
++ )
516 // already initialized
520 return wxEntryStart(argc
, argv
);
524 bool wxInitialize(int argc
, char **argv
)
526 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
528 if ( gs_initData
.nInitCount
++ )
530 // already initialized
534 return wxEntryStart(argc
, argv
);
536 #endif // wxUSE_UNICODE
538 void wxUninitialize()
540 wxCRIT_SECT_LOCKER(lockInit
, gs_initData
.csInit
);
542 if ( --gs_initData
.nInitCount
== 0 )