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