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