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"
32 #if wxUSE_WX_RESOURCES
33 #include "wx/resource.h"
36 #include "wx/module.h"
39 #ifdef __WXUNIVERSAL__
40 #include "wx/univ/theme.h"
41 #include "wx/univ/renderer.h"
45 #include "wx/thread.h"
54 // bug in the OpenBSD headers: at least in 3.1 there is no extern "C"
55 // in neither poll.h nor sys/poll.h which results in link errors later
68 // we implement poll() ourselves using select() which is supposed exist in
70 #include <sys/types.h>
73 #endif // HAVE_POLL/!HAVE_POLL
75 #include "wx/gtk/win_gtk.h"
80 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
84 wxApp
*wxTheApp
= (wxApp
*) NULL
;
85 wxAppInitializerFunction
wxAppBase::m_appInitFn
= (wxAppInitializerFunction
) NULL
;
87 bool g_mainThreadLocked
= FALSE
;
88 gint g_pendingTag
= 0;
90 static GtkWidget
*gs_RootWindow
= (GtkWidget
*) NULL
;
92 //-----------------------------------------------------------------------------
94 //-----------------------------------------------------------------------------
98 void wxapp_install_idle_handler();
100 //-----------------------------------------------------------------------------
102 //-----------------------------------------------------------------------------
109 //-----------------------------------------------------------------------------
111 //-----------------------------------------------------------------------------
113 // not static because used by textctrl.cpp
116 bool wxIsInsideYield
= FALSE
;
118 bool wxApp::Yield(bool onlyIfNeeded
)
120 if ( wxIsInsideYield
)
124 wxFAIL_MSG( wxT("wxYield called recursively" ) );
131 if ( !wxThread::IsMain() )
133 // can't call gtk_main_iteration() from other threads like this
136 #endif // wxUSE_THREADS
138 wxIsInsideYield
= TRUE
;
142 // We need to remove idle callbacks or the loop will
144 gtk_idle_remove( m_idleTag
);
149 // disable log flushing from here because a call to wxYield() shouldn't
150 // normally result in message boxes popping up &c
153 while (gtk_events_pending())
154 gtk_main_iteration();
156 // It's necessary to call ProcessIdle() to update the frames sizes which
157 // might have been changed (it also will update other things set from
158 // OnUpdateUI() which is a nice (and desired) side effect). But we
159 // call ProcessIdle() only once since this is not meant for longish
160 // background jobs (controlled by wxIdleEvent::RequestMore() and the
161 // return value of Processidle().
164 // let the logs be flashed again
167 wxIsInsideYield
= FALSE
;
172 //-----------------------------------------------------------------------------
174 //-----------------------------------------------------------------------------
179 if (!wxThread::IsMain())
184 wxapp_install_idle_handler();
187 if (!wxThread::IsMain())
192 //-----------------------------------------------------------------------------
194 //-----------------------------------------------------------------------------
196 // the callback functions must be extern "C" to comply with GTK+ declarations
200 static gint
wxapp_pending_callback( gpointer
WXUNUSED(data
) )
202 if (!wxTheApp
) return TRUE
;
204 // When getting called from GDK's time-out handler
205 // we are no longer within GDK's grab on the GUI
206 // thread so we must lock it here ourselves.
209 // Sent idle event to all who request them.
210 wxTheApp
->ProcessPendingEvents();
214 // Flush the logged messages if any.
216 wxLog::FlushActive();
219 // Release lock again
222 // Return FALSE to indicate that no more idle events are
223 // to be sent (single shot instead of continuous stream)
227 static gint
wxapp_idle_callback( gpointer
WXUNUSED(data
) )
233 // don't generate the idle events while the assert modal dialog is shown,
234 // this completely confuses the apps which don't expect to be reentered
235 // from some safely-looking functions
236 if ( wxTheApp
->IsInAssert() )
238 // But repaint the assertion message if necessary
239 if (wxTopLevelWindows
.GetCount() > 0)
241 wxWindow
* win
= (wxWindow
*) wxTopLevelWindows
.GetLast()->GetData();
242 if (win
->IsKindOf(CLASSINFO(wxGenericMessageDialog
)))
243 win
->OnInternalIdle();
247 #endif // __WXDEBUG__
249 // When getting called from GDK's time-out handler
250 // we are no longer within GDK's grab on the GUI
251 // thread so we must lock it here ourselves.
254 // Indicate that we are now in idle mode and event handlers
255 // will have to reinstall the idle handler again.
257 wxTheApp
->m_idleTag
= 0;
259 // Send idle event to all who request them as long as
260 // no events have popped up in the event queue.
261 while (wxTheApp
->ProcessIdle() && (gtk_events_pending() == 0))
264 // Release lock again
267 // Return FALSE to indicate that no more idle events are
268 // to be sent (single shot instead of continuous stream).
276 #define wxPollFd pollfd
279 typedef GPollFD wxPollFd
;
281 int wxPoll(wxPollFd
*ufds
, unsigned int nfds
, int timeout
)
283 // convert timeout from ms to struct timeval (s/us)
285 tv_timeout
.tv_sec
= timeout
/1000;
286 tv_timeout
.tv_usec
= (timeout%1000
)*1000;
288 // remember the highest fd used here
291 // and fill the sets for select()
300 for ( i
= 0; i
< nfds
; i
++ )
302 wxASSERT_MSG( ufds
[i
].fd
< FD_SETSIZE
, _T("fd out of range") );
304 if ( ufds
[i
].events
& G_IO_IN
)
305 FD_SET(ufds
[i
].fd
, &readfds
);
307 if ( ufds
[i
].events
& G_IO_PRI
)
308 FD_SET(ufds
[i
].fd
, &exceptfds
);
310 if ( ufds
[i
].events
& G_IO_OUT
)
311 FD_SET(ufds
[i
].fd
, &writefds
);
313 if ( ufds
[i
].fd
> fdMax
)
318 int res
= select(fdMax
, &readfds
, &writefds
, &exceptfds
, &tv_timeout
);
320 // translate the results back
321 for ( i
= 0; i
< nfds
; i
++ )
325 if ( FD_ISSET(ufds
[i
].fd
, &readfds
) )
326 ufds
[i
].revents
|= G_IO_IN
;
328 if ( FD_ISSET(ufds
[i
].fd
, &exceptfds
) )
329 ufds
[i
].revents
|= G_IO_PRI
;
331 if ( FD_ISSET(ufds
[i
].fd
, &writefds
) )
332 ufds
[i
].revents
|= G_IO_OUT
;
338 #endif // HAVE_POLL/!HAVE_POLL
340 static gint
wxapp_poll_func( GPollFD
*ufds
, guint nfds
, gint timeout
)
345 g_mainThreadLocked
= TRUE
;
347 // we rely on the fact that glib GPollFD struct is really just pollfd but
348 // I wonder how wise is this in the long term (VZ)
349 gint res
= wxPoll( (wxPollFd
*) ufds
, nfds
, timeout
);
352 g_mainThreadLocked
= FALSE
;
359 #endif // wxUSE_THREADS
363 void wxapp_install_idle_handler()
365 wxASSERT_MSG( wxTheApp
->m_idleTag
== 0, wxT("attempt to install idle handler twice") );
369 if (g_pendingTag
== 0)
370 g_pendingTag
= gtk_idle_add_priority( 900, wxapp_pending_callback
, (gpointer
) NULL
);
372 // This routine gets called by all event handlers
373 // indicating that the idle is over. It may also
374 // get called from other thread for sending events
375 // to the main thread (and processing these in
376 // idle time). Very low priority.
377 wxTheApp
->m_idleTag
= gtk_idle_add_priority( 1000, wxapp_idle_callback
, (gpointer
) NULL
);
380 //-----------------------------------------------------------------------------
381 // Access to the root window global
382 //-----------------------------------------------------------------------------
384 GtkWidget
* wxGetRootWindow()
386 if (gs_RootWindow
== NULL
)
388 gs_RootWindow
= gtk_window_new( GTK_WINDOW_TOPLEVEL
);
389 gtk_widget_realize( gs_RootWindow
);
391 return gs_RootWindow
;
394 //-----------------------------------------------------------------------------
396 //-----------------------------------------------------------------------------
398 IMPLEMENT_DYNAMIC_CLASS(wxApp
,wxEvtHandler
)
400 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
401 EVT_IDLE(wxApp::OnIdle
)
406 m_initialized
= FALSE
;
408 m_isInAssert
= FALSE
;
409 #endif // __WXDEBUG__
412 wxapp_install_idle_handler();
415 g_main_set_poll_func( wxapp_poll_func
);
418 m_colorCube
= (unsigned char*) NULL
;
420 // this is NULL for a "regular" wxApp, but is set (and freed) by a wxGLApp
421 m_glVisualInfo
= (void *) NULL
;
426 if (m_idleTag
) gtk_idle_remove( m_idleTag
);
428 if (m_colorCube
) free(m_colorCube
);
431 bool wxApp::OnInitGui()
433 if ( !wxAppBase::OnInitGui() )
436 GdkVisual
*visual
= gdk_visual_get_system();
438 // if this is a wxGLApp (derived from wxApp), and we've already
439 // chosen a specific visual, then derive the GdkVisual from that
440 if (m_glVisualInfo
!= NULL
)
443 // seems gtk_widget_set_default_visual no longer exists?
444 GdkVisual
* vis
= gtk_widget_get_default_visual();
446 GdkVisual
* vis
= gdkx_visual_get(
447 ((XVisualInfo
*) m_glVisualInfo
) ->visualid
);
448 gtk_widget_set_default_visual( vis
);
451 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
452 gtk_widget_set_default_colormap( colormap
);
457 // On some machines, the default visual is just 256 colours, so
458 // we make sure we get the best. This can sometimes be wasteful.
461 if ((gdk_visual_get_best() != gdk_visual_get_system()) && (m_useBestVisual
))
464 /* seems gtk_widget_set_default_visual no longer exists? */
465 GdkVisual
* vis
= gtk_widget_get_default_visual();
467 GdkVisual
* vis
= gdk_visual_get_best();
468 gtk_widget_set_default_visual( vis
);
471 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
472 gtk_widget_set_default_colormap( colormap
);
477 // Nothing to do for 15, 16, 24, 32 bit displays
478 if (visual
->depth
> 8) return TRUE
;
480 // initialize color cube for 8-bit color reduction dithering
482 GdkColormap
*cmap
= gtk_widget_get_default_colormap();
484 m_colorCube
= (unsigned char*)malloc(32 * 32 * 32);
486 for (int r
= 0; r
< 32; r
++)
488 for (int g
= 0; g
< 32; g
++)
490 for (int b
= 0; b
< 32; b
++)
492 int rr
= (r
<< 3) | (r
>> 2);
493 int gg
= (g
<< 3) | (g
>> 2);
494 int bb
= (b
<< 3) | (b
>> 2);
498 GdkColor
*colors
= cmap
->colors
;
503 for (int i
= 0; i
< cmap
->size
; i
++)
505 int rdiff
= ((rr
<< 8) - colors
[i
].red
);
506 int gdiff
= ((gg
<< 8) - colors
[i
].green
);
507 int bdiff
= ((bb
<< 8) - colors
[i
].blue
);
508 int sum
= ABS (rdiff
) + ABS (gdiff
) + ABS (bdiff
);
511 index
= i
; max
= sum
;
517 // assume 8-bit true or static colors. this really exists
518 GdkVisual
* vis
= gdk_colormap_get_visual( cmap
);
519 index
= (r
>> (5 - vis
->red_prec
)) << vis
->red_shift
;
520 index
|= (g
>> (5 - vis
->green_prec
)) << vis
->green_shift
;
521 index
|= (b
>> (5 - vis
->blue_prec
)) << vis
->blue_shift
;
523 m_colorCube
[ (r
*1024) + (g
*32) + b
] = index
;
531 GdkVisual
*wxApp::GetGdkVisual()
533 GdkVisual
*visual
= NULL
;
536 visual
= gdkx_visual_get( ((XVisualInfo
*) m_glVisualInfo
)->visualid
);
538 visual
= gdk_window_get_visual( wxGetRootWindow()->window
);
545 bool wxApp::ProcessIdle()
547 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
548 node
= wxTopLevelWindows
.GetFirst();
551 wxWindow
* win
= node
->GetData();
552 CallInternalIdle( win
);
554 node
= node
->GetNext();
558 event
.SetEventObject( this );
559 ProcessEvent( event
);
561 return event
.MoreRequested();
564 void wxApp::OnIdle( wxIdleEvent
&event
)
566 static bool s_inOnIdle
= FALSE
;
568 // Avoid recursion (via ProcessEvent default case)
574 // Resend in the main thread events which have been prepared in other
576 ProcessPendingEvents();
578 // 'Garbage' collection of windows deleted with Close()
579 DeletePendingObjects();
581 // Send OnIdle events to all windows
582 bool needMore
= SendIdleEvents();
585 event
.RequestMore(TRUE
);
590 bool wxApp::SendIdleEvents()
592 bool needMore
= FALSE
;
594 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
597 wxWindow
* win
= node
->GetData();
598 if (SendIdleEvents(win
))
601 node
= node
->GetNext();
607 bool wxApp::CallInternalIdle( wxWindow
* win
)
609 win
->OnInternalIdle();
611 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
614 wxWindow
*win
= node
->GetData();
616 CallInternalIdle( win
);
617 node
= node
->GetNext();
623 bool wxApp::SendIdleEvents( wxWindow
* win
)
625 bool needMore
= FALSE
;
628 event
.SetEventObject(win
);
630 win
->GetEventHandler()->ProcessEvent(event
);
632 if (event
.MoreRequested())
635 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
638 wxWindow
*win
= node
->GetData();
640 if (SendIdleEvents(win
))
642 node
= node
->GetNext();
648 int wxApp::MainLoop()
654 void wxApp::ExitMainLoop()
656 if (gtk_main_level() > 0)
660 bool wxApp::Initialized()
662 return m_initialized
;
665 bool wxApp::Pending()
667 return (gtk_events_pending() > 0);
670 void wxApp::Dispatch()
672 gtk_main_iteration();
675 void wxApp::DeletePendingObjects()
677 wxNode
*node
= wxPendingDelete
.GetFirst();
680 wxObject
*obj
= (wxObject
*)node
->GetData();
684 if (wxPendingDelete
.Find(obj
))
687 node
= wxPendingDelete
.GetFirst();
691 bool wxApp::Initialize()
693 wxClassInfo::InitializeClasses();
695 // GL: I'm annoyed ... I don't know where to put this and I don't want to
696 // create a module for that as it's part of the core.
698 wxPendingEvents
= new wxList();
699 wxPendingEventsLocker
= new wxCriticalSection();
702 wxTheColourDatabase
= new wxColourDatabase( wxKEY_STRING
);
703 wxTheColourDatabase
->Initialize();
705 wxInitializeStockLists();
706 wxInitializeStockObjects();
708 #if wxUSE_WX_RESOURCES
709 wxInitializeResourceSystem();
712 wxModule::RegisterModules();
713 if (!wxModule::InitializeModules())
717 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
723 void wxApp::CleanUp()
725 wxModule::CleanUpModules();
727 #if wxUSE_WX_RESOURCES
728 wxCleanUpResourceSystem();
731 delete wxTheColourDatabase
;
732 wxTheColourDatabase
= (wxColourDatabase
*) NULL
;
734 wxDeleteStockObjects();
736 wxDeleteStockLists();
739 wxTheApp
= (wxApp
*) NULL
;
741 wxClassInfo::CleanUpClasses();
744 delete wxPendingEvents
;
745 delete wxPendingEventsLocker
;
748 // check for memory leaks
749 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
750 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
752 wxLogDebug(wxT("There were memory leaks.\n"));
753 wxDebugContext::Dump();
754 wxDebugContext::PrintStatistics();
759 // do this as the very last thing because everything else can log messages
760 wxLog::DontCreateOnDemand();
762 wxLog
*oldLog
= wxLog::SetActiveTarget( (wxLog
*) NULL
);
768 //-----------------------------------------------------------------------------
770 //-----------------------------------------------------------------------------
772 // NB: argc and argv may be changed here, pass by reference!
773 int wxEntryStart( int& argc
, char *argv
[] )
776 // GTK 1.2 up to version 1.2.3 has broken threads
777 if ((gtk_major_version
== 1) &&
778 (gtk_minor_version
== 2) &&
779 (gtk_micro_version
< 4))
781 printf( "wxWindows warning: GUI threading disabled due to outdated GTK version\n" );
791 // We should have the wxUSE_WCHAR_T test on the _outside_
793 #if defined(__WXGTK20__)
794 // gtk+ 2.0 supports Unicode through UTF-8 strings
795 wxConvCurrent
= &wxConvUTF8
;
797 if (!wxOKlibc()) wxConvCurrent
= &wxConvLocal
;
800 if (!wxOKlibc()) wxConvCurrent
= (wxMBConv
*) NULL
;
805 gtk_init( &argc
, &argv
);
807 wxSetDetectableAutoRepeat( TRUE
);
809 if (!wxApp::Initialize())
823 if ( !wxTheApp
->OnInitGui() )
832 void wxEntryCleanup()
835 // flush the logged messages if any
836 wxLog
*log
= wxLog::GetActiveTarget();
837 if (log
!= NULL
&& log
->HasPendingMessages())
840 // continuing to use user defined log target is unsafe from now on because
841 // some resources may be already unavailable, so replace it by something
843 wxLog
*oldlog
= wxLog::SetActiveTarget(new wxLogStderr
);
854 int wxEntry( int argc
, char *argv
[] )
856 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
857 // This seems to be necessary since there are 'rogue'
858 // objects present at this point (perhaps global objects?)
859 // Setting a checkpoint will ignore them as far as the
860 // memory checking facility is concerned.
861 // Of course you may argue that memory allocated in globals should be
862 // checked, but this is a reasonable compromise.
863 wxDebugContext::SetCheckpoint();
865 int err
= wxEntryStart(argc
, argv
);
871 wxCHECK_MSG( wxApp::GetInitializerFunction(), -1,
872 wxT("wxWindows error: No initializer - use IMPLEMENT_APP macro.\n") );
874 wxAppInitializerFunction app_ini
= wxApp::GetInitializerFunction();
876 wxObject
*test_app
= app_ini();
878 wxTheApp
= (wxApp
*) test_app
;
881 wxCHECK_MSG( wxTheApp
, -1, wxT("wxWindows error: no application object") );
883 wxTheApp
->argc
= argc
;
885 wxTheApp
->argv
= new wxChar
*[argc
+1];
887 while (mb_argc
< argc
)
889 wxTheApp
->argv
[mb_argc
] = wxStrdup(wxConvLibc
.cMB2WX(argv
[mb_argc
]));
892 wxTheApp
->argv
[mb_argc
] = (wxChar
*)NULL
;
894 wxTheApp
->argv
= argv
;
897 if (wxTheApp
->argc
> 0)
899 wxFileName
fname( wxTheApp
->argv
[0] );
900 wxTheApp
->SetAppName( fname
.GetName() );
904 retValue
= wxEntryInitGui();
906 // Here frames insert themselves automatically into wxTopLevelWindows by
907 // getting created in OnInit().
910 if ( !wxTheApp
->OnInit() )
916 // Delete pending toplevel windows
917 wxTheApp
->DeletePendingObjects();
919 // When is the app not initialized ?
920 wxTheApp
->m_initialized
= TRUE
;
922 if (wxTheApp
->Initialized())
926 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
928 // Delete all pending windows if any
929 wxTheApp
->DeletePendingObjects();
933 wxTheApp
->SetTopWindow( (wxWindow
*) NULL
);
935 retValue
= wxTheApp
->OnExit();
946 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
* cond
, const wxChar
*msg
)
950 wxAppBase::OnAssert(file
, line
, cond
, msg
);
952 m_isInAssert
= FALSE
;
955 #endif // __WXDEBUG__