1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Robert Roebling
6 // Copyright: (c) 1998 Robert Roebling, Julian Smart
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
11 #pragma implementation "app.h"
15 #include "wx/gdicmn.h"
19 #include "wx/memory.h"
21 #include "wx/settings.h"
22 #include "wx/dialog.h"
24 #if wxUSE_WX_RESOURCES
25 #include "wx/resource.h"
28 #include "wx/module.h"
31 #ifdef __WXUNIVERSAL__
32 #include "wx/univ/theme.h"
33 #include "wx/univ/renderer.h"
37 #include "wx/thread.h"
42 #include "wx/gtk/win_gtk.h"
47 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
51 wxApp
*wxTheApp
= (wxApp
*) NULL
;
52 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
54 bool g_mainThreadLocked
= FALSE
;
55 gint g_pendingTag
= 0;
57 static GtkWidget
*gs_RootWindow
= (GtkWidget
*) NULL
;
59 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
65 void wxapp_install_idle_handler();
67 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
78 //-----------------------------------------------------------------------------
80 bool wxApp::Yield(bool onlyIfNeeded
)
83 static bool s_inYield
= FALSE
;
89 wxFAIL_MSG( wxT("wxYield called recursively" ) );
96 if ( !wxThread::IsMain() )
98 // can't call gtk_main_iteration() from other threads like this
101 #endif // wxUSE_THREADS
107 // We need to remove idle callbacks or the loop will
109 gtk_idle_remove( m_idleTag
);
114 // disable log flushing from here because a call to wxYield() shouldn't
115 // normally result in message boxes popping up &c
118 while (gtk_events_pending())
119 gtk_main_iteration();
121 // It's necessary to call ProcessIdle() to update the frames sizes which
122 // might have been changed (it also will update other things set from
123 // OnUpdateUI() which is a nice (and desired) side effect). But we
124 // call ProcessIdle() only once since this is not meant for longish
125 // background jobs (controlled by wxIdleEvent::RequestMore() and the
126 // return value of Processidle().
129 // let the logs be flashed again
137 //-----------------------------------------------------------------------------
139 //-----------------------------------------------------------------------------
144 if (!wxThread::IsMain())
149 wxapp_install_idle_handler();
152 if (!wxThread::IsMain())
157 //-----------------------------------------------------------------------------
159 //-----------------------------------------------------------------------------
161 // the callback functions must be extern "C" to comply with GTK+ declarations
165 static gint
wxapp_pending_callback( gpointer
WXUNUSED(data
) )
167 if (!wxTheApp
) return TRUE
;
169 // When getting called from GDK's time-out handler
170 // we are no longer within GDK's grab on the GUI
171 // thread so we must lock it here ourselves.
174 // Sent idle event to all who request them.
175 wxTheApp
->ProcessPendingEvents();
179 // Flush the logged messages if any.
181 wxLog::FlushActive();
184 // Release lock again
187 // Return FALSE to indicate that no more idle events are
188 // to be sent (single shot instead of continuous stream)
192 static gint
wxapp_idle_callback( gpointer
WXUNUSED(data
) )
198 // don't generate the idle events while the assert modal dialog is shown,
199 // this completely confuses the apps which don't expect to be reentered
200 // from some safely-looking functions
201 if ( wxTheApp
->IsInAssert() )
205 #endif // __WXDEBUG__
207 // When getting called from GDK's time-out handler
208 // we are no longer within GDK's grab on the GUI
209 // thread so we must lock it here ourselves.
212 // Indicate that we are now in idle mode and event handlers
213 // will have to reinstall the idle handler again.
215 wxTheApp
->m_idleTag
= 0;
217 // Send idle event to all who request them as long as
218 // no events have popped up in the event queue.
219 while (wxTheApp
->ProcessIdle() && (gtk_events_pending() == 0))
222 // Release lock again
225 // Return FALSE to indicate that no more idle events are
226 // to be sent (single shot instead of continuous stream).
232 static gint
wxapp_poll_func( GPollFD
*ufds
, guint nfds
, gint timeout
)
238 g_mainThreadLocked
= TRUE
;
240 res
= poll( (struct pollfd
*) ufds
, nfds
, timeout
);
243 g_mainThreadLocked
= FALSE
;
250 #endif // wxUSE_THREADS
254 void wxapp_install_idle_handler()
256 wxASSERT_MSG( wxTheApp
->m_idleTag
== 0, wxT("attempt to install idle handler twice") );
260 if (g_pendingTag
== 0)
261 g_pendingTag
= gtk_idle_add_priority( 900, wxapp_pending_callback
, (gpointer
) NULL
);
263 // This routine gets called by all event handlers
264 // indicating that the idle is over. It may also
265 // get called from other thread for sending events
266 // to the main thread (and processing these in
267 // idle time). Very low priority.
268 wxTheApp
->m_idleTag
= gtk_idle_add_priority( 1000, wxapp_idle_callback
, (gpointer
) NULL
);
271 //-----------------------------------------------------------------------------
272 // Access to the root window global
273 //-----------------------------------------------------------------------------
275 GtkWidget
* wxGetRootWindow()
277 if (gs_RootWindow
== NULL
)
279 gs_RootWindow
= gtk_window_new( GTK_WINDOW_TOPLEVEL
);
280 gtk_widget_realize( gs_RootWindow
);
282 return gs_RootWindow
;
285 //-----------------------------------------------------------------------------
287 //-----------------------------------------------------------------------------
289 IMPLEMENT_DYNAMIC_CLASS(wxApp
,wxEvtHandler
)
291 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
292 EVT_IDLE(wxApp::OnIdle
)
297 m_initialized
= FALSE
;
299 m_isInAssert
= FALSE
;
300 #endif // __WXDEBUG__
303 wxapp_install_idle_handler();
306 g_main_set_poll_func( wxapp_poll_func
);
309 m_colorCube
= (unsigned char*) NULL
;
311 // this is NULL for a "regular" wxApp, but is set (and freed) by a wxGLApp
312 m_glVisualInfo
= (void *) NULL
;
317 if (m_idleTag
) gtk_idle_remove( m_idleTag
);
319 if (m_colorCube
) free(m_colorCube
);
322 bool wxApp::OnInitGui()
324 if ( !wxAppBase::OnInitGui() )
327 GdkVisual
*visual
= gdk_visual_get_system();
329 // if this is a wxGLApp (derived from wxApp), and we've already
330 // chosen a specific visual, then derive the GdkVisual from that
331 if (m_glVisualInfo
!= NULL
)
334 // seems gtk_widget_set_default_visual no longer exists?
335 GdkVisual
* vis
= gtk_widget_get_default_visual();
337 GdkVisual
* vis
= gdkx_visual_get(
338 ((XVisualInfo
*) m_glVisualInfo
) ->visualid
);
339 gtk_widget_set_default_visual( vis
);
342 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
343 gtk_widget_set_default_colormap( colormap
);
348 // On some machines, the default visual is just 256 colours, so
349 // we make sure we get the best. This can sometimes be wasteful.
352 if ((gdk_visual_get_best() != gdk_visual_get_system()) && (m_useBestVisual
))
355 /* seems gtk_widget_set_default_visual no longer exists? */
356 GdkVisual
* vis
= gtk_widget_get_default_visual();
358 GdkVisual
* vis
= gdk_visual_get_best();
359 gtk_widget_set_default_visual( vis
);
362 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
363 gtk_widget_set_default_colormap( colormap
);
368 // Nothing to do for 15, 16, 24, 32 bit displays
369 if (visual
->depth
> 8) return TRUE
;
371 // initialize color cube for 8-bit color reduction dithering
373 GdkColormap
*cmap
= gtk_widget_get_default_colormap();
375 m_colorCube
= (unsigned char*)malloc(32 * 32 * 32);
377 for (int r
= 0; r
< 32; r
++)
379 for (int g
= 0; g
< 32; g
++)
381 for (int b
= 0; b
< 32; b
++)
383 int rr
= (r
<< 3) | (r
>> 2);
384 int gg
= (g
<< 3) | (g
>> 2);
385 int bb
= (b
<< 3) | (b
>> 2);
389 GdkColor
*colors
= cmap
->colors
;
394 for (int i
= 0; i
< cmap
->size
; i
++)
396 int rdiff
= ((rr
<< 8) - colors
[i
].red
);
397 int gdiff
= ((gg
<< 8) - colors
[i
].green
);
398 int bdiff
= ((bb
<< 8) - colors
[i
].blue
);
399 int sum
= ABS (rdiff
) + ABS (gdiff
) + ABS (bdiff
);
402 index
= i
; max
= sum
;
408 // assume 8-bit true or static colors. this really exists
409 GdkVisual
* vis
= gdk_colormap_get_visual( cmap
);
410 index
= (r
>> (5 - vis
->red_prec
)) << vis
->red_shift
;
411 index
|= (g
>> (5 - vis
->green_prec
)) << vis
->green_shift
;
412 index
|= (b
>> (5 - vis
->blue_prec
)) << vis
->blue_shift
;
414 m_colorCube
[ (r
*1024) + (g
*32) + b
] = index
;
422 GdkVisual
*wxApp::GetGdkVisual()
424 GdkVisual
*visual
= NULL
;
427 visual
= gdkx_visual_get( ((XVisualInfo
*) m_glVisualInfo
)->visualid
);
429 visual
= gdk_window_get_visual( wxGetRootWindow()->window
);
436 bool wxApp::ProcessIdle()
439 event
.SetEventObject( this );
440 ProcessEvent( event
);
442 return event
.MoreRequested();
445 void wxApp::OnIdle( wxIdleEvent
&event
)
447 static bool s_inOnIdle
= FALSE
;
449 // Avoid recursion (via ProcessEvent default case)
455 // Resend in the main thread events which have been prepared in other
457 ProcessPendingEvents();
459 // 'Garbage' collection of windows deleted with Close()
460 DeletePendingObjects();
462 // Send OnIdle events to all windows
463 bool needMore
= SendIdleEvents();
466 event
.RequestMore(TRUE
);
471 bool wxApp::SendIdleEvents()
473 bool needMore
= FALSE
;
475 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
478 wxWindow
* win
= node
->GetData();
479 if (SendIdleEvents(win
))
481 node
= node
->GetNext();
487 bool wxApp::SendIdleEvents( wxWindow
* win
)
489 bool needMore
= FALSE
;
492 event
.SetEventObject(win
);
494 win
->GetEventHandler()->ProcessEvent(event
);
496 win
->OnInternalIdle();
498 if (event
.MoreRequested())
501 wxNode
* node
= win
->GetChildren().First();
504 wxWindow
* win
= (wxWindow
*) node
->Data();
505 if (SendIdleEvents(win
))
513 int wxApp::MainLoop()
519 void wxApp::ExitMainLoop()
521 if (gtk_main_level() > 0)
525 bool wxApp::Initialized()
527 return m_initialized
;
530 bool wxApp::Pending()
532 return (gtk_events_pending() > 0);
535 void wxApp::Dispatch()
537 gtk_main_iteration();
540 void wxApp::DeletePendingObjects()
542 wxNode
*node
= wxPendingDelete
.First();
545 wxObject
*obj
= (wxObject
*)node
->Data();
549 if (wxPendingDelete
.Find(obj
))
552 node
= wxPendingDelete
.First();
556 bool wxApp::Initialize()
558 wxBuffer
= new wxChar
[BUFSIZ
+ 512];
560 wxClassInfo::InitializeClasses();
563 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
566 // GL: I'm annoyed ... I don't know where to put this and I don't want to
567 // create a module for that as it's part of the core.
569 wxPendingEvents
= new wxList();
570 wxPendingEventsLocker
= new wxCriticalSection();
573 wxTheColourDatabase
= new wxColourDatabase( wxKEY_STRING
);
574 wxTheColourDatabase
->Initialize();
576 wxInitializeStockLists();
577 wxInitializeStockObjects();
579 #if wxUSE_WX_RESOURCES
580 wxInitializeResourceSystem();
583 wxModule::RegisterModules();
584 if (!wxModule::InitializeModules()) return FALSE
;
589 void wxApp::CleanUp()
591 wxModule::CleanUpModules();
593 #if wxUSE_WX_RESOURCES
594 wxCleanUpResourceSystem();
597 if (wxTheColourDatabase
)
598 delete wxTheColourDatabase
;
600 wxTheColourDatabase
= (wxColourDatabase
*) NULL
;
602 wxDeleteStockObjects();
604 wxDeleteStockLists();
607 wxTheApp
= (wxApp
*) NULL
;
609 // GL: I'm annoyed ... I don't know where to put this and I don't want to
610 // create a module for that as it's part of the core.
612 delete wxPendingEvents
;
613 delete wxPendingEventsLocker
;
618 wxClassInfo::CleanUpClasses();
620 // check for memory leaks
621 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
622 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
624 wxLogDebug(wxT("There were memory leaks.\n"));
625 wxDebugContext::Dump();
626 wxDebugContext::PrintStatistics();
631 // do this as the very last thing because everything else can log messages
632 wxLog::DontCreateOnDemand();
634 wxLog
*oldLog
= wxLog::SetActiveTarget( (wxLog
*) NULL
);
640 //-----------------------------------------------------------------------------
642 //-----------------------------------------------------------------------------
644 // NB: argc and argv may be changed here, pass by reference!
645 int wxEntryStart( int& argc
, char *argv
[] )
648 // GTK 1.2 up to version 1.2.3 has broken threads
649 if ((gtk_major_version
== 1) &&
650 (gtk_minor_version
== 2) &&
651 (gtk_micro_version
< 4))
653 printf( "wxWindows warning: GUI threading disabled due to outdated GTK version\n" );
663 // We should have the wxUSE_WCHAR_T test on the _outside_
665 #if defined(__WXGTK20__)
666 // gtk+ 2.0 supports Unicode through UTF-8 strings
667 wxConvCurrent
= &wxConvUTF8
;
669 if (!wxOKlibc()) wxConvCurrent
= &wxConvLocal
;
672 if (!wxOKlibc()) wxConvCurrent
= (wxMBConv
*) NULL
;
677 gtk_init( &argc
, &argv
);
679 wxSetDetectableAutoRepeat( TRUE
);
681 if (!wxApp::Initialize())
695 if ( !wxTheApp
->OnInitGui() )
704 void wxEntryCleanup()
707 // flush the logged messages if any
708 wxLog
*log
= wxLog::GetActiveTarget();
709 if (log
!= NULL
&& log
->HasPendingMessages())
712 // continuing to use user defined log target is unsafe from now on because
713 // some resources may be already unavailable, so replace it by something
715 wxLog
*oldlog
= wxLog::SetActiveTarget(new wxLogStderr
);
726 int wxEntry( int argc
, char *argv
[] )
728 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
729 // This seems to be necessary since there are 'rogue'
730 // objects present at this point (perhaps global objects?)
731 // Setting a checkpoint will ignore them as far as the
732 // memory checking facility is concerned.
733 // Of course you may argue that memory allocated in globals should be
734 // checked, but this is a reasonable compromise.
735 wxDebugContext::SetCheckpoint();
737 int err
= wxEntryStart(argc
, argv
);
743 wxCHECK_MSG( wxApp::GetInitializerFunction(), -1,
744 wxT("wxWindows error: No initializer - use IMPLEMENT_APP macro.\n") );
746 wxAppInitializerFunction app_ini
= wxApp::GetInitializerFunction();
748 wxObject
*test_app
= app_ini();
750 wxTheApp
= (wxApp
*) test_app
;
753 wxCHECK_MSG( wxTheApp
, -1, wxT("wxWindows error: no application object") );
755 wxTheApp
->argc
= argc
;
757 wxTheApp
->argv
= new wxChar
*[argc
+1];
759 while (mb_argc
< argc
)
761 wxTheApp
->argv
[mb_argc
] = wxStrdup(wxConvLibc
.cMB2WX(argv
[mb_argc
]));
764 wxTheApp
->argv
[mb_argc
] = (wxChar
*)NULL
;
766 wxTheApp
->argv
= argv
;
769 wxString
name(wxFileNameFromPath(argv
[0]));
770 wxStripExtension( name
);
771 wxTheApp
->SetAppName( name
);
774 retValue
= wxEntryInitGui();
776 // Here frames insert themselves automatically into wxTopLevelWindows by
777 // getting created in OnInit().
780 if ( !wxTheApp
->OnInit() )
786 /* delete pending toplevel windows (typically a single
787 dialog) so that, if there isn't any left, we don't
789 wxTheApp
->DeletePendingObjects();
791 wxTheApp
->m_initialized
= wxTopLevelWindows
.GetCount() != 0;
793 if (wxTheApp
->Initialized())
797 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
800 /* Forcibly delete the window. */
801 if (topWindow
->IsKindOf(CLASSINFO(wxFrame
)) ||
802 topWindow
->IsKindOf(CLASSINFO(wxDialog
)) )
804 topWindow
->Close( TRUE
);
805 wxTheApp
->DeletePendingObjects();
810 wxTheApp
->SetTopWindow( (wxWindow
*) NULL
);
814 retValue
= wxTheApp
->OnExit();
823 #ifndef __WXUNIVERSAL__
825 // XPM hack: make the arrays const
826 #define static static const
828 #include "wx/gtk/info.xpm"
829 #include "wx/gtk/error.xpm"
830 #include "wx/gtk/question.xpm"
831 #include "wx/gtk/warning.xpm"
835 wxIcon
wxApp::GetStdIcon(int which
) const
839 case wxICON_INFORMATION
:
840 return wxIcon(info_xpm
);
842 case wxICON_QUESTION
:
843 return wxIcon(question_xpm
);
845 case wxICON_EXCLAMATION
:
846 return wxIcon(warning_xpm
);
849 wxFAIL_MSG(wxT("requested non existent standard icon"));
850 // still fall through
853 return wxIcon(error_xpm
);
857 wxIcon
wxApp::GetStdIcon(int which
) const
859 return wxTheme::Get()->GetRenderer()->GetStdIcon(which
);
861 #endif // !__WXUNIVERSAL__
866 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
*msg
)
870 wxAppBase::OnAssert(file
, line
, msg
);
872 m_isInAssert
= FALSE
;
875 #endif // __WXDEBUG__