1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appcmn.cpp
3 // Purpose: wxAppConsole and wxAppBase methods common to all platforms
4 // Author: Vadim Zeitlin
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
23 #if defined(__BORLANDC__)
29 #include "wx/window.h"
30 #include "wx/bitmap.h"
32 #include "wx/msgdlg.h"
33 #include "wx/confbase.h"
35 #include "wx/wxcrtvararg.h"
38 #include "wx/apptrait.h"
39 #include "wx/cmdline.h"
40 #include "wx/evtloop.h"
41 #include "wx/msgout.h"
42 #include "wx/thread.h"
43 #include "wx/vidmode.h"
44 #include "wx/ptr_scpd.h"
48 #include "wx/stackwalk.h"
49 #endif // wxUSE_STACKWALKER
52 #if defined(__WXMSW__)
53 #include "wx/msw/private.h" // includes windows.h for LOGFONT
57 #include "wx/fontmap.h"
58 #endif // wxUSE_FONTMAP
60 // DLL options compatibility check:
62 WX_CHECK_BUILD_OPTIONS("wxCore")
64 WXDLLIMPEXP_DATA_CORE(wxList
) wxPendingDelete
;
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
70 // this defines wxEventLoopPtr
71 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoop
)
73 // ============================================================================
74 // wxAppBase implementation
75 // ============================================================================
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 wxAppBase::wxAppBase()
83 m_topWindow
= (wxWindow
*)NULL
;
85 m_useBestVisual
= false;
86 m_forceTrueColour
= false;
92 // We don't want to exit the app if the user code shows a dialog from its
93 // OnInit() -- but this is what would happen if we set m_exitOnFrameDelete
94 // to Yes initially as this dialog would be the last top level window.
95 // OTOH, if we set it to No initially we'll have to overwrite it with Yes
96 // when we enter our OnRun() because we do want the default behaviour from
97 // then on. But this would be a problem if the user code calls
98 // SetExitOnFrameDelete(false) from OnInit().
100 // So we use the special "Later" value which is such that
101 // GetExitOnFrameDelete() returns false for it but which we know we can
102 // safely (i.e. without losing the effect of the users SetExitOnFrameDelete
103 // call) overwrite in OnRun()
104 m_exitOnFrameDelete
= Later
;
107 bool wxAppBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
109 if ( !wxAppConsole::Initialize(argcOrig
, argvOrig
) )
113 wxPendingEventsLocker
= new wxCriticalSection
;
116 wxInitializeStockLists();
118 wxBitmap::InitStandardHandlers();
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
127 wxAppBase::~wxAppBase()
129 // this destructor is required for Darwin
132 void wxAppBase::CleanUp()
134 // clean up all the pending objects
135 DeletePendingObjects();
137 // and any remaining TLWs (they remove themselves from wxTopLevelWindows
138 // when destroyed, so iterate until none are left)
139 while ( !wxTopLevelWindows
.empty() )
141 // do not use Destroy() here as it only puts the TLW in pending list
142 // but we want to delete them now
143 delete wxTopLevelWindows
.GetFirst()->GetData();
146 // undo everything we did in Initialize() above
147 wxBitmap::CleanUpHandlers();
149 wxStockGDI::DeleteAll();
151 wxDeleteStockLists();
153 delete wxTheColourDatabase
;
154 wxTheColourDatabase
= NULL
;
156 delete wxPendingEvents
;
157 wxPendingEvents
= NULL
;
160 delete wxPendingEventsLocker
;
161 wxPendingEventsLocker
= NULL
;
164 // If we don't do the following, we get an apparent memory leak.
165 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
166 #endif // wxUSE_VALIDATORS
167 #endif // wxUSE_THREADS
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 wxWindow
* wxAppBase::GetTopWindow() const
176 wxWindow
* window
= m_topWindow
;
177 if (window
== NULL
&& wxTopLevelWindows
.GetCount() > 0)
178 window
= wxTopLevelWindows
.GetFirst()->GetData();
182 wxVideoMode
wxAppBase::GetDisplayMode() const
184 return wxVideoMode();
187 wxLayoutDirection
wxAppBase::GetLayoutDirection() const
190 const wxLocale
*const locale
= wxGetLocale();
193 const wxLanguageInfo
*const
194 info
= wxLocale::GetLanguageInfo(locale
->GetLanguage());
197 return info
->LayoutDirection
;
202 return wxLayout_Default
;
205 #if wxUSE_CMDLINE_PARSER
207 // ----------------------------------------------------------------------------
208 // GUI-specific command line options handling
209 // ----------------------------------------------------------------------------
211 #define OPTION_THEME _T("theme")
212 #define OPTION_MODE _T("mode")
214 void wxAppBase::OnInitCmdLine(wxCmdLineParser
& parser
)
216 // first add the standard non GUI options
217 wxAppConsole::OnInitCmdLine(parser
);
219 // the standard command line options
220 static const wxCmdLineEntryDesc cmdLineGUIDesc
[] =
222 #ifdef __WXUNIVERSAL__
227 gettext_noop("specify the theme to use"),
228 wxCMD_LINE_VAL_STRING
,
231 #endif // __WXUNIVERSAL__
233 #if defined(__WXMGL__)
234 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
235 // should provide this option. That's why it is in common/appcmn.cpp
236 // and not mgl/app.cpp
241 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
242 wxCMD_LINE_VAL_STRING
,
258 parser
.SetDesc(cmdLineGUIDesc
);
261 bool wxAppBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
263 #ifdef __WXUNIVERSAL__
265 if ( parser
.Found(OPTION_THEME
, &themeName
) )
267 wxTheme
*theme
= wxTheme::Create(themeName
);
270 wxLogError(_("Unsupported theme '%s'."), themeName
.c_str());
274 // Delete the defaultly created theme and set the new theme.
275 delete wxTheme::Get();
278 #endif // __WXUNIVERSAL__
280 #if defined(__WXMGL__)
282 if ( parser
.Found(OPTION_MODE
, &modeDesc
) )
285 if ( wxSscanf(modeDesc
.c_str(), _T("%ux%u-%u"), &w
, &h
, &bpp
) != 3 )
287 wxLogError(_("Invalid display mode specification '%s'."), modeDesc
.c_str());
291 if ( !SetDisplayMode(wxVideoMode(w
, h
, bpp
)) )
296 return wxAppConsole::OnCmdLineParsed(parser
);
299 #endif // wxUSE_CMDLINE_PARSER
301 // ----------------------------------------------------------------------------
302 // main event loop implementation
303 // ----------------------------------------------------------------------------
305 int wxAppBase::MainLoop()
307 wxEventLoopTiedPtr
mainLoop(&m_mainLoop
, new wxEventLoop
);
309 return m_mainLoop
->Run();
312 void wxAppBase::ExitMainLoop()
314 // we should exit from the main event loop, not just any currently active
315 // (e.g. modal dialog) event loop
316 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
322 bool wxAppBase::Pending()
324 // use the currently active message loop here, not m_mainLoop, because if
325 // we're showing a modal dialog (with its own event loop) currently the
326 // main event loop is not running anyhow
327 wxEventLoop
* const loop
= wxEventLoop::GetActive();
329 return loop
&& loop
->Pending();
332 bool wxAppBase::Dispatch()
334 // see comment in Pending()
335 wxEventLoop
* const loop
= wxEventLoop::GetActive();
337 return loop
&& loop
->Dispatch();
340 // ----------------------------------------------------------------------------
342 // ----------------------------------------------------------------------------
344 bool wxAppBase::OnInitGui()
346 #ifdef __WXUNIVERSAL__
347 if ( !wxTheme::Get() && !wxTheme::CreateDefault() )
349 #endif // __WXUNIVERSAL__
354 int wxAppBase::OnRun()
356 // see the comment in ctor: if the initial value hasn't been changed, use
357 // the default Yes from now on
358 if ( m_exitOnFrameDelete
== Later
)
360 m_exitOnFrameDelete
= Yes
;
362 //else: it has been changed, assume the user knows what he is doing
367 int wxAppBase::OnExit()
369 #ifdef __WXUNIVERSAL__
370 delete wxTheme::Set(NULL
);
371 #endif // __WXUNIVERSAL__
373 return wxAppConsole::OnExit();
376 void wxAppBase::Exit()
381 wxAppTraits
*wxAppBase::CreateTraits()
383 return new wxGUIAppTraits
;
386 // ----------------------------------------------------------------------------
388 // ----------------------------------------------------------------------------
390 void wxAppBase::SetActive(bool active
, wxWindow
* WXUNUSED(lastFocus
))
392 if ( active
== m_isActive
)
397 wxActivateEvent
event(wxEVT_ACTIVATE_APP
, active
);
398 event
.SetEventObject(this);
400 (void)ProcessEvent(event
);
403 // ----------------------------------------------------------------------------
405 // ----------------------------------------------------------------------------
407 void wxAppBase::DeletePendingObjects()
409 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
412 wxObject
*obj
= node
->GetData();
414 // remove it from the list first so that if we get back here somehow
415 // during the object deletion (e.g. wxYield called from its dtor) we
416 // wouldn't try to delete it the second time
417 if ( wxPendingDelete
.Member(obj
) )
418 wxPendingDelete
.Erase(node
);
422 // Deleting one object may have deleted other pending
423 // objects, so start from beginning of list again.
424 node
= wxPendingDelete
.GetFirst();
428 // Returns true if more time is needed.
429 bool wxAppBase::ProcessIdle()
432 bool needMore
= false;
433 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
436 wxWindow
* win
= node
->GetData();
437 if (SendIdleEvents(win
, event
))
439 node
= node
->GetNext();
442 event
.SetEventObject(this);
443 (void) ProcessEvent(event
);
444 if (event
.MoreRequested())
447 wxUpdateUIEvent::ResetUpdateTime();
452 // Send idle event to window and all subwindows
453 bool wxAppBase::SendIdleEvents(wxWindow
* win
, wxIdleEvent
& event
)
455 bool needMore
= false;
457 win
->OnInternalIdle();
459 if (wxIdleEvent::CanSend(win
))
461 event
.SetEventObject(win
);
462 win
->GetEventHandler()->ProcessEvent(event
);
464 if (event
.MoreRequested())
467 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetFirst();
470 wxWindow
*child
= node
->GetData();
471 if (SendIdleEvents(child
, event
))
474 node
= node
->GetNext();
480 void wxAppBase::OnIdle(wxIdleEvent
& WXUNUSED(event
))
482 // If there are pending events, we must process them: pending events
483 // are either events to the threads other than main or events posted
484 // with wxPostEvent() functions
485 // GRG: I have moved this here so that all pending events are processed
486 // before starting to delete any objects. This behaves better (in
487 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
488 // behaviour. Changed Feb/2000 before 2.1.14
489 ProcessPendingEvents();
491 // 'Garbage' collection of windows deleted with Close().
492 DeletePendingObjects();
495 // flush the logged messages if any
496 wxLog::FlushActive();
501 // ----------------------------------------------------------------------------
502 // exceptions support
503 // ----------------------------------------------------------------------------
507 bool wxAppBase::OnExceptionInMainLoop()
511 // some compilers are too stupid to know that we never return after throw
512 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
517 #endif // wxUSE_EXCEPTIONS
519 // ----------------------------------------------------------------------------
520 // wxGUIAppTraitsBase
521 // ----------------------------------------------------------------------------
525 wxLog
*wxGUIAppTraitsBase::CreateLogTarget()
530 // we must have something!
531 return new wxLogStderr
;
537 wxMessageOutput
*wxGUIAppTraitsBase::CreateMessageOutput()
539 // The standard way of printing help on command line arguments (app --help)
540 // is (according to common practice):
541 // - console apps: to stderr (on any platform)
542 // - GUI apps: stderr on Unix platforms (!)
543 // message box under Windows and others
545 return new wxMessageOutputStderr
;
547 // wxMessageOutputMessageBox doesn't work under Motif
549 return new wxMessageOutputLog
;
551 return new wxMessageOutputMessageBox
;
553 #endif // __UNIX__/!__UNIX__
558 wxFontMapper
*wxGUIAppTraitsBase::CreateFontMapper()
560 return new wxFontMapper
;
563 #endif // wxUSE_FONTMAP
565 wxRendererNative
*wxGUIAppTraitsBase::CreateRenderer()
567 // use the default native renderer by default
573 bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
575 #if defined(__WXMSW__) || !wxUSE_MSGDLG
576 // under MSW we prefer to use the base class version using ::MessageBox()
577 // even if wxMessageBox() is available because it has less chances to
578 // double fault our app than our wxMessageBox()
579 return wxAppTraitsBase::ShowAssertDialog(msg
);
580 #else // wxUSE_MSGDLG
581 wxString msgDlg
= msg
;
583 #if wxUSE_STACKWALKER
584 // on Unix stack frame generation may take some time, depending on the
585 // size of the executable mainly... warn the user that we are working
586 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
589 const wxString stackTrace
= GetAssertStackTrace();
590 if ( !stackTrace
.empty() )
591 msgDlg
<< _T("\n\nCall stack:\n") << stackTrace
;
592 #endif // wxUSE_STACKWALKER
594 // this message is intentionally not translated -- it is for
596 msgDlg
+= wxT("\nDo you want to stop the program?\n")
597 wxT("You can also choose [Cancel] to suppress ")
598 wxT("further warnings.");
600 switch ( wxMessageBox(msgDlg
, wxT("wxWidgets Debug Alert"),
601 wxYES_NO
| wxCANCEL
| wxICON_STOP
) )
611 //case wxNO: nothing to do
615 #endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
618 #endif // __WXDEBUG__
620 bool wxGUIAppTraitsBase::HasStderr()
622 // we consider that under Unix stderr always goes somewhere, even if the
623 // user doesn't always see it under GUI desktops
631 void wxGUIAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
633 if ( !wxPendingDelete
.Member(object
) )
634 wxPendingDelete
.Append(object
);
637 void wxGUIAppTraitsBase::RemoveFromPendingDelete(wxObject
*object
)
639 wxPendingDelete
.DeleteObject(object
);
644 #if defined(__WINDOWS__)
645 #include "wx/msw/gsockmsw.h"
646 #elif defined(__UNIX__) || defined(__DARWIN__) || defined(__OS2__)
647 #include "wx/unix/gsockunx.h"
648 #elif defined(__WXMAC__)
649 #include <MacHeaders.c>
650 #define OTUNIXERRORS 1
651 #include <OpenTransport.h>
652 #include <OpenTransportProviders.h>
653 #include <OpenTptInternet.h>
655 #include "wx/mac/gsockmac.h"
657 #error "Must include correct GSocket header here"
660 GSocketGUIFunctionsTable
* wxGUIAppTraitsBase::GetSocketGUIFunctionsTable()
662 #if defined(__WXMAC__) && !defined(__DARWIN__)
663 // NB: wxMac CFM does not have any GUI-specific functions in gsocket.c and
664 // so it doesn't need this table at all
666 #else // !__WXMAC__ || __DARWIN__
667 static GSocketGUIFunctionsTableConcrete table
;
669 #endif // !__WXMAC__ || __DARWIN__