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