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