streamlining OSX event support first step, see #11805, see #11797
[wxWidgets.git] / src / osx / core / evtloop_cf.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/core/evtloop_cf.cpp
3 // Purpose: wxEventLoop implementation common to both Carbon and Cocoa
4 // Author: Vadim Zeitlin
5 // Created: 2009-10-18
6 // RCS-ID: $Id$
7 // Copyright: (c) 2009 Vadim Zeitlin <vadim@wxwidgets.org>
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 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #include "wx/evtloop.h"
27
28 #if wxUSE_EVENTLOOP_SOURCE
29
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #endif
34
35 #include "wx/evtloopsrc.h"
36
37 #include "wx/scopedptr.h"
38
39 #include "wx/osx/private.h"
40 #include "wx/osx/core/cfref.h"
41
42 // ============================================================================
43 // wxCFEventLoopSource and wxCFEventLoop implementation
44 // ============================================================================
45
46 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
47 namespace
48 {
49
50 void EnableDescriptorCallBacks(CFFileDescriptorRef cffd, int flags)
51 {
52 if ( flags & wxEVENT_SOURCE_INPUT )
53 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorReadCallBack);
54 if ( flags & wxEVENT_SOURCE_OUTPUT )
55 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorWriteCallBack);
56 }
57
58 void
59 wx_cffiledescriptor_callback(CFFileDescriptorRef cffd,
60 CFOptionFlags flags,
61 void *ctxData)
62 {
63 wxLogTrace(wxTRACE_EVT_SOURCE,
64 "CFFileDescriptor callback, flags=%d", flags);
65
66 wxCFEventLoopSource * const
67 source = static_cast<wxCFEventLoopSource *>(ctxData);
68
69 wxEventLoopSourceHandler * const
70 handler = source->GetHandler();
71 if ( flags & kCFFileDescriptorReadCallBack )
72 handler->OnReadWaiting();
73 if ( flags & kCFFileDescriptorWriteCallBack )
74 handler->OnWriteWaiting();
75
76 // we need to re-enable callbacks to be called again
77 EnableDescriptorCallBacks(cffd, source->GetFlags());
78 }
79
80 } // anonymous namespace
81
82 wxEventLoopSource *
83 wxCFEventLoop::AddSourceForFD(int fd,
84 wxEventLoopSourceHandler *handler,
85 int flags)
86 {
87 wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
88
89 wxScopedPtr<wxCFEventLoopSource>
90 source(new wxCFEventLoopSource(handler, flags));
91
92 CFFileDescriptorContext ctx = { 0, source.get(), NULL, NULL, NULL };
93 wxCFRef<CFFileDescriptorRef>
94 cffd(CFFileDescriptorCreate
95 (
96 kCFAllocatorDefault,
97 fd,
98 true, // close on invalidate
99 wx_cffiledescriptor_callback,
100 &ctx
101 ));
102 if ( !cffd )
103 return NULL;
104
105 source->SetFileDescriptor(cffd.release());
106
107 wxCFRef<CFRunLoopSourceRef>
108 cfsrc(CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, cffd, 0));
109 if ( !cfsrc )
110 return NULL;
111
112 CFRunLoopRef cfloop = CFGetCurrentRunLoop();
113 CFRunLoopAddSource(cfloop, cfsrc, kCFRunLoopDefaultMode);
114
115 return source.release();
116 }
117
118 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd)
119 {
120 wxASSERT_MSG( !m_cffd, "shouldn't be called more than once" );
121
122 m_cffd = cffd;
123 }
124
125 wxCFEventLoopSource::~wxCFEventLoopSource()
126 {
127 if ( m_cffd )
128 CFRelease(m_cffd);
129 }
130
131 #else // OS X < 10.5
132
133 wxEventLoopSource *
134 wxCFEventLoop::AddSourceForFD(int WXUNUSED(fd),
135 wxEventLoopSourceHandler * WXUNUSED(handler),
136 int WXUNUSED(flags))
137 {
138 return NULL;
139 }
140
141 #endif // MAC_OS_X_VERSION_MAX_ALLOWED
142
143 #endif // wxUSE_EVENTLOOP_SOURCE
144
145 wxCFEventLoop::wxCFEventLoop()
146 {
147 m_shouldExit = false;
148 m_sleepTime = 0.0;
149 }
150
151 wxCFEventLoop::~wxCFEventLoop()
152 {
153 }
154
155
156 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
157 {
158 return CFGetCurrentRunLoop();
159 }
160
161 void wxCFEventLoop::WakeUp()
162 {
163 extern void wxMacWakeUp();
164
165 wxMacWakeUp();
166 }
167
168 bool wxCFEventLoop::YieldFor(long eventsToProcess)
169 {
170 #if wxUSE_THREADS
171 // Yielding from a non-gui thread needs to bail out, otherwise we end up
172 // possibly sending events in the thread too.
173 if ( !wxThread::IsMain() )
174 {
175 return true;
176 }
177 #endif // wxUSE_THREADS
178
179 m_isInsideYield = true;
180 m_eventsToProcessInsideYield = eventsToProcess;
181
182 #if wxUSE_LOG
183 // disable log flushing from here because a call to wxYield() shouldn't
184 // normally result in message boxes popping up &c
185 wxLog::Suspend();
186 #endif // wxUSE_LOG
187
188 // process all pending events:
189 while ( DoProcessEvents() == 1 )
190 ;
191
192 // it's necessary to call ProcessIdle() to update the frames sizes which
193 // might have been changed (it also will update other things set from
194 // OnUpdateUI() which is a nice (and desired) side effect)
195 while ( ProcessIdle() ) {}
196
197 // if there are pending events, we must process them.
198 if (wxTheApp)
199 wxTheApp->ProcessPendingEvents();
200
201 #if wxUSE_LOG
202 wxLog::Resume();
203 #endif // wxUSE_LOG
204 m_isInsideYield = false;
205
206 return true;
207 }
208
209 // implement/override base class pure virtual
210 bool wxCFEventLoop::Pending() const
211 {
212 return true;
213 }
214
215 int wxCFEventLoop::DoProcessEvents()
216 {
217 // process pending wx events first as they correspond to low-level events
218 // which happened before, i.e. typically pending events were queued by a
219 // previous call to Dispatch() and if we didn't process them now the next
220 // call to it might enqueue them again (as happens with e.g. socket events
221 // which would be generated as long as there is input available on socket
222 // and this input is only removed from it when pending event handlers are
223 // executed)
224 if ( wxTheApp )
225 wxTheApp->ProcessPendingEvents();
226
227 return DispatchTimeout( (unsigned long)(m_sleepTime * 1000.0) );
228 }
229
230 bool wxCFEventLoop::Dispatch()
231 {
232 return DispatchTimeout( (unsigned long)(m_sleepTime * 1000.0) ) != 0;
233 }
234
235 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
236 {
237 if ( !wxTheApp )
238 return 0;
239
240 wxMacAutoreleasePool autoreleasepool;
241
242 int status = DoDispatchTimeout(timeout);
243
244 switch( status )
245 {
246 case 0:
247 break;
248 case -1:
249 if ( m_shouldExit )
250 return 0;
251
252 if ( ProcessIdle() )
253 m_sleepTime = 0.0 ;
254 else
255 {
256 m_sleepTime = 1.0;
257 #if wxUSE_THREADS
258 wxMutexGuiLeave();
259 wxMilliSleep(20);
260 wxMutexGuiEnter();
261 #endif
262 }
263 break;
264 case 1:
265 m_sleepTime = 0;
266 break;
267 }
268
269 return status;
270 }
271
272 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
273 {
274 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
275 switch( status )
276 {
277 case kCFRunLoopRunFinished:
278 wxFAIL_MSG( "incorrect run loop state" );
279 break;
280 case kCFRunLoopRunStopped:
281 return 0;
282 break;
283 case kCFRunLoopRunTimedOut:
284 return -1;
285 break;
286 case kCFRunLoopRunHandledSource:
287 default:
288 break;
289 }
290 return 1;
291 }
292
293 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
294 // terminating when Exit() is called
295 int wxCFEventLoop::Run()
296 {
297 // event loops are not recursive, you need to create another loop!
298 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
299
300 // ProcessIdle() and ProcessEvents() below may throw so the code here should
301 // be exception-safe, hence we must use local objects for all actions we
302 // should undo
303 wxEventLoopActivator activate(this);
304
305 // we must ensure that OnExit() is called even if an exception is thrown
306 // from inside ProcessEvents() but we must call it from Exit() in normal
307 // situations because it is supposed to be called synchronously,
308 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
309 // something similar here)
310 #if wxUSE_EXCEPTIONS
311 for ( ;; )
312 {
313 try
314 {
315 #endif // wxUSE_EXCEPTIONS
316 for ( ;; )
317 {
318 // generate and process idle events for as long as we don't
319 // have anything else to do
320 DoProcessEvents();
321
322 // if the "should exit" flag is set, the loop should terminate
323 // but not before processing any remaining messages so while
324 // Pending() returns true, do process them
325 if ( m_shouldExit )
326 {
327 while ( DoProcessEvents() == 1 )
328 ;
329
330 break;
331 }
332 }
333
334 #if wxUSE_EXCEPTIONS
335 // exit the outer loop as well
336 break;
337 }
338 catch ( ... )
339 {
340 try
341 {
342 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
343 {
344 OnExit();
345 break;
346 }
347 //else: continue running the event loop
348 }
349 catch ( ... )
350 {
351 // OnException() throwed, possibly rethrowing the same
352 // exception again: very good, but we still need OnExit() to
353 // be called
354 OnExit();
355 throw;
356 }
357 }
358 }
359 #endif // wxUSE_EXCEPTIONS
360
361 return m_exitcode;
362 }
363
364 // sets the "should exit" flag and wakes up the loop so that it terminates
365 // soon
366 void wxCFEventLoop::Exit(int rc)
367 {
368 m_exitcode = rc;
369 m_shouldExit = true;
370 m_sleepTime = 0;
371 }
372
373