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"
33 #include "wx/evtloopsrc.h"
35 #include "wx/scopedptr.h"
37 #include "wx/osx/private.h"
38 #include "wx/osx/core/cfref.h"
39 #include "wx/thread.h"
42 #include "wx/nonownedwnd.h"
45 // ============================================================================
46 // wxCFEventLoopSource and wxCFEventLoop implementation
47 // ============================================================================
49 #if wxUSE_EVENTLOOP_SOURCE
51 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd
)
53 wxASSERT_MSG( !m_cffd
, "shouldn't be called more than once" );
58 wxCFEventLoopSource::~wxCFEventLoopSource()
64 #endif // wxUSE_EVENTLOOP_SOURCE
66 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
68 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
70 eventloop
->CommonModeObserverCallBack(observer
, activity
);
73 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
75 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
77 eventloop
->DefaultModeObserverCallBack(observer
, activity
);
80 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
82 if ( activity
& kCFRunLoopBeforeTimers
)
84 // process pending wx events first as they correspond to low-level events
85 // which happened before, i.e. typically pending events were queued by a
86 // previous call to Dispatch() and if we didn't process them now the next
87 // call to it might enqueue them again (as happens with e.g. socket events
88 // which would be generated as long as there is input available on socket
89 // and this input is only removed from it when pending event handlers are
92 if ( wxTheApp
&& ShouldProcessIdleEvents() )
93 wxTheApp
->ProcessPendingEvents();
96 if ( activity
& kCFRunLoopBeforeWaiting
)
98 if ( ShouldProcessIdleEvents() && ProcessIdle() )
105 wxMutexGuiLeaveOrEnter();
112 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
),
113 int WXUNUSED(activity
))
116 if ( activity & kCFRunLoopBeforeTimers )
120 if ( activity & kCFRunLoopBeforeWaiting )
127 wxCFEventLoop::wxCFEventLoop()
129 m_shouldExit
= false;
130 m_processIdleEvents
= true;
132 #if wxUSE_UIACTIONSIMULATOR
133 m_shouldWaitForEvent
= false;
136 m_runLoop
= CFGetCurrentRunLoop();
138 CFRunLoopObserverContext ctxt
;
139 bzero( &ctxt
, sizeof(ctxt
) );
141 m_commonModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
142 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXCommonModeObserverCallBack
, &ctxt
);
143 CFRunLoopAddObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
145 m_defaultModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
146 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXDefaultModeObserverCallBack
, &ctxt
);
147 CFRunLoopAddObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
150 wxCFEventLoop::~wxCFEventLoop()
152 CFRunLoopRemoveObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
153 CFRunLoopRemoveObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
155 CFRelease(m_defaultModeRunLoopObserver
);
156 CFRelease(m_commonModeRunLoopObserver
);
160 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
162 return CFRunLoopGetCurrent();
165 void wxCFEventLoop::WakeUp()
167 CFRunLoopWakeUp(m_runLoop
);
174 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
182 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
185 // Yielding from a non-gui thread needs to bail out, otherwise we end up
186 // possibly sending events in the thread too.
187 if ( !wxThread::IsMain() )
191 #endif // wxUSE_THREADS
193 m_isInsideYield
= true;
194 m_eventsToProcessInsideYield
= eventsToProcess
;
197 // disable log flushing from here because a call to wxYield() shouldn't
198 // normally result in message boxes popping up &c
202 // process all pending events:
203 while ( DoProcessEvents() == 1 )
206 // it's necessary to call ProcessIdle() to update the frames sizes which
207 // might have been changed (it also will update other things set from
208 // OnUpdateUI() which is a nice (and desired) side effect)
209 while ( ProcessIdle() ) {}
211 // if there are pending events, we must process them.
213 wxTheApp
->ProcessPendingEvents();
218 m_isInsideYield
= false;
223 // implement/override base class pure virtual
224 bool wxCFEventLoop::Pending() const
229 int wxCFEventLoop::DoProcessEvents()
231 #if wxUSE_UIACTIONSIMULATOR
232 if ( m_shouldWaitForEvent
)
234 int handled
= DispatchTimeout( 1000 );
235 wxASSERT_MSG( handled
== 1, "No Event Available");
236 m_shouldWaitForEvent
= false;
241 return DispatchTimeout( 0 );
244 bool wxCFEventLoop::Dispatch()
246 return DoProcessEvents() != 0;
249 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
254 int status
= DoDispatchTimeout(timeout
);
272 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
274 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
277 case kCFRunLoopRunFinished
:
278 wxFAIL_MSG( "incorrect run loop state" );
280 case kCFRunLoopRunStopped
:
283 case kCFRunLoopRunTimedOut
:
286 case kCFRunLoopRunHandledSource
:
293 void wxCFEventLoop::OSXDoRun()
297 // generate and process idle events for as long as we don't
298 // have anything else to do
301 // if the "should exit" flag is set, the loop should terminate
302 // but not before processing any remaining messages so while
303 // Pending() returns true, do process them
306 while ( DoProcessEvents() == 1 )
314 void wxCFEventLoop::OSXDoStop()
316 CFRunLoopStop(CFGetCurrentRunLoop());
319 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
320 // terminating when Exit() is called
321 int wxCFEventLoop::DoRun()
323 // we must ensure that OnExit() is called even if an exception is thrown
324 // from inside ProcessEvents() but we must call it from Exit() in normal
325 // situations because it is supposed to be called synchronously,
326 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
327 // something similar here)
333 #endif // wxUSE_EXCEPTIONS
338 // exit the outer loop as well
345 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
350 //else: continue running the event loop
354 // OnException() throwed, possibly rethrowing the same
355 // exception again: very good, but we still need OnExit() to
362 #endif // wxUSE_EXCEPTIONS
367 // sets the "should exit" flag and wakes up the loop so that it terminates
369 void wxCFEventLoop::ScheduleExit(int rc
)
376 wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
378 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
381 m_formerState
= cfl
->ShouldProcessIdleEvents();
382 cfl
->SetProcessIdleEvents(false);
385 m_formerState
= true;
388 wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
390 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
392 cfl
->SetProcessIdleEvents(m_formerState
);
395 // TODO Move to thread_osx.cpp
399 // ----------------------------------------------------------------------------
400 // GUI Serialization copied from MSW implementation
401 // ----------------------------------------------------------------------------
403 // if it's false, some secondary thread is holding the GUI lock
404 static bool gs_bGuiOwnedByMainThread
= true;
406 // critical section which controls access to all GUI functions: any secondary
407 // thread (i.e. except the main one) must enter this crit section before doing
409 static wxCriticalSection
*gs_critsectGui
= NULL
;
411 // critical section which protects gs_nWaitingForGui variable
412 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
414 // number of threads waiting for GUI in wxMutexGuiEnter()
415 static size_t gs_nWaitingForGui
= 0;
417 void wxOSXThreadModuleOnInit()
419 gs_critsectWaitingForGui
= new wxCriticalSection();
420 gs_critsectGui
= new wxCriticalSection();
421 gs_critsectGui
->Enter();
425 void wxOSXThreadModuleOnExit()
427 if ( gs_critsectGui
)
429 if ( !wxGuiOwnedByMainThread() )
431 gs_critsectGui
->Enter();
432 gs_bGuiOwnedByMainThread
= true;
435 gs_critsectGui
->Leave();
436 wxDELETE(gs_critsectGui
);
439 wxDELETE(gs_critsectWaitingForGui
);
443 // wake up the main thread
444 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
449 void wxMutexGuiEnterImpl()
451 // this would dead lock everything...
452 wxASSERT_MSG( !wxThread::IsMain(),
453 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
455 // the order in which we enter the critical sections here is crucial!!
457 // set the flag telling to the main thread that we want to do some GUI
459 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
464 wxWakeUpMainThread();
466 // now we may block here because the main thread will soon let us in
467 // (during the next iteration of OnIdle())
468 gs_critsectGui
->Enter();
471 void wxMutexGuiLeaveImpl()
473 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
475 if ( wxThread::IsMain() )
477 gs_bGuiOwnedByMainThread
= false;
481 // decrement the number of threads waiting for GUI access now
482 wxASSERT_MSG( gs_nWaitingForGui
> 0,
483 wxT("calling wxMutexGuiLeave() without entering it first?") );
487 wxWakeUpMainThread();
490 gs_critsectGui
->Leave();
493 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
495 wxASSERT_MSG( wxThread::IsMain(),
496 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
498 if ( !gs_critsectWaitingForGui
)
501 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
503 if ( gs_nWaitingForGui
== 0 )
505 // no threads are waiting for GUI - so we may acquire the lock without
506 // any danger (but only if we don't already have it)
507 if ( !wxGuiOwnedByMainThread() )
509 gs_critsectGui
->Enter();
511 gs_bGuiOwnedByMainThread
= true;
513 //else: already have it, nothing to do
517 // some threads are waiting, release the GUI lock if we have it
518 if ( wxGuiOwnedByMainThread() )
520 //else: some other worker thread is doing GUI
524 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
526 return gs_bGuiOwnedByMainThread
;