Final MSW/PalmOS split. Remove dump copies of MSW specific code.
[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 #if wxUSE_LOG
132 // If some code logged something before wxApp instance was created,
133 // wxLogStderr was set as the target. Undo it here by destroying the
134 // current target. It will be re-created next time logging is needed, but
135 // this time wxAppTraits will be used:
136 delete wxLog::SetActiveTarget(NULL);
137 #endif // wxUSE_LOG
138
139 // remember the command line arguments
140 this->argc = argc;
141 this->argv = argv;
142
143 #ifndef __WXPALMOS__
144 if ( m_appName.empty() && argv )
145 {
146 // the application name is, by default, the name of its executable file
147 wxFileName::SplitPath(argv[0], NULL, &m_appName, NULL);
148 }
149 #endif
150
151 return true;
152 }
153
154 void wxAppConsole::CleanUp()
155 {
156 }
157
158 // ----------------------------------------------------------------------------
159 // OnXXX() callbacks
160 // ----------------------------------------------------------------------------
161
162 bool wxAppConsole::OnInit()
163 {
164 #if wxUSE_CMDLINE_PARSER
165 wxCmdLineParser parser(argc, argv);
166
167 OnInitCmdLine(parser);
168
169 bool cont;
170 switch ( parser.Parse(false /* don't show usage */) )
171 {
172 case -1:
173 cont = OnCmdLineHelp(parser);
174 break;
175
176 case 0:
177 cont = OnCmdLineParsed(parser);
178 break;
179
180 default:
181 cont = OnCmdLineError(parser);
182 break;
183 }
184
185 if ( !cont )
186 return false;
187 #endif // wxUSE_CMDLINE_PARSER
188
189 return true;
190 }
191
192 int wxAppConsole::OnExit()
193 {
194 #if wxUSE_CONFIG
195 // delete the config object if any (don't use Get() here, but Set()
196 // because Get() could create a new config object)
197 delete wxConfigBase::Set((wxConfigBase *) NULL);
198 #endif // wxUSE_CONFIG
199
200 // use Set(NULL) and not Get() to avoid creating a message output object on
201 // demand when we just want to delete it
202 delete wxMessageOutput::Set(NULL);
203
204 return 0;
205 }
206
207 void wxAppConsole::Exit()
208 {
209 exit(-1);
210 }
211
212 // ----------------------------------------------------------------------------
213 // traits stuff
214 // ----------------------------------------------------------------------------
215
216 wxAppTraits *wxAppConsole::CreateTraits()
217 {
218 return new wxConsoleAppTraits;
219 }
220
221 wxAppTraits *wxAppConsole::GetTraits()
222 {
223 // FIXME-MT: protect this with a CS?
224 if ( !m_traits )
225 {
226 m_traits = CreateTraits();
227
228 wxASSERT_MSG( m_traits, _T("wxApp::CreateTraits() failed?") );
229 }
230
231 return m_traits;
232 }
233
234 // we must implement CreateXXX() in wxApp itself for backwards compatibility
235 #if WXWIN_COMPATIBILITY_2_4
236
237 #if wxUSE_LOG
238
239 wxLog *wxAppConsole::CreateLogTarget()
240 {
241 wxAppTraits *traits = GetTraits();
242 return traits ? traits->CreateLogTarget() : NULL;
243 }
244
245 #endif // wxUSE_LOG
246
247 wxMessageOutput *wxAppConsole::CreateMessageOutput()
248 {
249 wxAppTraits *traits = GetTraits();
250 return traits ? traits->CreateMessageOutput() : NULL;
251 }
252
253 #endif // WXWIN_COMPATIBILITY_2_4
254
255 // ----------------------------------------------------------------------------
256 // event processing
257 // ----------------------------------------------------------------------------
258
259 void wxAppConsole::ProcessPendingEvents()
260 {
261 // ensure that we're the only thread to modify the pending events list
262 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
263
264 if ( !wxPendingEvents )
265 {
266 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
267 return;
268 }
269
270 // iterate until the list becomes empty
271 wxList::compatibility_iterator node = wxPendingEvents->GetFirst();
272 while (node)
273 {
274 wxEvtHandler *handler = (wxEvtHandler *)node->GetData();
275 wxPendingEvents->Erase(node);
276
277 // In ProcessPendingEvents(), new handlers might be add
278 // and we can safely leave the critical section here.
279 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
280 handler->ProcessPendingEvents();
281 wxENTER_CRIT_SECT( *wxPendingEventsLocker );
282
283 node = wxPendingEvents->GetFirst();
284 }
285
286 wxLEAVE_CRIT_SECT( *wxPendingEventsLocker );
287 }
288
289 int wxAppConsole::FilterEvent(wxEvent& WXUNUSED(event))
290 {
291 // process the events normally by default
292 return -1;
293 }
294
295 // ----------------------------------------------------------------------------
296 // exception handling
297 // ----------------------------------------------------------------------------
298
299 #if wxUSE_EXCEPTIONS
300
301 void
302 wxAppConsole::HandleEvent(wxEvtHandler *handler,
303 wxEventFunction func,
304 wxEvent& event) const
305 {
306 // by default, simply call the handler
307 (handler->*func)(event);
308 }
309
310 bool
311 wxAppConsole::OnExceptionInMainLoop()
312 {
313 throw;
314
315 // some compilers are too stupid to know that we never return after throw
316 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
317 return false;
318 #endif
319 }
320
321 #endif // wxUSE_EXCEPTIONS
322
323 // ----------------------------------------------------------------------------
324 // cmd line parsing
325 // ----------------------------------------------------------------------------
326
327 #if wxUSE_CMDLINE_PARSER
328
329 #define OPTION_VERBOSE _T("verbose")
330
331 void wxAppConsole::OnInitCmdLine(wxCmdLineParser& parser)
332 {
333 // the standard command line options
334 static const wxCmdLineEntryDesc cmdLineDesc[] =
335 {
336 {
337 wxCMD_LINE_SWITCH,
338 _T("h"),
339 _T("help"),
340 gettext_noop("show this help message"),
341 wxCMD_LINE_VAL_NONE,
342 wxCMD_LINE_OPTION_HELP
343 },
344
345 #if wxUSE_LOG
346 {
347 wxCMD_LINE_SWITCH,
348 _T(""),
349 OPTION_VERBOSE,
350 gettext_noop("generate verbose log messages"),
351 wxCMD_LINE_VAL_NONE,
352 0x0
353 },
354 #endif // wxUSE_LOG
355
356 // terminator
357 {
358 wxCMD_LINE_NONE,
359 _T(""),
360 _T(""),
361 _T(""),
362 wxCMD_LINE_VAL_NONE,
363 0x0
364 }
365 };
366
367 parser.SetDesc(cmdLineDesc);
368 }
369
370 bool wxAppConsole::OnCmdLineParsed(wxCmdLineParser& parser)
371 {
372 #if wxUSE_LOG
373 if ( parser.Found(OPTION_VERBOSE) )
374 {
375 wxLog::SetVerbose(true);
376 }
377 #else
378 wxUnusedVar(parser);
379 #endif // wxUSE_LOG
380
381 return true;
382 }
383
384 bool wxAppConsole::OnCmdLineHelp(wxCmdLineParser& parser)
385 {
386 parser.Usage();
387
388 return false;
389 }
390
391 bool wxAppConsole::OnCmdLineError(wxCmdLineParser& parser)
392 {
393 parser.Usage();
394
395 return false;
396 }
397
398 #endif // wxUSE_CMDLINE_PARSER
399
400 // ----------------------------------------------------------------------------
401 // debugging support
402 // ----------------------------------------------------------------------------
403
404 /* static */
405 bool wxAppConsole::CheckBuildOptions(const char *optionsSignature,
406 const char *componentName)
407 {
408 #if 0 // can't use wxLogTrace, not up and running yet
409 printf("checking build options object '%s' (ptr %p) in '%s'\n",
410 optionsSignature, optionsSignature, componentName);
411 #endif
412
413 if ( strcmp(optionsSignature, WX_BUILD_OPTIONS_SIGNATURE) != 0 )
414 {
415 wxString lib = wxString::FromAscii(WX_BUILD_OPTIONS_SIGNATURE);
416 wxString prog = wxString::FromAscii(optionsSignature);
417 wxString progName = wxString::FromAscii(componentName);
418 wxString msg;
419
420 msg.Printf(_T("Mismatch between the program and library build versions detected.\nThe library used %s,\nand %s used %s."),
421 lib.c_str(), progName.c_str(), prog.c_str());
422
423 wxLogFatalError(msg.c_str());
424
425 // normally wxLogFatalError doesn't return
426 return false;
427 }
428 #undef wxCMP
429
430 return true;
431 }
432
433 #ifdef __WXDEBUG__
434
435 void wxAppConsole::OnAssert(const wxChar *file,
436 int line,
437 const wxChar *cond,
438 const wxChar *msg)
439 {
440 ShowAssertDialog(file, line, cond, msg, GetTraits());
441 }
442
443 #endif // __WXDEBUG__
444
445 // ============================================================================
446 // other classes implementations
447 // ============================================================================
448
449 // ----------------------------------------------------------------------------
450 // wxConsoleAppTraitsBase
451 // ----------------------------------------------------------------------------
452
453 #if wxUSE_LOG
454
455 wxLog *wxConsoleAppTraitsBase::CreateLogTarget()
456 {
457 return new wxLogStderr;
458 }
459
460 #endif // wxUSE_LOG
461
462 wxMessageOutput *wxConsoleAppTraitsBase::CreateMessageOutput()
463 {
464 return new wxMessageOutputStderr;
465 }
466
467 #if wxUSE_FONTMAP
468
469 wxFontMapper *wxConsoleAppTraitsBase::CreateFontMapper()
470 {
471 return (wxFontMapper *)new wxFontMapperBase;
472 }
473
474 #endif // wxUSE_FONTMAP
475
476 wxRendererNative *wxConsoleAppTraitsBase::CreateRenderer()
477 {
478 // console applications don't use renderers
479 return NULL;
480 }
481
482 #ifdef __WXDEBUG__
483 bool wxConsoleAppTraitsBase::ShowAssertDialog(const wxString& msg)
484 {
485 return wxAppTraitsBase::ShowAssertDialog(msg);
486 }
487 #endif
488
489 bool wxConsoleAppTraitsBase::HasStderr()
490 {
491 // console applications always have stderr, even under Mac/Windows
492 return true;
493 }
494
495 void wxConsoleAppTraitsBase::ScheduleForDestroy(wxObject *object)
496 {
497 delete object;
498 }
499
500 void wxConsoleAppTraitsBase::RemoveFromPendingDelete(wxObject * WXUNUSED(object))
501 {
502 // nothing to do
503 }
504
505 #if wxUSE_SOCKETS
506 GSocketGUIFunctionsTable* wxConsoleAppTraitsBase::GetSocketGUIFunctionsTable()
507 {
508 return NULL;
509 }
510 #endif
511
512 // ----------------------------------------------------------------------------
513 // wxAppTraits
514 // ----------------------------------------------------------------------------
515
516 #ifdef __WXDEBUG__
517
518 bool wxAppTraitsBase::ShowAssertDialog(const wxString& msg)
519 {
520 return DoShowAssertDialog(msg);
521 }
522
523 #endif // __WXDEBUG__
524
525 // ============================================================================
526 // global functions implementation
527 // ============================================================================
528
529 void wxExit()
530 {
531 if ( wxTheApp )
532 {
533 wxTheApp->Exit();
534 }
535 else
536 {
537 // what else can we do?
538 exit(-1);
539 }
540 }
541
542 void wxWakeUpIdle()
543 {
544 if ( wxTheApp )
545 {
546 wxTheApp->WakeUpIdle();
547 }
548 //else: do nothing, what can we do?
549 }
550
551 #ifdef __WXDEBUG__
552
553 // wxASSERT() helper
554 bool wxAssertIsEqual(int x, int y)
555 {
556 return x == y;
557 }
558
559 // break into the debugger
560 void wxTrap()
561 {
562 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
563 DebugBreak();
564 #elif defined(__WXMAC__) && !defined(__DARWIN__)
565 #if __powerc
566 Debugger();
567 #else
568 SysBreak();
569 #endif
570 #elif defined(__UNIX__)
571 raise(SIGTRAP);
572 #else
573 // TODO
574 #endif // Win/Unix
575 }
576
577 void wxAssert(int cond,
578 const wxChar *szFile,
579 int nLine,
580 const wxChar *szCond,
581 const wxChar *szMsg)
582 {
583 if ( !cond )
584 wxOnAssert(szFile, nLine, szCond, szMsg);
585 }
586
587 // this function is called when an assert fails
588 void wxOnAssert(const wxChar *szFile,
589 int nLine,
590 const wxChar *szCond,
591 const wxChar *szMsg)
592 {
593 // FIXME MT-unsafe
594 static bool s_bInAssert = false;
595
596 if ( s_bInAssert )
597 {
598 // He-e-e-e-elp!! we're trapped in endless loop
599 wxTrap();
600
601 s_bInAssert = false;
602
603 return;
604 }
605
606 s_bInAssert = true;
607
608 if ( !wxTheApp )
609 {
610 // by default, show the assert dialog box -- we can't customize this
611 // behaviour
612 ShowAssertDialog(szFile, nLine, szCond, szMsg);
613 }
614 else
615 {
616 // let the app process it as it wants
617 wxTheApp->OnAssert(szFile, nLine, szCond, szMsg);
618 }
619
620 s_bInAssert = false;
621 }
622
623 #endif // __WXDEBUG__
624
625 // ============================================================================
626 // private functions implementation
627 // ============================================================================
628
629 #ifdef __WXDEBUG__
630
631 static void LINKAGEMODE SetTraceMasks()
632 {
633 #if wxUSE_LOG
634 wxString mask;
635 if ( wxGetEnv(wxT("WXTRACE"), &mask) )
636 {
637 wxStringTokenizer tkn(mask, wxT(",;:"));
638 while ( tkn.HasMoreTokens() )
639 wxLog::AddTraceMask(tkn.GetNextToken());
640 }
641 #endif // wxUSE_LOG
642 }
643
644 bool DoShowAssertDialog(const wxString& msg)
645 {
646 // under MSW we can show the dialog even in the console mode
647 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
648 wxString msgDlg(msg);
649
650 // this message is intentionally not translated -- it is for
651 // developpers only
652 msgDlg += wxT("\nDo you want to stop the program?\n")
653 wxT("You can also choose [Cancel] to suppress ")
654 wxT("further warnings.");
655
656 switch ( ::MessageBox(NULL, msgDlg, _T("wxWidgets Debug Alert"),
657 MB_YESNOCANCEL | MB_ICONSTOP ) )
658 {
659 case IDYES:
660 wxTrap();
661 break;
662
663 case IDCANCEL:
664 // stop the asserts
665 return true;
666
667 //case IDNO: nothing to do
668 }
669 #else // !__WXMSW__
670 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
671 fflush(stderr);
672
673 // TODO: ask the user to enter "Y" or "N" on the console?
674 wxTrap();
675 #endif // __WXMSW__/!__WXMSW__
676
677 // continue with the asserts
678 return false;
679 }
680
681 // show the assert modal dialog
682 static
683 void ShowAssertDialog(const wxChar *szFile,
684 int nLine,
685 const wxChar *szCond,
686 const wxChar *szMsg,
687 wxAppTraits *traits)
688 {
689 // this variable can be set to true to suppress "assert failure" messages
690 static bool s_bNoAsserts = false;
691
692 wxString msg;
693 msg.reserve(2048);
694
695 // make life easier for people using VC++ IDE by using this format: like
696 // this, clicking on the message will take us immediately to the place of
697 // the failed assert
698 msg.Printf(wxT("%s(%d): assert \"%s\" failed"), szFile, nLine, szCond);
699
700 if ( szMsg )
701 {
702 msg << _T(": ") << szMsg;
703 }
704 else // no message given
705 {
706 msg << _T('.');
707 }
708
709 #if wxUSE_THREADS
710 // if we are not in the main thread, output the assert directly and trap
711 // since dialogs cannot be displayed
712 if ( !wxThread::IsMain() )
713 {
714 msg += wxT(" [in child thread]");
715
716 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
717 msg << wxT("\r\n");
718 OutputDebugString(msg );
719 #else
720 // send to stderr
721 wxFprintf(stderr, wxT("%s\n"), msg.c_str());
722 fflush(stderr);
723 #endif
724 // He-e-e-e-elp!! we're asserting in a child thread
725 wxTrap();
726 }
727 #endif // wxUSE_THREADS
728
729 if ( !s_bNoAsserts )
730 {
731 // send it to the normal log destination
732 wxLogDebug(_T("%s"), msg.c_str());
733
734 if ( traits )
735 {
736 // delegate showing assert dialog (if possible) to that class
737 s_bNoAsserts = traits->ShowAssertDialog(msg);
738 }
739 else // no traits object
740 {
741 // fall back to the function of last resort
742 s_bNoAsserts = DoShowAssertDialog(msg);
743 }
744 }
745 }
746
747 #endif // __WXDEBUG__
748