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 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
152 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
154 eventloop
->CommonModeObserverCallBack(observer
, activity
);
157 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
159 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
161 eventloop
->DefaultModeObserverCallBack(observer
, activity
);
164 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
166 if ( activity
& kCFRunLoopBeforeTimers
)
168 // process pending wx events first as they correspond to low-level events
169 // which happened before, i.e. typically pending events were queued by a
170 // previous call to Dispatch() and if we didn't process them now the next
171 // call to it might enqueue them again (as happens with e.g. socket events
172 // which would be generated as long as there is input available on socket
173 // and this input is only removed from it when pending event handlers are
177 wxTheApp
->ProcessPendingEvents();
180 if ( activity
& kCFRunLoopBeforeWaiting
)
183 wxMutexGuiLeaveOrEnter();
188 void wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
190 if ( activity
& kCFRunLoopBeforeTimers
)
194 if ( activity
& kCFRunLoopBeforeWaiting
)
204 wxCFEventLoop::wxCFEventLoop()
206 m_shouldExit
= false;
208 m_runLoop
= CFGetCurrentRunLoop();
210 CFRunLoopObserverContext ctxt
;
211 bzero( &ctxt
, sizeof(ctxt
) );
213 m_commonModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
214 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXCommonModeObserverCallBack
, &ctxt
);
215 CFRunLoopAddObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
216 CFRelease(m_commonModeRunLoopObserver
);
218 m_defaultModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
219 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXDefaultModeObserverCallBack
, &ctxt
);
220 CFRunLoopAddObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
221 CFRelease(m_defaultModeRunLoopObserver
);
224 wxCFEventLoop::~wxCFEventLoop()
226 CFRunLoopRemoveObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
227 CFRunLoopRemoveObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
231 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
233 return CFRunLoopGetCurrent();
236 void wxCFEventLoop::WakeUp()
238 CFRunLoopWakeUp(m_runLoop
);
245 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
253 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
256 // Yielding from a non-gui thread needs to bail out, otherwise we end up
257 // possibly sending events in the thread too.
258 if ( !wxThread::IsMain() )
262 #endif // wxUSE_THREADS
264 m_isInsideYield
= true;
265 m_eventsToProcessInsideYield
= eventsToProcess
;
268 // disable log flushing from here because a call to wxYield() shouldn't
269 // normally result in message boxes popping up &c
273 // process all pending events:
274 while ( DoProcessEvents() == 1 )
277 // it's necessary to call ProcessIdle() to update the frames sizes which
278 // might have been changed (it also will update other things set from
279 // OnUpdateUI() which is a nice (and desired) side effect)
280 while ( ProcessIdle() ) {}
282 // if there are pending events, we must process them.
284 wxTheApp
->ProcessPendingEvents();
289 m_isInsideYield
= false;
294 // implement/override base class pure virtual
295 bool wxCFEventLoop::Pending() const
300 int wxCFEventLoop::DoProcessEvents()
302 return DispatchTimeout( 0 );
305 bool wxCFEventLoop::Dispatch()
307 return DoProcessEvents() != 0;
310 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
315 int status
= DoDispatchTimeout(timeout
);
333 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
335 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
338 case kCFRunLoopRunFinished
:
339 wxFAIL_MSG( "incorrect run loop state" );
341 case kCFRunLoopRunStopped
:
344 case kCFRunLoopRunTimedOut
:
347 case kCFRunLoopRunHandledSource
:
354 void wxCFEventLoop::DoRun()
358 // generate and process idle events for as long as we don't
359 // have anything else to do
362 // if the "should exit" flag is set, the loop should terminate
363 // but not before processing any remaining messages so while
364 // Pending() returns true, do process them
367 while ( DoProcessEvents() == 1 )
375 void wxCFEventLoop::DoStop()
377 CFRunLoopStop(CFGetCurrentRunLoop());
380 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
381 // terminating when Exit() is called
382 int wxCFEventLoop::Run()
384 // event loops are not recursive, you need to create another loop!
385 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
387 // ProcessIdle() and ProcessEvents() below may throw so the code here should
388 // be exception-safe, hence we must use local objects for all actions we
390 wxEventLoopActivator
activate(this);
392 // we must ensure that OnExit() is called even if an exception is thrown
393 // from inside ProcessEvents() but we must call it from Exit() in normal
394 // situations because it is supposed to be called synchronously,
395 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
396 // something similar here)
402 #endif // wxUSE_EXCEPTIONS
407 // exit the outer loop as well
414 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
419 //else: continue running the event loop
423 // OnException() throwed, possibly rethrowing the same
424 // exception again: very good, but we still need OnExit() to
431 #endif // wxUSE_EXCEPTIONS
436 // sets the "should exit" flag and wakes up the loop so that it terminates
438 void wxCFEventLoop::Exit(int rc
)
445 // TODO Move to thread_osx.cpp
449 // ----------------------------------------------------------------------------
450 // GUI Serialization copied from MSW implementation
451 // ----------------------------------------------------------------------------
453 // if it's false, some secondary thread is holding the GUI lock
454 static bool gs_bGuiOwnedByMainThread
= true;
456 // critical section which controls access to all GUI functions: any secondary
457 // thread (i.e. except the main one) must enter this crit section before doing
459 static wxCriticalSection
*gs_critsectGui
= NULL
;
461 // critical section which protects gs_nWaitingForGui variable
462 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
464 // number of threads waiting for GUI in wxMutexGuiEnter()
465 static size_t gs_nWaitingForGui
= 0;
467 void wxOSXThreadModuleOnInit()
469 gs_critsectWaitingForGui
= new wxCriticalSection();
470 gs_critsectGui
= new wxCriticalSection();
471 gs_critsectGui
->Enter();
475 void wxOSXThreadModuleOnExit()
477 if ( gs_critsectGui
)
479 if ( !wxGuiOwnedByMainThread() )
481 gs_critsectGui
->Enter();
482 gs_bGuiOwnedByMainThread
= true;
485 gs_critsectGui
->Leave();
486 wxDELETE(gs_critsectGui
);
489 wxDELETE(gs_critsectWaitingForGui
);
493 // wake up the main thread
494 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
499 void wxMutexGuiEnterImpl()
501 // this would dead lock everything...
502 wxASSERT_MSG( !wxThread::IsMain(),
503 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
505 // the order in which we enter the critical sections here is crucial!!
507 // set the flag telling to the main thread that we want to do some GUI
509 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
514 wxWakeUpMainThread();
516 // now we may block here because the main thread will soon let us in
517 // (during the next iteration of OnIdle())
518 gs_critsectGui
->Enter();
521 void wxMutexGuiLeaveImpl()
523 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
525 if ( wxThread::IsMain() )
527 gs_bGuiOwnedByMainThread
= false;
531 // decrement the number of threads waiting for GUI access now
532 wxASSERT_MSG( gs_nWaitingForGui
> 0,
533 wxT("calling wxMutexGuiLeave() without entering it first?") );
537 wxWakeUpMainThread();
540 gs_critsectGui
->Leave();
543 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
545 wxASSERT_MSG( wxThread::IsMain(),
546 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
548 if ( !gs_critsectWaitingForGui
)
551 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
553 if ( gs_nWaitingForGui
== 0 )
555 // no threads are waiting for GUI - so we may acquire the lock without
556 // any danger (but only if we don't already have it)
557 if ( !wxGuiOwnedByMainThread() )
559 gs_critsectGui
->Enter();
561 gs_bGuiOwnedByMainThread
= true;
563 //else: already have it, nothing to do
567 // some threads are waiting, release the GUI lock if we have it
568 if ( wxGuiOwnedByMainThread() )
570 //else: some other worker thread is doing GUI
574 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
576 return gs_bGuiOwnedByMainThread
;