1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/core/evtloop_cf.cpp
3 // Purpose: wxEventLoop implementation common to both Carbon and Cocoa
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 2009 Vadim Zeitlin <vadim@wxwidgets.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 #include "wx/evtloop.h"
28 #if wxUSE_EVENTLOOP_SOURCE
35 #include "wx/evtloopsrc.h"
37 #include "wx/scopedptr.h"
39 #include "wx/osx/private.h"
40 #include "wx/osx/core/cfref.h"
41 #include "wx/thread.h"
44 #include "wx/nonownedwnd.h"
47 // ============================================================================
48 // wxCFEventLoopSource and wxCFEventLoop implementation
49 // ============================================================================
51 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
55 void EnableDescriptorCallBacks(CFFileDescriptorRef cffd
, int flags
)
57 if ( flags
& wxEVENT_SOURCE_INPUT
)
58 CFFileDescriptorEnableCallBacks(cffd
, kCFFileDescriptorReadCallBack
);
59 if ( flags
& wxEVENT_SOURCE_OUTPUT
)
60 CFFileDescriptorEnableCallBacks(cffd
, kCFFileDescriptorWriteCallBack
);
64 wx_cffiledescriptor_callback(CFFileDescriptorRef cffd
,
68 wxLogTrace(wxTRACE_EVT_SOURCE
,
69 "CFFileDescriptor callback, flags=%d", flags
);
71 wxCFEventLoopSource
* const
72 source
= static_cast<wxCFEventLoopSource
*>(ctxData
);
74 wxEventLoopSourceHandler
* const
75 handler
= source
->GetHandler();
76 if ( flags
& kCFFileDescriptorReadCallBack
)
77 handler
->OnReadWaiting();
78 if ( flags
& kCFFileDescriptorWriteCallBack
)
79 handler
->OnWriteWaiting();
81 // we need to re-enable callbacks to be called again
82 EnableDescriptorCallBacks(cffd
, source
->GetFlags());
85 } // anonymous namespace
88 wxCFEventLoop::AddSourceForFD(int fd
,
89 wxEventLoopSourceHandler
*handler
,
92 wxCHECK_MSG( fd
!= -1, NULL
, "can't monitor invalid fd" );
94 wxScopedPtr
<wxCFEventLoopSource
>
95 source(new wxCFEventLoopSource(handler
, flags
));
97 CFFileDescriptorContext ctx
= { 0, source
.get(), NULL
, NULL
, NULL
};
98 wxCFRef
<CFFileDescriptorRef
>
99 cffd(CFFileDescriptorCreate
103 true, // close on invalidate
104 wx_cffiledescriptor_callback
,
110 wxCFRef
<CFRunLoopSourceRef
>
111 cfsrc(CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault
, cffd
, 0));
115 CFRunLoopRef cfloop
= CFGetCurrentRunLoop();
116 CFRunLoopAddSource(cfloop
, cfsrc
, kCFRunLoopDefaultMode
);
118 source
->SetFileDescriptor(cffd
.release());
120 return source
.release();
123 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd
)
125 wxASSERT_MSG( !m_cffd
, "shouldn't be called more than once" );
130 wxCFEventLoopSource::~wxCFEventLoopSource()
139 wxCFEventLoop::AddSourceForFD(int WXUNUSED(fd
),
140 wxEventLoopSourceHandler
* WXUNUSED(handler
),
146 #endif // MAC_OS_X_VERSION_MAX_ALLOWED
148 #endif // wxUSE_EVENTLOOP_SOURCE
150 extern "C" void wxObserverCallBack(CFRunLoopObserverRef observer
, CFRunLoopActivity activity
, void *info
)
152 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
154 eventloop
->ObserverCallBack(observer
, activity
);
157 void wxCFEventLoop::ObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
159 if ( activity
& kCFRunLoopBeforeTimers
)
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
170 wxTheApp
->ProcessPendingEvents();
173 if ( activity
& kCFRunLoopBeforeWaiting
)
182 wxMutexGuiLeaveOrEnter();
188 wxCFEventLoop::wxCFEventLoop()
190 m_shouldExit
= false;
192 m_runLoop
= CFGetCurrentRunLoop();
194 CFRunLoopObserverContext ctxt
;
195 bzero( &ctxt
, sizeof(ctxt
) );
197 m_runLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
198 wxObserverCallBack
, &ctxt
);
199 CFRunLoopAddObserver(m_runLoop
, m_runLoopObserver
, kCFRunLoopCommonModes
);
200 CFRelease(m_runLoopObserver
);
203 wxCFEventLoop::~wxCFEventLoop()
205 CFRunLoopRemoveObserver(m_runLoop
, m_runLoopObserver
, kCFRunLoopCommonModes
);
209 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
211 return CFRunLoopGetCurrent();
214 void wxCFEventLoop::WakeUp()
216 CFRunLoopWakeUp(m_runLoop
);
223 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
231 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
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() )
240 #endif // wxUSE_THREADS
242 m_isInsideYield
= true;
243 m_eventsToProcessInsideYield
= eventsToProcess
;
246 // disable log flushing from here because a call to wxYield() shouldn't
247 // normally result in message boxes popping up &c
251 // process all pending events:
252 while ( DoProcessEvents() == 1 )
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() ) {}
260 // if there are pending events, we must process them.
262 wxTheApp
->ProcessPendingEvents();
267 m_isInsideYield
= false;
272 // implement/override base class pure virtual
273 bool wxCFEventLoop::Pending() const
278 int wxCFEventLoop::DoProcessEvents()
280 return DispatchTimeout( 0 );
283 bool wxCFEventLoop::Dispatch()
285 return DoProcessEvents() != 0;
288 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
293 int status
= DoDispatchTimeout(timeout
);
311 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
313 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
316 case kCFRunLoopRunFinished
:
317 wxFAIL_MSG( "incorrect run loop state" );
319 case kCFRunLoopRunStopped
:
322 case kCFRunLoopRunTimedOut
:
325 case kCFRunLoopRunHandledSource
:
332 void wxCFEventLoop::DoRun()
336 // generate and process idle events for as long as we don't
337 // have anything else to do
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
345 while ( DoProcessEvents() == 1 )
353 void wxCFEventLoop::DoStop()
355 CFRunLoopStop(CFGetCurrentRunLoop());
358 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
359 // terminating when Exit() is called
360 int wxCFEventLoop::Run()
362 // event loops are not recursive, you need to create another loop!
363 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
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
368 wxEventLoopActivator
activate(this);
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)
380 #endif // wxUSE_EXCEPTIONS
385 // exit the outer loop as well
392 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
397 //else: continue running the event loop
401 // OnException() throwed, possibly rethrowing the same
402 // exception again: very good, but we still need OnExit() to
409 #endif // wxUSE_EXCEPTIONS
414 // sets the "should exit" flag and wakes up the loop so that it terminates
416 void wxCFEventLoop::Exit(int rc
)
423 // TODO Move to thread_osx.cpp
427 // ----------------------------------------------------------------------------
428 // GUI Serialization copied from MSW implementation
429 // ----------------------------------------------------------------------------
431 // if it's false, some secondary thread is holding the GUI lock
432 static bool gs_bGuiOwnedByMainThread
= true;
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
437 static wxCriticalSection
*gs_critsectGui
= NULL
;
439 // critical section which protects gs_nWaitingForGui variable
440 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
442 // number of threads waiting for GUI in wxMutexGuiEnter()
443 static size_t gs_nWaitingForGui
= 0;
445 void wxOSXThreadModuleOnInit()
447 gs_critsectWaitingForGui
= new wxCriticalSection();
448 gs_critsectGui
= new wxCriticalSection();
449 gs_critsectGui
->Enter();
453 void wxOSXThreadModuleOnExit()
455 if ( gs_critsectGui
)
457 if ( !wxGuiOwnedByMainThread() )
459 gs_critsectGui
->Enter();
460 gs_bGuiOwnedByMainThread
= true;
463 gs_critsectGui
->Leave();
464 wxDELETE(gs_critsectGui
);
467 wxDELETE(gs_critsectWaitingForGui
);
471 // wake up the main thread
472 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
477 void wxMutexGuiEnterImpl()
479 // this would dead lock everything...
480 wxASSERT_MSG( !wxThread::IsMain(),
481 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
483 // the order in which we enter the critical sections here is crucial!!
485 // set the flag telling to the main thread that we want to do some GUI
487 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
492 wxWakeUpMainThread();
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();
499 void wxMutexGuiLeaveImpl()
501 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
503 if ( wxThread::IsMain() )
505 gs_bGuiOwnedByMainThread
= false;
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?") );
515 wxWakeUpMainThread();
518 gs_critsectGui
->Leave();
521 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
523 wxASSERT_MSG( wxThread::IsMain(),
524 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
526 if ( !gs_critsectWaitingForGui
)
529 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
531 if ( gs_nWaitingForGui
== 0 )
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() )
537 gs_critsectGui
->Enter();
539 gs_bGuiOwnedByMainThread
= true;
541 //else: already have it, nothing to do
545 // some threads are waiting, release the GUI lock if we have it
546 if ( wxGuiOwnedByMainThread() )
548 //else: some other worker thread is doing GUI
552 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
554 return gs_bGuiOwnedByMainThread
;