]> git.saurik.com Git - wxWidgets.git/blob - src/common/init.cpp
Clip drawing in wxRendererGeneric::DrawHeaderButtonContents().
[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(__WXMSW__)
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 // __WXMSW__
57
58 // ----------------------------------------------------------------------------
59 // private classes
60 // ----------------------------------------------------------------------------
61
62 // we need a dummy app object if the user doesn't want to create a real one
63 class wxDummyConsoleApp : public wxAppConsole
64 {
65 public:
66 wxDummyConsoleApp() { }
67
68 virtual int OnRun() { wxFAIL_MSG( wxT("unreachable code") ); return 0; }
69 virtual bool DoYield(bool, long) { return true; }
70
71 wxDECLARE_NO_COPY_CLASS(wxDummyConsoleApp);
72 };
73
74 // we need a special kind of auto pointer to wxApp which not only deletes the
75 // pointer it holds in its dtor but also resets the global application pointer
76 wxDECLARE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
77 wxDEFINE_SCOPED_PTR(wxAppConsole, wxAppPtrBase)
78
79 class wxAppPtr : public wxAppPtrBase
80 {
81 public:
82 wxEXPLICIT wxAppPtr(wxAppConsole *ptr = NULL) : wxAppPtrBase(ptr) { }
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!
89 wxApp::SetInstance(NULL);
90 }
91 }
92
93 void Set(wxAppConsole *ptr)
94 {
95 reset(ptr);
96
97 wxApp::SetInstance(ptr);
98 }
99
100 wxDECLARE_NO_COPY_CLASS(wxAppPtr);
101 };
102
103 // class to ensure that wxAppBase::CleanUp() is called if our Initialize()
104 // fails
105 class wxCallAppCleanup
106 {
107 public:
108 wxCallAppCleanup(wxAppConsole *app) : m_app(app) { }
109 ~wxCallAppCleanup() { if ( m_app ) m_app->CleanUp(); }
110
111 void Dismiss() { m_app = NULL; }
112
113 private:
114 wxAppConsole *m_app;
115 };
116
117 // ----------------------------------------------------------------------------
118 // private functions
119 // ----------------------------------------------------------------------------
120
121 // suppress warnings about unused variables
122 static inline void Use(void *) { }
123
124 #define WX_SUPPRESS_UNUSED_WARN(x) Use(&x)
125
126 // ----------------------------------------------------------------------------
127 // initialization data
128 // ----------------------------------------------------------------------------
129
130 static 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
156 wchar_t **argv;
157 #endif // wxUSE_UNICODE
158
159 wxDECLARE_NO_COPY_CLASS(InitData);
160 } gs_initData;
161
162 // ============================================================================
163 // implementation
164 // ============================================================================
165
166 // ----------------------------------------------------------------------------
167 // command line arguments ANSI -> Unicode conversion
168 // ----------------------------------------------------------------------------
169
170 #if wxUSE_UNICODE
171
172 static void ConvertArgsToUnicode(int argc, char **argv)
173 {
174 gs_initData.argv = new wchar_t *[argc + 1];
175 int wargc = 0;
176 for ( int i = 0; i < argc; i++ )
177 {
178 #ifdef __DARWIN__
179 wxWCharBuffer buf(wxConvFileName->cMB2WX(argv[i]));
180 #else
181 wxWCharBuffer buf(wxConvLocal.cMB2WX(argv[i]));
182 #endif
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 }
192 }
193
194 gs_initData.argc = wargc;
195 gs_initData.argv[wargc] = NULL;
196 }
197
198 static void FreeConvertedArgs()
199 {
200 if ( gs_initData.argv )
201 {
202 for ( int i = 0; i < gs_initData.argc; i++ )
203 {
204 free(gs_initData.argv[i]);
205 }
206
207 delete [] gs_initData.argv;
208 gs_initData.argv = NULL;
209 gs_initData.argc = 0;
210 }
211 }
212
213 #endif // wxUSE_UNICODE
214
215 // ----------------------------------------------------------------------------
216 // start up
217 // ----------------------------------------------------------------------------
218
219 // initialization which is always done (not customizable) before wxApp creation
220 static bool DoCommonPreInit()
221 {
222 #if wxUSE_LOG
223 // Reset logging in case we were cleaned up and are being reinitialized.
224 wxLog::DoCreateOnDemand();
225
226 // force wxLog to create a log target now: we do it because wxTheApp
227 // doesn't exist yet so wxLog will create a special log target which is
228 // safe to use even when the GUI is not available while without this call
229 // we could create wxApp in wxEntryStart() below, then log an error about
230 // e.g. failure to establish connection to the X server and wxLog would
231 // send it to wxLogGui (because wxTheApp does exist already) which, of
232 // course, can't be used in this case
233 //
234 // notice also that this does nothing if the user had set up a custom log
235 // target before -- which is fine as we want to give him this possibility
236 // (as it's impossible to override logging by overriding wxAppTraits::
237 // CreateLogTarget() before wxApp is created) and we just assume he knows
238 // what he is doing
239 wxLog::GetActiveTarget();
240 #endif // wxUSE_LOG
241
242 #ifdef __WXMSW__
243 // GUI applications obtain HINSTANCE in their WinMain() but we also need to
244 // initialize the global wxhInstance variable for the console programs as
245 // they may need it too, so set it here if it wasn't done yet
246 if ( !wxGetInstance() )
247 {
248 wxSetInstance(::GetModuleHandle(NULL));
249 }
250 #endif // __WXMSW__
251
252 return true;
253 }
254
255 // non customizable initialization done after wxApp creation and initialization
256 static bool DoCommonPostInit()
257 {
258 wxModule::RegisterModules();
259
260 if ( !wxModule::InitializeModules() )
261 {
262 wxLogError(_("Initialization failed in post init, aborting."));
263 return false;
264 }
265
266 return true;
267 }
268
269 bool wxEntryStart(int& argc, wxChar **argv)
270 {
271 // do minimal, always necessary, initialization
272 // --------------------------------------------
273
274 // initialize wxRTTI
275 if ( !DoCommonPreInit() )
276 return false;
277
278
279 // first of all, we need an application object
280 // -------------------------------------------
281
282 // the user might have already created it himself somehow
283 wxAppPtr app(wxTheApp);
284 if ( !app.get() )
285 {
286 // if not, he might have used IMPLEMENT_APP() to give us a function to
287 // create it
288 wxAppInitializerFunction fnCreate = wxApp::GetInitializerFunction();
289
290 if ( fnCreate )
291 {
292 // he did, try to create the custom wxApp object
293 app.Set((*fnCreate)());
294 }
295 }
296
297 if ( !app.get() )
298 {
299 // either IMPLEMENT_APP() was not used at all or it failed -- in any
300 // case we still need something
301 app.Set(new wxDummyConsoleApp);
302 }
303
304
305 // wxApp initialization: this can be customized
306 // --------------------------------------------
307
308 if ( !app->Initialize(argc, argv) )
309 return false;
310
311 // remember, possibly modified (e.g. due to removal of toolkit-specific
312 // parameters), command line arguments in member variables
313 app->argc = argc;
314 app->argv = argv;
315
316 wxCallAppCleanup callAppCleanup(app.get());
317
318
319 // common initialization after wxTheApp creation
320 // ---------------------------------------------
321
322 if ( !DoCommonPostInit() )
323 return false;
324
325
326 // prevent the smart pointer from destroying its contents
327 app.release();
328
329 // and the cleanup object from doing cleanup
330 callAppCleanup.Dismiss();
331
332 #if wxUSE_LOG
333 // now that we have a valid wxApp (wxLogGui would have crashed if we used
334 // it before now), we can delete the temporary sink we had created for the
335 // initialization messages -- the next time logging function is called, the
336 // sink will be recreated but this time wxAppTraits will be used
337 delete wxLog::SetActiveTarget(NULL);
338 #endif // wxUSE_LOG
339
340 return true;
341 }
342
343 #if wxUSE_UNICODE
344
345 // we provide a wxEntryStart() wrapper taking "char *" pointer too
346 bool wxEntryStart(int& argc, char **argv)
347 {
348 ConvertArgsToUnicode(argc, argv);
349
350 if ( !wxEntryStart(gs_initData.argc, gs_initData.argv) )
351 {
352 FreeConvertedArgs();
353
354 return false;
355 }
356
357 return true;
358 }
359
360 #endif // wxUSE_UNICODE
361
362 // ----------------------------------------------------------------------------
363 // clean up
364 // ----------------------------------------------------------------------------
365
366 // cleanup done before destroying wxTheApp
367 static void DoCommonPreCleanup()
368 {
369 #if wxUSE_LOG
370 // flush the logged messages if any and don't use the current probably
371 // unsafe log target any more: the default one (wxLogGui) can't be used
372 // after the resources are freed which happens when we return and the user
373 // supplied one might be even more unsafe (using any wxWidgets GUI function
374 // is unsafe starting from now)
375 //
376 // notice that wxLog will still recreate a default log target if any
377 // messages are logged but that one will be safe to use until the very end
378 delete wxLog::SetActiveTarget(NULL);
379 #endif // wxUSE_LOG
380 }
381
382 // cleanup done after destroying wxTheApp
383 static void DoCommonPostCleanup()
384 {
385 wxModule::CleanUpModules();
386
387 // we can't do this in wxApp itself because it doesn't know if argv had
388 // been allocated
389 #if wxUSE_UNICODE
390 FreeConvertedArgs();
391 #endif // wxUSE_UNICODE
392
393 // use Set(NULL) and not Get() to avoid creating a message output object on
394 // demand when we just want to delete it
395 delete wxMessageOutput::Set(NULL);
396
397 #if wxUSE_LOG
398 // and now delete the last logger as well
399 //
400 // we still don't disable log target auto-vivification even if any log
401 // objects created now will result in memory leaks because it seems better
402 // to leak memory which doesn't matter much considering the application is
403 // exiting anyhow than to not show messages which could still be logged
404 // from the user code (e.g. static dtors and such)
405 delete wxLog::SetActiveTarget(NULL);
406 #endif // wxUSE_LOG
407 }
408
409 void wxEntryCleanup()
410 {
411 DoCommonPreCleanup();
412
413
414 // delete the application object
415 if ( wxTheApp )
416 {
417 wxTheApp->CleanUp();
418
419 // reset the global pointer to it to NULL before destroying it as in
420 // some circumstances this can result in executing the code using
421 // wxTheApp and using half-destroyed object is no good
422 wxAppConsole * const app = wxApp::GetInstance();
423 wxApp::SetInstance(NULL);
424 delete app;
425 }
426
427
428 DoCommonPostCleanup();
429 }
430
431 // ----------------------------------------------------------------------------
432 // wxEntry
433 // ----------------------------------------------------------------------------
434
435 // for MSW the real wxEntry is defined in msw/main.cpp
436 #ifndef __WXMSW__
437 #define wxEntryReal wxEntry
438 #endif // !__WXMSW__
439
440 int wxEntryReal(int& argc, wxChar **argv)
441 {
442 // library initialization
443 wxInitializer initializer(argc, argv);
444
445 if ( !initializer.IsOk() )
446 {
447 #if wxUSE_LOG
448 // flush any log messages explaining why we failed
449 delete wxLog::SetActiveTarget(NULL);
450 #endif
451 return -1;
452 }
453
454 wxTRY
455 {
456 // app initialization
457 if ( !wxTheApp->CallOnInit() )
458 {
459 // don't call OnExit() if OnInit() failed
460 return -1;
461 }
462
463 // ensure that OnExit() is called if OnInit() had succeeded
464 class CallOnExit
465 {
466 public:
467 ~CallOnExit() { wxTheApp->OnExit(); }
468 } callOnExit;
469
470 WX_SUPPRESS_UNUSED_WARN(callOnExit);
471
472 // app execution
473 return wxTheApp->OnRun();
474 }
475 wxCATCH_ALL( wxTheApp->OnUnhandledException(); return -1; )
476 }
477
478 #if wxUSE_UNICODE
479
480 // as with wxEntryStart, we provide an ANSI wrapper
481 int wxEntry(int& argc, char **argv)
482 {
483 ConvertArgsToUnicode(argc, argv);
484
485 return wxEntry(gs_initData.argc, gs_initData.argv);
486 }
487
488 #endif // wxUSE_UNICODE
489
490 // ----------------------------------------------------------------------------
491 // wxInitialize/wxUninitialize
492 // ----------------------------------------------------------------------------
493
494 bool wxInitialize()
495 {
496 return wxInitialize(0, (wxChar**)NULL);
497 }
498
499 bool wxInitialize(int argc, wxChar **argv)
500 {
501 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
502
503 if ( gs_initData.nInitCount++ )
504 {
505 // already initialized
506 return true;
507 }
508
509 return wxEntryStart(argc, argv);
510 }
511
512 #if wxUSE_UNICODE
513 bool wxInitialize(int argc, char **argv)
514 {
515 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
516
517 if ( gs_initData.nInitCount++ )
518 {
519 // already initialized
520 return true;
521 }
522
523 return wxEntryStart(argc, argv);
524 }
525 #endif // wxUSE_UNICODE
526
527 void wxUninitialize()
528 {
529 wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit);
530
531 if ( --gs_initData.nInitCount == 0 )
532 {
533 wxEntryCleanup();
534 }
535 }