1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/gtk/evtloop.cpp
3 // Purpose:     implements wxEventLoop for GTK+
4 // Author:      Vadim Zeitlin
5 // Created:     10.07.01
6 // Copyright:   (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
7 //              (c) 2013 Rob Bresalier, Vadim Zeitlin
8 // Licence:     wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
10 
11 // ============================================================================
12 // declarations
13 // ============================================================================
14 
15 // ----------------------------------------------------------------------------
16 // headers
17 // ----------------------------------------------------------------------------
18 
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21 
22 
23 #include "wx/evtloop.h"
24 #include "wx/evtloopsrc.h"
25 
26 #ifndef WX_PRECOMP
27     #include "wx/app.h"
28     #include "wx/log.h"
29 #endif // WX_PRECOMP
30 
31 #include "wx/private/eventloopsourcesmanager.h"
32 #include "wx/apptrait.h"
33 
34 #include "wx/gtk/private/wrapgtk.h"
35 
36 GdkWindow* wxGetTopLevelGDK();
37 
38 // ============================================================================
39 // wxEventLoop implementation
40 // ============================================================================
41 
42 // ----------------------------------------------------------------------------
43 // wxEventLoop running and exiting
44 // ----------------------------------------------------------------------------
45 
wxGUIEventLoop()46 wxGUIEventLoop::wxGUIEventLoop()
47 {
48     m_exitcode = 0;
49 }
50 
DoRun()51 int wxGUIEventLoop::DoRun()
52 {
53     guint loopLevel = gtk_main_level();
54 
55     // This is placed inside of a loop to take into account nested
56     // event loops.  For example, inside this event loop, we may receive
57     // Exit() for a different event loop (which we are currently inside of)
58     // That Exit() will cause this gtk_main() to exit so we need to re-enter it.
59     while ( !m_shouldExit )
60     {
61         gtk_main();
62     }
63 
64     // Force the enclosing event loop to also exit to see if it is done in case
65     // that event loop had Exit() called inside of the just ended loop. If it
66     // is not time yet for that event loop to exit, it will be executed again
67     // due to the while() loop on m_shouldExit().
68     //
69     // This is unnecessary if we are the top level loop, i.e. loop of level 0.
70     if ( loopLevel )
71     {
72         gtk_main_quit();
73     }
74 
75     OnExit();
76 
77 #if wxUSE_EXCEPTIONS
78     // Rethrow any exceptions which could have been produced by the handlers
79     // ran by the event loop.
80     if ( wxTheApp )
81         wxTheApp->RethrowStoredException();
82 #endif // wxUSE_EXCEPTIONS
83 
84     return m_exitcode;
85 }
86 
ScheduleExit(int rc)87 void wxGUIEventLoop::ScheduleExit(int rc)
88 {
89     wxCHECK_RET( IsInsideRun(), wxT("can't call ScheduleExit() if not started") );
90 
91     m_exitcode = rc;
92 
93     m_shouldExit = true;
94 
95     gtk_main_quit();
96 }
97 
WakeUp()98 void wxGUIEventLoop::WakeUp()
99 {
100     // TODO: idle events handling should really be done by wxEventLoop itself
101     //       but for now it's completely in gtk/app.cpp so just call there when
102     //       we have wxTheApp and hope that it doesn't matter that we do
103     //       nothing when we don't...
104     if ( wxTheApp )
105         wxTheApp->WakeUpIdle();
106 }
107 
108 // ----------------------------------------------------------------------------
109 // wxEventLoop adding & removing sources
110 // ----------------------------------------------------------------------------
111 
112 #if wxUSE_EVENTLOOP_SOURCE
113 
114 extern "C"
115 {
wx_on_channel_event(GIOChannel * channel,GIOCondition condition,gpointer data)116 static gboolean wx_on_channel_event(GIOChannel *channel,
117                                     GIOCondition condition,
118                                     gpointer data)
119 {
120     wxUnusedVar(channel); // Unused if !wxUSE_LOG || !wxDEBUG_LEVEL
121 
122     wxLogTrace(wxTRACE_EVT_SOURCE,
123                "wx_on_channel_event, fd=%d, condition=%08x",
124                g_io_channel_unix_get_fd(channel), condition);
125 
126     wxEventLoopSourceHandler * const
127         handler = static_cast<wxEventLoopSourceHandler *>(data);
128 
129     if ( (condition & G_IO_IN) || (condition & G_IO_PRI) || (condition & G_IO_HUP) )
130         handler->OnReadWaiting();
131 
132     if (condition & G_IO_OUT)
133         handler->OnWriteWaiting();
134 
135     if ( (condition & G_IO_ERR) || (condition & G_IO_NVAL) )
136         handler->OnExceptionWaiting();
137 
138     // we never want to remove source here, so always return true
139     //
140     // The source may have been removed by the handler, so it may be
141     // a good idea to return FALSE when the source has already been
142     // removed.  However, that would involve somehow informing this function
143     // that the source was removed, which is not trivial to implement
144     // and handle all cases.  It has been found through testing
145     // that if the source was removed by the handler, that even if we
146     // return TRUE here, the source/callback will not get called again.
147     return TRUE;
148 }
149 }
150 
151 class wxGUIEventLoopSourcesManager : public wxEventLoopSourcesManagerBase
152 {
153 public:
154     virtual wxEventLoopSource*
AddSourceForFD(int fd,wxEventLoopSourceHandler * handler,int flags)155     AddSourceForFD(int fd, wxEventLoopSourceHandler *handler, int flags) wxOVERRIDE
156     {
157         wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
158 
159         int condition = 0;
160         if ( flags & wxEVENT_SOURCE_INPUT )
161             condition |= G_IO_IN | G_IO_PRI | G_IO_HUP;
162         if ( flags & wxEVENT_SOURCE_OUTPUT )
163             condition |= G_IO_OUT;
164         if ( flags & wxEVENT_SOURCE_EXCEPTION )
165             condition |= G_IO_ERR | G_IO_NVAL;
166 
167         GIOChannel* channel = g_io_channel_unix_new(fd);
168         const unsigned sourceId  = g_io_add_watch
169                                    (
170                                     channel,
171                                     (GIOCondition)condition,
172                                     &wx_on_channel_event,
173                                     handler
174                                    );
175         // it was ref'd by g_io_add_watch() so we can unref it here
176         g_io_channel_unref(channel);
177 
178         if ( !sourceId )
179             return NULL;
180 
181         wxLogTrace(wxTRACE_EVT_SOURCE,
182                    "Adding event loop source for fd=%d with GTK id=%u",
183                    fd, sourceId);
184 
185 
186         return new wxGTKEventLoopSource(sourceId, handler, flags);
187     }
188 };
189 
GetEventLoopSourcesManager()190 wxEventLoopSourcesManagerBase* wxGUIAppTraits::GetEventLoopSourcesManager()
191 {
192     static wxGUIEventLoopSourcesManager s_eventLoopSourcesManager;
193 
194     return &s_eventLoopSourcesManager;
195 }
196 
~wxGTKEventLoopSource()197 wxGTKEventLoopSource::~wxGTKEventLoopSource()
198 {
199     wxLogTrace(wxTRACE_EVT_SOURCE,
200                "Removing event loop source with GTK id=%u", m_sourceId);
201 
202     g_source_remove(m_sourceId);
203 }
204 
205 #endif // wxUSE_EVENTLOOP_SOURCE
206 
207 // ----------------------------------------------------------------------------
208 // wxEventLoop message processing dispatching
209 // ----------------------------------------------------------------------------
210 
Pending() const211 bool wxGUIEventLoop::Pending() const
212 {
213     if ( wxTheApp )
214     {
215         // this avoids false positives from our idle source
216         return wxTheApp->EventsPending();
217     }
218 
219     return gtk_events_pending() != 0;
220 }
221 
Dispatch()222 bool wxGUIEventLoop::Dispatch()
223 {
224     wxCHECK_MSG( IsRunning(), false, wxT("can't call Dispatch() if not running") );
225 
226     // gtk_main_iteration() returns TRUE only if gtk_main_quit() was called
227     return !gtk_main_iteration();
228 }
229 
230 extern "C" {
wx_event_loop_timeout(void * data)231 static gboolean wx_event_loop_timeout(void* data)
232 {
233     bool* expired = static_cast<bool*>(data);
234     *expired = true;
235 
236     // return FALSE to remove this timeout
237     return FALSE;
238 }
239 }
240 
DispatchTimeout(unsigned long timeout)241 int wxGUIEventLoop::DispatchTimeout(unsigned long timeout)
242 {
243     bool expired = false;
244     const unsigned id = g_timeout_add(timeout, wx_event_loop_timeout, &expired);
245     bool quit = gtk_main_iteration() != 0;
246 
247     if ( expired )
248         return -1;
249 
250     g_source_remove(id);
251 
252     return !quit;
253 }
254 
255 //-----------------------------------------------------------------------------
256 // YieldFor
257 //-----------------------------------------------------------------------------
258 
259 extern "C" {
wxgtk_main_do_event(GdkEvent * event,void * data)260 static void wxgtk_main_do_event(GdkEvent* event, void* data)
261 {
262     // categorize the GDK event according to wxEventCategory.
263     // See http://library.gnome.org/devel/gdk/unstable/gdk-Events.html#GdkEventType
264     // for more info.
265 
266     // NOTE: GDK_* constants which were not present in the GDK2.0 can be tested for
267     //       only at compile-time; when running the program (compiled with a recent GDK)
268     //       on a system with an older GDK lib we can be sure there won't be problems
269     //       because event->type will never assume those values corresponding to
270     //       new event types (since new event types are always added in GDK with non
271     //       conflicting values for ABI compatibility).
272 
273     // Some events (currently only a single one) may be used for more than one
274     // category, so we need 2 variables. The second one will remain "unknown"
275     // in most cases.
276     wxEventCategory cat = wxEVT_CATEGORY_UNKNOWN,
277                     cat2 = wxEVT_CATEGORY_UNKNOWN;
278     switch (event->type)
279     {
280     case GDK_SELECTION_REQUEST:
281     case GDK_SELECTION_NOTIFY:
282     case GDK_SELECTION_CLEAR:
283     case GDK_OWNER_CHANGE:
284         cat = wxEVT_CATEGORY_CLIPBOARD;
285         break;
286 
287     case GDK_KEY_PRESS:
288     case GDK_KEY_RELEASE:
289     case GDK_BUTTON_PRESS:
290     case GDK_2BUTTON_PRESS:
291     case GDK_3BUTTON_PRESS:
292     case GDK_BUTTON_RELEASE:
293     case GDK_SCROLL:        // generated from mouse buttons
294     case GDK_CLIENT_EVENT:
295         cat = wxEVT_CATEGORY_USER_INPUT;
296         break;
297 
298     case GDK_PROPERTY_NOTIFY:
299         // This one is special: it can be used for UI purposes but also for
300         // clipboard operations, so allow it in both cases (we probably could
301         // examine the event itself to distinguish between the two cases but
302         // this would be unnecessarily complicated).
303         cat2 = wxEVT_CATEGORY_CLIPBOARD;
304         wxFALLTHROUGH;
305 
306     case GDK_PROXIMITY_IN:
307     case GDK_PROXIMITY_OUT:
308 
309     case GDK_MOTION_NOTIFY:
310     case GDK_ENTER_NOTIFY:
311     case GDK_LEAVE_NOTIFY:
312     case GDK_VISIBILITY_NOTIFY:
313 
314     case GDK_FOCUS_CHANGE:
315     case GDK_CONFIGURE:
316     case GDK_WINDOW_STATE:
317     case GDK_SETTING:
318     case GDK_DELETE:
319     case GDK_DESTROY:
320 
321     case GDK_EXPOSE:
322 #ifndef __WXGTK3__
323     case GDK_NO_EXPOSE:
324 #endif
325     case GDK_MAP:
326     case GDK_UNMAP:
327 
328     case GDK_DRAG_ENTER:
329     case GDK_DRAG_LEAVE:
330     case GDK_DRAG_MOTION:
331     case GDK_DRAG_STATUS:
332     case GDK_DROP_START:
333     case GDK_DROP_FINISHED:
334 #if GTK_CHECK_VERSION(2,8,0)
335     case GDK_GRAB_BROKEN:
336 #endif
337 #if GTK_CHECK_VERSION(2,14,0)
338     case GDK_DAMAGE:
339 #endif
340         cat = wxEVT_CATEGORY_UI;
341         break;
342 
343     default:
344         cat = wxEVT_CATEGORY_UNKNOWN;
345         break;
346     }
347 
348     wxGUIEventLoop* evtloop = static_cast<wxGUIEventLoop*>(data);
349 
350     // is this event allowed now?
351     if (evtloop->IsEventAllowedInsideYield(cat) ||
352             (cat2 != wxEVT_CATEGORY_UNKNOWN &&
353                 evtloop->IsEventAllowedInsideYield(cat2)))
354     {
355         // process it now
356         gtk_main_do_event(event);
357     }
358     else if (event->type != GDK_NOTHING)
359     {
360         // process it later (but make a copy; the caller will free the event
361         // pointer)
362         evtloop->StoreGdkEventForLaterProcessing(gdk_event_copy(event));
363     }
364 }
365 }
366 
DoYieldFor(long eventsToProcess)367 void wxGUIEventLoop::DoYieldFor(long eventsToProcess)
368 {
369     // temporarily replace the global GDK event handler with our function, which
370     // categorizes the events and using m_eventsToProcessInsideYield decides
371     // if an event should be processed immediately or not
372     // NOTE: this approach is better than using gdk_display_get_event() because
373     //       gtk_main_iteration() does more than just calling gdk_display_get_event()
374     //       and then call gtk_main_do_event()!
375     //       In particular in this way we also process input from sources like
376     //       GIOChannels (this is needed for e.g. wxGUIAppTraits::WaitForChild).
377     gdk_event_handler_set(wxgtk_main_do_event, this, NULL);
378     while (Pending())   // avoid false positives from our idle source
379         gtk_main_iteration();
380 
381     wxGCC_WARNING_SUPPRESS_CAST_FUNCTION_TYPE()
382     gdk_event_handler_set ((GdkEventFunc)gtk_main_do_event, NULL, NULL);
383     wxGCC_WARNING_RESTORE_CAST_FUNCTION_TYPE()
384 
385     wxEventLoopBase::DoYieldFor(eventsToProcess);
386 
387     // put any unprocessed GDK events back in the queue
388     if ( !m_arrGdkEvents.IsEmpty() )
389     {
390         GdkDisplay* disp = gdk_window_get_display(wxGetTopLevelGDK());
391         for (size_t i=0; i<m_arrGdkEvents.GetCount(); i++)
392         {
393             GdkEvent* ev = (GdkEvent*)m_arrGdkEvents[i];
394 
395             // NOTE: gdk_display_put_event makes a copy of the event passed to it
396             gdk_display_put_event(disp, ev);
397             gdk_event_free(ev);
398         }
399 
400         m_arrGdkEvents.Clear();
401     }
402 }
403