replace more __WXDEBUG__ occurrences with wxDEBUG_LEVEL
[wxWidgets.git] / src / common / init.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/init.cpp
3 // Purpose: initialisation for the library
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 04.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif //__BORLANDC__
25
26 #ifndef WX_PRECOMP
27 #include "wx/app.h"
28 #include "wx/filefn.h"
29 #include "wx/log.h"
30 #include "wx/intl.h"
31 #include "wx/module.h"
32 #endif
33
34 #include "wx/init.h"
35 #include "wx/thread.h"
36
37 #include "wx/scopedptr.h"
38 #include "wx/except.h"
39
40 #if defined(__WXMSW__)
41 #include "wx/msw/msvcrt.h"
42
43 #ifdef wxCrtSetDbgFlag
44 static struct EnableMemLeakChecking
45 {
46 EnableMemLeakChecking()
47 {
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);
52 }
53 } gs_enableLeakChecks;
54 #endif // wxCrtSetDbgFlag
55 #endif // __WXMSW__
56
57 // ----------------------------------------------------------------------------
58 // private classes
59 // ----------------------------------------------------------------------------
60
61 // we need a dummy app object if the user doesn't want to create a real one
62 class wxDummyConsoleApp : public wxAppConsole
63 {
64 public:
65 wxDummyConsoleApp() { }
66
67 virtual int OnRun() { wxFAIL_MSG( _T("unreachable code") ); return 0; }
68 virtual bool DoYield(bool, long) { return true; }
69
70 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp);
71 };
72
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)
77
78 class wxAppPtr : public wxAppPtrBase
79 {
80 public:
81 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
82 ~wxAppPtr()
83 {
84 if ( get() )
85 {
86 // the pointer is going to be deleted in the base class dtor, don't
87 // leave the dangling pointer!
88 wxApp::SetInstance(NULL);
89 }
90 }
91
92 void Set(wxAppConsole *ptr)
93 {
94 reset(ptr);
95
96 wxApp::SetInstance(ptr);
97 }
98
99 wxDECLARE_NO_COPY_CLASS(wxAppPtr);
100 };
101
102 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
103 // fails
104 class wxCallAppCleanup
105 {
106 public:
107 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
108 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
109
110 void Dismiss() { m_app = NULL; }
111
112 private:
113 wxAppConsole *m_app;
114 };
115
116 // another tiny class which simply exists to ensure that wxEntryCleanup is
117 // always called
118 class wxCleanupOnExit
119 {
120 public:
121 ~wxCleanupOnExit() { wxEntryCleanup(); }
122 };
123
124 // ----------------------------------------------------------------------------
125 // private functions
126 // ----------------------------------------------------------------------------
127
128 // suppress warnings about unused variables
129 static inline void Use(void *) { }
130
131 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
132
133 // ----------------------------------------------------------------------------
134 // initialization data
135 // ----------------------------------------------------------------------------
136
137 static struct InitData
138 {
139 InitData()
140 {
141 nInitCount = 0;
142
143 #if wxUSE_UNICODE
144 argc = 0;
145 // argv = NULL; -- not even really needed
146 #endif // wxUSE_UNICODE
147 }
148
149 // critical section protecting this struct
150 wxCRIT_SECT_DECLARE_MEMBER(csInit);
151
152 // number of times wxInitialize() was called minus the number of times
153 // wxUninitialize() was
154 size_t nInitCount;
155
156 #if wxUSE_UNICODE
157 int argc;
158
159 // if we receive the command line arguments as ASCII and have to convert
160 // them to Unicode ourselves (this is the case under Unix but not Windows,
161 // for example), we remember the converted argv here because we'll have to
162 // free it when doing cleanup to avoid memory leaks
163 wchar_t **argv;
164 #endif // wxUSE_UNICODE
165
166 wxDECLARE_NO_COPY_CLASS(InitData);
167 } gs_initData;
168
169 // ============================================================================
170 // implementation
171 // ============================================================================
172
173 // ----------------------------------------------------------------------------
174 // command line arguments ANSI -> Unicode conversion
175 // ----------------------------------------------------------------------------
176
177 #if wxUSE_UNICODE
178
179 static void ConvertArgsToUnicode(int argc, char **argv)
180 {
181 gs_initData.argv = new wchar_t *[argc + 1];
182 int wargc = 0;
183 for ( int i = 0; i < argc; i++ )
184 {
185 #ifdef __DARWIN__
186 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
187 #else
188 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
189 #endif
190 if ( !buf )
191 {
192 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
193 i);
194 }
195 else // converted ok
196 {
197 gs_initData.argv[wargc++] = wxStrdup(buf);
198 }
199 }
200
201 gs_initData.argc = wargc;
202 gs_initData.argv[wargc] = NULL;
203 }
204
205 static void FreeConvertedArgs()
206 {
207 if ( gs_initData.argv )
208 {
209 for ( int i = 0; i < gs_initData.argc; i++ )
210 {
211 free(gs_initData.argv[i]);
212 }
213
214 delete [] gs_initData.argv;
215 gs_initData.argv = NULL;
216 gs_initData.argc = 0;
217 }
218 }
219
220 #endif // wxUSE_UNICODE
221
222 // ----------------------------------------------------------------------------
223 // start up
224 // ----------------------------------------------------------------------------
225
226 // initialization which is always done (not customizable) before wxApp creation
227 static bool DoCommonPreInit()
228 {
229 #if wxUSE_LOG
230 // Reset logging in case we were cleaned up and are being reinitialized.
231 wxLog::DoCreateOnDemand();
232
233 // install temporary log sink: we can't use wxLogGui before wxApp is
234 // constructed and if we use wxLogStderr, all messages during
235 // initialization simply disappear under Windows
236 //
237 // note that we will delete this log target below
238 delete wxLog::SetActiveTarget(new wxLogBuffer);
239 #endif // wxUSE_LOG
240
241 return true;
242 }
243
244 // non customizable initialization done after wxApp creation and initialization
245 static bool DoCommonPostInit()
246 {
247 wxModule::RegisterModules();
248
249 if ( !wxModule::InitializeModules() )
250 {
251 wxLogError(_("Initialization failed in post init, aborting."));
252 return false;
253 }
254
255 #if defined(__WXDEBUG__)
256 // check if event classes implement Clone() correctly
257 // NOTE: the check is done against _all_ event classes which are linked to
258 // the executable currently running, which are not necessarily all
259 // wxWidgets event classes.
260 const wxClassInfo *ci = wxClassInfo::GetFirst();
261 for (; ci; ci = ci->GetNext())
262 {
263 // is this class derived from wxEvent?
264 if (!ci->IsKindOf(CLASSINFO(wxEvent)) || wxString(ci->GetClassName()) == "wxEvent")
265 continue;
266
267 if (!ci->IsDynamic())
268 {
269 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
270 ci->GetClassName());
271 continue;
272 }
273
274 // yes; test if it implements Clone() correctly
275 wxEvent* test = wxDynamicCast(ci->CreateObject(),wxEvent);
276 if (test == NULL)
277 {
278 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
279 ci->GetClassName());
280 continue;
281 }
282
283 wxEvent* cloned = test->Clone();
284 if (!cloned || cloned->GetClassInfo() != ci)
285 wxLogWarning("The event class '%s' does not correctly implement Clone()!",
286 ci->GetClassName());
287
288 delete cloned;
289 delete test;
290 }
291 #endif
292
293 return true;
294 }
295
296 bool wxEntryStart(int& argc, wxChar **argv)
297 {
298 // do minimal, always necessary, initialization
299 // --------------------------------------------
300
301 // initialize wxRTTI
302 if ( !DoCommonPreInit() )
303 return false;
304
305
306 // first of all, we need an application object
307 // -------------------------------------------
308
309 // the user might have already created it himself somehow
310 wxAppPtr app(wxTheApp);
311 if ( !app.get() )
312 {
313 // if not, he might have used IMPLEMENT_APP() to give us a function to
314 // create it
315 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
316
317 if ( fnCreate )
318 {
319 // he did, try to create the custom wxApp object
320 app.Set((*fnCreate)());
321 }
322 }
323
324 if ( !app.get() )
325 {
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);
329 }
330
331
332 // wxApp initialization: this can be customized
333 // --------------------------------------------
334
335 if ( !app->Initialize(argc, argv) )
336 return false;
337
338 // remember, possibly modified (e.g. due to removal of toolkit-specific
339 // parameters), command line arguments in member variables
340 app->argc = argc;
341 app->argv = argv;
342
343 wxCallAppCleanup callAppCleanup(app.get());
344
345
346 // common initialization after wxTheApp creation
347 // ---------------------------------------------
348
349 if ( !DoCommonPostInit() )
350 return false;
351
352
353 // prevent the smart pointer from destroying its contents
354 app.release();
355
356 // and the cleanup object from doing cleanup
357 callAppCleanup.Dismiss();
358
359 #if wxUSE_LOG
360 // now that we have a valid wxApp (wxLogGui would have crashed if we used
361 // it before now), we can delete the temporary sink we had created for the
362 // initialization messages -- the next time logging function is called, the
363 // sink will be recreated but this time wxAppTraits will be used
364 delete wxLog::SetActiveTarget(NULL);
365 #endif // wxUSE_LOG
366
367 return true;
368 }
369
370 #if wxUSE_UNICODE
371
372 // we provide a wxEntryStart() wrapper taking "char *" pointer too
373 bool wxEntryStart(int& argc, char **argv)
374 {
375 ConvertArgsToUnicode(argc, argv);
376
377 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
378 {
379 FreeConvertedArgs();
380
381 return false;
382 }
383
384 return true;
385 }
386
387 #endif // wxUSE_UNICODE
388
389 // ----------------------------------------------------------------------------
390 // clean up
391 // ----------------------------------------------------------------------------
392
393 // cleanup done before destroying wxTheApp
394 static void DoCommonPreCleanup()
395 {
396 #if wxUSE_LOG
397 // flush the logged messages if any and install a 'safer' log target: the
398 // default one (wxLogGui) can't be used after the resources are freed just
399 // below and the user supplied one might be even more unsafe (using any
400 // wxWidgets GUI function is unsafe starting from now)
401 wxLog::DontCreateOnDemand();
402
403 // this will flush the old messages if any
404 delete wxLog::SetActiveTarget(new wxLogStderr);
405 #endif // wxUSE_LOG
406 }
407
408 // cleanup done after destroying wxTheApp
409 static void DoCommonPostCleanup()
410 {
411 wxModule::CleanUpModules();
412
413 // we can't do this in wxApp itself because it doesn't know if argv had
414 // been allocated
415 #if wxUSE_UNICODE
416 FreeConvertedArgs();
417 #endif // wxUSE_UNICODE
418
419 // use Set(NULL) and not Get() to avoid creating a message output object on
420 // demand when we just want to delete it
421 delete wxMessageOutput::Set(NULL);
422
423 #if wxUSE_LOG
424 // and now delete the last logger as well
425 delete wxLog::SetActiveTarget(NULL);
426 #endif // wxUSE_LOG
427 }
428
429 void wxEntryCleanup()
430 {
431 DoCommonPreCleanup();
432
433
434 // delete the application object
435 if ( wxTheApp )
436 {
437 wxTheApp->CleanUp();
438
439 // reset the global pointer to it to NULL before destroying it as in
440 // some circumstances this can result in executing the code using
441 // wxTheApp and using half-destroyed object is no good
442 wxAppConsole * const app = wxApp::GetInstance();
443 wxApp::SetInstance(NULL);
444 delete app;
445 }
446
447
448 DoCommonPostCleanup();
449 }
450
451 // ----------------------------------------------------------------------------
452 // wxEntry
453 // ----------------------------------------------------------------------------
454
455 // for MSW the real wxEntry is defined in msw/main.cpp
456 #ifndef __WXMSW__
457 #define wxEntryReal wxEntry
458 #endif // !__WXMSW__
459
460 int wxEntryReal(int& argc, wxChar **argv)
461 {
462 // library initialization
463 if ( !wxEntryStart(argc, argv) )
464 {
465 #if wxUSE_LOG
466 // flush any log messages explaining why we failed
467 delete wxLog::SetActiveTarget(NULL);
468 #endif
469 return -1;
470 }
471
472 // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code
473 // below returns or throws
474 wxCleanupOnExit cleanupOnExit;
475
476 WX_SUPPRESS_UNUSED_WARN(cleanupOnExit);
477
478 wxTRY
479 {
480 // app initialization
481 if ( !wxTheApp->CallOnInit() )
482 {
483 // don't call OnExit() if OnInit() failed
484 return -1;
485 }
486
487 // ensure that OnExit() is called if OnInit() had succeeded
488 class CallOnExit
489 {
490 public:
491 ~CallOnExit() { wxTheApp->OnExit(); }
492 } callOnExit;
493
494 WX_SUPPRESS_UNUSED_WARN(callOnExit);
495
496 // app execution
497 return wxTheApp->OnRun();
498 }
499 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
500 }
501
502 #if wxUSE_UNICODE
503
504 // as with wxEntryStart, we provide an ANSI wrapper
505 int wxEntry(int& argc, char **argv)
506 {
507 ConvertArgsToUnicode(argc, argv);
508
509 return wxEntry(gs_initData.argc, gs_initData.argv);
510 }
511
512 #endif // wxUSE_UNICODE
513
514 // ----------------------------------------------------------------------------
515 // wxInitialize/wxUninitialize
516 // ----------------------------------------------------------------------------
517
518 bool wxInitialize(int argc, wxChar **argv)
519 {
520 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
521
522 if ( gs_initData.nInitCount++ )
523 {
524 // already initialized
525 return true;
526 }
527
528 return wxEntryStart(argc, argv);
529 }
530
531 void wxUninitialize()
532 {
533 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
534
535 if ( --gs_initData.nInitCount == 0 )
536 {
537 wxEntryCleanup();
538 }
539 }