wxMac linking fix
[wxWidgets.git] / src / common / appcmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/appcmn.cpp
3 // Purpose: wxAppConsole and wxAppBase methods common to all platforms
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 18.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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #if defined(__BORLANDC__)
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/app.h"
29 #include "wx/bitmap.h"
30 #include "wx/intl.h"
31 #include "wx/list.h"
32 #include "wx/log.h"
33 #include "wx/msgdlg.h"
34 #include "wx/bitmap.h"
35 #include "wx/confbase.h"
36 #endif
37
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/utils.h"
44 #include "wx/ptr_scpd.h"
45 #include "wx/evtloop.h"
46
47 #if defined(__WXMSW__)
48 #include "wx/msw/private.h" // includes windows.h for LOGFONT
49 #endif
50
51 #if wxUSE_FONTMAP
52 #include "wx/fontmap.h"
53 #endif // wxUSE_FONTMAP
54
55 // DLL options compatibility check:
56 #include "wx/build.h"
57 WX_CHECK_BUILD_OPTIONS("wxCore")
58
59
60 // ----------------------------------------------------------------------------
61 // wxEventLoopPtr
62 // ----------------------------------------------------------------------------
63
64 // this defines wxEventLoopPtr
65 #if wxUSE_EVTLOOP_IN_APP
66 wxDEFINE_TIED_SCOPED_PTR_TYPE(wxEventLoop)
67 #endif
68
69 // ============================================================================
70 // wxAppBase implementation
71 // ============================================================================
72
73 // ----------------------------------------------------------------------------
74 // initialization
75 // ----------------------------------------------------------------------------
76
77 wxAppBase::wxAppBase()
78 {
79 m_topWindow = (wxWindow *)NULL;
80 m_useBestVisual = false;
81 m_isActive = true;
82
83 #if wxUSE_EVTLOOP_IN_APP
84 m_mainLoop = NULL;
85 #endif // wxUSE_EVTLOOP_IN_APP
86
87 // We don't want to exit the app if the user code shows a dialog from its
88 // OnInit() -- but this is what would happen if we set m_exitOnFrameDelete
89 // to Yes initially as this dialog would be the last top level window.
90 // OTOH, if we set it to No initially we'll have to overwrite it with Yes
91 // when we enter our OnRun() because we do want the default behaviour from
92 // then on. But this would be a problem if the user code calls
93 // SetExitOnFrameDelete(false) from OnInit().
94 //
95 // So we use the special "Later" value which is such that
96 // GetExitOnFrameDelete() returns false for it but which we know we can
97 // safely (i.e. without losing the effect of the users SetExitOnFrameDelete
98 // call) overwrite in OnRun()
99 m_exitOnFrameDelete = Later;
100 }
101
102 bool wxAppBase::Initialize(int& argcOrig, wxChar **argvOrig)
103 {
104 if ( !wxAppConsole::Initialize(argcOrig, argvOrig) )
105 return false;
106
107 #if wxUSE_THREADS
108 wxPendingEventsLocker = new wxCriticalSection;
109 #endif
110
111 wxInitializeStockLists();
112 wxInitializeStockObjects();
113
114 wxBitmap::InitStandardHandlers();
115
116 return true;
117 }
118
119 // ----------------------------------------------------------------------------
120 // cleanup
121 // ----------------------------------------------------------------------------
122
123 wxAppBase::~wxAppBase()
124 {
125 // this destructor is required for Darwin
126 }
127
128 void wxAppBase::CleanUp()
129 {
130 // clean up all the pending objects
131 DeletePendingObjects();
132
133 // and any remaining TLWs (they remove themselves from wxTopLevelWindows
134 // when destroyed, so iterate until none are left)
135 while ( !wxTopLevelWindows.empty() )
136 {
137 // do not use Destroy() here as it only puts the TLW in pending list
138 // but we want to delete them now
139 delete wxTopLevelWindows.GetFirst()->GetData();
140 }
141
142 // undo everything we did in Initialize() above
143 wxBitmap::CleanUpHandlers();
144
145 wxDeleteStockObjects();
146
147 wxDeleteStockLists();
148
149 delete wxTheColourDatabase;
150 wxTheColourDatabase = NULL;
151
152 delete wxPendingEvents;
153 wxPendingEvents = NULL;
154
155 #if wxUSE_THREADS
156 delete wxPendingEventsLocker;
157 wxPendingEventsLocker = NULL;
158
159 #if wxUSE_VALIDATORS
160 // If we don't do the following, we get an apparent memory leak.
161 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
162 #endif // wxUSE_VALIDATORS
163 #endif // wxUSE_THREADS
164 }
165
166 #if wxUSE_CMDLINE_PARSER
167
168 // ----------------------------------------------------------------------------
169 // GUI-specific command line options handling
170 // ----------------------------------------------------------------------------
171
172 #define OPTION_THEME _T("theme")
173 #define OPTION_MODE _T("mode")
174
175 void wxAppBase::OnInitCmdLine(wxCmdLineParser& parser)
176 {
177 // first add the standard non GUI options
178 wxAppConsole::OnInitCmdLine(parser);
179
180 // the standard command line options
181 static const wxCmdLineEntryDesc cmdLineGUIDesc[] =
182 {
183 #ifdef __WXUNIVERSAL__
184 {
185 wxCMD_LINE_OPTION,
186 wxEmptyString,
187 OPTION_THEME,
188 gettext_noop("specify the theme to use"),
189 wxCMD_LINE_VAL_STRING,
190 0x0
191 },
192 #endif // __WXUNIVERSAL__
193
194 #if defined(__WXMGL__)
195 // VS: this is not specific to wxMGL, all fullscreen (framebuffer) ports
196 // should provide this option. That's why it is in common/appcmn.cpp
197 // and not mgl/app.cpp
198 {
199 wxCMD_LINE_OPTION,
200 wxEmptyString,
201 OPTION_MODE,
202 gettext_noop("specify display mode to use (e.g. 640x480-16)"),
203 wxCMD_LINE_VAL_STRING,
204 0x0
205 },
206 #endif // __WXMGL__
207
208 // terminator
209 {
210 wxCMD_LINE_NONE,
211 wxEmptyString,
212 wxEmptyString,
213 wxEmptyString,
214 wxCMD_LINE_VAL_NONE,
215 0x0
216 }
217 };
218
219 parser.SetDesc(cmdLineGUIDesc);
220 }
221
222 bool wxAppBase::OnCmdLineParsed(wxCmdLineParser& parser)
223 {
224 #ifdef __WXUNIVERSAL__
225 wxString themeName;
226 if ( parser.Found(OPTION_THEME, &themeName) )
227 {
228 wxTheme *theme = wxTheme::Create(themeName);
229 if ( !theme )
230 {
231 wxLogError(_("Unsupported theme '%s'."), themeName.c_str());
232 return false;
233 }
234
235 // Delete the defaultly created theme and set the new theme.
236 delete wxTheme::Get();
237 wxTheme::Set(theme);
238 }
239 #endif // __WXUNIVERSAL__
240
241 #if defined(__WXMGL__)
242 wxString modeDesc;
243 if ( parser.Found(OPTION_MODE, &modeDesc) )
244 {
245 unsigned w, h, bpp;
246 if ( wxSscanf(modeDesc.c_str(), _T("%ux%u-%u"), &w, &h, &bpp) != 3 )
247 {
248 wxLogError(_("Invalid display mode specification '%s'."), modeDesc.c_str());
249 return false;
250 }
251
252 if ( !SetDisplayMode(wxVideoMode(w, h, bpp)) )
253 return false;
254 }
255 #endif // __WXMGL__
256
257 return wxAppConsole::OnCmdLineParsed(parser);
258 }
259
260 #endif // wxUSE_CMDLINE_PARSER
261
262 // ----------------------------------------------------------------------------
263 // main event loop implementation
264 // ----------------------------------------------------------------------------
265
266 int wxAppBase::MainLoop()
267 {
268 #if wxUSE_EVTLOOP_IN_APP
269 wxEventLoopTiedPtr mainLoop(&m_mainLoop, new wxEventLoop);
270
271 return m_mainLoop->Run();
272 #else // !wxUSE_EVTLOOP_IN_APP
273 return 0;
274 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
275 }
276
277 void wxAppBase::ExitMainLoop()
278 {
279 #if wxUSE_EVTLOOP_IN_APP
280 // we should exit from the main event loop, not just any currently active
281 // (e.g. modal dialog) event loop
282 if ( m_mainLoop && m_mainLoop->IsRunning() )
283 {
284 m_mainLoop->Exit(0);
285 }
286 #endif // wxUSE_EVTLOOP_IN_APP
287 }
288
289 bool wxAppBase::Pending()
290 {
291 #if wxUSE_EVTLOOP_IN_APP
292 // use the currently active message loop here, not m_mainLoop, because if
293 // we're showing a modal dialog (with its own event loop) currently the
294 // main event loop is not running anyhow
295 wxEventLoop * const loop = wxEventLoop::GetActive();
296
297 return loop && loop->Pending();
298 #else // wxUSE_EVTLOOP_IN_APP
299 return false;
300 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
301 }
302
303 bool wxAppBase::Dispatch()
304 {
305 #if wxUSE_EVTLOOP_IN_APP
306 // see comment in Pending()
307 wxEventLoop * const loop = wxEventLoop::GetActive();
308
309 return loop && loop->Dispatch();
310 #else // wxUSE_EVTLOOP_IN_APP
311 return true;
312 #endif // wxUSE_EVTLOOP_IN_APP/!wxUSE_EVTLOOP_IN_APP
313 }
314
315 // ----------------------------------------------------------------------------
316 // OnXXX() hooks
317 // ----------------------------------------------------------------------------
318
319 bool wxAppBase::OnInitGui()
320 {
321 #ifdef __WXUNIVERSAL__
322 if ( !wxTheme::Get() && !wxTheme::CreateDefault() )
323 return false;
324 #endif // __WXUNIVERSAL__
325
326 return true;
327 }
328
329 int wxAppBase::OnRun()
330 {
331 // see the comment in ctor: if the initial value hasn't been changed, use
332 // the default Yes from now on
333 if ( m_exitOnFrameDelete == Later )
334 {
335 m_exitOnFrameDelete = Yes;
336 }
337 //else: it has been changed, assume the user knows what he is doing
338
339 return MainLoop();
340 }
341
342 int wxAppBase::OnExit()
343 {
344 #ifdef __WXUNIVERSAL__
345 delete wxTheme::Set(NULL);
346 #endif // __WXUNIVERSAL__
347
348 return wxAppConsole::OnExit();
349 }
350
351 void wxAppBase::Exit()
352 {
353 ExitMainLoop();
354 }
355
356 wxAppTraits *wxAppBase::CreateTraits()
357 {
358 return new wxGUIAppTraits;
359 }
360
361 // ----------------------------------------------------------------------------
362 // misc
363 // ----------------------------------------------------------------------------
364
365 void wxAppBase::SetActive(bool active, wxWindow * WXUNUSED(lastFocus))
366 {
367 if ( active == m_isActive )
368 return;
369
370 m_isActive = active;
371
372 wxActivateEvent event(wxEVT_ACTIVATE_APP, active);
373 event.SetEventObject(this);
374
375 (void)ProcessEvent(event);
376 }
377
378 void wxAppBase::DeletePendingObjects()
379 {
380 wxList::compatibility_iterator node = wxPendingDelete.GetFirst();
381 while (node)
382 {
383 wxObject *obj = node->GetData();
384
385 delete obj;
386
387 if (wxPendingDelete.Member(obj))
388 wxPendingDelete.Erase(node);
389
390 // Deleting one object may have deleted other pending
391 // objects, so start from beginning of list again.
392 node = wxPendingDelete.GetFirst();
393 }
394 }
395
396 // Returns true if more time is needed.
397 bool wxAppBase::ProcessIdle()
398 {
399 wxIdleEvent event;
400 bool needMore = false;
401 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
402 while (node)
403 {
404 wxWindow* win = node->GetData();
405 if (SendIdleEvents(win, event))
406 needMore = true;
407 node = node->GetNext();
408 }
409
410 event.SetEventObject(this);
411 (void) ProcessEvent(event);
412 if (event.MoreRequested())
413 needMore = true;
414
415 wxUpdateUIEvent::ResetUpdateTime();
416
417 return needMore;
418 }
419
420 // Send idle event to window and all subwindows
421 bool wxAppBase::SendIdleEvents(wxWindow* win, wxIdleEvent& event)
422 {
423 bool needMore = false;
424
425 win->OnInternalIdle();
426
427 if (wxIdleEvent::CanSend(win))
428 {
429 event.SetEventObject(win);
430 win->GetEventHandler()->ProcessEvent(event);
431
432 if (event.MoreRequested())
433 needMore = true;
434 }
435 wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst();
436 while ( node )
437 {
438 wxWindow *child = node->GetData();
439 if (SendIdleEvents(child, event))
440 needMore = true;
441
442 node = node->GetNext();
443 }
444
445 return needMore;
446 }
447
448 void wxAppBase::OnIdle(wxIdleEvent& WXUNUSED(event))
449 {
450 // If there are pending events, we must process them: pending events
451 // are either events to the threads other than main or events posted
452 // with wxPostEvent() functions
453 // GRG: I have moved this here so that all pending events are processed
454 // before starting to delete any objects. This behaves better (in
455 // particular, wrt wxPostEvent) and is coherent with wxGTK's current
456 // behaviour. Changed Feb/2000 before 2.1.14
457 ProcessPendingEvents();
458
459 // 'Garbage' collection of windows deleted with Close().
460 DeletePendingObjects();
461
462 #if wxUSE_LOG
463 // flush the logged messages if any
464 wxLog::FlushActive();
465 #endif // wxUSE_LOG
466
467 }
468
469 // ----------------------------------------------------------------------------
470 // exception handling
471 // ----------------------------------------------------------------------------
472
473 #if wxUSE_EXCEPTIONS
474
475 void wxAppBase::HandleEvent(wxEvtHandler *handler,
476 wxEventFunction func,
477 wxEvent& event) const
478 {
479 // by default, call wxApp::OnExceptionInMainLoop if an exception occurs
480 try
481 {
482 handler->DoHandleEvent(func, event);
483 }
484 catch ( ... )
485 {
486 if ( !wxConstCast(this, wxAppBase)->OnExceptionInMainLoop() )
487 {
488 #if wxUSE_EVTLOOP_IN_APP
489 wxEventLoop *loop = wxEventLoop::GetActive();
490 if ( loop )
491 loop->Exit(-1);
492 #else
493 wxConstCast(this, wxAppBase)->ExitMainLoop();
494 #endif
495 }
496 //else: continue running the event loop
497 }
498 }
499
500 #endif // wxUSE_EXCEPTIONS
501
502 // ----------------------------------------------------------------------------
503 // wxGUIAppTraitsBase
504 // ----------------------------------------------------------------------------
505
506 #if wxUSE_LOG
507
508 wxLog *wxGUIAppTraitsBase::CreateLogTarget()
509 {
510 #if wxUSE_LOGGUI
511 return new wxLogGui;
512 #else
513 // we must have something!
514 return new wxLogStderr;
515 #endif
516 }
517
518 #endif // wxUSE_LOG
519
520 wxMessageOutput *wxGUIAppTraitsBase::CreateMessageOutput()
521 {
522 // The standard way of printing help on command line arguments (app --help)
523 // is (according to common practice):
524 // - console apps: to stderr (on any platform)
525 // - GUI apps: stderr on Unix platforms (!)
526 // message box under Windows and others
527 #ifdef __UNIX__
528 return new wxMessageOutputStderr;
529 #else // !__UNIX__
530 // wxMessageOutputMessageBox doesn't work under Motif
531 #ifdef __WXMOTIF__
532 return new wxMessageOutputLog;
533 #else
534 return new wxMessageOutputMessageBox;
535 #endif
536 #endif // __UNIX__/!__UNIX__
537 }
538
539 #if wxUSE_FONTMAP
540
541 wxFontMapper *wxGUIAppTraitsBase::CreateFontMapper()
542 {
543 return new wxFontMapper;
544 }
545
546 #endif // wxUSE_FONTMAP
547
548 wxRendererNative *wxGUIAppTraitsBase::CreateRenderer()
549 {
550 // use the default native renderer by default
551 return NULL;
552 }
553
554 #ifdef __WXDEBUG__
555
556 bool wxGUIAppTraitsBase::ShowAssertDialog(const wxString& msg)
557 {
558 // under MSW we prefer to use the base class version using ::MessageBox()
559 // even if wxMessageBox() is available because it has less chances to
560 // double fault our app than our wxMessageBox()
561 #if defined(__WXMSW__) || !wxUSE_MSGDLG
562 return wxAppTraitsBase::ShowAssertDialog(msg);
563 #else // wxUSE_MSGDLG
564 // this message is intentionally not translated -- it is for
565 // developpers only
566 wxString msgDlg(msg);
567 msgDlg += wxT("\nDo you want to stop the program?\n")
568 wxT("You can also choose [Cancel] to suppress ")
569 wxT("further warnings.");
570
571 switch ( wxMessageBox(msgDlg, wxT("wxWidgets Debug Alert"),
572 wxYES_NO | wxCANCEL | wxICON_STOP ) )
573 {
574 case wxYES:
575 wxTrap();
576 break;
577
578 case wxCANCEL:
579 // no more asserts
580 return true;
581
582 //case wxNO: nothing to do
583 }
584
585 return false;
586 #endif // !wxUSE_MSGDLG/wxUSE_MSGDLG
587 }
588
589 #endif // __WXDEBUG__
590
591 bool wxGUIAppTraitsBase::HasStderr()
592 {
593 // we consider that under Unix stderr always goes somewhere, even if the
594 // user doesn't always see it under GUI desktops
595 #ifdef __UNIX__
596 return true;
597 #else
598 return false;
599 #endif
600 }
601
602 void wxGUIAppTraitsBase::ScheduleForDestroy(wxObject *object)
603 {
604 if ( !wxPendingDelete.Member(object) )
605 wxPendingDelete.Append(object);
606 }
607
608 void wxGUIAppTraitsBase::RemoveFromPendingDelete(wxObject *object)
609 {
610 wxPendingDelete.DeleteObject(object);
611 }
612
613 #if wxUSE_SOCKETS
614
615 #if defined(__WINDOWS__)
616 #include "wx/msw/gsockmsw.h"
617 #elif defined(__UNIX__) || defined(__DARWIN__) || defined(__OS2__)
618 #include "wx/unix/gsockunx.h"
619 #elif defined(__WXMAC__)
620 #include <MacHeaders.c>
621 #define OTUNIXERRORS 1
622 #include <OpenTransport.h>
623 #include <OpenTransportProviders.h>
624 #include <OpenTptInternet.h>
625
626 #include "wx/mac/gsockmac.h"
627 #else
628 #error "Must include correct GSocket header here"
629 #endif
630
631 GSocketGUIFunctionsTable* wxGUIAppTraitsBase::GetSocketGUIFunctionsTable()
632 {
633 #if defined(__WXMAC__) && !defined(__DARWIN__)
634 // NB: wxMac CFM does not have any GUI-specific functions in gsocket.c and
635 // so it doesn't need this table at all
636 return NULL;
637 #else // !__WXMAC__ || __DARWIN__
638 static GSocketGUIFunctionsTableConcrete table;
639 return &table;
640 #endif // !__WXMAC__ || __DARWIN__
641 }
642
643 #endif