Fix crash in wxCFEventLoop::AddSourceForFD().
[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 #include "wx/thread.h"
42
43 #if wxUSE_GUI
44 #include "wx/nonownedwnd.h"
45 #endif
46
47 // ============================================================================
48 // wxCFEventLoopSource and wxCFEventLoop implementation
49 // ============================================================================
50
51 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
52 namespace
53 {
54
55 void EnableDescriptorCallBacks(CFFileDescriptorRef cffd, int flags)
56 {
57 if ( flags & wxEVENT_SOURCE_INPUT )
58 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorReadCallBack);
59 if ( flags & wxEVENT_SOURCE_OUTPUT )
60 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorWriteCallBack);
61 }
62
63 void
64 wx_cffiledescriptor_callback(CFFileDescriptorRef cffd,
65 CFOptionFlags flags,
66 void *ctxData)
67 {
68 wxLogTrace(wxTRACE_EVT_SOURCE,
69 "CFFileDescriptor callback, flags=%d", flags);
70
71 wxCFEventLoopSource * const
72 source = static_cast<wxCFEventLoopSource *>(ctxData);
73
74 wxEventLoopSourceHandler * const
75 handler = source->GetHandler();
76 if ( flags & kCFFileDescriptorReadCallBack )
77 handler->OnReadWaiting();
78 if ( flags & kCFFileDescriptorWriteCallBack )
79 handler->OnWriteWaiting();
80
81 // we need to re-enable callbacks to be called again
82 EnableDescriptorCallBacks(cffd, source->GetFlags());
83 }
84
85 } // anonymous namespace
86
87 wxEventLoopSource *
88 wxCFEventLoop::AddSourceForFD(int fd,
89 wxEventLoopSourceHandler *handler,
90 int flags)
91 {
92 wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
93
94 wxScopedPtr<wxCFEventLoopSource>
95 source(new wxCFEventLoopSource(handler, flags));
96
97 CFFileDescriptorContext ctx = { 0, source.get(), NULL, NULL, NULL };
98 wxCFRef<CFFileDescriptorRef>
99 cffd(CFFileDescriptorCreate
100 (
101 kCFAllocatorDefault,
102 fd,
103 true, // close on invalidate
104 wx_cffiledescriptor_callback,
105 &ctx
106 ));
107 if ( !cffd )
108 return NULL;
109
110 wxCFRef<CFRunLoopSourceRef>
111 cfsrc(CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, cffd, 0));
112 if ( !cfsrc )
113 return NULL;
114
115 CFRunLoopRef cfloop = CFGetCurrentRunLoop();
116 CFRunLoopAddSource(cfloop, cfsrc, kCFRunLoopDefaultMode);
117
118 source->SetFileDescriptor(cffd.release());
119
120 return source.release();
121 }
122
123 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd)
124 {
125 wxASSERT_MSG( !m_cffd, "shouldn't be called more than once" );
126
127 m_cffd = cffd;
128 }
129
130 wxCFEventLoopSource::~wxCFEventLoopSource()
131 {
132 if ( m_cffd )
133 CFRelease(m_cffd);
134 }
135
136 #else // OS X < 10.5
137
138 wxEventLoopSource *
139 wxCFEventLoop::AddSourceForFD(int WXUNUSED(fd),
140 wxEventLoopSourceHandler * WXUNUSED(handler),
141 int WXUNUSED(flags))
142 {
143 return NULL;
144 }
145
146 #endif // MAC_OS_X_VERSION_MAX_ALLOWED
147
148 #endif // wxUSE_EVENTLOOP_SOURCE
149
150 extern "C" void wxObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
151 {
152 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
153 if ( eventloop )
154 eventloop->ObserverCallBack(observer, activity);
155 }
156
157 void wxCFEventLoop::ObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
158 {
159 if ( activity & kCFRunLoopBeforeTimers )
160 {
161 // process pending wx events first as they correspond to low-level events
162 // which happened before, i.e. typically pending events were queued by a
163 // previous call to Dispatch() and if we didn't process them now the next
164 // call to it might enqueue them again (as happens with e.g. socket events
165 // which would be generated as long as there is input available on socket
166 // and this input is only removed from it when pending event handlers are
167 // executed)
168
169 if ( wxTheApp )
170 wxTheApp->ProcessPendingEvents();
171 }
172
173 if ( activity & kCFRunLoopBeforeWaiting )
174 {
175 if ( ProcessIdle() )
176 {
177 WakeUp();
178 }
179 else
180 {
181 #if wxUSE_THREADS
182 wxMutexGuiLeaveOrEnter();
183 #endif
184 }
185 }
186 }
187
188 wxCFEventLoop::wxCFEventLoop()
189 {
190 m_shouldExit = false;
191
192 m_runLoop = CFGetCurrentRunLoop();
193
194 CFRunLoopObserverContext ctxt;
195 bzero( &ctxt, sizeof(ctxt) );
196 ctxt.info = this;
197 m_runLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
198 wxObserverCallBack, &ctxt );
199 CFRunLoopAddObserver(m_runLoop, m_runLoopObserver, kCFRunLoopCommonModes);
200 CFRelease(m_runLoopObserver);
201 }
202
203 wxCFEventLoop::~wxCFEventLoop()
204 {
205 CFRunLoopRemoveObserver(m_runLoop, m_runLoopObserver, kCFRunLoopCommonModes);
206 }
207
208
209 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
210 {
211 return CFRunLoopGetCurrent();
212 }
213
214 void wxCFEventLoop::WakeUp()
215 {
216 CFRunLoopWakeUp(m_runLoop);
217 }
218
219 #if wxUSE_BASE
220
221 void wxMacWakeUp()
222 {
223 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
224
225 if ( loop )
226 loop->WakeUp();
227 }
228
229 #endif
230
231 bool wxCFEventLoop::YieldFor(long eventsToProcess)
232 {
233 #if wxUSE_THREADS
234 // Yielding from a non-gui thread needs to bail out, otherwise we end up
235 // possibly sending events in the thread too.
236 if ( !wxThread::IsMain() )
237 {
238 return true;
239 }
240 #endif // wxUSE_THREADS
241
242 m_isInsideYield = true;
243 m_eventsToProcessInsideYield = eventsToProcess;
244
245 #if wxUSE_LOG
246 // disable log flushing from here because a call to wxYield() shouldn't
247 // normally result in message boxes popping up &c
248 wxLog::Suspend();
249 #endif // wxUSE_LOG
250
251 // process all pending events:
252 while ( DoProcessEvents() == 1 )
253 ;
254
255 // it's necessary to call ProcessIdle() to update the frames sizes which
256 // might have been changed (it also will update other things set from
257 // OnUpdateUI() which is a nice (and desired) side effect)
258 while ( ProcessIdle() ) {}
259
260 // if there are pending events, we must process them.
261 if (wxTheApp)
262 wxTheApp->ProcessPendingEvents();
263
264 #if wxUSE_LOG
265 wxLog::Resume();
266 #endif // wxUSE_LOG
267 m_isInsideYield = false;
268
269 return true;
270 }
271
272 // implement/override base class pure virtual
273 bool wxCFEventLoop::Pending() const
274 {
275 return true;
276 }
277
278 int wxCFEventLoop::DoProcessEvents()
279 {
280 return DispatchTimeout( 0 );
281 }
282
283 bool wxCFEventLoop::Dispatch()
284 {
285 return DoProcessEvents() != 0;
286 }
287
288 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
289 {
290 if ( !wxTheApp )
291 return 0;
292
293 int status = DoDispatchTimeout(timeout);
294
295 switch( status )
296 {
297 case 0:
298 break;
299 case -1:
300 if ( m_shouldExit )
301 return 0;
302
303 break;
304 case 1:
305 break;
306 }
307
308 return status;
309 }
310
311 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
312 {
313 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
314 switch( status )
315 {
316 case kCFRunLoopRunFinished:
317 wxFAIL_MSG( "incorrect run loop state" );
318 break;
319 case kCFRunLoopRunStopped:
320 return 0;
321 break;
322 case kCFRunLoopRunTimedOut:
323 return -1;
324 break;
325 case kCFRunLoopRunHandledSource:
326 default:
327 break;
328 }
329 return 1;
330 }
331
332 void wxCFEventLoop::DoRun()
333 {
334 for ( ;; )
335 {
336 // generate and process idle events for as long as we don't
337 // have anything else to do
338 DoProcessEvents();
339
340 // if the "should exit" flag is set, the loop should terminate
341 // but not before processing any remaining messages so while
342 // Pending() returns true, do process them
343 if ( m_shouldExit )
344 {
345 while ( DoProcessEvents() == 1 )
346 ;
347
348 break;
349 }
350 }
351 }
352
353 void wxCFEventLoop::DoStop()
354 {
355 CFRunLoopStop(CFGetCurrentRunLoop());
356 }
357
358 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
359 // terminating when Exit() is called
360 int wxCFEventLoop::Run()
361 {
362 // event loops are not recursive, you need to create another loop!
363 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
364
365 // ProcessIdle() and ProcessEvents() below may throw so the code here should
366 // be exception-safe, hence we must use local objects for all actions we
367 // should undo
368 wxEventLoopActivator activate(this);
369
370 // we must ensure that OnExit() is called even if an exception is thrown
371 // from inside ProcessEvents() but we must call it from Exit() in normal
372 // situations because it is supposed to be called synchronously,
373 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
374 // something similar here)
375 #if wxUSE_EXCEPTIONS
376 for ( ;; )
377 {
378 try
379 {
380 #endif // wxUSE_EXCEPTIONS
381
382 DoRun();
383
384 #if wxUSE_EXCEPTIONS
385 // exit the outer loop as well
386 break;
387 }
388 catch ( ... )
389 {
390 try
391 {
392 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
393 {
394 OnExit();
395 break;
396 }
397 //else: continue running the event loop
398 }
399 catch ( ... )
400 {
401 // OnException() throwed, possibly rethrowing the same
402 // exception again: very good, but we still need OnExit() to
403 // be called
404 OnExit();
405 throw;
406 }
407 }
408 }
409 #endif // wxUSE_EXCEPTIONS
410
411 return m_exitcode;
412 }
413
414 // sets the "should exit" flag and wakes up the loop so that it terminates
415 // soon
416 void wxCFEventLoop::Exit(int rc)
417 {
418 m_exitcode = rc;
419 m_shouldExit = true;
420 DoStop();
421 }
422
423 // TODO Move to thread_osx.cpp
424
425 #if wxUSE_THREADS
426
427 // ----------------------------------------------------------------------------
428 // GUI Serialization copied from MSW implementation
429 // ----------------------------------------------------------------------------
430
431 // if it's false, some secondary thread is holding the GUI lock
432 static bool gs_bGuiOwnedByMainThread = true;
433
434 // critical section which controls access to all GUI functions: any secondary
435 // thread (i.e. except the main one) must enter this crit section before doing
436 // any GUI calls
437 static wxCriticalSection *gs_critsectGui = NULL;
438
439 // critical section which protects gs_nWaitingForGui variable
440 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
441
442 // number of threads waiting for GUI in wxMutexGuiEnter()
443 static size_t gs_nWaitingForGui = 0;
444
445 void wxOSXThreadModuleOnInit()
446 {
447 gs_critsectWaitingForGui = new wxCriticalSection();
448 gs_critsectGui = new wxCriticalSection();
449 gs_critsectGui->Enter();
450 }
451
452
453 void wxOSXThreadModuleOnExit()
454 {
455 if ( gs_critsectGui )
456 {
457 if ( !wxGuiOwnedByMainThread() )
458 {
459 gs_critsectGui->Enter();
460 gs_bGuiOwnedByMainThread = true;
461 }
462
463 gs_critsectGui->Leave();
464 wxDELETE(gs_critsectGui);
465 }
466
467 wxDELETE(gs_critsectWaitingForGui);
468 }
469
470
471 // wake up the main thread
472 void WXDLLIMPEXP_BASE wxWakeUpMainThread()
473 {
474 wxMacWakeUp();
475 }
476
477 void wxMutexGuiEnterImpl()
478 {
479 // this would dead lock everything...
480 wxASSERT_MSG( !wxThread::IsMain(),
481 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
482
483 // the order in which we enter the critical sections here is crucial!!
484
485 // set the flag telling to the main thread that we want to do some GUI
486 {
487 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
488
489 gs_nWaitingForGui++;
490 }
491
492 wxWakeUpMainThread();
493
494 // now we may block here because the main thread will soon let us in
495 // (during the next iteration of OnIdle())
496 gs_critsectGui->Enter();
497 }
498
499 void wxMutexGuiLeaveImpl()
500 {
501 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
502
503 if ( wxThread::IsMain() )
504 {
505 gs_bGuiOwnedByMainThread = false;
506 }
507 else
508 {
509 // decrement the number of threads waiting for GUI access now
510 wxASSERT_MSG( gs_nWaitingForGui > 0,
511 wxT("calling wxMutexGuiLeave() without entering it first?") );
512
513 gs_nWaitingForGui--;
514
515 wxWakeUpMainThread();
516 }
517
518 gs_critsectGui->Leave();
519 }
520
521 void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
522 {
523 wxASSERT_MSG( wxThread::IsMain(),
524 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
525
526 if ( !gs_critsectWaitingForGui )
527 return;
528
529 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
530
531 if ( gs_nWaitingForGui == 0 )
532 {
533 // no threads are waiting for GUI - so we may acquire the lock without
534 // any danger (but only if we don't already have it)
535 if ( !wxGuiOwnedByMainThread() )
536 {
537 gs_critsectGui->Enter();
538
539 gs_bGuiOwnedByMainThread = true;
540 }
541 //else: already have it, nothing to do
542 }
543 else
544 {
545 // some threads are waiting, release the GUI lock if we have it
546 if ( wxGuiOwnedByMainThread() )
547 wxMutexGuiLeave();
548 //else: some other worker thread is doing GUI
549 }
550 }
551
552 bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
553 {
554 return gs_bGuiOwnedByMainThread;
555 }
556
557 #endif