]> git.saurik.com Git - wxWidgets.git/blob - src/common/appbase.cpp
Inital fill in background, removed tabs, -1->wxID_ANY, TRUE->true, FALSE->false
[wxWidgets.git] / src / common / appbase.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/base/appbase.cpp
3 // Purpose: implements wxAppConsole class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 19.06.2003 (extracted from common/appcmn.cpp)
7 // RCS-ID: $Id$
8 // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
9 // License: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/app.h"
29 #include "wx/intl.h"
30 #include "wx/list.h"
31 #include "wx/log.h"
32 #endif //WX_PRECOMP
33
34 #include "wx/utils.h"
35 #include "wx/apptrait.h"
36 #include "wx/cmdline.h"
37 #include "wx/confbase.h"
38 #include "wx/filename.h"
39 #include "wx/msgout.h"
40 #include "wx/tokenzr.h"
41
42 #if !defined(__WXMSW__) || defined(__WXMICROWIN__)
43 #include <signal.h> // for SIGTRAP used by wxTrap()
44 #endif //Win/Unix
45
46 #if defined(__WXMSW__)
47 #include "wx/msw/wrapwin.h" // includes windows.h for MessageBox()
48 #endif
49
50 #if wxUSE_FONTMAP
51 #include "wx/fontmap.h"
52 #endif // wxUSE_FONTMAP
53
54 #if defined(__WXMAC__)
55 // VZ: MacTypes.h is enough under Mac OS X (where I could test it) but
56 // I don't know which headers are needed under earlier systems so
57 // include everything when in doubt
58 #ifdef __DARWIN__
59 #include "MacTypes.h"
60 #else
61 #include "wx/mac/private.h" // includes mac headers
62 #endif
63 #endif // __WXMAC__
64
65 // ----------------------------------------------------------------------------
66 // private functions prototypes
67 // ----------------------------------------------------------------------------
68
69 #ifdef __WXDEBUG__
70 // really just show the assert dialog
71 static bool DoShowAssertDialog(const wxString& msg);
72
73 // prepare for showing the assert dialog, use the given traits or
74 // DoShowAssertDialog() as last fallback to really show it
75 static
76 void ShowAssertDialog(const wxChar *szFile,
77 int nLine,
78 const wxChar *szCond,
79 const wxChar *szMsg,
80 wxAppTraits *traits = NULL);
81
82 // turn on the trace masks specified in the env variable WXTRACE
83 static void LINKAGEMODE SetTraceMasks();
84 #endif // __WXDEBUG__
85
86 // ----------------------------------------------------------------------------
87 // global vars
88 // ----------------------------------------------------------------------------
89
90 wxAppConsole *wxAppConsole::ms_appInstance = NULL;
91
92 wxAppInitializerFunction wxAppConsole::ms_appInitFn = NULL;
93
94 // ============================================================================
95 // wxAppConsole implementation
96 // ============================================================================
97
98 // ----------------------------------------------------------------------------
99 // ctor/dtor
100 // ----------------------------------------------------------------------------
101
102 wxAppConsole::wxAppConsole()
103 {
104 m_traits = NULL;
105
106 ms_appInstance = this;
107
108 #ifdef __WXDEBUG__
109 SetTraceMasks();
110 #if wxUSE_UNICODE
111 // In unicode mode the SetTraceMasks call can cause an apptraits to be
112 // created, but since we are still in the constructor the wrong kind will
113 // be created for GUI apps. Destroy it so it can be created again later.
114 delete m_traits;
115 m_traits = NULL;
116 #endif
117 #endif
118 }
119
120 wxAppConsole::~wxAppConsole()
121 {
122 delete m_traits;
123 }
124
125 // ----------------------------------------------------------------------------
126 // initilization/cleanup
127 // ----------------------------------------------------------------------------
128
129 bool wxAppConsole::Initialize(int& argc, wxChar **argv)
130 {
131 // remember the command line arguments
132 this->argc = argc;
133 this->argv = argv;
134
135 if ( m_appName.empty() && argv )
136 {
137 // the application name is, by default, the name of its executable file
138 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
139 }
140
141 return true;
142 }
143
144 void wxAppConsole::CleanUp()
145 {
146 }
147
148 // ----------------------------------------------------------------------------
149 // OnXXX() callbacks
150 // ----------------------------------------------------------------------------
151
152 bool wxAppConsole::OnInit()
153 {
154 #if wxUSE_CMDLINE_PARSER
155 wxCmdLineParser parser(argc, argv);
156
157 OnInitCmdLine(parser);
158
159 bool cont;
160 switch ( parser.Parse(FALSE /* don't show usage */) )
161 {
162 case -1:
163 cont = OnCmdLineHelp(parser);
164 break;
165
166 case 0:
167 cont = OnCmdLineParsed(parser);
168 break;
169
170 default:
171 cont = OnCmdLineError(parser);
172 break;
173 }
174
175 if ( !cont )
176 return FALSE;
177 #endif // wxUSE_CMDLINE_PARSER
178
179 return TRUE;
180 }
181
182 int wxAppConsole::OnExit()
183 {
184 #if wxUSE_CONFIG
185 // delete the config object if any (don't use Get() here, but Set()
186 // because Get() could create a new config object)
187 delete wxConfigBase::Set((wxConfigBase *) NULL);
188 #endif // wxUSE_CONFIG
189
190 // use Set(NULL) and not Get() to avoid creating a message output object on
191 // demand when we just want to delete it
192 delete wxMessageOutput::Set(NULL);
193
194 return 0;
195 }
196
197 void wxAppConsole::Exit()
198 {
199 exit(-1);
200 }
201
202 // ----------------------------------------------------------------------------
203 // traits stuff
204 // ----------------------------------------------------------------------------
205
206 wxAppTraits *wxAppConsole::CreateTraits()
207 {
208 return new wxConsoleAppTraits;
209 }
210
211 wxAppTraits *wxAppConsole::GetTraits()
212 {
213 // FIXME-MT: protect this with a CS?
214 if ( !m_traits )
215 {
216 m_traits = CreateTraits();
217
218 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
219 }
220
221 return m_traits;
222 }
223
224 // we must implement CreateXXX() in wxApp itself for backwards compatibility
225 #if WXWIN_COMPATIBILITY_2_4
226
227 #if wxUSE_LOG
228
229 wxLog *wxAppConsole::CreateLogTarget()
230 {
231 wxAppTraits *traits = GetTraits();
232 return traits ? traits->CreateLogTarget() : NULL;
233 }
234
235 #endif // wxUSE_LOG
236
237 wxMessageOutput *wxAppConsole::CreateMessageOutput()
238 {
239 wxAppTraits *traits = GetTraits();
240 return traits ? traits->CreateMessageOutput() : NULL;
241 }
242
243 #endif // WXWIN_COMPATIBILITY_2_4
244
245 // ----------------------------------------------------------------------------
246 // event processing
247 // ----------------------------------------------------------------------------
248
249 void wxAppConsole::ProcessPendingEvents()
250 {
251 // ensure that we're the only thread to modify the pending events list
252 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
253
254 if ( !wxPendingEvents )
255 {
256 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
257 return;
258 }
259
260 // iterate until the list becomes empty
261 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
262 while (node)
263 {
264 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
265 wxPendingEvents->Erase(node);
266
267 // In ProcessPendingEvents(), new handlers might be add
268 // and we can safely leave the critical section here.
269 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
270 handler->ProcessPendingEvents();
271 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
272
273 node = wxPendingEvents->GetFirst();
274 }
275
276 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
277 }
278
279 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
280 {
281 // process the events normally by default
282 return -1;
283 }
284
285 // ----------------------------------------------------------------------------
286 // exception handling
287 // ----------------------------------------------------------------------------
288
289 #if wxUSE_EXCEPTIONS
290
291 void
292 wxAppConsole::HandleEvent(wxEvtHandler *handler,
293 wxEventFunction func,
294 wxEvent& event) const
295 {
296 // by default, simply call the handler
297 (handler->*func)(event);
298 }
299
300 bool
301 wxAppConsole::OnExceptionInMainLoop()
302 {
303 throw;
304
305 // some compilers are too stupid to know that we never return after throw
306 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
307 return false;
308 #endif
309 }
310
311 #endif // wxUSE_EXCEPTIONS
312
313 // ----------------------------------------------------------------------------
314 // cmd line parsing
315 // ----------------------------------------------------------------------------
316
317 #if wxUSE_CMDLINE_PARSER
318
319 #define OPTION_VERBOSE _T("verbose")
320
321 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
322 {
323 // the standard command line options
324 static const wxCmdLineEntryDesc cmdLineDesc[] =
325 {
326 {
327 wxCMD_LINE_SWITCH,
328 _T("h"),
329 _T("help"),
330 gettext_noop("show this help message"),
331 wxCMD_LINE_VAL_NONE,
332 wxCMD_LINE_OPTION_HELP
333 },
334
335 #if wxUSE_LOG
336 {
337 wxCMD_LINE_SWITCH,
338 _T(""),
339 OPTION_VERBOSE,
340 gettext_noop("generate verbose log messages"),
341 wxCMD_LINE_VAL_NONE,
342 0x0
343 },
344 #endif // wxUSE_LOG
345
346 // terminator
347 {
348 wxCMD_LINE_NONE,
349 _T(""),
350 _T(""),
351 _T(""),
352 wxCMD_LINE_VAL_NONE,
353 0x0
354 }
355 };
356
357 parser.SetDesc(cmdLineDesc);
358 }
359
360 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
361 {
362 #if wxUSE_LOG
363 if ( parser.Found(OPTION_VERBOSE) )
364 {
365 wxLog::SetVerbose(TRUE);
366 }
367 #endif // wxUSE_LOG
368
369 return TRUE;
370 }
371
372 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
373 {
374 parser.Usage();
375
376 return FALSE;
377 }
378
379 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
380 {
381 parser.Usage();
382
383 return FALSE;
384 }
385
386 #endif // wxUSE_CMDLINE_PARSER
387
388 // ----------------------------------------------------------------------------
389 // debugging support
390 // ----------------------------------------------------------------------------
391
392 /* static */
393 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
394 const char *componentName)
395 {
396 #if 0 // can't use wxLogTrace, not up and running yet
397 printf("checking build options object '%s' (ptr %p) in '%s'\n",
398 optionsSignature, optionsSignature, componentName);
399 #endif
400
401 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
402 {
403 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
404 wxString prog = wxString::FromAscii(optionsSignature);
405 wxString progName = wxString::FromAscii(componentName);
406 wxString msg;
407
408 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
409 lib.c_str(), progName.c_str(), prog.c_str());
410
411 wxLogFatalError(msg.c_str());
412
413 // normally wxLogFatalError doesn't return
414 return FALSE;
415 }
416 #undef wxCMP
417
418 return TRUE;
419 }
420
421 #ifdef __WXDEBUG__
422
423 void wxAppConsole::OnAssert(const wxChar *file,
424 int line,
425 const wxChar *cond,
426 const wxChar *msg)
427 {
428 ShowAssertDialog(file, line, cond, msg, GetTraits());
429 }
430
431 #endif // __WXDEBUG__
432
433 // ============================================================================
434 // other classes implementations
435 // ============================================================================
436
437 // ----------------------------------------------------------------------------
438 // wxConsoleAppTraitsBase
439 // ----------------------------------------------------------------------------
440
441 #if wxUSE_LOG
442
443 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
444 {
445 return new wxLogStderr;
446 }
447
448 #endif // wxUSE_LOG
449
450 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
451 {
452 return new wxMessageOutputStderr;
453 }
454
455 #if wxUSE_FONTMAP
456
457 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
458 {
459 return (wxFontMapper *)new wxFontMapperBase;
460 }
461
462 #endif // wxUSE_FONTMAP
463
464 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
465 {
466 // console applications don't use renderers
467 return NULL;
468 }
469
470 #ifdef __WXDEBUG__
471 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
472 {
473 return wxAppTraitsBase::ShowAssertDialog(msg);
474 }
475 #endif
476
477 bool wxConsoleAppTraitsBase::HasStderr()
478 {
479 // console applications always have stderr, even under Mac/Windows
480 return true;
481 }
482
483 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
484 {
485 delete object;
486 }
487
488 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
489 {
490 // nothing to do
491 }
492
493 #if wxUSE_SOCKETS
494 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
495 {
496 return NULL;
497 }
498 #endif
499
500 // ----------------------------------------------------------------------------
501 // wxAppTraits
502 // ----------------------------------------------------------------------------
503
504 #ifdef __WXDEBUG__
505
506 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
507 {
508 return DoShowAssertDialog(msg);
509 }
510
511 #endif // __WXDEBUG__
512
513 // ============================================================================
514 // global functions implementation
515 // ============================================================================
516
517 void wxExit()
518 {
519 if ( wxTheApp )
520 {
521 wxTheApp->Exit();
522 }
523 else
524 {
525 // what else can we do?
526 exit(-1);
527 }
528 }
529
530 void wxWakeUpIdle()
531 {
532 if ( wxTheApp )
533 {
534 wxTheApp->WakeUpIdle();
535 }
536 //else: do nothing, what can we do?
537 }
538
539 #ifdef __WXDEBUG__
540
541 // wxASSERT() helper
542 bool wxAssertIsEqual(int x, int y)
543 {
544 return x == y;
545 }
546
547 // break into the debugger
548 void wxTrap()
549 {
550 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
551 DebugBreak();
552 #elif defined(__WXMAC__) && !defined(__DARWIN__)
553 #if __powerc
554 Debugger();
555 #else
556 SysBreak();
557 #endif
558 #elif defined(__UNIX__)
559 raise(SIGTRAP);
560 #else
561 // TODO
562 #endif // Win/Unix
563 }
564
565 void wxAssert(int cond,
566 const wxChar *szFile,
567 int nLine,
568 const wxChar *szCond,
569 const wxChar *szMsg)
570 {
571 if ( !cond )
572 wxOnAssert(szFile, nLine, szCond, szMsg);
573 }
574
575 // this function is called when an assert fails
576 void wxOnAssert(const wxChar *szFile,
577 int nLine,
578 const wxChar *szCond,
579 const wxChar *szMsg)
580 {
581 // FIXME MT-unsafe
582 static bool s_bInAssert = FALSE;
583
584 if ( s_bInAssert )
585 {
586 // He-e-e-e-elp!! we're trapped in endless loop
587 wxTrap();
588
589 s_bInAssert = FALSE;
590
591 return;
592 }
593
594 s_bInAssert = TRUE;
595
596 if ( !wxTheApp )
597 {
598 // by default, show the assert dialog box -- we can't customize this
599 // behaviour
600 ShowAssertDialog(szFile, nLine, szCond, szMsg);
601 }
602 else
603 {
604 // let the app process it as it wants
605 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
606 }
607
608 s_bInAssert = FALSE;
609 }
610
611 #endif // __WXDEBUG__
612
613 // ============================================================================
614 // private functions implementation
615 // ============================================================================
616
617 #ifdef __WXDEBUG__
618
619 static void LINKAGEMODE SetTraceMasks()
620 {
621 #if wxUSE_LOG
622 wxString mask;
623 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
624 {
625 wxStringTokenizer tkn(mask, wxT(",;:"));
626 while ( tkn.HasMoreTokens() )
627 wxLog::AddTraceMask(tkn.GetNextToken());
628 }
629 #endif // wxUSE_LOG
630 }
631
632 bool DoShowAssertDialog(const wxString& msg)
633 {
634 // under MSW we can show the dialog even in the console mode
635 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
636 wxString msgDlg(msg);
637
638 // this message is intentionally not translated -- it is for
639 // developpers only
640 msgDlg += wxT("\nDo you want to stop the program?\n")
641 wxT("You can also choose [Cancel] to suppress ")
642 wxT("further warnings.");
643
644 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
645 MB_YESNOCANCEL | MB_ICONSTOP ) )
646 {
647 case IDYES:
648 wxTrap();
649 break;
650
651 case IDCANCEL:
652 // stop the asserts
653 return true;
654
655 //case IDNO: nothing to do
656 }
657 #else // !__WXMSW__
658 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
659 fflush(stderr);
660
661 // TODO: ask the user to enter "Y" or "N" on the console?
662 wxTrap();
663 #endif // __WXMSW__/!__WXMSW__
664
665 // continue with the asserts
666 return false;
667 }
668
669 // show the assert modal dialog
670 static
671 void ShowAssertDialog(const wxChar *szFile,
672 int nLine,
673 const wxChar *szCond,
674 const wxChar *szMsg,
675 wxAppTraits *traits)
676 {
677 // this variable can be set to true to suppress "assert failure" messages
678 static bool s_bNoAsserts = FALSE;
679
680 wxString msg;
681 msg.reserve(2048);
682
683 // make life easier for people using VC++ IDE by using this format: like
684 // this, clicking on the message will take us immediately to the place of
685 // the failed assert
686 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
687
688 if ( szMsg )
689 {
690 msg << _T(": ") << szMsg;
691 }
692 else // no message given
693 {
694 msg << _T('.');
695 }
696
697 #if wxUSE_THREADS
698 // if we are not in the main thread, output the assert directly and trap
699 // since dialogs cannot be displayed
700 if ( !wxThread::IsMain() )
701 {
702 msg += wxT(" [in child thread]");
703
704 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
705 msg << wxT("\r\n");
706 OutputDebugString(msg );
707 #else
708 // send to stderr
709 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
710 fflush(stderr);
711 #endif
712 // He-e-e-e-elp!! we're asserting in a child thread
713 wxTrap();
714 }
715 #endif // wxUSE_THREADS
716
717 if ( !s_bNoAsserts )
718 {
719 // send it to the normal log destination
720 wxLogDebug(_T("%s"), msg.c_str());
721
722 if ( traits )
723 {
724 // delegate showing assert dialog (if possible) to that class
725 s_bNoAsserts = traits->ShowAssertDialog(msg);
726 }
727 else // no traits object
728 {
729 // fall back to the function of last resort
730 s_bNoAsserts = DoShowAssertDialog(msg);
731 }
732 }
733 }
734
735 #endif // __WXDEBUG__
736