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