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"
37 #include "wx/apptrait.h"
38 #include "wx/cmdline.h"
39 #include "wx/evtloop.h"
40 #include "wx/msgout.h"
41 #include "wx/thread.h"
42 #include "wx/vidmode.h"
43 #include "wx/ptr_scpd.h"
47 #include "wx/stackwalk.h"
48 #endif // wxUSE_STACKWALKER
51 #if defined(__WXMSW__)
52 #include "wx/msw/private.h" // includes windows.h for LOGFONT
56 #include "wx/fontmap.h"
57 #endif // wxUSE_FONTMAP
59 // DLL options compatibility check:
61 WX_CHECK_BUILD_OPTIONS("wxCore")
63 WXDLLIMPEXP_DATA_CORE(wxList
) wxPendingDelete
;
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // this defines wxEventLoopPtr
70 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoop
)
72 // ============================================================================
73 // wxAppBase implementation
74 // ============================================================================
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 wxAppBase::wxAppBase()
82 m_topWindow
= (wxWindow
*)NULL
;
84 m_useBestVisual
= false;
85 m_forceTrueColour
= false;
91 // We don't want to exit the app if the user code shows a dialog from its
92 // OnInit() -- but this is what would happen if we set m_exitOnFrameDelete
93 // to Yes initially as this dialog would be the last top level window.
94 // OTOH, if we set it to No initially we'll have to overwrite it with Yes
95 // when we enter our OnRun() because we do want the default behaviour from
96 // then on. But this would be a problem if the user code calls
97 // SetExitOnFrameDelete(false) from OnInit().
99 // So we use the special "Later" value which is such that
100 // GetExitOnFrameDelete() returns false for it but which we know we can
101 // safely (i.e. without losing the effect of the users SetExitOnFrameDelete
102 // call) overwrite in OnRun()
103 m_exitOnFrameDelete
= Later
;
106 bool wxAppBase::Initialize(int& argcOrig
, wxChar
**argvOrig
)
108 if ( !wxAppConsole::Initialize(argcOrig
, argvOrig
) )
112 wxPendingEventsLocker
= new wxCriticalSection
;
115 wxInitializeStockLists();
117 wxBitmap::InitStandardHandlers();
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 wxAppBase::~wxAppBase()
128 // this destructor is required for Darwin
131 void wxAppBase::CleanUp()
133 // clean up all the pending objects
134 DeletePendingObjects();
136 // and any remaining TLWs (they remove themselves from wxTopLevelWindows
137 // when destroyed, so iterate until none are left)
138 while ( !wxTopLevelWindows
.empty() )
140 // do not use Destroy() here as it only puts the TLW in pending list
141 // but we want to delete them now
142 delete wxTopLevelWindows
.GetFirst()->GetData();
145 // undo everything we did in Initialize() above
146 wxBitmap::CleanUpHandlers();
148 wxStockGDI::DeleteAll();
150 wxDeleteStockLists();
152 delete wxTheColourDatabase
;
153 wxTheColourDatabase
= NULL
;
155 delete wxPendingEvents
;
156 wxPendingEvents
= NULL
;
159 delete wxPendingEventsLocker
;
160 wxPendingEventsLocker
= NULL
;
163 // If we don't do the following, we get an apparent memory leak.
164 ((wxEvtHandler
&) wxDefaultValidator
).ClearEventLocker();
165 #endif // wxUSE_VALIDATORS
166 #endif // wxUSE_THREADS
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 wxWindow
* wxAppBase::GetTopWindow() const
175 wxWindow
* window
= m_topWindow
;
176 if (window
== NULL
&& wxTopLevelWindows
.GetCount() > 0)
177 window
= wxTopLevelWindows
.GetFirst()->GetData();
181 wxVideoMode
wxAppBase::GetDisplayMode() const
183 return wxVideoMode();
186 wxLayoutDirection
wxAppBase::GetLayoutDirection() const
189 const wxLocale
*const locale
= wxGetLocale();
192 const wxLanguageInfo
*const
193 info
= wxLocale::GetLanguageInfo(locale
->GetLanguage());
196 return info
->LayoutDirection
;
201 return wxLayout_Default
;
204 #if wxUSE_CMDLINE_PARSER
206 // ----------------------------------------------------------------------------
207 // GUI-specific command line options handling
208 // ----------------------------------------------------------------------------
210 #define OPTION_THEME _T("theme")
211 #define OPTION_MODE _T("mode")
213 void wxAppBase::OnInitCmdLine(wxCmdLineParser
& parser
)
215 // first add the standard non GUI options
216 wxAppConsole::OnInitCmdLine(parser
);
218 // the standard command line options
219 static const wxCmdLineEntryDesc cmdLineGUIDesc
[] =
221 #ifdef __WXUNIVERSAL__
226 gettext_noop("specify the theme to use"),
227 wxCMD_LINE_VAL_STRING
,
230 #endif // __WXUNIVERSAL__
232 #if defined(__WXMGL__)
233 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
234 // should provide this option. That's why it is in common/appcmn.cpp
235 // and not mgl/app.cpp
240 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
241 wxCMD_LINE_VAL_STRING
,
257 parser
.SetDesc(cmdLineGUIDesc
);
260 bool wxAppBase::OnCmdLineParsed(wxCmdLineParser
& parser
)
262 #ifdef __WXUNIVERSAL__
264 if ( parser
.Found(OPTION_THEME
, &themeName
) )
266 wxTheme
*theme
= wxTheme::Create(themeName
);
269 wxLogError(_("Unsupported theme '%s'."), themeName
.c_str());
273 // Delete the defaultly created theme and set the new theme.
274 delete wxTheme::Get();
277 #endif // __WXUNIVERSAL__
279 #if defined(__WXMGL__)
281 if ( parser
.Found(OPTION_MODE
, &modeDesc
) )
284 if ( wxSscanf(modeDesc
.c_str(), _T("%ux%u-%u"), &w
, &h
, &bpp
) != 3 )
286 wxLogError(_("Invalid display mode specification '%s'."), modeDesc
.c_str());
290 if ( !SetDisplayMode(wxVideoMode(w
, h
, bpp
)) )
295 return wxAppConsole::OnCmdLineParsed(parser
);
298 #endif // wxUSE_CMDLINE_PARSER
300 // ----------------------------------------------------------------------------
301 // main event loop implementation
302 // ----------------------------------------------------------------------------
304 int wxAppBase::MainLoop()
306 wxEventLoopTiedPtr
mainLoop(&m_mainLoop
, new wxEventLoop
);
308 return m_mainLoop
->Run();
311 void wxAppBase::ExitMainLoop()
313 // we should exit from the main event loop, not just any currently active
314 // (e.g. modal dialog) event loop
315 if ( m_mainLoop
&& m_mainLoop
->IsRunning() )
321 bool wxAppBase::Pending()
323 // use the currently active message loop here, not m_mainLoop, because if
324 // we're showing a modal dialog (with its own event loop) currently the
325 // main event loop is not running anyhow
326 wxEventLoop
* const loop
= wxEventLoop::GetActive();
328 return loop
&& loop
->Pending();
331 bool wxAppBase::Dispatch()
333 // see comment in Pending()
334 wxEventLoop
* const loop
= wxEventLoop::GetActive();
336 return loop
&& loop
->Dispatch();
339 // ----------------------------------------------------------------------------
341 // ----------------------------------------------------------------------------
343 bool wxAppBase::OnInitGui()
345 #ifdef __WXUNIVERSAL__
346 if ( !wxTheme::Get() && !wxTheme::CreateDefault() )
348 #endif // __WXUNIVERSAL__
353 int wxAppBase::OnRun()
355 // see the comment in ctor: if the initial value hasn't been changed, use
356 // the default Yes from now on
357 if ( m_exitOnFrameDelete
== Later
)
359 m_exitOnFrameDelete
= Yes
;
361 //else: it has been changed, assume the user knows what he is doing
366 int wxAppBase::OnExit()
368 #ifdef __WXUNIVERSAL__
369 delete wxTheme::Set(NULL
);
370 #endif // __WXUNIVERSAL__
372 return wxAppConsole::OnExit();
375 void wxAppBase::Exit()
380 wxAppTraits
*wxAppBase::CreateTraits()
382 return new wxGUIAppTraits
;
385 // ----------------------------------------------------------------------------
387 // ----------------------------------------------------------------------------
389 void wxAppBase::SetActive(bool active
, wxWindow
* WXUNUSED(lastFocus
))
391 if ( active
== m_isActive
)
396 wxActivateEvent
event(wxEVT_ACTIVATE_APP
, active
);
397 event
.SetEventObject(this);
399 (void)ProcessEvent(event
);
402 // ----------------------------------------------------------------------------
404 // ----------------------------------------------------------------------------
406 void wxAppBase::DeletePendingObjects()
408 wxList::compatibility_iterator node
= wxPendingDelete
.GetFirst();
411 wxObject
*obj
= node
->GetData();
413 // remove it from the list first so that if we get back here somehow
414 // during the object deletion (e.g. wxYield called from its dtor) we
415 // wouldn't try to delete it the second time
416 if ( wxPendingDelete
.Member(obj
) )
417 wxPendingDelete
.Erase(node
);
421 // Deleting one object may have deleted other pending
422 // objects, so start from beginning of list again.
423 node
= wxPendingDelete
.GetFirst();
427 // Returns true if more time is needed.
428 bool wxAppBase::ProcessIdle()
431 bool needMore
= false;
432 wxWindowList::compatibility_iterator node
= wxTopLevelWindows
.GetFirst();
435 wxWindow
* win
= node
->GetData();
436 if (SendIdleEvents(win
, event
))
438 node
= node
->GetNext();
441 event
.SetEventObject(this);
442 (void) ProcessEvent(event
);
443 if (event
.MoreRequested())
446 wxUpdateUIEvent::ResetUpdateTime();
451 // Send idle event to window and all subwindows
452 bool wxAppBase::SendIdleEvents(wxWindow
* win
, wxIdleEvent
& event
)
454 bool needMore
= false;
456 win
->OnInternalIdle();
458 if (wxIdleEvent::CanSend(win
))
460 event
.SetEventObject(win
);
461 win
->GetEventHandler()->ProcessEvent(event
);
463 if (event
.MoreRequested())
466 wxWindowList::compatibility_iterator node
= win
->GetChildren().GetFirst();
469 wxWindow
*child
= node
->GetData();
470 if (SendIdleEvents(child
, event
))
473 node
= node
->GetNext();
479 void wxAppBase::OnIdle(wxIdleEvent
& WXUNUSED(event
))
481 // If there are pending events, we must process them: pending events
482 // are either events to the threads other than main or events posted
483 // with wxPostEvent() functions
484 // GRG: I have moved this here so that all pending events are processed
485 // before starting to delete any objects. This behaves better (in
486 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
487 // behaviour. Changed Feb/2000 before 2.1.14
488 ProcessPendingEvents();
490 // 'Garbage' collection of windows deleted with Close().
491 DeletePendingObjects();
494 // flush the logged messages if any
495 wxLog::FlushActive();
500 // ----------------------------------------------------------------------------
501 // exceptions support
502 // ----------------------------------------------------------------------------
506 bool wxAppBase::OnExceptionInMainLoop()
510 // some compilers are too stupid to know that we never return after throw
511 #if defined(__DMC__) || (defined(_MSC_VER) && _MSC_VER < 1200)
516 #endif // wxUSE_EXCEPTIONS
518 // ----------------------------------------------------------------------------
519 // wxGUIAppTraitsBase
520 // ----------------------------------------------------------------------------
524 wxLog
*wxGUIAppTraitsBase::CreateLogTarget()
529 // we must have something!
530 return new wxLogStderr
;
536 wxMessageOutput
*wxGUIAppTraitsBase::CreateMessageOutput()
538 // The standard way of printing help on command line arguments (app --help)
539 // is (according to common practice):
540 // - console apps: to stderr (on any platform)
541 // - GUI apps: stderr on Unix platforms (!)
542 // message box under Windows and others
544 return new wxMessageOutputStderr
;
546 // wxMessageOutputMessageBox doesn't work under Motif
548 return new wxMessageOutputLog
;
550 return new wxMessageOutputMessageBox
;
552 #endif // __UNIX__/!__UNIX__
557 wxFontMapper
*wxGUIAppTraitsBase::CreateFontMapper()
559 return new wxFontMapper
;
562 #endif // wxUSE_FONTMAP
564 wxRendererNative
*wxGUIAppTraitsBase::CreateRenderer()
566 // use the default native renderer by default
572 bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString
& msg
)
574 #if defined(__WXMSW__) || !wxUSE_MSGDLG
575 // under MSW we prefer to use the base class version using ::MessageBox()
576 // even if wxMessageBox() is available because it has less chances to
577 // double fault our app than our wxMessageBox()
578 return wxAppTraitsBase::ShowAssertDialog(msg
);
579 #else // wxUSE_MSGDLG
580 wxString msgDlg
= msg
;
582 #if wxUSE_STACKWALKER
583 // on Unix stack frame generation may take some time, depending on the
584 // size of the executable mainly... warn the user that we are working
585 wxFprintf(stderr
, wxT("[Debug] Generating a stack trace... please wait"));
588 const wxString stackTrace
= GetAssertStackTrace();
589 if ( !stackTrace
.empty() )
590 msgDlg
<< _T("\n\nCall stack:\n") << stackTrace
;
591 #endif // wxUSE_STACKWALKER
593 // this message is intentionally not translated -- it is for
595 msgDlg
+= wxT("\nDo you want to stop the program?\n")
596 wxT("You can also choose [Cancel] to suppress ")
597 wxT("further warnings.");
599 switch ( wxMessageBox(msgDlg
, wxT("wxWidgets Debug Alert"),
600 wxYES_NO
| wxCANCEL
| wxICON_STOP
) )
610 //case wxNO: nothing to do
614 #endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
617 #endif // __WXDEBUG__
619 bool wxGUIAppTraitsBase::HasStderr()
621 // we consider that under Unix stderr always goes somewhere, even if the
622 // user doesn't always see it under GUI desktops
630 void wxGUIAppTraitsBase::ScheduleForDestroy(wxObject
*object
)
632 if ( !wxPendingDelete
.Member(object
) )
633 wxPendingDelete
.Append(object
);
636 void wxGUIAppTraitsBase::RemoveFromPendingDelete(wxObject
*object
)
638 wxPendingDelete
.DeleteObject(object
);
643 #if defined(__WINDOWS__)
644 #include "wx/msw/gsockmsw.h"
645 #elif defined(__UNIX__) || defined(__DARWIN__) || defined(__OS2__)
646 #include "wx/unix/gsockunx.h"
647 #elif defined(__WXMAC__)
648 #include <MacHeaders.c>
649 #define OTUNIXERRORS 1
650 #include <OpenTransport.h>
651 #include <OpenTransportProviders.h>
652 #include <OpenTptInternet.h>
654 #include "wx/mac/gsockmac.h"
656 #error "Must include correct GSocket header here"
659 GSocketGUIFunctionsTable
* wxGUIAppTraitsBase::GetSocketGUIFunctionsTable()
661 #if defined(__WXMAC__) && !defined(__DARWIN__)
662 // NB: wxMac CFM does not have any GUI-specific functions in gsocket.c and
663 // so it doesn't need this table at all
665 #else // !__WXMAC__ || __DARWIN__
666 static GSocketGUIFunctionsTableConcrete table
;
668 #endif // !__WXMAC__ || __DARWIN__