delete the old log target if one had been created somehow even before DoCommonPreInit...
[wxWidgets.git] / src / common / init.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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/debug.h"
29 #include "wx/filefn.h"
30 #include "wx/log.h"
31 #include "wx/thread.h"
32 #include "wx/intl.h"
33 #endif
34
35 #include "wx/init.h"
36
37 #include "wx/ptr_scpd.h"
38 #include "wx/module.h"
39 #include "wx/except.h"
40
41 #if defined(__WXMSW__) && defined(__WXDEBUG__)
42 #include "wx/msw/msvcrt.h"
43
44 static struct EnableMemLeakChecking
45 {
46 EnableMemLeakChecking()
47 {
48 // do 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 // __WXMSW__ && __WXDEBUG__
55
56 // ----------------------------------------------------------------------------
57 // private classes
58 // ----------------------------------------------------------------------------
59
60 // we need a dummy app object if the user doesn't want to create a real one
61 class wxDummyConsoleApp : public wxAppConsole
62 {
63 public:
64 wxDummyConsoleApp() { }
65
66 virtual int OnRun() { wxFAIL_MSG( _T("unreachable code") ); return 0; }
67
68 DECLARE_NO_COPY_CLASS(wxDummyConsoleApp)
69 };
70
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)
75
76 class wxAppPtr : public wxAppPtrBase
77 {
78 public:
79 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
80 ~wxAppPtr()
81 {
82 if ( get() )
83 {
84 // the pointer is going to be deleted in the base class dtor, don't
85 // leave the dangling pointer!
86 wxApp::SetInstance(NULL);
87 }
88 }
89
90 void Set(wxAppConsole *ptr)
91 {
92 reset(ptr);
93
94 wxApp::SetInstance(ptr);
95 }
96
97 DECLARE_NO_COPY_CLASS(wxAppPtr)
98 };
99
100 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
101 // fails
102 class wxCallAppCleanup
103 {
104 public:
105 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
106 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
107
108 void Dismiss() { m_app = NULL; }
109
110 private:
111 wxAppConsole *m_app;
112 };
113
114 // another tiny class which simply exists to ensure that wxEntryCleanup is
115 // always called
116 class wxCleanupOnExit
117 {
118 public:
119 ~wxCleanupOnExit() { wxEntryCleanup(); }
120 };
121
122 // ----------------------------------------------------------------------------
123 // private functions
124 // ----------------------------------------------------------------------------
125
126 // suppress warnings about unused variables
127 static inline void Use(void *) { }
128
129 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
130
131 // ----------------------------------------------------------------------------
132 // initialization data
133 // ----------------------------------------------------------------------------
134
135 static struct InitData
136 {
137 InitData()
138 {
139 nInitCount = 0;
140
141 #if wxUSE_UNICODE
142 argc = 0;
143 // argv = NULL; -- not even really needed
144 #endif // wxUSE_UNICODE
145 }
146
147 // critical section protecting this struct
148 wxCRIT_SECT_DECLARE_MEMBER(csInit);
149
150 // number of times wxInitialize() was called minus the number of times
151 // wxUninitialize() was
152 size_t nInitCount;
153
154 #if wxUSE_UNICODE
155 int argc;
156
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
161 wchar_t **argv;
162 #endif // wxUSE_UNICODE
163
164 DECLARE_NO_COPY_CLASS(InitData)
165 } gs_initData;
166
167 // ============================================================================
168 // implementation
169 // ============================================================================
170
171 // ----------------------------------------------------------------------------
172 // command line arguments ANSI -> Unicode conversion
173 // ----------------------------------------------------------------------------
174
175 #if wxUSE_UNICODE
176
177 static void ConvertArgsToUnicode(int argc, char **argv)
178 {
179 gs_initData.argv = new wchar_t *[argc + 1];
180 for ( int i = 0; i < argc; i++ )
181 {
182 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
183 gs_initData.argv[i] = buf ? wxStrdup(buf) : NULL;
184 }
185
186 gs_initData.argc = argc;
187 gs_initData.argv[argc] = NULL;
188 }
189
190 static void FreeConvertedArgs()
191 {
192 if ( gs_initData.argv )
193 {
194 for ( int i = 0; i < gs_initData.argc; i++ )
195 {
196 free(gs_initData.argv[i]);
197 }
198
199 delete [] gs_initData.argv;
200 gs_initData.argv = NULL;
201 gs_initData.argc = 0;
202 }
203 }
204
205 #endif // wxUSE_UNICODE
206
207 // ----------------------------------------------------------------------------
208 // start up
209 // ----------------------------------------------------------------------------
210
211 // initialization which is always done (not customizable) before wxApp creation
212 static bool DoCommonPreInit()
213 {
214 #if wxUSE_LOG
215 // install temporary log sink: we can't use wxLogGui before wxApp is
216 // constructed and if we use wxLogStderr, all messages during
217 // initialization simply disappear under Windows
218 //
219 // note that we will delete this log target below
220 delete wxLog::SetActiveTarget(new wxLogBuffer);
221 #endif // wxUSE_LOG
222
223 return true;
224 }
225
226 // non customizable initialization done after wxApp creation and initialization
227 static bool DoCommonPostInit()
228 {
229 wxModule::RegisterModules();
230
231 if ( !wxModule::InitializeModules() )
232 {
233 wxLogError(_("Initialization failed in post init, aborting."));
234 return false;
235 }
236
237 return true;
238 }
239
240 bool wxEntryStart(int& argc, wxChar **argv)
241 {
242 // do minimal, always necessary, initialization
243 // --------------------------------------------
244
245 // initialize wxRTTI
246 if ( !DoCommonPreInit() )
247 {
248 return false;
249 }
250
251
252 // first of all, we need an application object
253 // -------------------------------------------
254
255 // the user might have already created it himself somehow
256 wxAppPtr app(wxTheApp);
257 if ( !app.get() )
258 {
259 // if not, he might have used IMPLEMENT_APP() to give us a function to
260 // create it
261 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
262
263 if ( fnCreate )
264 {
265 // he did, try to create the custom wxApp object
266 app.Set((*fnCreate)());
267 }
268 }
269
270 if ( !app.get() )
271 {
272 // either IMPLEMENT_APP() was not used at all or it failed -- in any
273 // case we still need something
274 app.Set(new wxDummyConsoleApp);
275 }
276
277
278 // wxApp initialization: this can be customized
279 // --------------------------------------------
280
281 if ( !app->Initialize(argc, argv) )
282 {
283 return false;
284 }
285
286 wxCallAppCleanup callAppCleanup(app.get());
287
288 // for compatibility call the old initialization function too
289 if ( !app->OnInitGui() )
290 return false;
291
292
293 // common initialization after wxTheApp creation
294 // ---------------------------------------------
295
296 if ( !DoCommonPostInit() )
297 return false;
298
299
300 // prevent the smart pointer from destroying its contents
301 app.release();
302
303 // and the cleanup object from doing cleanup
304 callAppCleanup.Dismiss();
305
306 #if wxUSE_LOG
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);
312 #endif // wxUSE_LOG
313
314 return true;
315 }
316
317 #if wxUSE_UNICODE
318
319 // we provide a wxEntryStart() wrapper taking "char *" pointer too
320 bool wxEntryStart(int& argc, char **argv)
321 {
322 ConvertArgsToUnicode(argc, argv);
323
324 if ( !wxEntryStart(argc, gs_initData.argv) )
325 {
326 FreeConvertedArgs();
327
328 return false;
329 }
330
331 return true;
332 }
333
334 #endif // wxUSE_UNICODE
335
336 // ----------------------------------------------------------------------------
337 // clean up
338 // ----------------------------------------------------------------------------
339
340 // cleanup done before destroying wxTheApp
341 static void DoCommonPreCleanup()
342 {
343 #if wxUSE_LOG
344 // flush the logged messages if any and install a 'safer' log target: the
345 // default one (wxLogGui) can't be used after the resources are freed just
346 // below and the user supplied one might be even more unsafe (using any
347 // wxWidgets GUI function is unsafe starting from now)
348 wxLog::DontCreateOnDemand();
349
350 // this will flush the old messages if any
351 delete wxLog::SetActiveTarget(new wxLogStderr);
352 #endif // wxUSE_LOG
353 }
354
355 // cleanup done after destroying wxTheApp
356 static void DoCommonPostCleanup()
357 {
358 wxModule::CleanUpModules();
359
360 // we can't do this in wxApp itself because it doesn't know if argv had
361 // been allocated
362 #if wxUSE_UNICODE
363 FreeConvertedArgs();
364 #endif // wxUSE_UNICODE
365
366 // use Set(NULL) and not Get() to avoid creating a message output object on
367 // demand when we just want to delete it
368 delete wxMessageOutput::Set(NULL);
369
370 #if wxUSE_LOG
371 // and now delete the last logger as well
372 delete wxLog::SetActiveTarget(NULL);
373 #endif // wxUSE_LOG
374 }
375
376 void wxEntryCleanup()
377 {
378 DoCommonPreCleanup();
379
380
381 // delete the application object
382 if ( wxTheApp )
383 {
384 wxTheApp->CleanUp();
385
386 delete wxTheApp;
387 wxApp::SetInstance(NULL);
388 }
389
390
391 DoCommonPostCleanup();
392 }
393
394 // ----------------------------------------------------------------------------
395 // wxEntry
396 // ----------------------------------------------------------------------------
397
398 // for MSW the real wxEntry is defined in msw/main.cpp
399 #ifndef __WXMSW__
400 #define wxEntryReal wxEntry
401 #endif // !__WXMSW__
402
403 int wxEntryReal(int& argc, wxChar **argv)
404 {
405 // library initialization
406 if ( !wxEntryStart(argc, argv) )
407 {
408 #if wxUSE_LOG
409 // flush any log messages explaining why we failed
410 delete wxLog::SetActiveTarget(NULL);
411 #endif
412 return -1;
413 }
414
415 // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code
416 // below returns or throws
417 wxCleanupOnExit cleanupOnExit;
418
419 WX_SUPPRESS_UNUSED_WARN(cleanupOnExit);
420
421 wxTRY
422 {
423
424 // app initialization
425 if ( !wxTheApp->CallOnInit() )
426 {
427 // don't call OnExit() if OnInit() failed
428 return -1;
429 }
430
431 // ensure that OnExit() is called if OnInit() had succeeded
432 class CallOnExit
433 {
434 public:
435 ~CallOnExit() { wxTheApp->OnExit(); }
436 } callOnExit;
437
438 WX_SUPPRESS_UNUSED_WARN(callOnExit);
439
440 // app execution
441 return wxTheApp->OnRun();
442 }
443 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
444 }
445
446 #if wxUSE_UNICODE
447
448 // as with wxEntryStart, we provide an ANSI wrapper
449 int wxEntry(int& argc, char **argv)
450 {
451 ConvertArgsToUnicode(argc, argv);
452
453 return wxEntry(argc, gs_initData.argv);
454 }
455
456 #endif // wxUSE_UNICODE
457
458 // ----------------------------------------------------------------------------
459 // wxInitialize/wxUninitialize
460 // ----------------------------------------------------------------------------
461
462 bool wxInitialize(int argc, wxChar **argv)
463 {
464 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
465
466 if ( gs_initData.nInitCount++ )
467 {
468 // already initialized
469 return true;
470 }
471
472 return wxEntryStart(argc, argv);
473 }
474
475 void wxUninitialize()
476 {
477 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
478
479 if ( --gs_initData.nInitCount == 0 )
480 {
481 wxEntryCleanup();
482 }
483 }
484