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