]> git.saurik.com Git - wxWidgets.git/blame - src/common/init.cpp
Use wxRound() instead of (int)(my_double + 0.5);
[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
94826170
VZ
40#if defined(__WXMSW__) && defined(__WXDEBUG__)
41 #include "wx/msw/msvcrt.h"
42
43 static struct EnableMemLeakChecking
44 {
45 EnableMemLeakChecking()
46 {
47 // do check for memory leaks on program exit (another useful flag
48 // is _CRTDBG_DELAY_FREE_MEM_DF which doesn't free deallocated
49 // memory which may be used to simulate low-memory condition)
50 wxCrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
51 }
52 } gs_enableLeakChecks;
53#endif // __WXMSW__ && __WXDEBUG__
54
e90c1d2a
VZ
55// ----------------------------------------------------------------------------
56// private classes
57// ----------------------------------------------------------------------------
58
e2478fde 59// we need a dummy app object if the user doesn't want to create a real one
94826170 60class wxDummyConsoleApp : public wxAppConsole
e90c1d2a
VZ
61{
62public:
fc7a2a60
VZ
63 wxDummyConsoleApp() { }
64
e2478fde 65 virtual int OnRun() { wxFAIL_MSG( _T("unreachable code") ); return 0; }
d48b06bd 66 virtual bool DoYield(bool, long) { return true; }
fc7a2a60
VZ
67
68 DECLARE_NO_COPY_CLASS(wxDummyConsoleApp)
e90c1d2a
VZ
69};
70
94826170 71// we need a special kind of auto pointer to wxApp which not only deletes the
7cafd224 72// pointer it holds in its dtor but also resets the global application pointer
d0ee33f5
WS
73wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
74wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
bc385ba9 75
94826170
VZ
76class wxAppPtr : public wxAppPtrBase
77{
78public:
77c6966e 79 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
94826170
VZ
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!
a80e5f9e 86 wxApp::SetInstance(NULL);
94826170
VZ
87 }
88 }
89
77c6966e 90 void Set(wxAppConsole *ptr)
94826170
VZ
91 {
92 reset(ptr);
93
a80e5f9e 94 wxApp::SetInstance(ptr);
94826170 95 }
fc7a2a60
VZ
96
97 DECLARE_NO_COPY_CLASS(wxAppPtr)
94826170
VZ
98};
99
05e2b077
VZ
100// class to ensure that wxAppBase::CleanUp() is called if our Initialize()
101// fails
102class wxCallAppCleanup
103{
104public:
77c6966e 105 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
05e2b077
VZ
106 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
107
108 void Dismiss() { m_app = NULL; }
109
110private:
77c6966e 111 wxAppConsole *m_app;
05e2b077
VZ
112};
113
94826170
VZ
114// another tiny class which simply exists to ensure that wxEntryCleanup is
115// always called
116class wxCleanupOnExit
117{
118public:
119 ~wxCleanupOnExit() { wxEntryCleanup(); }
120};
bc385ba9 121
005b5298
VZ
122// ----------------------------------------------------------------------------
123// private functions
124// ----------------------------------------------------------------------------
125
126// suppress warnings about unused variables
127static inline void Use(void *) { }
128
129#define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
130
e90c1d2a 131// ----------------------------------------------------------------------------
94826170 132// initialization data
e90c1d2a
VZ
133// ----------------------------------------------------------------------------
134
94826170
VZ
135static 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
150cb195 161 wchar_t **argv;
94826170 162#endif // wxUSE_UNICODE
fc7a2a60
VZ
163
164 DECLARE_NO_COPY_CLASS(InitData)
94826170 165} gs_initData;
e90c1d2a
VZ
166
167// ============================================================================
168// implementation
169// ============================================================================
170
252a752e 171// ----------------------------------------------------------------------------
94826170 172// command line arguments ANSI -> Unicode conversion
252a752e
VZ
173// ----------------------------------------------------------------------------
174
94826170
VZ
175#if wxUSE_UNICODE
176
177static void ConvertArgsToUnicode(int argc, char **argv)
e90c1d2a 178{
94826170 179 gs_initData.argv = new wchar_t *[argc + 1];
265db88d 180 int wargc = 0;
94826170 181 for ( int i = 0; i < argc; i++ )
e90c1d2a 182 {
a47f55c5
SC
183#ifdef __DARWIN__
184 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
185#else
faa112c4 186 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
a47f55c5 187#endif
265db88d
VZ
188 if ( !buf )
189 {
190 wxLogWarning(_("Command line argument %d couldn't be converted to Unicode and will be ignored."),
191 i);
192 }
193 else // converted ok
194 {
195 gs_initData.argv[wargc++] = wxStrdup(buf);
196 }
e90c1d2a
VZ
197 }
198
265db88d
VZ
199 gs_initData.argc = wargc;
200 gs_initData.argv[wargc] = NULL;
94826170 201}
e90c1d2a 202
94826170
VZ
203static void FreeConvertedArgs()
204{
150cb195 205 if ( gs_initData.argv )
bbfa0322 206 {
150cb195
VZ
207 for ( int i = 0; i < gs_initData.argc; i++ )
208 {
209 free(gs_initData.argv[i]);
210 }
211
212 delete [] gs_initData.argv;
213 gs_initData.argv = NULL;
08989e30 214 gs_initData.argc = 0;
bbfa0322 215 }
94826170 216}
bbfa0322 217
94826170 218#endif // wxUSE_UNICODE
e90c1d2a 219
94826170
VZ
220// ----------------------------------------------------------------------------
221// start up
222// ----------------------------------------------------------------------------
bbfa0322 223
94826170
VZ
224// initialization which is always done (not customizable) before wxApp creation
225static bool DoCommonPreInit()
226{
1c7b2f01 227#if wxUSE_LOG
e94cd97d
DE
228 // Reset logging in case we were cleaned up and are being reinitialized.
229 wxLog::DoCreateOnDemand();
230
1c7b2f01
VZ
231 // install temporary log sink: we can't use wxLogGui before wxApp is
232 // constructed and if we use wxLogStderr, all messages during
233 // initialization simply disappear under Windows
234 //
235 // note that we will delete this log target below
5db920c9 236 delete wxLog::SetActiveTarget(new wxLogBuffer);
1c7b2f01
VZ
237#endif // wxUSE_LOG
238
94826170 239 return true;
e90c1d2a
VZ
240}
241
94826170
VZ
242// non customizable initialization done after wxApp creation and initialization
243static bool DoCommonPostInit()
e90c1d2a 244{
94826170
VZ
245 wxModule::RegisterModules();
246
1c7b2f01
VZ
247 if ( !wxModule::InitializeModules() )
248 {
249 wxLogError(_("Initialization failed in post init, aborting."));
250 return false;
251 }
252
f775771a
FM
253#if defined(__WXDEBUG__)
254 // check if event classes implement Clone() correctly
255 // NOTE: the check is done against _all_ event classes which are linked to
256 // the executable currently running, which are not necessarily all
257 // wxWidgets event classes.
258 const wxClassInfo *ci = wxClassInfo::GetFirst();
95fa881e 259 for (; ci; ci = ci->GetNext())
f775771a
FM
260 {
261 // is this class derived from wxEvent?
95fa881e
PC
262 if (!ci->IsKindOf(CLASSINFO(wxEvent)) || wxString(ci->GetClassName()) == "wxEvent")
263 continue;
f775771a 264
95fa881e
PC
265 if (!ci->IsDynamic())
266 {
267 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
268 ci->GetClassName());
269 continue;
270 }
f775771a 271
95fa881e 272 // yes; test if it implements Clone() correctly
67f30682 273 wxEvent* test = wxDynamicCast(ci->CreateObject(),wxEvent);
95fa881e
PC
274 if (test == NULL)
275 {
276 wxLogWarning("The event class '%s' should have a DECLARE_DYNAMIC_CLASS macro!",
277 ci->GetClassName());
278 continue;
f775771a
FM
279 }
280
95fa881e
PC
281 wxEvent* cloned = test->Clone();
282 if (!cloned || cloned->GetClassInfo() != ci)
283 wxLogWarning("The event class '%s' does not correctly implement Clone()!",
284 ci->GetClassName());
285
f7ae43f0 286 delete cloned;
95fa881e 287 delete test;
f775771a
FM
288 }
289#endif
290
1c7b2f01 291 return true;
bc385ba9
VZ
292}
293
05e2b077 294bool wxEntryStart(int& argc, wxChar **argv)
bc385ba9 295{
94826170
VZ
296 // do minimal, always necessary, initialization
297 // --------------------------------------------
298
299 // initialize wxRTTI
300 if ( !DoCommonPreInit() )
bc385ba9 301 {
94826170 302 return false;
bc385ba9
VZ
303 }
304
bc385ba9 305
94826170
VZ
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
bc385ba9
VZ
315 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
316
94826170
VZ
317 if ( fnCreate )
318 {
319 // he did, try to create the custom wxApp object
7cafd224 320 app.Set((*fnCreate)());
94826170
VZ
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
7cafd224 328 app.Set(new wxDummyConsoleApp);
bc385ba9
VZ
329 }
330
bc385ba9 331
94826170
VZ
332 // wxApp initialization: this can be customized
333 // --------------------------------------------
bc385ba9 334
7cafd224 335 if ( !app->Initialize(argc, argv) )
bc385ba9 336 {
94826170 337 return false;
bc385ba9 338 }
bc385ba9 339
4f6b94a3
VZ
340 // remember, possibly modified (e.g. due to removal of toolkit-specific
341 // parameters), command line arguments in member variables
342 app->argc = argc;
343 app->argv = argv;
344
345
7cafd224 346 wxCallAppCleanup callAppCleanup(app.get());
05e2b077
VZ
347
348 // for compatibility call the old initialization function too
7cafd224 349 if ( !app->OnInitGui() )
05e2b077
VZ
350 return false;
351
bc385ba9 352
94826170
VZ
353 // common initialization after wxTheApp creation
354 // ---------------------------------------------
bc385ba9 355
94826170 356 if ( !DoCommonPostInit() )
94826170 357 return false;
bc385ba9 358
bc385ba9 359
94826170
VZ
360 // prevent the smart pointer from destroying its contents
361 app.release();
362
05e2b077
VZ
363 // and the cleanup object from doing cleanup
364 callAppCleanup.Dismiss();
365
1c7b2f01
VZ
366#if wxUSE_LOG
367 // now that we have a valid wxApp (wxLogGui would have crashed if we used
368 // it before now), we can delete the temporary sink we had created for the
369 // initialization messages -- the next time logging function is called, the
370 // sink will be recreated but this time wxAppTraits will be used
371 delete wxLog::SetActiveTarget(NULL);
372#endif // wxUSE_LOG
373
94826170 374 return true;
bc385ba9
VZ
375}
376
94826170 377#if wxUSE_UNICODE
bbfa0322 378
94826170 379// we provide a wxEntryStart() wrapper taking "char *" pointer too
05e2b077 380bool wxEntryStart(int& argc, char **argv)
bc385ba9 381{
94826170 382 ConvertArgsToUnicode(argc, argv);
bc385ba9 383
265db88d 384 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
bc385ba9 385 {
94826170
VZ
386 FreeConvertedArgs();
387
388 return false;
e90c1d2a 389 }
bc385ba9 390
94826170 391 return true;
bc385ba9
VZ
392}
393
94826170
VZ
394#endif // wxUSE_UNICODE
395
396// ----------------------------------------------------------------------------
397// clean up
398// ----------------------------------------------------------------------------
399
7beb59f3 400// cleanup done before destroying wxTheApp
94826170 401static void DoCommonPreCleanup()
bc385ba9
VZ
402{
403#if wxUSE_LOG
94826170
VZ
404 // flush the logged messages if any and install a 'safer' log target: the
405 // default one (wxLogGui) can't be used after the resources are freed just
406 // below and the user supplied one might be even more unsafe (using any
77ffb593 407 // wxWidgets GUI function is unsafe starting from now)
8a9c2246 408 wxLog::DontCreateOnDemand();
94826170
VZ
409
410 // this will flush the old messages if any
8a9c2246 411 delete wxLog::SetActiveTarget(new wxLogStderr);
bc385ba9 412#endif // wxUSE_LOG
94826170 413}
bc385ba9 414
94826170
VZ
415// cleanup done after destroying wxTheApp
416static void DoCommonPostCleanup()
417{
a4de7e8c
VZ
418 wxModule::CleanUpModules();
419
94826170
VZ
420 // we can't do this in wxApp itself because it doesn't know if argv had
421 // been allocated
90aaa865 422#if wxUSE_UNICODE
94826170 423 FreeConvertedArgs();
90aaa865
VZ
424#endif // wxUSE_UNICODE
425
2ee96a25
VZ
426 // use Set(NULL) and not Get() to avoid creating a message output object on
427 // demand when we just want to delete it
428 delete wxMessageOutput::Set(NULL);
429
8a9c2246
VZ
430#if wxUSE_LOG
431 // and now delete the last logger as well
432 delete wxLog::SetActiveTarget(NULL);
433#endif // wxUSE_LOG
e90c1d2a 434}
e2450fa9 435
94826170
VZ
436void wxEntryCleanup()
437{
438 DoCommonPreCleanup();
439
440
441 // delete the application object
442 if ( wxTheApp )
443 {
444 wxTheApp->CleanUp();
445
b7b00ae1
VZ
446 // reset the global pointer to it to NULL before destroying it as in
447 // some circumstances this can result in executing the code using
448 // wxTheApp and using half-destroyed object is no good
449 wxAppConsole * const app = wxApp::GetInstance();
a80e5f9e 450 wxApp::SetInstance(NULL);
b7b00ae1 451 delete app;
94826170
VZ
452 }
453
454
455 DoCommonPostCleanup();
94826170
VZ
456}
457
458// ----------------------------------------------------------------------------
459// wxEntry
460// ----------------------------------------------------------------------------
461
226c11c0
VZ
462// for MSW the real wxEntry is defined in msw/main.cpp
463#ifndef __WXMSW__
94826170 464 #define wxEntryReal wxEntry
226c11c0 465#endif // !__WXMSW__
94826170 466
05e2b077 467int wxEntryReal(int& argc, wxChar **argv)
94826170
VZ
468{
469 // library initialization
470 if ( !wxEntryStart(argc, argv) )
471 {
688e04b1 472#if wxUSE_LOG
1c7b2f01
VZ
473 // flush any log messages explaining why we failed
474 delete wxLog::SetActiveTarget(NULL);
688e04b1 475#endif
94826170
VZ
476 return -1;
477 }
478
479 // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code
480 // below returns or throws
481 wxCleanupOnExit cleanupOnExit;
482
005b5298
VZ
483 WX_SUPPRESS_UNUSED_WARN(cleanupOnExit);
484
fb3e83b6 485 wxTRY
94826170 486 {
e83f2301 487
fb3e83b6
VZ
488 // app initialization
489 if ( !wxTheApp->CallOnInit() )
490 {
491 // don't call OnExit() if OnInit() failed
492 return -1;
493 }
94826170 494
fe277be0
VZ
495 // ensure that OnExit() is called if OnInit() had succeeded
496 class CallOnExit
497 {
498 public:
499 ~CallOnExit() { wxTheApp->OnExit(); }
500 } callOnExit;
94826170 501
9e9eea73
VZ
502 WX_SUPPRESS_UNUSED_WARN(callOnExit);
503
fe277be0
VZ
504 // app execution
505 return wxTheApp->OnRun();
fb3e83b6
VZ
506 }
507 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
94826170
VZ
508}
509
94826170
VZ
510#if wxUSE_UNICODE
511
512// as with wxEntryStart, we provide an ANSI wrapper
abca8ebf 513int wxEntry(int& argc, char **argv)
94826170
VZ
514{
515 ConvertArgsToUnicode(argc, argv);
516
265db88d 517 return wxEntry(gs_initData.argc, gs_initData.argv);
94826170
VZ
518}
519
520#endif // wxUSE_UNICODE
521
522// ----------------------------------------------------------------------------
523// wxInitialize/wxUninitialize
524// ----------------------------------------------------------------------------
525
526bool wxInitialize(int argc, wxChar **argv)
527{
528 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
529
530 if ( gs_initData.nInitCount++ )
531 {
532 // already initialized
533 return true;
534 }
535
536 return wxEntryStart(argc, argv);
537}
538
539void wxUninitialize()
540{
541 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
542
8d7eaf91 543 if ( --gs_initData.nInitCount == 0 )
94826170
VZ
544 {
545 wxEntryCleanup();
546 }
547}