]> git.saurik.com Git - wxWidgets.git/blob - src/common/init.cpp
use common bottleneck
[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(__WINDOWS__)
41 #include "wx/msw/private.h"
42 #include "wx/msw/msvcrt.h"
43
44 #ifdef wxCrtSetDbgFlag
45 static struct EnableMemLeakChecking
46 {
47 EnableMemLeakChecking()
48 {
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);
53 }
54 } gs_enableLeakChecks;
55 #endif // wxCrtSetDbgFlag
56 #endif // __WINDOWS__
57
58 #if wxUSE_UNICODE && defined(__WXOSX__)
59 #include <locale.h>
60 #endif
61
62 // ----------------------------------------------------------------------------
63 // private classes
64 // ----------------------------------------------------------------------------
65
66 // we need a dummy app object if the user doesn't want to create a real one
67 class wxDummyConsoleApp : public wxAppConsole
68 {
69 public:
70 wxDummyConsoleApp() { }
71
72 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
73 virtual bool DoYield(bool, long) { return true; }
74
75 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp);
76 };
77
78 // we need a special kind of auto pointer to wxApp which not only deletes the
79 // pointer it holds in its dtor but also resets the global application pointer
80 wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
81 wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
82
83 class wxAppPtr : public wxAppPtrBase
84 {
85 public:
86 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
87 ~wxAppPtr()
88 {
89 if ( get() )
90 {
91 // the pointer is going to be deleted in the base class dtor, don't
92 // leave the dangling pointer!
93 wxApp::SetInstance(NULL);
94 }
95 }
96
97 void Set(wxAppConsole *ptr)
98 {
99 reset(ptr);
100
101 wxApp::SetInstance(ptr);
102 }
103
104 wxDECLARE_NO_COPY_CLASS(wxAppPtr);
105 };
106
107 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
108 // fails
109 class wxCallAppCleanup
110 {
111 public:
112 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
113 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
114
115 void Dismiss() { m_app = NULL; }
116
117 private:
118 wxAppConsole *m_app;
119 };
120
121 // ----------------------------------------------------------------------------
122 // private functions
123 // ----------------------------------------------------------------------------
124
125 // suppress warnings about unused variables
126 static inline void Use(void *) { }
127
128 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
129
130 // ----------------------------------------------------------------------------
131 // initialization data
132 // ----------------------------------------------------------------------------
133
134 static struct InitData
135 {
136 InitData()
137 {
138 nInitCount = 0;
139
140 #if wxUSE_UNICODE
141 argc = 0;
142 // argv = NULL; -- not even really needed
143 #endif // wxUSE_UNICODE
144 }
145
146 // critical section protecting this struct
147 wxCRIT_SECT_DECLARE_MEMBER(csInit);
148
149 // number of times wxInitialize() was called minus the number of times
150 // wxUninitialize() was
151 size_t nInitCount;
152
153 #if wxUSE_UNICODE
154 int argc;
155
156 // if we receive the command line arguments as ASCII and have to convert
157 // them to Unicode ourselves (this is the case under Unix but not Windows,
158 // for example), we remember the converted argv here because we'll have to
159 // free it when doing cleanup to avoid memory leaks
160 wchar_t **argv;
161 #endif // wxUSE_UNICODE
162
163 wxDECLARE_NO_COPY_CLASS(InitData);
164 } gs_initData;
165
166 // ============================================================================
167 // implementation
168 // ============================================================================
169
170 // ----------------------------------------------------------------------------
171 // command line arguments ANSI -> Unicode conversion
172 // ----------------------------------------------------------------------------
173
174 #if wxUSE_UNICODE
175
176 static void ConvertArgsToUnicode(int argc, char **argv)
177 {
178 gs_initData.argv = new wchar_t *[argc + 1];
179 int wargc = 0;
180 for ( int i = 0; i < argc; i++ )
181 {
182 #ifdef __DARWIN__
183 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
184 #else
185 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
186 #endif
187 if ( !buf )
188 {
189 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
190 i);
191 }
192 else // converted ok
193 {
194 gs_initData.argv[wargc++] = wxStrdup(buf);
195 }
196 }
197
198 gs_initData.argc = wargc;
199 gs_initData.argv[wargc] = NULL;
200 }
201
202 static void FreeConvertedArgs()
203 {
204 if ( gs_initData.argv )
205 {
206 for ( int i = 0; i < gs_initData.argc; i++ )
207 {
208 free(gs_initData.argv[i]);
209 }
210
211 wxDELETEA(gs_initData.argv);
212 gs_initData.argc = 0;
213 }
214 }
215
216 #endif // wxUSE_UNICODE
217
218 // ----------------------------------------------------------------------------
219 // start up
220 // ----------------------------------------------------------------------------
221
222 // initialization which is always done (not customizable) before wxApp creation
223 static bool DoCommonPreInit()
224 {
225 #if wxUSE_UNICODE && defined(__WXOSX__)
226 // In OS X and iOS, wchar_t CRT functions convert to char* and fail under
227 // some locales. The safest fix is to set LC_CTYPE to UTF-8 to ensure that
228 // they can handle any input.
229 //
230 // Note that this must be done for any app, Cocoa or console, whether or
231 // not it uses wxLocale.
232 //
233 // See http://stackoverflow.com/questions/11713745/why-does-the-printf-family-of-functions-care-about-locale
234 setlocale(LC_CTYPE, "UTF-8");
235 #endif // wxUSE_UNICODE && defined(__WXOSX__)
236
237 #if wxUSE_LOG
238 // Reset logging in case we were cleaned up and are being reinitialized.
239 wxLog::DoCreateOnDemand();
240
241 // force wxLog to create a log target now: we do it because wxTheApp
242 // doesn't exist yet so wxLog will create a special log target which is
243 // safe to use even when the GUI is not available while without this call
244 // we could create wxApp in wxEntryStart() below, then log an error about
245 // e.g. failure to establish connection to the X server and wxLog would
246 // send it to wxLogGui (because wxTheApp does exist already) which, of
247 // course, can't be used in this case
248 //
249 // notice also that this does nothing if the user had set up a custom log
250 // target before -- which is fine as we want to give him this possibility
251 // (as it's impossible to override logging by overriding wxAppTraits::
252 // CreateLogTarget() before wxApp is created) and we just assume he knows
253 // what he is doing
254 wxLog::GetActiveTarget();
255 #endif // wxUSE_LOG
256
257 #ifdef __WINDOWS__
258 // GUI applications obtain HINSTANCE in their WinMain() but we also need to
259 // initialize the global wxhInstance variable for the console programs as
260 // they may need it too, so set it here if it wasn't done yet
261 if ( !wxGetInstance() )
262 {
263 wxSetInstance(::GetModuleHandle(NULL));
264 }
265 #endif // __WINDOWS__
266
267 return true;
268 }
269
270 // non customizable initialization done after wxApp creation and initialization
271 static bool DoCommonPostInit()
272 {
273 wxModule::RegisterModules();
274
275 if ( !wxModule::InitializeModules() )
276 {
277 wxLogError(_("Initialization failed in post init, aborting."));
278 return false;
279 }
280
281 return true;
282 }
283
284 bool wxEntryStart(int& argc, wxChar **argv)
285 {
286 // do minimal, always necessary, initialization
287 // --------------------------------------------
288
289 // initialize wxRTTI
290 if ( !DoCommonPreInit() )
291 return false;
292
293
294 // first of all, we need an application object
295 // -------------------------------------------
296
297 // the user might have already created it himself somehow
298 wxAppPtr app(wxTheApp);
299 if ( !app.get() )
300 {
301 // if not, he might have used IMPLEMENT_APP() to give us a function to
302 // create it
303 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
304
305 if ( fnCreate )
306 {
307 // he did, try to create the custom wxApp object
308 app.Set((*fnCreate)());
309 }
310 }
311
312 if ( !app.get() )
313 {
314 // either IMPLEMENT_APP() was not used at all or it failed -- in any
315 // case we still need something
316 app.Set(new wxDummyConsoleApp);
317 }
318
319
320 // wxApp initialization: this can be customized
321 // --------------------------------------------
322
323 if ( !app->Initialize(argc, argv) )
324 return false;
325
326 // remember, possibly modified (e.g. due to removal of toolkit-specific
327 // parameters), command line arguments in member variables
328 app->argc = argc;
329 app->argv = argv;
330
331 wxCallAppCleanup callAppCleanup(app.get());
332
333
334 // common initialization after wxTheApp creation
335 // ---------------------------------------------
336
337 if ( !DoCommonPostInit() )
338 return false;
339
340
341 // prevent the smart pointer from destroying its contents
342 app.release();
343
344 // and the cleanup object from doing cleanup
345 callAppCleanup.Dismiss();
346
347 #if wxUSE_LOG
348 // now that we have a valid wxApp (wxLogGui would have crashed if we used
349 // it before now), we can delete the temporary sink we had created for the
350 // initialization messages -- the next time logging function is called, the
351 // sink will be recreated but this time wxAppTraits will be used
352 delete wxLog::SetActiveTarget(NULL);
353 #endif // wxUSE_LOG
354
355 return true;
356 }
357
358 #if wxUSE_UNICODE
359
360 // we provide a wxEntryStart() wrapper taking "char *" pointer too
361 bool wxEntryStart(int& argc, char **argv)
362 {
363 ConvertArgsToUnicode(argc, argv);
364
365 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
366 {
367 FreeConvertedArgs();
368
369 return false;
370 }
371
372 return true;
373 }
374
375 #endif // wxUSE_UNICODE
376
377 // ----------------------------------------------------------------------------
378 // clean up
379 // ----------------------------------------------------------------------------
380
381 // cleanup done before destroying wxTheApp
382 static void DoCommonPreCleanup()
383 {
384 #if wxUSE_LOG
385 // flush the logged messages if any and don't use the current probably
386 // unsafe log target any more: the default one (wxLogGui) can't be used
387 // after the resources are freed which happens when we return and the user
388 // supplied one might be even more unsafe (using any wxWidgets GUI function
389 // is unsafe starting from now)
390 //
391 // notice that wxLog will still recreate a default log target if any
392 // messages are logged but that one will be safe to use until the very end
393 delete wxLog::SetActiveTarget(NULL);
394 #endif // wxUSE_LOG
395 }
396
397 // cleanup done after destroying wxTheApp
398 static void DoCommonPostCleanup()
399 {
400 wxModule::CleanUpModules();
401
402 // we can't do this in wxApp itself because it doesn't know if argv had
403 // been allocated
404 #if wxUSE_UNICODE
405 FreeConvertedArgs();
406 #endif // wxUSE_UNICODE
407
408 // use Set(NULL) and not Get() to avoid creating a message output object on
409 // demand when we just want to delete it
410 delete wxMessageOutput::Set(NULL);
411
412 #if wxUSE_LOG
413 // call this first as it has a side effect: in addition to flushing all
414 // logs for this thread, it also flushes everything logged from other
415 // threads
416 wxLog::FlushActive();
417
418 // and now delete the last logger as well
419 //
420 // we still don't disable log target auto-vivification even if any log
421 // objects created now will result in memory leaks because it seems better
422 // to leak memory which doesn't matter much considering the application is
423 // exiting anyhow than to not show messages which could still be logged
424 // from the user code (e.g. static dtors and such)
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 __WINDOWS__
457 #define wxEntryReal wxEntry
458 #endif // !__WINDOWS__
459
460 int wxEntryReal(int& argc, wxChar **argv)
461 {
462 // library initialization
463 wxInitializer initializer(argc, argv);
464
465 if ( !initializer.IsOk() )
466 {
467 #if wxUSE_LOG
468 // flush any log messages explaining why we failed
469 delete wxLog::SetActiveTarget(NULL);
470 #endif
471 return -1;
472 }
473
474 wxTRY
475 {
476 // app initialization
477 if ( !wxTheApp->CallOnInit() )
478 {
479 // don't call OnExit() if OnInit() failed
480 return -1;
481 }
482
483 // ensure that OnExit() is called if OnInit() had succeeded
484 class CallOnExit
485 {
486 public:
487 ~CallOnExit() { wxTheApp->OnExit(); }
488 } callOnExit;
489
490 WX_SUPPRESS_UNUSED_WARN(callOnExit);
491
492 // app execution
493 return wxTheApp->OnRun();
494 }
495 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
496 }
497
498 #if wxUSE_UNICODE
499
500 // as with wxEntryStart, we provide an ANSI wrapper
501 int wxEntry(int& argc, char **argv)
502 {
503 ConvertArgsToUnicode(argc, argv);
504
505 return wxEntry(gs_initData.argc, gs_initData.argv);
506 }
507
508 #endif // wxUSE_UNICODE
509
510 // ----------------------------------------------------------------------------
511 // wxInitialize/wxUninitialize
512 // ----------------------------------------------------------------------------
513
514 bool wxInitialize()
515 {
516 return wxInitialize(0, (wxChar**)NULL);
517 }
518
519 bool wxInitialize(int argc, wxChar **argv)
520 {
521 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
522
523 if ( gs_initData.nInitCount++ )
524 {
525 // already initialized
526 return true;
527 }
528
529 return wxEntryStart(argc, argv);
530 }
531
532 #if wxUSE_UNICODE
533 bool wxInitialize(int argc, char **argv)
534 {
535 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
536
537 if ( gs_initData.nInitCount++ )
538 {
539 // already initialized
540 return true;
541 }
542
543 return wxEntryStart(argc, argv);
544 }
545 #endif // wxUSE_UNICODE
546
547 void wxUninitialize()
548 {
549 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
550
551 if ( --gs_initData.nInitCount == 0 )
552 {
553 wxEntryCleanup();
554 }
555 }