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();
243 if (win
->IsKindOf(CLASSINFO(wxMessageDialog
)))
245 if (win
->IsKindOf(CLASSINFO(wxGenericMessageDialog
)))
247 win
->OnInternalIdle();
251 #endif // __WXDEBUG__
253 // When getting called from GDK's time-out handler
254 // we are no longer within GDK's grab on the GUI
255 // thread so we must lock it here ourselves.
258 // Indicate that we are now in idle mode and event handlers
259 // will have to reinstall the idle handler again.
261 wxTheApp
->m_idleTag
= 0;
263 // Send idle event to all who request them as long as
264 // no events have popped up in the event queue.
265 while (wxTheApp
->ProcessIdle() && (gtk_events_pending() == 0))
268 // Release lock again
271 // Return FALSE to indicate that no more idle events are
272 // to be sent (single shot instead of continuous stream).
280 #define wxPollFd pollfd
283 typedef GPollFD wxPollFd
;
285 int wxPoll(wxPollFd
*ufds
, unsigned int nfds
, int timeout
)
287 // convert timeout from ms to struct timeval (s/us)
289 tv_timeout
.tv_sec
= timeout
/1000;
290 tv_timeout
.tv_usec
= (timeout%1000
)*1000;
292 // remember the highest fd used here
295 // and fill the sets for select()
304 for ( i
= 0; i
< nfds
; i
++ )
306 wxASSERT_MSG( ufds
[i
].fd
< FD_SETSIZE
, _T("fd out of range") );
308 if ( ufds
[i
].events
& G_IO_IN
)
309 FD_SET(ufds
[i
].fd
, &readfds
);
311 if ( ufds
[i
].events
& G_IO_PRI
)
312 FD_SET(ufds
[i
].fd
, &exceptfds
);
314 if ( ufds
[i
].events
& G_IO_OUT
)
315 FD_SET(ufds
[i
].fd
, &writefds
);
317 if ( ufds
[i
].fd
> fdMax
)
322 int res
= select(fdMax
, &readfds
, &writefds
, &exceptfds
, &tv_timeout
);
324 // translate the results back
325 for ( i
= 0; i
< nfds
; i
++ )
329 if ( FD_ISSET(ufds
[i
].fd
, &readfds
) )
330 ufds
[i
].revents
|= G_IO_IN
;
332 if ( FD_ISSET(ufds
[i
].fd
, &exceptfds
) )
333 ufds
[i
].revents
|= G_IO_PRI
;
335 if ( FD_ISSET(ufds
[i
].fd
, &writefds
) )
336 ufds
[i
].revents
|= G_IO_OUT
;
342 #endif // HAVE_POLL/!HAVE_POLL
344 static gint
wxapp_poll_func( GPollFD
*ufds
, guint nfds
, gint timeout
)
349 g_mainThreadLocked
= TRUE
;
351 // we rely on the fact that glib GPollFD struct is really just pollfd but
352 // I wonder how wise is this in the long term (VZ)
353 gint res
= wxPoll( (wxPollFd
*) ufds
, nfds
, timeout
);
356 g_mainThreadLocked
= FALSE
;
363 #endif // wxUSE_THREADS
367 void wxapp_install_idle_handler()
369 wxASSERT_MSG( wxTheApp
->m_idleTag
== 0, wxT("attempt to install idle handler twice") );
373 if (g_pendingTag
== 0)
374 g_pendingTag
= gtk_idle_add_priority( 900, wxapp_pending_callback
, (gpointer
) NULL
);
376 // This routine gets called by all event handlers
377 // indicating that the idle is over. It may also
378 // get called from other thread for sending events
379 // to the main thread (and processing these in
380 // idle time). Very low priority.
381 wxTheApp
->m_idleTag
= gtk_idle_add_priority( 1000, wxapp_idle_callback
, (gpointer
) NULL
);
384 //-----------------------------------------------------------------------------
385 // Access to the root window global
386 //-----------------------------------------------------------------------------
388 GtkWidget
* wxGetRootWindow()
390 if (gs_RootWindow
== NULL
)
392 gs_RootWindow
= gtk_window_new( GTK_WINDOW_TOPLEVEL
);
393 gtk_widget_realize( gs_RootWindow
);
395 return gs_RootWindow
;
398 //-----------------------------------------------------------------------------
400 //-----------------------------------------------------------------------------
402 IMPLEMENT_DYNAMIC_CLASS(wxApp
,wxEvtHandler
)
404 BEGIN_EVENT_TABLE(wxApp
, wxEvtHandler
)
405 EVT_IDLE(wxApp::OnIdle
)
410 m_initialized
= FALSE
;
412 m_isInAssert
= FALSE
;
413 #endif // __WXDEBUG__
416 wxapp_install_idle_handler();
419 g_main_set_poll_func( wxapp_poll_func
);
422 m_colorCube
= (unsigned char*) NULL
;
424 // this is NULL for a "regular" wxApp, but is set (and freed) by a wxGLApp
425 m_glVisualInfo
= (void *) NULL
;
430 if (m_idleTag
) gtk_idle_remove( m_idleTag
);
432 if (m_colorCube
) free(m_colorCube
);
435 bool wxApp::OnInitGui()
437 if ( !wxAppBase::OnInitGui() )
440 GdkVisual
*visual
= gdk_visual_get_system();
442 // if this is a wxGLApp (derived from wxApp), and we've already
443 // chosen a specific visual, then derive the GdkVisual from that
444 if (m_glVisualInfo
!= NULL
)
447 // seems gtk_widget_set_default_visual no longer exists?
448 GdkVisual
* vis
= gtk_widget_get_default_visual();
450 GdkVisual
* vis
= gdkx_visual_get(
451 ((XVisualInfo
*) m_glVisualInfo
) ->visualid
);
452 gtk_widget_set_default_visual( vis
);
455 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
456 gtk_widget_set_default_colormap( colormap
);
461 // On some machines, the default visual is just 256 colours, so
462 // we make sure we get the best. This can sometimes be wasteful.
465 if ((gdk_visual_get_best() != gdk_visual_get_system()) && (m_useBestVisual
))
468 /* seems gtk_widget_set_default_visual no longer exists? */
469 GdkVisual
* vis
= gtk_widget_get_default_visual();
471 GdkVisual
* vis
= gdk_visual_get_best();
472 gtk_widget_set_default_visual( vis
);
475 GdkColormap
*colormap
= gdk_colormap_new( vis
, FALSE
);
476 gtk_widget_set_default_colormap( colormap
);
481 // Nothing to do for 15, 16, 24, 32 bit displays
482 if (visual
->depth
> 8) return TRUE
;
484 // initialize color cube for 8-bit color reduction dithering
486 GdkColormap
*cmap
= gtk_widget_get_default_colormap();
488 m_colorCube
= (unsigned char*)malloc(32 * 32 * 32);
490 for (int r
= 0; r
< 32; r
++)
492 for (int g
= 0; g
< 32; g
++)
494 for (int b
= 0; b
< 32; b
++)
496 int rr
= (r
<< 3) | (r
>> 2);
497 int gg
= (g
<< 3) | (g
>> 2);
498 int bb
= (b
<< 3) | (b
>> 2);
502 GdkColor
*colors
= cmap
->colors
;
507 for (int i
= 0; i
< cmap
->size
; i
++)
509 int rdiff
= ((rr
<< 8) - colors
[i
].red
);
510 int gdiff
= ((gg
<< 8) - colors
[i
].green
);
511 int bdiff
= ((bb
<< 8) - colors
[i
].blue
);
512 int sum
= ABS (rdiff
) + ABS (gdiff
) + ABS (bdiff
);
515 index
= i
; max
= sum
;
521 // assume 8-bit true or static colors. this really exists
522 GdkVisual
* vis
= gdk_colormap_get_visual( cmap
);
523 index
= (r
>> (5 - vis
->red_prec
)) << vis
->red_shift
;
524 index
|= (g
>> (5 - vis
->green_prec
)) << vis
->green_shift
;
525 index
|= (b
>> (5 - vis
->blue_prec
)) << vis
->blue_shift
;
527 m_colorCube
[ (r
*1024) + (g
*32) + b
] = index
;
535 GdkVisual
*wxApp::GetGdkVisual()
537 GdkVisual
*visual
= NULL
;
540 visual
= gdkx_visual_get( ((XVisualInfo
*) m_glVisualInfo
)->visualid
);
542 visual
= gdk_window_get_visual( wxGetRootWindow()->window
);
549 bool wxApp::ProcessIdle()
551 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
552 node
= wxTopLevelWindows
.GetFirst();
555 wxWindow
* win
= node
->GetData();
556 CallInternalIdle( win
);
558 node
= node
->GetNext();
562 event
.SetEventObject( this );
563 ProcessEvent( event
);
565 return event
.MoreRequested();
568 void wxApp::OnIdle( wxIdleEvent
&event
)
570 static bool s_inOnIdle
= FALSE
;
572 // Avoid recursion (via ProcessEvent default case)
578 // Resend in the main thread events which have been prepared in other
580 ProcessPendingEvents();
582 // 'Garbage' collection of windows deleted with Close()
583 DeletePendingObjects();
585 // Send OnIdle events to all windows
586 bool needMore
= SendIdleEvents();
589 event
.RequestMore(TRUE
);
594 bool wxApp::SendIdleEvents()
596 bool needMore
= FALSE
;
598 wxWindowList::Node
* node
= wxTopLevelWindows
.GetFirst();
601 wxWindow
* win
= node
->GetData();
602 if (SendIdleEvents(win
))
605 node
= node
->GetNext();
611 bool wxApp::CallInternalIdle( wxWindow
* win
)
613 win
->OnInternalIdle();
615 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
618 wxWindow
*win
= node
->GetData();
620 CallInternalIdle( win
);
621 node
= node
->GetNext();
627 bool wxApp::SendIdleEvents( wxWindow
* win
)
629 bool needMore
= FALSE
;
632 event
.SetEventObject(win
);
634 win
->GetEventHandler()->ProcessEvent(event
);
636 if (event
.MoreRequested())
639 wxWindowList::Node
*node
= win
->GetChildren().GetFirst();
642 wxWindow
*win
= node
->GetData();
644 if (SendIdleEvents(win
))
646 node
= node
->GetNext();
652 int wxApp::MainLoop()
658 void wxApp::ExitMainLoop()
660 if (gtk_main_level() > 0)
664 bool wxApp::Initialized()
666 return m_initialized
;
669 bool wxApp::Pending()
671 return (gtk_events_pending() > 0);
674 void wxApp::Dispatch()
676 gtk_main_iteration();
679 void wxApp::DeletePendingObjects()
681 wxNode
*node
= wxPendingDelete
.GetFirst();
684 wxObject
*obj
= (wxObject
*)node
->GetData();
688 if (wxPendingDelete
.Find(obj
))
691 node
= wxPendingDelete
.GetFirst();
695 bool wxApp::Initialize()
697 wxClassInfo::InitializeClasses();
699 // GL: I'm annoyed ... I don't know where to put this and I don't want to
700 // create a module for that as it's part of the core.
702 wxPendingEvents
= new wxList();
703 wxPendingEventsLocker
= new wxCriticalSection();
706 wxTheColourDatabase
= new wxColourDatabase( wxKEY_STRING
);
707 wxTheColourDatabase
->Initialize();
709 wxInitializeStockLists();
710 wxInitializeStockObjects();
712 #if wxUSE_WX_RESOURCES
713 wxInitializeResourceSystem();
716 wxModule::RegisterModules();
717 if (!wxModule::InitializeModules())
721 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
727 void wxApp::CleanUp()
729 wxModule::CleanUpModules();
731 #if wxUSE_WX_RESOURCES
732 wxCleanUpResourceSystem();
735 delete wxTheColourDatabase
;
736 wxTheColourDatabase
= (wxColourDatabase
*) NULL
;
738 wxDeleteStockObjects();
740 wxDeleteStockLists();
743 wxTheApp
= (wxApp
*) NULL
;
745 wxClassInfo::CleanUpClasses();
748 delete wxPendingEvents
;
749 delete wxPendingEventsLocker
;
752 // check for memory leaks
753 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
754 if (wxDebugContext::CountObjectsLeft(TRUE
) > 0)
756 wxLogDebug(wxT("There were memory leaks.\n"));
757 wxDebugContext::Dump();
758 wxDebugContext::PrintStatistics();
763 // do this as the very last thing because everything else can log messages
764 wxLog::DontCreateOnDemand();
766 wxLog
*oldLog
= wxLog::SetActiveTarget( (wxLog
*) NULL
);
772 //-----------------------------------------------------------------------------
774 //-----------------------------------------------------------------------------
776 // NB: argc and argv may be changed here, pass by reference!
777 int wxEntryStart( int& argc
, char *argv
[] )
780 // GTK 1.2 up to version 1.2.3 has broken threads
781 if ((gtk_major_version
== 1) &&
782 (gtk_minor_version
== 2) &&
783 (gtk_micro_version
< 4))
785 printf( "wxWindows warning: GUI threading disabled due to outdated GTK version\n" );
795 // We should have the wxUSE_WCHAR_T test on the _outside_
797 #if defined(__WXGTK20__)
798 // gtk+ 2.0 supports Unicode through UTF-8 strings
799 wxConvCurrent
= &wxConvUTF8
;
801 if (!wxOKlibc()) wxConvCurrent
= &wxConvLocal
;
804 if (!wxOKlibc()) wxConvCurrent
= (wxMBConv
*) NULL
;
809 gtk_init( &argc
, &argv
);
811 wxSetDetectableAutoRepeat( TRUE
);
813 if (!wxApp::Initialize())
827 if ( !wxTheApp
->OnInitGui() )
836 void wxEntryCleanup()
839 // flush the logged messages if any
840 wxLog
*log
= wxLog::GetActiveTarget();
841 if (log
!= NULL
&& log
->HasPendingMessages())
844 // continuing to use user defined log target is unsafe from now on because
845 // some resources may be already unavailable, so replace it by something
847 wxLog
*oldlog
= wxLog::SetActiveTarget(new wxLogStderr
);
858 int wxEntry( int argc
, char *argv
[] )
860 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
861 // This seems to be necessary since there are 'rogue'
862 // objects present at this point (perhaps global objects?)
863 // Setting a checkpoint will ignore them as far as the
864 // memory checking facility is concerned.
865 // Of course you may argue that memory allocated in globals should be
866 // checked, but this is a reasonable compromise.
867 wxDebugContext::SetCheckpoint();
869 int err
= wxEntryStart(argc
, argv
);
875 wxCHECK_MSG( wxApp::GetInitializerFunction(), -1,
876 wxT("wxWindows error: No initializer - use IMPLEMENT_APP macro.\n") );
878 wxAppInitializerFunction app_ini
= wxApp::GetInitializerFunction();
880 wxObject
*test_app
= app_ini();
882 wxTheApp
= (wxApp
*) test_app
;
885 wxCHECK_MSG( wxTheApp
, -1, wxT("wxWindows error: no application object") );
887 wxTheApp
->argc
= argc
;
889 wxTheApp
->argv
= new wxChar
*[argc
+1];
891 while (mb_argc
< argc
)
893 wxTheApp
->argv
[mb_argc
] = wxStrdup(wxConvLibc
.cMB2WX(argv
[mb_argc
]));
896 wxTheApp
->argv
[mb_argc
] = (wxChar
*)NULL
;
898 wxTheApp
->argv
= argv
;
901 if (wxTheApp
->argc
> 0)
903 wxFileName
fname( wxTheApp
->argv
[0] );
904 wxTheApp
->SetAppName( fname
.GetName() );
908 retValue
= wxEntryInitGui();
910 // Here frames insert themselves automatically into wxTopLevelWindows by
911 // getting created in OnInit().
914 if ( !wxTheApp
->OnInit() )
920 // Delete pending toplevel windows
921 wxTheApp
->DeletePendingObjects();
923 // When is the app not initialized ?
924 wxTheApp
->m_initialized
= TRUE
;
926 if (wxTheApp
->Initialized())
930 wxWindow
*topWindow
= wxTheApp
->GetTopWindow();
932 // Delete all pending windows if any
933 wxTheApp
->DeletePendingObjects();
937 wxTheApp
->SetTopWindow( (wxWindow
*) NULL
);
939 retValue
= wxTheApp
->OnExit();
950 void wxApp::OnAssert(const wxChar
*file
, int line
, const wxChar
* cond
, const wxChar
*msg
)
954 wxAppBase::OnAssert(file
, line
, cond
, msg
);
956 m_isInAssert
= FALSE
;
959 #endif // __WXDEBUG__