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 <vms_jackets.h>
16 #undef ConnectionNumber
20 #include "wx/gdicmn.h"
24 #include "wx/memory.h"
26 #include "wx/settings.h"
27 #include "wx/dialog.h"
28 #include "wx/msgdlg.h"
30 #include "wx/filename.h"
31 #include "wx/module.h"
34 #ifdef __WXUNIVERSAL__
35 #include "wx/univ/theme.h"
36 #include "wx/univ/renderer.h"
40 #include "wx/thread.h"
49 // bug in the OpenBSD headers: at least in 3.1 there is no extern "C"
50 // in neither poll.h nor sys/poll.h which results in link errors later
63 // we implement poll() ourselves using select() which is supposed exist in
65 #include <sys/types.h>
68 #endif // HAVE_POLL/!HAVE_POLL
70 #include "wx/gtk/win_gtk.h"
75 //-----------------------------------------------------------------------------
77 //-----------------------------------------------------------------------------
79 wxApp
*wxTheApp
= (wxApp
*) NULL
;
80 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
82 bool g_mainThreadLocked
= FALSE
;
83 gint g_pendingTag
= 0;
85 static GtkWidget
*gs_RootWindow
= (GtkWidget
*) NULL
;
87 //-----------------------------------------------------------------------------
89 //-----------------------------------------------------------------------------
93 void wxapp_install_idle_handler();
95 //-----------------------------------------------------------------------------
97 //-----------------------------------------------------------------------------
99 // not static because used by textctrl.cpp
102 bool wxIsInsideYield
= FALSE
;
104 bool wxApp::Yield(bool onlyIfNeeded
)
106 if ( wxIsInsideYield
)
110 wxFAIL_MSG( wxT("wxYield called recursively" ) );
117 if ( !wxThread::IsMain() )
119 // can't call gtk_main_iteration() from other threads like this
122 #endif // wxUSE_THREADS
124 wxIsInsideYield
= TRUE
;
128 // We need to remove idle callbacks or the loop will
130 gtk_idle_remove( m_idleTag
);
135 // disable log flushing from here because a call to wxYield() shouldn't
136 // normally result in message boxes popping up &c
139 while (gtk_events_pending())
140 gtk_main_iteration();
142 // It's necessary to call ProcessIdle() to update the frames sizes which
143 // might have been changed (it also will update other things set from
144 // OnUpdateUI() which is a nice (and desired) side effect). But we
145 // call ProcessIdle() only once since this is not meant for longish
146 // background jobs (controlled by wxIdleEvent::RequestMore() and the
147 // return value of Processidle().
150 // let the logs be flashed again
153 wxIsInsideYield
= FALSE
;
158 //-----------------------------------------------------------------------------
160 //-----------------------------------------------------------------------------
162 void wxApp::WakeUpIdle()
165 if (!wxThread::IsMain())
170 wxapp_install_idle_handler();
173 if (!wxThread::IsMain())
178 //-----------------------------------------------------------------------------
180 //-----------------------------------------------------------------------------
182 // the callback functions must be extern "C" to comply with GTK+ declarations
186 static gint
wxapp_pending_callback( gpointer
WXUNUSED(data
) )
188 if (!wxTheApp
) return TRUE
;
190 // When getting called from GDK's time-out handler
191 // we are no longer within GDK's grab on the GUI
192 // thread so we must lock it here ourselves.
195 // Sent idle event to all who request them.
196 wxTheApp
->ProcessPendingEvents();
200 // Flush the logged messages if any.
202 wxLog::FlushActive();
205 // Release lock again
208 // Return FALSE to indicate that no more idle events are
209 // to be sent (single shot instead of continuous stream)
213 static gint
wxapp_idle_callback( gpointer
WXUNUSED(data
) )
219 // don't generate the idle events while the assert modal dialog is shown,
220 // this completely confuses the apps which don't expect to be reentered
221 // from some safely-looking functions
222 if ( wxTheApp
->IsInAssert() )
224 // But repaint the assertion message if necessary
225 if (wxTopLevelWindows
.GetCount() > 0)
227 wxWindow
* win
= (wxWindow
*) wxTopLevelWindows
.GetLast()->GetData();
229 if (win
->IsKindOf(CLASSINFO(wxMessageDialog
)))
231 if (win
->IsKindOf(CLASSINFO(wxGenericMessageDialog
)))
233 win
->OnInternalIdle();
237 #endif // __WXDEBUG__
239 // When getting called from GDK's time-out handler
240 // we are no longer within GDK's grab on the GUI
241 // thread so we must lock it here ourselves.
244 // Indicate that we are now in idle mode and event handlers
245 // will have to reinstall the idle handler again.
247 wxTheApp
->m_idleTag
= 0;
249 // Send idle event to all who request them as long as
250 // no events have popped up in the event queue.
251 while (wxTheApp
->ProcessIdle() && (gtk_events_pending() == 0))
254 // Release lock again
257 // Return FALSE to indicate that no more idle events are
258 // to be sent (single shot instead of continuous stream).
266 #define wxPollFd pollfd
269 typedef GPollFD wxPollFd
;
271 int wxPoll(wxPollFd
*ufds
, unsigned int nfds
, int timeout
)
273 // convert timeout from ms to struct timeval (s/us)
275 tv_timeout
.tv_sec
= timeout
/1000;
276 tv_timeout
.tv_usec
= (timeout%1000
)*1000;
278 // remember the highest fd used here
281 // and fill the sets for select()
290 for ( i
= 0; i
< nfds
; i
++ )
292 wxASSERT_MSG( ufds
[i
].fd
< FD_SETSIZE
, _T("fd out of range") );
294 if ( ufds
[i
].events
& G_IO_IN
)
295 FD_SET(ufds
[i
].fd
, &readfds
);
297 if ( ufds
[i
].events
& G_IO_PRI
)
298 FD_SET(ufds
[i
].fd
, &exceptfds
);
300 if ( ufds
[i
].events
& G_IO_OUT
)
301 FD_SET(ufds
[i
].fd
, &writefds
);
303 if ( ufds
[i
].fd
> fdMax
)
308 int res
= select(fdMax
, &readfds
, &writefds
, &exceptfds
, &tv_timeout
);
310 // translate the results back
311 for ( i
= 0; i
< nfds
; i
++ )
315 if ( FD_ISSET(ufds
[i
].fd
, &readfds
) )
316 ufds
[i
].revents
|= G_IO_IN
;
318 if ( FD_ISSET(ufds
[i
].fd
, &exceptfds
) )
319 ufds
[i
].revents
|= G_IO_PRI
;
321 if ( FD_ISSET(ufds
[i
].fd
, &writefds
) )
322 ufds
[i
].revents
|= G_IO_OUT
;
328 #endif // HAVE_POLL/!HAVE_POLL
330 static gint
wxapp_poll_func( GPollFD
*ufds
, guint nfds
, gint timeout
)
335 g_mainThreadLocked
= TRUE
;
337 // we rely on the fact that glib GPollFD struct is really just pollfd but
338 // I wonder how wise is this in the long term (VZ)
339 gint res
= wxPoll( (wxPollFd
*) ufds
, nfds
, timeout
);
342 g_mainThreadLocked
= FALSE
;
349 #endif // wxUSE_THREADS
353 void wxapp_install_idle_handler()
355 // GD: this assert is raised when using the thread sample (which works)
356 // so the test is probably not so easy. Can widget callbacks be
357 // triggered from child threads and, if so, for which widgets?
358 // wxASSERT_MSG( wxThread::IsMain() || gs_WakeUpIdle, wxT("attempt to install idle handler from widget callback in child thread (should be exclusively from wxWakeUpIdle)") );
360 wxASSERT_MSG( wxTheApp
->m_idleTag
== 0, wxT("attempt to install idle handler twice") );
364 if (g_pendingTag
== 0)
365 g_pendingTag
= gtk_idle_add_priority( 900, wxapp_pending_callback
, (gpointer
) NULL
);
367 // This routine gets called by all event handlers
368 // indicating that the idle is over. It may also
369 // get called from other thread for sending events
370 // to the main thread (and processing these in
371 // idle time). Very low priority.
372 wxTheApp
->m_idleTag
= gtk_idle_add_priority( 1000, wxapp_idle_callback
, (gpointer
) NULL
);
375 //-----------------------------------------------------------------------------
376 // Access to the root window global
377 //-----------------------------------------------------------------------------
379 GtkWidget
* wxGetRootWindow()
381 if (gs_RootWindow
== NULL
)
383 gs_RootWindow
= gtk_window_new( GTK_WINDOW_TOPLEVEL
);
384 gtk_widget_realize( gs_RootWindow
);
386 return gs_RootWindow
;
389 //-----------------------------------------------------------------------------
391 //-----------------------------------------------------------------------------
393 IMPLEMENT_DYNAMIC_CLASS(wxApp
,wxEvtHandler
)
395 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
396 EVT_IDLE(wxApp::OnIdle
)
401 m_initialized
= FALSE
;
403 m_isInAssert
= FALSE
;
404 #endif // __WXDEBUG__
407 wxapp_install_idle_handler();
410 g_main_set_poll_func( wxapp_poll_func
);
413 m_colorCube
= (unsigned char*) NULL
;
415 // this is NULL for a "regular" wxApp, but is set (and freed) by a wxGLApp
416 m_glVisualInfo
= (void *) NULL
;
421 if (m_idleTag
) gtk_idle_remove( m_idleTag
);
423 if (m_colorCube
) free(m_colorCube
);
426 bool wxApp::OnInitGui()
428 if ( !wxAppBase::OnInitGui() )
431 GdkVisual
*visual
= gdk_visual_get_system();
433 // if this is a wxGLApp (derived from wxApp), and we've already
434 // chosen a specific visual, then derive the GdkVisual from that
435 if (m_glVisualInfo
!= NULL
)
438 // seems gtk_widget_set_default_visual no longer exists?
439 GdkVisual
* vis
= gtk_widget_get_default_visual();
441 GdkVisual
* vis
= gdkx_visual_get(
442 ((XVisualInfo
*) m_glVisualInfo
) ->visualid
);
443 gtk_widget_set_default_visual( vis
);
446 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
447 gtk_widget_set_default_colormap( colormap
);
452 // On some machines, the default visual is just 256 colours, so
453 // we make sure we get the best. This can sometimes be wasteful.
456 if ((gdk_visual_get_best() != gdk_visual_get_system()) && (m_useBestVisual
))
459 /* seems gtk_widget_set_default_visual no longer exists? */
460 GdkVisual
* vis
= gtk_widget_get_default_visual();
462 GdkVisual
* vis
= gdk_visual_get_best();
463 gtk_widget_set_default_visual( vis
);
466 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
467 gtk_widget_set_default_colormap( colormap
);
472 // Nothing to do for 15, 16, 24, 32 bit displays
473 if (visual
->depth
> 8) return TRUE
;
475 // initialize color cube for 8-bit color reduction dithering
477 GdkColormap
*cmap
= gtk_widget_get_default_colormap();
479 m_colorCube
= (unsigned char*)malloc(32 * 32 * 32);
481 for (int r
= 0; r
< 32; r
++)
483 for (int g
= 0; g
< 32; g
++)
485 for (int b
= 0; b
< 32; b
++)
487 int rr
= (r
<< 3) | (r
>> 2);
488 int gg
= (g
<< 3) | (g
>> 2);
489 int bb
= (b
<< 3) | (b
>> 2);
493 GdkColor
*colors
= cmap
->colors
;
498 for (int i
= 0; i
< cmap
->size
; i
++)
500 int rdiff
= ((rr
<< 8) - colors
[i
].red
);
501 int gdiff
= ((gg
<< 8) - colors
[i
].green
);
502 int bdiff
= ((bb
<< 8) - colors
[i
].blue
);
503 int sum
= ABS (rdiff
) + ABS (gdiff
) + ABS (bdiff
);
506 index
= i
; max
= sum
;
512 // assume 8-bit true or static colors. this really exists
513 GdkVisual
* vis
= gdk_colormap_get_visual( cmap
);
514 index
= (r
>> (5 - vis
->red_prec
)) << vis
->red_shift
;
515 index
|= (g
>> (5 - vis
->green_prec
)) << vis
->green_shift
;
516 index
|= (b
>> (5 - vis
->blue_prec
)) << vis
->blue_shift
;
518 m_colorCube
[ (r
*1024) + (g
*32) + b
] = index
;
526 GdkVisual
*wxApp::GetGdkVisual()
528 GdkVisual
*visual
= NULL
;
531 visual
= gdkx_visual_get( ((XVisualInfo
*) m_glVisualInfo
)->visualid
);
533 visual
= gdk_window_get_visual( wxGetRootWindow()->window
);
540 bool wxApp::ProcessIdle()
542 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
543 node
= wxTopLevelWindows
.GetFirst();
546 wxWindow
* win
= node
->GetData();
547 CallInternalIdle( win
);
549 node
= node
->GetNext();
553 event
.SetEventObject( this );
554 ProcessEvent( event
);
556 return event
.MoreRequested();
559 void wxApp::OnIdle( wxIdleEvent
&event
)
561 static bool s_inOnIdle
= FALSE
;
563 // Avoid recursion (via ProcessEvent default case)
569 // Resend in the main thread events which have been prepared in other
571 ProcessPendingEvents();
573 // 'Garbage' collection of windows deleted with Close()
574 DeletePendingObjects();
576 // Send OnIdle events to all windows
577 bool needMore
= SendIdleEvents();
580 event
.RequestMore(TRUE
);
585 bool wxApp::SendIdleEvents()
587 bool needMore
= FALSE
;
589 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
592 wxWindow
* win
= node
->GetData();
593 if (SendIdleEvents(win
))
596 node
= node
->GetNext();
602 bool wxApp::CallInternalIdle( wxWindow
* win
)
604 win
->OnInternalIdle();
606 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
609 wxWindow
*win
= node
->GetData();
611 CallInternalIdle( win
);
612 node
= node
->GetNext();
618 bool wxApp::SendIdleEvents( wxWindow
* win
)
620 bool needMore
= FALSE
;
623 event
.SetEventObject(win
);
625 win
->GetEventHandler()->ProcessEvent(event
);
627 if (event
.MoreRequested())
630 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
633 wxWindow
*win
= node
->GetData();
635 if (SendIdleEvents(win
))
637 node
= node
->GetNext();
643 int wxApp::MainLoop()
651 // VZ: no idea why is it different from ExitMainLoop() but this is what
652 // wxExit() used to do
656 void wxApp::ExitMainLoop()
658 if (gtk_main_level() > 0)
662 bool wxApp::Initialized()
664 return m_initialized
;
667 bool wxApp::Pending()
669 return (gtk_events_pending() > 0);
672 void wxApp::Dispatch()
674 gtk_main_iteration();
677 void wxApp::DeletePendingObjects()
679 wxNode
*node
= wxPendingDelete
.GetFirst();
682 wxObject
*obj
= (wxObject
*)node
->GetData();
686 if (wxPendingDelete
.Find(obj
))
689 node
= wxPendingDelete
.GetFirst();
693 bool wxApp::Initialize()
695 wxClassInfo::InitializeClasses();
697 // GL: I'm annoyed ... I don't know where to put this and I don't want to
698 // create a module for that as it's part of the core.
700 wxPendingEvents
= new wxList();
701 wxPendingEventsLocker
= new wxCriticalSection();
704 wxTheColourDatabase
= new wxColourDatabase( wxKEY_STRING
);
705 wxTheColourDatabase
->Initialize();
707 wxInitializeStockLists();
708 wxInitializeStockObjects();
710 wxModule::RegisterModules();
711 if (!wxModule::InitializeModules())
715 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
721 void wxApp::CleanUp()
723 wxModule::CleanUpModules();
725 delete wxTheColourDatabase
;
726 wxTheColourDatabase
= (wxColourDatabase
*) NULL
;
728 wxDeleteStockObjects();
730 wxDeleteStockLists();
733 wxTheApp
= (wxApp
*) NULL
;
735 wxClassInfo::CleanUpClasses();
738 delete wxPendingEvents
;
739 wxPendingEvents
= NULL
;
740 delete wxPendingEventsLocker
;
741 wxPendingEventsLocker
= NULL
;
744 // check for memory leaks
745 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
746 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
748 wxLogDebug(wxT("There were memory leaks.\n"));
749 wxDebugContext::Dump();
750 wxDebugContext::PrintStatistics();
755 // do this as the very last thing because everything else can log messages
756 wxLog::DontCreateOnDemand();
758 wxLog
*oldLog
= wxLog::SetActiveTarget( (wxLog
*) NULL
);
764 //-----------------------------------------------------------------------------
766 //-----------------------------------------------------------------------------
768 // NB: argc and argv may be changed here, pass by reference!
769 int wxEntryStart( int& argc
, char *argv
[] )
772 // GTK 1.2 up to version 1.2.3 has broken threads
773 if ((gtk_major_version
== 1) &&
774 (gtk_minor_version
== 2) &&
775 (gtk_micro_version
< 4))
777 printf( "wxWindows warning: GUI threading disabled due to outdated GTK version\n" );
787 // We should have the wxUSE_WCHAR_T test on the _outside_
789 #if defined(__WXGTK20__)
790 // gtk+ 2.0 supports Unicode through UTF-8 strings
791 wxConvCurrent
= &wxConvUTF8
;
793 if (!wxOKlibc()) wxConvCurrent
= &wxConvLocal
;
796 if (!wxOKlibc()) wxConvCurrent
= (wxMBConv
*) NULL
;
799 gtk_init( &argc
, &argv
);
801 /* we can not enter threads before gtk_init is done */
804 wxSetDetectableAutoRepeat( TRUE
);
806 if (!wxApp::Initialize())
820 if ( !wxTheApp
->OnInitGui() )
829 void wxEntryCleanup()
832 // flush the logged messages if any
833 wxLog
*log
= wxLog::GetActiveTarget();
834 if (log
!= NULL
&& log
->HasPendingMessages())
837 // continuing to use user defined log target is unsafe from now on because
838 // some resources may be already unavailable, so replace it by something
840 wxLog
*oldlog
= wxLog::SetActiveTarget(new wxLogStderr
);
851 int wxEntry( int argc
, char *argv
[] )
853 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
854 // This seems to be necessary since there are 'rogue'
855 // objects present at this point (perhaps global objects?)
856 // Setting a checkpoint will ignore them as far as the
857 // memory checking facility is concerned.
858 // Of course you may argue that memory allocated in globals should be
859 // checked, but this is a reasonable compromise.
860 wxDebugContext::SetCheckpoint();
862 int err
= wxEntryStart(argc
, argv
);
868 wxCHECK_MSG( wxApp::GetInitializerFunction(), -1,
869 wxT("wxWindows error: No initializer - use IMPLEMENT_APP macro.\n") );
871 wxAppInitializerFunction app_ini
= wxApp::GetInitializerFunction();
873 wxObject
*test_app
= app_ini();
875 wxTheApp
= (wxApp
*) test_app
;
878 wxCHECK_MSG( wxTheApp
, -1, wxT("wxWindows error: no application object") );
880 wxTheApp
->argc
= argc
;
882 wxTheApp
->argv
= new wxChar
*[argc
+1];
884 while (mb_argc
< argc
)
886 wxTheApp
->argv
[mb_argc
] = wxStrdup(wxConvLibc
.cMB2WX(argv
[mb_argc
]));
889 wxTheApp
->argv
[mb_argc
] = (wxChar
*)NULL
;
891 wxTheApp
->argv
= argv
;
894 if (wxTheApp
->argc
> 0)
896 wxFileName
fname( wxTheApp
->argv
[0] );
897 wxTheApp
->SetAppName( fname
.GetName() );
901 retValue
= wxEntryInitGui();
903 // Here frames insert themselves automatically into wxTopLevelWindows by
904 // getting created in OnInit().
907 if ( !wxTheApp
->OnInit() )
913 // Delete pending toplevel windows
914 wxTheApp
->DeletePendingObjects();
916 // When is the app not initialized ?
917 wxTheApp
->m_initialized
= TRUE
;
919 if (wxTheApp
->Initialized())
923 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
925 // Delete all pending windows if any
926 wxTheApp
->DeletePendingObjects();
930 wxTheApp
->SetTopWindow( (wxWindow
*) NULL
);
932 retValue
= wxTheApp
->OnExit();
943 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
* cond
, const wxChar
*msg
)
947 wxAppBase::OnAssert(file
, line
, cond
, msg
);
949 m_isInAssert
= FALSE
;
952 #endif // __WXDEBUG__