]> git.saurik.com Git - wxWidgets.git/blame - src/common/init.cpp
Fixed typo in dialog project file
[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
e90c1d2a
VZ
58// ----------------------------------------------------------------------------
59// private classes
60// ----------------------------------------------------------------------------
61
e2478fde 62// we need a dummy app object if the user doesn't want to create a real one
94826170 63class wxDummyConsoleApp : public wxAppConsole
e90c1d2a
VZ
64{
65public:
fc7a2a60
VZ
66 wxDummyConsoleApp() { }
67
9a83f860 68 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
d48b06bd 69 virtual bool DoYield(bool, long) { return true; }
fc7a2a60 70
c0c133e1 71 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp);
e90c1d2a
VZ
72};
73
94826170 74// we need a special kind of auto pointer to wxApp which not only deletes the
7cafd224 75// pointer it holds in its dtor but also resets the global application pointer
d0ee33f5
WS
76wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
77wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
bc385ba9 78
94826170
VZ
79class wxAppPtr : public wxAppPtrBase
80{
81public:
77c6966e 82 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
94826170
VZ
83 ~wxAppPtr()
84 {
85 if ( get() )
86 {
87 // the pointer is going to be deleted in the base class dtor, don't
88 // leave the dangling pointer!
a80e5f9e 89 wxApp::SetInstance(NULL);
94826170
VZ
90 }
91 }
92
77c6966e 93 void Set(wxAppConsole *ptr)
94826170
VZ
94 {
95 reset(ptr);
96
a80e5f9e 97 wxApp::SetInstance(ptr);
94826170 98 }
fc7a2a60 99
c0c133e1 100 wxDECLARE_NO_COPY_CLASS(wxAppPtr);
94826170
VZ
101};
102
05e2b077
VZ
103// class to ensure that wxAppBase::CleanUp() is called if our Initialize()
104// fails
105class wxCallAppCleanup
106{
107public:
77c6966e 108 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
05e2b077
VZ
109 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
110
111 void Dismiss() { m_app = NULL; }
112
113private:
77c6966e 114 wxAppConsole *m_app;
05e2b077
VZ
115};
116
005b5298
VZ
117// ----------------------------------------------------------------------------
118// private functions
119// ----------------------------------------------------------------------------
120
121// suppress warnings about unused variables
122static inline void Use(void *) { }
123
124#define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
125
e90c1d2a 126// ----------------------------------------------------------------------------
94826170 127// initialization data
e90c1d2a
VZ
128// ----------------------------------------------------------------------------
129
94826170
VZ
130static struct InitData
131{
132 InitData()
133 {
134 nInitCount = 0;
135
136#if wxUSE_UNICODE
137 argc = 0;
138 // argv = NULL; -- not even really needed
139#endif // wxUSE_UNICODE
140 }
141
142 // critical section protecting this struct
143 wxCRIT_SECT_DECLARE_MEMBER(csInit);
144
145 // number of times wxInitialize() was called minus the number of times
146 // wxUninitialize() was
147 size_t nInitCount;
148
149#if wxUSE_UNICODE
150 int argc;
151
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
150cb195 156 wchar_t **argv;
94826170 157#endif // wxUSE_UNICODE
fc7a2a60 158
c0c133e1 159 wxDECLARE_NO_COPY_CLASS(InitData);
94826170 160} gs_initData;
e90c1d2a
VZ
161
162// ============================================================================
163// implementation
164// ============================================================================
165
252a752e 166// ----------------------------------------------------------------------------
94826170 167// command line arguments ANSI -> Unicode conversion
252a752e
VZ
168// ----------------------------------------------------------------------------
169
94826170
VZ
170#if wxUSE_UNICODE
171
172static void ConvertArgsToUnicode(int argc, char **argv)
e90c1d2a 173{
94826170 174 gs_initData.argv = new wchar_t *[argc + 1];
265db88d 175 int wargc = 0;
94826170 176 for ( int i = 0; i < argc; i++ )
e90c1d2a 177 {
a47f55c5
SC
178#ifdef __DARWIN__
179 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
180#else
faa112c4 181 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
a47f55c5 182#endif
265db88d
VZ
183 if ( !buf )
184 {
185 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
186 i);
187 }
188 else // converted ok
189 {
190 gs_initData.argv[wargc++] = wxStrdup(buf);
191 }
e90c1d2a
VZ
192 }
193
265db88d
VZ
194 gs_initData.argc = wargc;
195 gs_initData.argv[wargc] = NULL;
94826170 196}
e90c1d2a 197
94826170
VZ
198static void FreeConvertedArgs()
199{
150cb195 200 if ( gs_initData.argv )
bbfa0322 201 {
150cb195
VZ
202 for ( int i = 0; i < gs_initData.argc; i++ )
203 {
204 free(gs_initData.argv[i]);
205 }
206
5276b0a5 207 wxDELETEA(gs_initData.argv);
08989e30 208 gs_initData.argc = 0;
bbfa0322 209 }
94826170 210}
bbfa0322 211
94826170 212#endif // wxUSE_UNICODE
e90c1d2a 213
94826170
VZ
214// ----------------------------------------------------------------------------
215// start up
216// ----------------------------------------------------------------------------
bbfa0322 217
94826170
VZ
218// initialization which is always done (not customizable) before wxApp creation
219static bool DoCommonPreInit()
220{
270bae20
VS
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.
225 //
226 // Note that this must be done for any app, Cocoa or console, whether or
227 // not it uses wxLocale.
228 //
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__)
232
1c7b2f01 233#if wxUSE_LOG
e94cd97d
DE
234 // Reset logging in case we were cleaned up and are being reinitialized.
235 wxLog::DoCreateOnDemand();
a2084452
VZ
236
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
244 //
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
249 // what he is doing
250 wxLog::GetActiveTarget();
1c7b2f01
VZ
251#endif // wxUSE_LOG
252
d98a58c5 253#ifdef __WINDOWS__
98a0eff6
VZ
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() )
258 {
259 wxSetInstance(::GetModuleHandle(NULL));
260 }
d98a58c5 261#endif // __WINDOWS__
98a0eff6 262
94826170 263 return true;
e90c1d2a
VZ
264}
265
94826170
VZ
266// non customizable initialization done after wxApp creation and initialization
267static bool DoCommonPostInit()
e90c1d2a 268{
94826170
VZ
269 wxModule::RegisterModules();
270
1c7b2f01
VZ
271 if ( !wxModule::InitializeModules() )
272 {
273 wxLogError(_("Initialization failed in post init, aborting."));
274 return false;
275 }
276
277 return true;
bc385ba9
VZ
278}
279
05e2b077 280bool wxEntryStart(int& argc, wxChar **argv)
bc385ba9 281{
94826170
VZ
282 // do minimal, always necessary, initialization
283 // --------------------------------------------
284
285 // initialize wxRTTI
286 if ( !DoCommonPreInit() )
94826170 287 return false;
bc385ba9 288
bc385ba9 289
94826170
VZ
290 // first of all, we need an application object
291 // -------------------------------------------
292
293 // the user might have already created it himself somehow
294 wxAppPtr app(wxTheApp);
295 if ( !app.get() )
296 {
297 // if not, he might have used IMPLEMENT_APP() to give us a function to
298 // create it
bc385ba9
VZ
299 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
300
94826170
VZ
301 if ( fnCreate )
302 {
303 // he did, try to create the custom wxApp object
7cafd224 304 app.Set((*fnCreate)());
94826170
VZ
305 }
306 }
307
308 if ( !app.get() )
309 {
310 // either IMPLEMENT_APP() was not used at all or it failed -- in any
311 // case we still need something
7cafd224 312 app.Set(new wxDummyConsoleApp);
bc385ba9
VZ
313 }
314
bc385ba9 315
94826170
VZ
316 // wxApp initialization: this can be customized
317 // --------------------------------------------
bc385ba9 318
7cafd224 319 if ( !app->Initialize(argc, argv) )
94826170 320 return false;
bc385ba9 321
4f6b94a3
VZ
322 // remember, possibly modified (e.g. due to removal of toolkit-specific
323 // parameters), command line arguments in member variables
324 app->argc = argc;
325 app->argv = argv;
326
7cafd224 327 wxCallAppCleanup callAppCleanup(app.get());
05e2b077 328
bc385ba9 329
94826170
VZ
330 // common initialization after wxTheApp creation
331 // ---------------------------------------------
bc385ba9 332
94826170 333 if ( !DoCommonPostInit() )
94826170 334 return false;
bc385ba9 335
bc385ba9 336
94826170
VZ
337 // prevent the smart pointer from destroying its contents
338 app.release();
339
05e2b077
VZ
340 // and the cleanup object from doing cleanup
341 callAppCleanup.Dismiss();
342
1c7b2f01
VZ
343#if wxUSE_LOG
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);
349#endif // wxUSE_LOG
350
94826170 351 return true;
bc385ba9
VZ
352}
353
94826170 354#if wxUSE_UNICODE
bbfa0322 355
94826170 356// we provide a wxEntryStart() wrapper taking "char *" pointer too
05e2b077 357bool wxEntryStart(int& argc, char **argv)
bc385ba9 358{
94826170 359 ConvertArgsToUnicode(argc, argv);
bc385ba9 360
265db88d 361 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
bc385ba9 362 {
94826170
VZ
363 FreeConvertedArgs();
364
365 return false;
e90c1d2a 366 }
bc385ba9 367
94826170 368 return true;
bc385ba9
VZ
369}
370
94826170
VZ
371#endif // wxUSE_UNICODE
372
373// ----------------------------------------------------------------------------
374// clean up
375// ----------------------------------------------------------------------------
376
7beb59f3 377// cleanup done before destroying wxTheApp
94826170 378static void DoCommonPreCleanup()
bc385ba9
VZ
379{
380#if wxUSE_LOG
55b24eb8
VZ
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)
386 //
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);
bc385ba9 390#endif // wxUSE_LOG
94826170 391}
bc385ba9 392
94826170
VZ
393// cleanup done after destroying wxTheApp
394static void DoCommonPostCleanup()
395{
a4de7e8c
VZ
396 wxModule::CleanUpModules();
397
94826170
VZ
398 // we can't do this in wxApp itself because it doesn't know if argv had
399 // been allocated
90aaa865 400#if wxUSE_UNICODE
94826170 401 FreeConvertedArgs();
90aaa865
VZ
402#endif // wxUSE_UNICODE
403
2ee96a25
VZ
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);
407
8a9c2246
VZ
408#if wxUSE_LOG
409 // and now delete the last logger as well
55b24eb8
VZ
410 //
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)
8a9c2246
VZ
416 delete wxLog::SetActiveTarget(NULL);
417#endif // wxUSE_LOG
e90c1d2a 418}
e2450fa9 419
94826170
VZ
420void wxEntryCleanup()
421{
422 DoCommonPreCleanup();
423
424
425 // delete the application object
426 if ( wxTheApp )
427 {
428 wxTheApp->CleanUp();
429
b7b00ae1
VZ
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();
a80e5f9e 434 wxApp::SetInstance(NULL);
b7b00ae1 435 delete app;
94826170
VZ
436 }
437
438
439 DoCommonPostCleanup();
94826170
VZ
440}
441
442// ----------------------------------------------------------------------------
443// wxEntry
444// ----------------------------------------------------------------------------
445
226c11c0 446// for MSW the real wxEntry is defined in msw/main.cpp
d98a58c5 447#ifndef __WINDOWS__
94826170 448 #define wxEntryReal wxEntry
d98a58c5 449#endif // !__WINDOWS__
94826170 450
05e2b077 451int wxEntryReal(int& argc, wxChar **argv)
94826170
VZ
452{
453 // library initialization
6ecb1fdd
VS
454 wxInitializer initializer(argc, argv);
455
456 if ( !initializer.IsOk() )
94826170 457 {
688e04b1 458#if wxUSE_LOG
1c7b2f01
VZ
459 // flush any log messages explaining why we failed
460 delete wxLog::SetActiveTarget(NULL);
688e04b1 461#endif
94826170
VZ
462 return -1;
463 }
464
fb3e83b6 465 wxTRY
94826170 466 {
fb3e83b6
VZ
467 // app initialization
468 if ( !wxTheApp->CallOnInit() )
469 {
470 // don't call OnExit() if OnInit() failed
471 return -1;
472 }
94826170 473
fe277be0
VZ
474 // ensure that OnExit() is called if OnInit() had succeeded
475 class CallOnExit
476 {
477 public:
478 ~CallOnExit() { wxTheApp->OnExit(); }
479 } callOnExit;
94826170 480
9e9eea73
VZ
481 WX_SUPPRESS_UNUSED_WARN(callOnExit);
482
fe277be0
VZ
483 // app execution
484 return wxTheApp->OnRun();
fb3e83b6
VZ
485 }
486 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
94826170
VZ
487}
488
94826170
VZ
489#if wxUSE_UNICODE
490
491// as with wxEntryStart, we provide an ANSI wrapper
abca8ebf 492int wxEntry(int& argc, char **argv)
94826170
VZ
493{
494 ConvertArgsToUnicode(argc, argv);
495
265db88d 496 return wxEntry(gs_initData.argc, gs_initData.argv);
94826170
VZ
497}
498
499#endif // wxUSE_UNICODE
500
501// ----------------------------------------------------------------------------
502// wxInitialize/wxUninitialize
503// ----------------------------------------------------------------------------
504
d3688603
VS
505bool wxInitialize()
506{
507 return wxInitialize(0, (wxChar**)NULL);
508}
509
94826170
VZ
510bool wxInitialize(int argc, wxChar **argv)
511{
512 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
513
514 if ( gs_initData.nInitCount++ )
515 {
516 // already initialized
517 return true;
518 }
519
520 return wxEntryStart(argc, argv);
521}
522
f380e251
VS
523#if wxUSE_UNICODE
524bool wxInitialize(int argc, char **argv)
525{
526 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
527
528 if ( gs_initData.nInitCount++ )
529 {
530 // already initialized
531 return true;
532 }
533
534 return wxEntryStart(argc, argv);
535}
536#endif // wxUSE_UNICODE
537
94826170
VZ
538void wxUninitialize()
539{
540 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
541
8d7eaf91 542 if ( --gs_initData.nInitCount == 0 )
94826170
VZ
543 {
544 wxEntryCleanup();
545 }
546}