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