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
54 void EnableDescriptorCallBacks(CFFileDescriptorRef cffd
, int flags
)
56 if ( flags
& wxEVENT_SOURCE_INPUT
)
57 CFFileDescriptorEnableCallBacks(cffd
, kCFFileDescriptorReadCallBack
);
58 if ( flags
& wxEVENT_SOURCE_OUTPUT
)
59 CFFileDescriptorEnableCallBacks(cffd
, kCFFileDescriptorWriteCallBack
);
63 wx_cffiledescriptor_callback(CFFileDescriptorRef cffd
,
67 wxLogTrace(wxTRACE_EVT_SOURCE
,
68 "CFFileDescriptor callback, flags=%d", flags
);
70 wxCFEventLoopSource
* const
71 source
= static_cast<wxCFEventLoopSource
*>(ctxData
);
73 wxEventLoopSourceHandler
* const
74 handler
= source
->GetHandler();
75 if ( flags
& kCFFileDescriptorReadCallBack
)
76 handler
->OnReadWaiting();
77 if ( flags
& kCFFileDescriptorWriteCallBack
)
78 handler
->OnWriteWaiting();
80 // we need to re-enable callbacks to be called again
81 EnableDescriptorCallBacks(cffd
, source
->GetFlags());
84 } // anonymous namespace
87 wxCFEventLoop::AddSourceForFD(int fd
,
88 wxEventLoopSourceHandler
*handler
,
91 wxCHECK_MSG( fd
!= -1, NULL
, "can't monitor invalid fd" );
93 wxScopedPtr
<wxCFEventLoopSource
>
94 source(new wxCFEventLoopSource(handler
, flags
));
96 CFFileDescriptorContext ctx
= { 0, source
.get(), NULL
, NULL
, NULL
};
97 wxCFRef
<CFFileDescriptorRef
>
98 cffd(CFFileDescriptorCreate
102 true, // close on invalidate
103 wx_cffiledescriptor_callback
,
109 wxCFRef
<CFRunLoopSourceRef
>
110 cfsrc(CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault
, cffd
, 0));
114 CFRunLoopRef cfloop
= CFGetCurrentRunLoop();
115 CFRunLoopAddSource(cfloop
, cfsrc
, kCFRunLoopDefaultMode
);
117 // Enable the callbacks initially.
118 EnableDescriptorCallBacks(cffd
, source
->GetFlags());
120 source
->SetFileDescriptor(cffd
.release());
122 return source
.release();
125 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd
)
127 wxASSERT_MSG( !m_cffd
, "shouldn't be called more than once" );
132 wxCFEventLoopSource::~wxCFEventLoopSource()
138 #endif // wxUSE_EVENTLOOP_SOURCE
140 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
142 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
144 eventloop
->CommonModeObserverCallBack(observer
, activity
);
147 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
149 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
151 eventloop
->DefaultModeObserverCallBack(observer
, activity
);
154 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
156 if ( activity
& kCFRunLoopBeforeTimers
)
158 // process pending wx events first as they correspond to low-level events
159 // which happened before, i.e. typically pending events were queued by a
160 // previous call to Dispatch() and if we didn't process them now the next
161 // call to it might enqueue them again (as happens with e.g. socket events
162 // which would be generated as long as there is input available on socket
163 // and this input is only removed from it when pending event handlers are
166 if ( wxTheApp
&& ShouldProcessIdleEvents() )
167 wxTheApp
->ProcessPendingEvents();
170 if ( activity
& kCFRunLoopBeforeWaiting
)
172 if ( ShouldProcessIdleEvents() && ProcessIdle() )
179 wxMutexGuiLeaveOrEnter();
186 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
),
187 int WXUNUSED(activity
))
190 if ( activity & kCFRunLoopBeforeTimers )
194 if ( activity & kCFRunLoopBeforeWaiting )
201 wxCFEventLoop::wxCFEventLoop()
203 m_shouldExit
= false;
204 m_processIdleEvents
= true;
206 #if wxUSE_UIACTIONSIMULATOR
207 m_shouldWaitForEvent
= false;
210 m_runLoop
= CFGetCurrentRunLoop();
212 CFRunLoopObserverContext ctxt
;
213 bzero( &ctxt
, sizeof(ctxt
) );
215 m_commonModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
216 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXCommonModeObserverCallBack
, &ctxt
);
217 CFRunLoopAddObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
219 m_defaultModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
220 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXDefaultModeObserverCallBack
, &ctxt
);
221 CFRunLoopAddObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
224 wxCFEventLoop::~wxCFEventLoop()
226 CFRunLoopRemoveObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
227 CFRunLoopRemoveObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
229 CFRelease(m_defaultModeRunLoopObserver
);
230 CFRelease(m_commonModeRunLoopObserver
);
234 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
236 return CFRunLoopGetCurrent();
239 void wxCFEventLoop::WakeUp()
241 CFRunLoopWakeUp(m_runLoop
);
248 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
256 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
259 // Yielding from a non-gui thread needs to bail out, otherwise we end up
260 // possibly sending events in the thread too.
261 if ( !wxThread::IsMain() )
265 #endif // wxUSE_THREADS
267 m_isInsideYield
= true;
268 m_eventsToProcessInsideYield
= eventsToProcess
;
271 // disable log flushing from here because a call to wxYield() shouldn't
272 // normally result in message boxes popping up &c
276 // process all pending events:
277 while ( DoProcessEvents() == 1 )
280 // it's necessary to call ProcessIdle() to update the frames sizes which
281 // might have been changed (it also will update other things set from
282 // OnUpdateUI() which is a nice (and desired) side effect)
283 while ( ProcessIdle() ) {}
285 // if there are pending events, we must process them.
287 wxTheApp
->ProcessPendingEvents();
292 m_isInsideYield
= false;
297 // implement/override base class pure virtual
298 bool wxCFEventLoop::Pending() const
303 int wxCFEventLoop::DoProcessEvents()
305 #if wxUSE_UIACTIONSIMULATOR
306 if ( m_shouldWaitForEvent
)
308 int handled
= DispatchTimeout( 1000 );
309 wxASSERT_MSG( handled
== 1, "No Event Available");
310 m_shouldWaitForEvent
= false;
315 return DispatchTimeout( 0 );
318 bool wxCFEventLoop::Dispatch()
320 return DoProcessEvents() != 0;
323 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
328 int status
= DoDispatchTimeout(timeout
);
346 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
348 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
351 case kCFRunLoopRunFinished
:
352 wxFAIL_MSG( "incorrect run loop state" );
354 case kCFRunLoopRunStopped
:
357 case kCFRunLoopRunTimedOut
:
360 case kCFRunLoopRunHandledSource
:
367 void wxCFEventLoop::OSXDoRun()
371 // generate and process idle events for as long as we don't
372 // have anything else to do
375 // if the "should exit" flag is set, the loop should terminate
376 // but not before processing any remaining messages so while
377 // Pending() returns true, do process them
380 while ( DoProcessEvents() == 1 )
388 void wxCFEventLoop::OSXDoStop()
390 CFRunLoopStop(CFGetCurrentRunLoop());
393 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
394 // terminating when Exit() is called
395 int wxCFEventLoop::DoRun()
397 // we must ensure that OnExit() is called even if an exception is thrown
398 // from inside ProcessEvents() but we must call it from Exit() in normal
399 // situations because it is supposed to be called synchronously,
400 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
401 // something similar here)
407 #endif // wxUSE_EXCEPTIONS
412 // exit the outer loop as well
419 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
424 //else: continue running the event loop
428 // OnException() throwed, possibly rethrowing the same
429 // exception again: very good, but we still need OnExit() to
436 #endif // wxUSE_EXCEPTIONS
441 // sets the "should exit" flag and wakes up the loop so that it terminates
443 void wxCFEventLoop::ScheduleExit(int rc
)
450 wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
452 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
455 m_formerState
= cfl
->ShouldProcessIdleEvents();
456 cfl
->SetProcessIdleEvents(false);
459 m_formerState
= true;
462 wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
464 wxCFEventLoop
* cfl
= dynamic_cast<wxCFEventLoop
*>(wxEventLoopBase::GetActive());
466 cfl
->SetProcessIdleEvents(m_formerState
);
469 // TODO Move to thread_osx.cpp
473 // ----------------------------------------------------------------------------
474 // GUI Serialization copied from MSW implementation
475 // ----------------------------------------------------------------------------
477 // if it's false, some secondary thread is holding the GUI lock
478 static bool gs_bGuiOwnedByMainThread
= true;
480 // critical section which controls access to all GUI functions: any secondary
481 // thread (i.e. except the main one) must enter this crit section before doing
483 static wxCriticalSection
*gs_critsectGui
= NULL
;
485 // critical section which protects gs_nWaitingForGui variable
486 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
488 // number of threads waiting for GUI in wxMutexGuiEnter()
489 static size_t gs_nWaitingForGui
= 0;
491 void wxOSXThreadModuleOnInit()
493 gs_critsectWaitingForGui
= new wxCriticalSection();
494 gs_critsectGui
= new wxCriticalSection();
495 gs_critsectGui
->Enter();
499 void wxOSXThreadModuleOnExit()
501 if ( gs_critsectGui
)
503 if ( !wxGuiOwnedByMainThread() )
505 gs_critsectGui
->Enter();
506 gs_bGuiOwnedByMainThread
= true;
509 gs_critsectGui
->Leave();
510 wxDELETE(gs_critsectGui
);
513 wxDELETE(gs_critsectWaitingForGui
);
517 // wake up the main thread
518 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
523 void wxMutexGuiEnterImpl()
525 // this would dead lock everything...
526 wxASSERT_MSG( !wxThread::IsMain(),
527 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
529 // the order in which we enter the critical sections here is crucial!!
531 // set the flag telling to the main thread that we want to do some GUI
533 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
538 wxWakeUpMainThread();
540 // now we may block here because the main thread will soon let us in
541 // (during the next iteration of OnIdle())
542 gs_critsectGui
->Enter();
545 void wxMutexGuiLeaveImpl()
547 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
549 if ( wxThread::IsMain() )
551 gs_bGuiOwnedByMainThread
= false;
555 // decrement the number of threads waiting for GUI access now
556 wxASSERT_MSG( gs_nWaitingForGui
> 0,
557 wxT("calling wxMutexGuiLeave() without entering it first?") );
561 wxWakeUpMainThread();
564 gs_critsectGui
->Leave();
567 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
569 wxASSERT_MSG( wxThread::IsMain(),
570 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
572 if ( !gs_critsectWaitingForGui
)
575 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
577 if ( gs_nWaitingForGui
== 0 )
579 // no threads are waiting for GUI - so we may acquire the lock without
580 // any danger (but only if we don't already have it)
581 if ( !wxGuiOwnedByMainThread() )
583 gs_critsectGui
->Enter();
585 gs_bGuiOwnedByMainThread
= true;
587 //else: already have it, nothing to do
591 // some threads are waiting, release the GUI lock if we have it
592 if ( wxGuiOwnedByMainThread() )
594 //else: some other worker thread is doing GUI
598 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
600 return gs_bGuiOwnedByMainThread
;