]> git.saurik.com Git - wxWidgets.git/blame - src/common/init.cpp
Better compatibility with old files when creating an image cache
[wxWidgets.git] / src / common / init.cpp
CommitLineData
e90c1d2a 1/////////////////////////////////////////////////////////////////////////////
9a6384ca 2// Name: src/common/init.cpp
e90c1d2a
VZ
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
65571936 9// Licence: wxWindows licence
e90c1d2a
VZ
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
f4c890fd
JS
20#include "wx/wxprec.h"
21
22#ifdef __BORLANDC__
9a6384ca 23 #pragma hdrstop
f4c890fd
JS
24#endif //__BORLANDC__
25
e87271f3
VZ
26#ifndef WX_PRECOMP
27 #include "wx/app.h"
bc385ba9 28 #include "wx/filefn.h"
e2450fa9 29 #include "wx/log.h"
a20599da 30 #include "wx/intl.h"
02761f6c 31 #include "wx/module.h"
e87271f3 32#endif
e90c1d2a 33
abca8ebf 34#include "wx/init.h"
50a743c9 35#include "wx/thread.h"
abca8ebf 36
664e1314 37#include "wx/scopedptr.h"
fb3e83b6 38#include "wx/except.h"
51abe921 39
d98a58c5 40#if defined(__WINDOWS__)
98a0eff6 41 #include "wx/msw/private.h"
94826170
VZ
42 #include "wx/msw/msvcrt.h"
43
4b6a582b
VZ
44 #ifdef wxCrtSetDbgFlag
45 static struct EnableMemLeakChecking
94826170 46 {
4b6a582b
VZ
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
d98a58c5 56#endif // __WINDOWS__
94826170 57
f5462b02
VS
58#if wxUSE_UNICODE && defined(__WXOSX__)
59 #include <locale.h>
60#endif
61
e90c1d2a
VZ
62// ----------------------------------------------------------------------------
63// private classes
64// ----------------------------------------------------------------------------
65
e2478fde 66// we need a dummy app object if the user doesn't want to create a real one
94826170 67class wxDummyConsoleApp : public wxAppConsole
e90c1d2a
VZ
68{
69public:
fc7a2a60
VZ
70 wxDummyConsoleApp() { }
71
9a83f860 72 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
d48b06bd 73 virtual bool DoYield(bool, long) { return true; }
fc7a2a60 74
c0c133e1 75 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp);
e90c1d2a
VZ
76};
77
94826170 78// we need a special kind of auto pointer to wxApp which not only deletes the
7cafd224 79// pointer it holds in its dtor but also resets the global application pointer
d0ee33f5
WS
80wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
81wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
bc385ba9 82
94826170
VZ
83class wxAppPtr : public wxAppPtrBase
84{
85public:
77c6966e 86 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
94826170
VZ
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!
a80e5f9e 93 wxApp::SetInstance(NULL);
94826170
VZ
94 }
95 }
96
77c6966e 97 void Set(wxAppConsole *ptr)
94826170
VZ
98 {
99 reset(ptr);
100
a80e5f9e 101 wxApp::SetInstance(ptr);
94826170 102 }
fc7a2a60 103
c0c133e1 104 wxDECLARE_NO_COPY_CLASS(wxAppPtr);
94826170
VZ
105};
106
05e2b077
VZ
107// class to ensure that wxAppBase::CleanUp() is called if our Initialize()
108// fails
109class wxCallAppCleanup
110{
111public:
77c6966e 112 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
05e2b077
VZ
113 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
114
115 void Dismiss() { m_app = NULL; }
116
117private:
77c6966e 118 wxAppConsole *m_app;
05e2b077
VZ
119};
120
005b5298
VZ
121// ----------------------------------------------------------------------------
122// private functions
123// ----------------------------------------------------------------------------
124
125// suppress warnings about unused variables
126static inline void Use(void *) { }
127
128#define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
129
e90c1d2a 130// ----------------------------------------------------------------------------
94826170 131// initialization data
e90c1d2a
VZ
132// ----------------------------------------------------------------------------
133
94826170
VZ
134static 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
150cb195 160 wchar_t **argv;
94826170 161#endif // wxUSE_UNICODE
fc7a2a60 162
c0c133e1 163 wxDECLARE_NO_COPY_CLASS(InitData);
94826170 164} gs_initData;
e90c1d2a
VZ
165
166// ============================================================================
167// implementation
168// ============================================================================
169
252a752e 170// ----------------------------------------------------------------------------
94826170 171// command line arguments ANSI -> Unicode conversion
252a752e
VZ
172// ----------------------------------------------------------------------------
173
94826170
VZ
174#if wxUSE_UNICODE
175
176static void ConvertArgsToUnicode(int argc, char **argv)
e90c1d2a 177{
94826170 178 gs_initData.argv = new wchar_t *[argc + 1];
265db88d 179 int wargc = 0;
94826170 180 for ( int i = 0; i < argc; i++ )
e90c1d2a 181 {
a47f55c5
SC
182#ifdef __DARWIN__
183 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
184#else
faa112c4 185 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
a47f55c5 186#endif
265db88d
VZ
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 }
e90c1d2a
VZ
196 }
197
265db88d
VZ
198 gs_initData.argc = wargc;
199 gs_initData.argv[wargc] = NULL;
94826170 200}
e90c1d2a 201
94826170
VZ
202static void FreeConvertedArgs()
203{
150cb195 204 if ( gs_initData.argv )
bbfa0322 205 {
150cb195
VZ
206 for ( int i = 0; i < gs_initData.argc; i++ )
207 {
208 free(gs_initData.argv[i]);
209 }
210
5276b0a5 211 wxDELETEA(gs_initData.argv);
08989e30 212 gs_initData.argc = 0;
bbfa0322 213 }
94826170 214}
bbfa0322 215
94826170 216#endif // wxUSE_UNICODE
e90c1d2a 217
94826170
VZ
218// ----------------------------------------------------------------------------
219// start up
220// ----------------------------------------------------------------------------
bbfa0322 221
94826170
VZ
222// initialization which is always done (not customizable) before wxApp creation
223static bool DoCommonPreInit()
224{
270bae20
VS
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
1c7b2f01 237#if wxUSE_LOG
e94cd97d
DE
238 // Reset logging in case we were cleaned up and are being reinitialized.
239 wxLog::DoCreateOnDemand();
a2084452
VZ
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();
1c7b2f01
VZ
255#endif // wxUSE_LOG
256
d98a58c5 257#ifdef __WINDOWS__
98a0eff6
VZ
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 }
d98a58c5 265#endif // __WINDOWS__
98a0eff6 266
94826170 267 return true;
e90c1d2a
VZ
268}
269
94826170
VZ
270// non customizable initialization done after wxApp creation and initialization
271static bool DoCommonPostInit()
e90c1d2a 272{
94826170
VZ
273 wxModule::RegisterModules();
274
1c7b2f01
VZ
275 if ( !wxModule::InitializeModules() )
276 {
277 wxLogError(_("Initialization failed in post init, aborting."));
278 return false;
279 }
280
281 return true;
bc385ba9
VZ
282}
283
05e2b077 284bool wxEntryStart(int& argc, wxChar **argv)
bc385ba9 285{
94826170
VZ
286 // do minimal, always necessary, initialization
287 // --------------------------------------------
288
289 // initialize wxRTTI
290 if ( !DoCommonPreInit() )
94826170 291 return false;
bc385ba9 292
bc385ba9 293
94826170
VZ
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
bc385ba9
VZ
303 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
304
94826170
VZ
305 if ( fnCreate )
306 {
307 // he did, try to create the custom wxApp object
7cafd224 308 app.Set((*fnCreate)());
94826170
VZ
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
7cafd224 316 app.Set(new wxDummyConsoleApp);
bc385ba9
VZ
317 }
318
bc385ba9 319
94826170
VZ
320 // wxApp initialization: this can be customized
321 // --------------------------------------------
bc385ba9 322
7cafd224 323 if ( !app->Initialize(argc, argv) )
94826170 324 return false;
bc385ba9 325
4f6b94a3
VZ
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
7cafd224 331 wxCallAppCleanup callAppCleanup(app.get());
05e2b077 332
bc385ba9 333
94826170
VZ
334 // common initialization after wxTheApp creation
335 // ---------------------------------------------
bc385ba9 336
94826170 337 if ( !DoCommonPostInit() )
94826170 338 return false;
bc385ba9 339
bc385ba9 340
94826170
VZ
341 // prevent the smart pointer from destroying its contents
342 app.release();
343
05e2b077
VZ
344 // and the cleanup object from doing cleanup
345 callAppCleanup.Dismiss();
346
1c7b2f01
VZ
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
94826170 355 return true;
bc385ba9
VZ
356}
357
94826170 358#if wxUSE_UNICODE
bbfa0322 359
94826170 360// we provide a wxEntryStart() wrapper taking "char *" pointer too
05e2b077 361bool wxEntryStart(int& argc, char **argv)
bc385ba9 362{
94826170 363 ConvertArgsToUnicode(argc, argv);
bc385ba9 364
265db88d 365 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
bc385ba9 366 {
94826170
VZ
367 FreeConvertedArgs();
368
369 return false;
e90c1d2a 370 }
bc385ba9 371
94826170 372 return true;
bc385ba9
VZ
373}
374
94826170
VZ
375#endif // wxUSE_UNICODE
376
377// ----------------------------------------------------------------------------
378// clean up
379// ----------------------------------------------------------------------------
380
7beb59f3 381// cleanup done before destroying wxTheApp
94826170 382static void DoCommonPreCleanup()
bc385ba9
VZ
383{
384#if wxUSE_LOG
55b24eb8
VZ
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);
bc385ba9 394#endif // wxUSE_LOG
94826170 395}
bc385ba9 396
94826170
VZ
397// cleanup done after destroying wxTheApp
398static void DoCommonPostCleanup()
399{
a4de7e8c
VZ
400 wxModule::CleanUpModules();
401
94826170
VZ
402 // we can't do this in wxApp itself because it doesn't know if argv had
403 // been allocated
90aaa865 404#if wxUSE_UNICODE
94826170 405 FreeConvertedArgs();
90aaa865
VZ
406#endif // wxUSE_UNICODE
407
2ee96a25
VZ
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
8a9c2246 412#if wxUSE_LOG
bca27719
VZ
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
8a9c2246 418 // and now delete the last logger as well
55b24eb8
VZ
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)
8a9c2246
VZ
425 delete wxLog::SetActiveTarget(NULL);
426#endif // wxUSE_LOG
e90c1d2a 427}
e2450fa9 428
94826170
VZ
429void wxEntryCleanup()
430{
431 DoCommonPreCleanup();
432
433
434 // delete the application object
435 if ( wxTheApp )
436 {
437 wxTheApp->CleanUp();
438
b7b00ae1
VZ
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();
a80e5f9e 443 wxApp::SetInstance(NULL);
b7b00ae1 444 delete app;
94826170
VZ
445 }
446
447
448 DoCommonPostCleanup();
94826170
VZ
449}
450
451// ----------------------------------------------------------------------------
452// wxEntry
453// ----------------------------------------------------------------------------
454
226c11c0 455// for MSW the real wxEntry is defined in msw/main.cpp
d98a58c5 456#ifndef __WINDOWS__
94826170 457 #define wxEntryReal wxEntry
d98a58c5 458#endif // !__WINDOWS__
94826170 459
05e2b077 460int wxEntryReal(int& argc, wxChar **argv)
94826170
VZ
461{
462 // library initialization
6ecb1fdd
VS
463 wxInitializer initializer(argc, argv);
464
465 if ( !initializer.IsOk() )
94826170 466 {
688e04b1 467#if wxUSE_LOG
1c7b2f01
VZ
468 // flush any log messages explaining why we failed
469 delete wxLog::SetActiveTarget(NULL);
688e04b1 470#endif
94826170
VZ
471 return -1;
472 }
473
fb3e83b6 474 wxTRY
94826170 475 {
fb3e83b6
VZ
476 // app initialization
477 if ( !wxTheApp->CallOnInit() )
478 {
479 // don't call OnExit() if OnInit() failed
480 return -1;
481 }
94826170 482
fe277be0
VZ
483 // ensure that OnExit() is called if OnInit() had succeeded
484 class CallOnExit
485 {
486 public:
487 ~CallOnExit() { wxTheApp->OnExit(); }
488 } callOnExit;
94826170 489
9e9eea73
VZ
490 WX_SUPPRESS_UNUSED_WARN(callOnExit);
491
fe277be0
VZ
492 // app execution
493 return wxTheApp->OnRun();
fb3e83b6
VZ
494 }
495 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
94826170
VZ
496}
497
94826170
VZ
498#if wxUSE_UNICODE
499
500// as with wxEntryStart, we provide an ANSI wrapper
abca8ebf 501int wxEntry(int& argc, char **argv)
94826170
VZ
502{
503 ConvertArgsToUnicode(argc, argv);
504
265db88d 505 return wxEntry(gs_initData.argc, gs_initData.argv);
94826170
VZ
506}
507
508#endif // wxUSE_UNICODE
509
510// ----------------------------------------------------------------------------
511// wxInitialize/wxUninitialize
512// ----------------------------------------------------------------------------
513
d3688603
VS
514bool wxInitialize()
515{
516 return wxInitialize(0, (wxChar**)NULL);
517}
518
94826170
VZ
519bool 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
f380e251
VS
532#if wxUSE_UNICODE
533bool 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
94826170
VZ
547void wxUninitialize()
548{
549 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
550
8d7eaf91 551 if ( --gs_initData.nInitCount == 0 )
94826170
VZ
552 {
553 wxEntryCleanup();
554 }
555}