adding proper removal of observer for stacked event loops, using cfrunloop for consol...
[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 void wxObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
146 {
147 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
148 if ( eventloop )
149 eventloop->ObserverCallBack(observer, activity);
150 }
151
152 void wxCFEventLoop::ObserverCallBack(CFRunLoopObserverRef observer, int activity)
153 {
154 if ( activity & kCFRunLoopBeforeTimers )
155 {
156 // process pending wx events first as they correspond to low-level events
157 // which happened before, i.e. typically pending events were queued by a
158 // previous call to Dispatch() and if we didn't process them now the next
159 // call to it might enqueue them again (as happens with e.g. socket events
160 // which would be generated as long as there is input available on socket
161 // and this input is only removed from it when pending event handlers are
162 // executed)
163
164 if ( wxTheApp )
165 wxTheApp->ProcessPendingEvents();
166 }
167
168 if ( activity & kCFRunLoopBeforeWaiting )
169 {
170 if ( ProcessIdle() )
171 {
172 WakeUp();
173 }
174 else
175 {
176 #if wxUSE_THREADS
177 wxMutexGuiLeave();
178 wxMilliSleep(20);
179 wxMutexGuiEnter();
180 #endif
181 }
182 }
183 }
184
185 wxCFEventLoop::wxCFEventLoop()
186 {
187 m_shouldExit = false;
188
189 m_runLoop = CFGetCurrentRunLoop();
190
191 CFRunLoopObserverContext ctxt;
192 bzero( &ctxt, sizeof(ctxt) );
193 ctxt.info = this;
194 m_runLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
195 wxObserverCallBack, &ctxt );
196 CFRunLoopAddObserver(m_runLoop, m_runLoopObserver, kCFRunLoopDefaultMode);
197 }
198
199 wxCFEventLoop::~wxCFEventLoop()
200 {
201 CFRunLoopRemoveObserver(m_runLoop, m_runLoopObserver, kCFRunLoopDefaultMode);
202 }
203
204
205 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
206 {
207 return CFRunLoopGetCurrent();
208 }
209
210 void wxCFEventLoop::WakeUp()
211 {
212 extern void wxMacWakeUp();
213
214 wxMacWakeUp();
215 }
216
217 bool wxCFEventLoop::YieldFor(long eventsToProcess)
218 {
219 #if wxUSE_THREADS
220 // Yielding from a non-gui thread needs to bail out, otherwise we end up
221 // possibly sending events in the thread too.
222 if ( !wxThread::IsMain() )
223 {
224 return true;
225 }
226 #endif // wxUSE_THREADS
227
228 m_isInsideYield = true;
229 m_eventsToProcessInsideYield = eventsToProcess;
230
231 #if wxUSE_LOG
232 // disable log flushing from here because a call to wxYield() shouldn't
233 // normally result in message boxes popping up &c
234 wxLog::Suspend();
235 #endif // wxUSE_LOG
236
237 // process all pending events:
238 while ( DoProcessEvents() == 1 )
239 ;
240
241 // it's necessary to call ProcessIdle() to update the frames sizes which
242 // might have been changed (it also will update other things set from
243 // OnUpdateUI() which is a nice (and desired) side effect)
244 while ( ProcessIdle() ) {}
245
246 // if there are pending events, we must process them.
247 if (wxTheApp)
248 wxTheApp->ProcessPendingEvents();
249
250 #if wxUSE_LOG
251 wxLog::Resume();
252 #endif // wxUSE_LOG
253 m_isInsideYield = false;
254
255 return true;
256 }
257
258 // implement/override base class pure virtual
259 bool wxCFEventLoop::Pending() const
260 {
261 return true;
262 }
263
264 int wxCFEventLoop::DoProcessEvents()
265 {
266 return DispatchTimeout( 1000 );
267 }
268
269 bool wxCFEventLoop::Dispatch()
270 {
271 return DoProcessEvents() != 0;
272 }
273
274 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
275 {
276 if ( !wxTheApp )
277 return 0;
278
279 int status = DoDispatchTimeout(timeout);
280
281 switch( status )
282 {
283 case 0:
284 break;
285 case -1:
286 if ( m_shouldExit )
287 return 0;
288
289 break;
290 case 1:
291 break;
292 }
293
294 return status;
295 }
296
297 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
298 {
299 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
300 switch( status )
301 {
302 case kCFRunLoopRunFinished:
303 wxFAIL_MSG( "incorrect run loop state" );
304 break;
305 case kCFRunLoopRunStopped:
306 return 0;
307 break;
308 case kCFRunLoopRunTimedOut:
309 return -1;
310 break;
311 case kCFRunLoopRunHandledSource:
312 default:
313 break;
314 }
315 return 1;
316 }
317
318 void wxCFEventLoop::DoRun()
319 {
320 for ( ;; )
321 {
322 // generate and process idle events for as long as we don't
323 // have anything else to do
324 DoProcessEvents();
325
326 // if the "should exit" flag is set, the loop should terminate
327 // but not before processing any remaining messages so while
328 // Pending() returns true, do process them
329 if ( m_shouldExit )
330 {
331 while ( DoProcessEvents() == 1 )
332 ;
333
334 break;
335 }
336 }
337 }
338
339 void wxCFEventLoop::DoStop()
340 {
341 CFRunLoopStop(CFGetCurrentRunLoop());
342 }
343
344 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
345 // terminating when Exit() is called
346 int wxCFEventLoop::Run()
347 {
348 // event loops are not recursive, you need to create another loop!
349 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
350
351 // ProcessIdle() and ProcessEvents() below may throw so the code here should
352 // be exception-safe, hence we must use local objects for all actions we
353 // should undo
354 wxEventLoopActivator activate(this);
355
356 // we must ensure that OnExit() is called even if an exception is thrown
357 // from inside ProcessEvents() but we must call it from Exit() in normal
358 // situations because it is supposed to be called synchronously,
359 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
360 // something similar here)
361 #if wxUSE_EXCEPTIONS
362 for ( ;; )
363 {
364 try
365 {
366 #endif // wxUSE_EXCEPTIONS
367
368 DoRun();
369
370 #if wxUSE_EXCEPTIONS
371 // exit the outer loop as well
372 break;
373 }
374 catch ( ... )
375 {
376 try
377 {
378 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
379 {
380 OnExit();
381 break;
382 }
383 //else: continue running the event loop
384 }
385 catch ( ... )
386 {
387 // OnException() throwed, possibly rethrowing the same
388 // exception again: very good, but we still need OnExit() to
389 // be called
390 OnExit();
391 throw;
392 }
393 }
394 }
395 #endif // wxUSE_EXCEPTIONS
396
397 return m_exitcode;
398 }
399
400 // sets the "should exit" flag and wakes up the loop so that it terminates
401 // soon
402 void wxCFEventLoop::Exit(int rc)
403 {
404 m_exitcode = rc;
405 m_shouldExit = true;
406 DoStop();
407 }
408
409 #if wxUSE_GUI
410
411 wxModalEventLoop::wxModalEventLoop(wxWindow *winModal)
412 {
413 m_modalWindow = dynamic_cast<wxNonOwnedWindow*> (winModal);
414 wxASSERT_MSG( m_modalWindow != NULL, "must pass in a toplevel window for modal event loop" );
415 }
416
417 #ifdef __WXOSX_IPHONE__
418
419 void wxModalEventLoop::DoRun()
420 {
421 // presentModalViewController:animated:
422 }
423
424 void wxModalEventLoop::DoStop()
425 {
426 // (void)dismissModalViewControllerAnimated:(BOOL)animated
427 }
428
429 #endif // wxUSE_GUI
430
431 #endif