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 // (c) 2013 Rob Bresalier
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #include "wx/evtloop.h"
34 #include "wx/evtloopsrc.h"
36 #include "wx/scopedptr.h"
38 #include "wx/osx/private.h"
39 #include "wx/osx/core/cfref.h"
40 #include "wx/thread.h"
43 #include "wx/nonownedwnd.h"
46 #include <CoreFoundation/CFSocket.h>
48 // ============================================================================
49 // wxCFEventLoopSource and wxCFEventLoop implementation
50 // ============================================================================
52 #if wxUSE_EVENTLOOP_SOURCE
54 void wxCFEventLoopSource::InitSourceSocket(CFSocketRef cfSocket
)
56 wxASSERT_MSG( !m_cfSocket
, "shouldn't be called more than once" );
58 m_cfSocket
= cfSocket
;
61 wxCFEventLoopSource::~wxCFEventLoopSource()
65 CFSocketInvalidate(m_cfSocket
);
66 CFRelease(m_cfSocket
);
70 #endif // wxUSE_EVENTLOOP_SOURCE
72 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
74 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
76 eventloop
->CommonModeObserverCallBack(observer
, activity
);
79 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
81 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
83 eventloop
->DefaultModeObserverCallBack(observer
, activity
);
86 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
88 if ( activity
& kCFRunLoopBeforeTimers
)
90 // process pending wx events first as they correspond to low-level events
91 // which happened before, i.e. typically pending events were queued by a
92 // previous call to Dispatch() and if we didn't process them now the next
93 // call to it might enqueue them again (as happens with e.g. socket events
94 // which would be generated as long as there is input available on socket
95 // and this input is only removed from it when pending event handlers are
98 if ( wxTheApp
&& ShouldProcessIdleEvents() )
99 wxTheApp
->ProcessPendingEvents();
102 if ( activity
& kCFRunLoopBeforeWaiting
)
104 if ( ShouldProcessIdleEvents() && ProcessIdle() )
111 wxMutexGuiLeaveOrEnter();
118 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
),
119 int WXUNUSED(activity
))
122 if ( activity & kCFRunLoopBeforeTimers )
126 if ( activity & kCFRunLoopBeforeWaiting )
133 wxCFEventLoop::wxCFEventLoop()
135 m_shouldExit
= false;
136 m_processIdleEvents
= true;
138 #if wxUSE_UIACTIONSIMULATOR
139 m_shouldWaitForEvent
= false;
142 m_runLoop
= CFGetCurrentRunLoop();
144 CFRunLoopObserverContext ctxt
;
145 bzero( &ctxt
, sizeof(ctxt
) );
147 m_commonModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
148 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXCommonModeObserverCallBack
, &ctxt
);
149 CFRunLoopAddObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
151 m_defaultModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
152 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXDefaultModeObserverCallBack
, &ctxt
);
153 CFRunLoopAddObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
156 wxCFEventLoop::~wxCFEventLoop()
158 CFRunLoopRemoveObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
159 CFRunLoopRemoveObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
161 CFRelease(m_defaultModeRunLoopObserver
);
162 CFRelease(m_commonModeRunLoopObserver
);
166 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
168 return CFRunLoopGetCurrent();
171 void wxCFEventLoop::WakeUp()
173 CFRunLoopWakeUp(m_runLoop
);
180 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
188 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
191 // Yielding from a non-gui thread needs to bail out, otherwise we end up
192 // possibly sending events in the thread too.
193 if ( !wxThread::IsMain() )
197 #endif // wxUSE_THREADS
199 m_isInsideYield
= true;
200 m_eventsToProcessInsideYield
= eventsToProcess
;
203 // disable log flushing from here because a call to wxYield() shouldn't
204 // normally result in message boxes popping up &c
208 // process all pending events:
209 while ( DoProcessEvents() == 1 )
212 // it's necessary to call ProcessIdle() to update the frames sizes which
213 // might have been changed (it also will update other things set from
214 // OnUpdateUI() which is a nice (and desired) side effect)
215 while ( ProcessIdle() ) {}
217 // if there are pending events, we must process them.
219 wxTheApp
->ProcessPendingEvents();
224 m_isInsideYield
= false;
229 // implement/override base class pure virtual
230 bool wxCFEventLoop::Pending() const
235 int wxCFEventLoop::DoProcessEvents()
237 #if wxUSE_UIACTIONSIMULATOR
238 if ( m_shouldWaitForEvent
)
240 int handled
= DispatchTimeout( 1000 );
241 wxASSERT_MSG( handled
== 1, "No Event Available");
242 m_shouldWaitForEvent
= false;
247 return DispatchTimeout( 0 );
250 bool wxCFEventLoop::Dispatch()
252 return DoProcessEvents() != 0;
255 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
260 int status
= DoDispatchTimeout(timeout
);
278 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
280 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
283 case kCFRunLoopRunFinished
:
284 wxFAIL_MSG( "incorrect run loop state" );
286 case kCFRunLoopRunStopped
:
289 case kCFRunLoopRunTimedOut
:
292 case kCFRunLoopRunHandledSource
:
299 void wxCFEventLoop::OSXDoRun()
303 // generate and process idle events for as long as we don't
304 // have anything else to do
307 // if the "should exit" flag is set, the loop should terminate
308 // but not before processing any remaining messages so while
309 // Pending() returns true, do process them
312 while ( DoProcessEvents() == 1 )
320 void wxCFEventLoop::OSXDoStop()
322 CFRunLoopStop(CFGetCurrentRunLoop());
325 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
326 // terminating when Exit() is called
327 int wxCFEventLoop::DoRun()
329 // we must ensure that OnExit() is called even if an exception is thrown
330 // from inside ProcessEvents() but we must call it from Exit() in normal
331 // situations because it is supposed to be called synchronously,
332 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
333 // something similar here)
339 #endif // wxUSE_EXCEPTIONS
344 // exit the outer loop as well
351 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
356 //else: continue running the event loop
360 // OnException() throwed, possibly rethrowing the same
361 // exception again: very good, but we still need OnExit() to
368 #endif // wxUSE_EXCEPTIONS
373 // sets the "should exit" flag and wakes up the loop so that it terminates
375 void wxCFEventLoop::ScheduleExit(int rc
)
382 wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
384 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
387 m_formerState
= cfl
->ShouldProcessIdleEvents();
388 cfl
->SetProcessIdleEvents(false);
391 m_formerState
= true;
394 wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
396 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
398 cfl
->SetProcessIdleEvents(m_formerState
);
401 // TODO Move to thread_osx.cpp
405 // ----------------------------------------------------------------------------
406 // GUI Serialization copied from MSW implementation
407 // ----------------------------------------------------------------------------
409 // if it's false, some secondary thread is holding the GUI lock
410 static bool gs_bGuiOwnedByMainThread
= true;
412 // critical section which controls access to all GUI functions: any secondary
413 // thread (i.e. except the main one) must enter this crit section before doing
415 static wxCriticalSection
*gs_critsectGui
= NULL
;
417 // critical section which protects gs_nWaitingForGui variable
418 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
420 // number of threads waiting for GUI in wxMutexGuiEnter()
421 static size_t gs_nWaitingForGui
= 0;
423 void wxOSXThreadModuleOnInit()
425 gs_critsectWaitingForGui
= new wxCriticalSection();
426 gs_critsectGui
= new wxCriticalSection();
427 gs_critsectGui
->Enter();
431 void wxOSXThreadModuleOnExit()
433 if ( gs_critsectGui
)
435 if ( !wxGuiOwnedByMainThread() )
437 gs_critsectGui
->Enter();
438 gs_bGuiOwnedByMainThread
= true;
441 gs_critsectGui
->Leave();
442 wxDELETE(gs_critsectGui
);
445 wxDELETE(gs_critsectWaitingForGui
);
449 // wake up the main thread
450 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
455 void wxMutexGuiEnterImpl()
457 // this would dead lock everything...
458 wxASSERT_MSG( !wxThread::IsMain(),
459 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
461 // the order in which we enter the critical sections here is crucial!!
463 // set the flag telling to the main thread that we want to do some GUI
465 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
470 wxWakeUpMainThread();
472 // now we may block here because the main thread will soon let us in
473 // (during the next iteration of OnIdle())
474 gs_critsectGui
->Enter();
477 void wxMutexGuiLeaveImpl()
479 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
481 if ( wxThread::IsMain() )
483 gs_bGuiOwnedByMainThread
= false;
487 // decrement the number of threads waiting for GUI access now
488 wxASSERT_MSG( gs_nWaitingForGui
> 0,
489 wxT("calling wxMutexGuiLeave() without entering it first?") );
493 wxWakeUpMainThread();
496 gs_critsectGui
->Leave();
499 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
501 wxASSERT_MSG( wxThread::IsMain(),
502 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
504 if ( !gs_critsectWaitingForGui
)
507 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
509 if ( gs_nWaitingForGui
== 0 )
511 // no threads are waiting for GUI - so we may acquire the lock without
512 // any danger (but only if we don't already have it)
513 if ( !wxGuiOwnedByMainThread() )
515 gs_critsectGui
->Enter();
517 gs_bGuiOwnedByMainThread
= true;
519 //else: already have it, nothing to do
523 // some threads are waiting, release the GUI lock if we have it
524 if ( wxGuiOwnedByMainThread() )
526 //else: some other worker thread is doing GUI
530 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
532 return gs_bGuiOwnedByMainThread
;