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 // Enable the callbacks initially.
119 EnableDescriptorCallBacks(cffd
, source
->GetFlags());
121 source
->SetFileDescriptor(cffd
.release());
123 return source
.release();
126 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd
)
128 wxASSERT_MSG( !m_cffd
, "shouldn't be called more than once" );
133 wxCFEventLoopSource::~wxCFEventLoopSource()
142 wxCFEventLoop::AddSourceForFD(int WXUNUSED(fd
),
143 wxEventLoopSourceHandler
* WXUNUSED(handler
),
149 #endif // MAC_OS_X_VERSION_MAX_ALLOWED
151 #endif // wxUSE_EVENTLOOP_SOURCE
153 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
155 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
157 eventloop
->CommonModeObserverCallBack(observer
, activity
);
160 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer
, int activity
, void *info
)
162 wxCFEventLoop
* eventloop
= static_cast<wxCFEventLoop
*>(info
);
164 eventloop
->DefaultModeObserverCallBack(observer
, activity
);
167 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
), int activity
)
169 if ( activity
& kCFRunLoopBeforeTimers
)
171 // process pending wx events first as they correspond to low-level events
172 // which happened before, i.e. typically pending events were queued by a
173 // previous call to Dispatch() and if we didn't process them now the next
174 // call to it might enqueue them again (as happens with e.g. socket events
175 // which would be generated as long as there is input available on socket
176 // and this input is only removed from it when pending event handlers are
180 wxTheApp
->ProcessPendingEvents();
183 if ( activity
& kCFRunLoopBeforeWaiting
)
192 wxMutexGuiLeaveOrEnter();
199 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef
WXUNUSED(observer
),
200 int WXUNUSED(activity
))
203 if ( activity & kCFRunLoopBeforeTimers )
207 if ( activity & kCFRunLoopBeforeWaiting )
214 wxCFEventLoop::wxCFEventLoop()
216 m_shouldExit
= false;
218 m_runLoop
= CFGetCurrentRunLoop();
220 CFRunLoopObserverContext ctxt
;
221 bzero( &ctxt
, sizeof(ctxt
) );
223 m_commonModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
224 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXCommonModeObserverCallBack
, &ctxt
);
225 CFRunLoopAddObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
226 CFRelease(m_commonModeRunLoopObserver
);
228 m_defaultModeRunLoopObserver
= CFRunLoopObserverCreate( kCFAllocatorDefault
, kCFRunLoopBeforeTimers
| kCFRunLoopBeforeWaiting
, true /* repeats */, 0,
229 (CFRunLoopObserverCallBack
) wxCFEventLoop::OSXDefaultModeObserverCallBack
, &ctxt
);
230 CFRunLoopAddObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
231 CFRelease(m_defaultModeRunLoopObserver
);
234 wxCFEventLoop::~wxCFEventLoop()
236 CFRunLoopRemoveObserver(m_runLoop
, m_commonModeRunLoopObserver
, kCFRunLoopCommonModes
);
237 CFRunLoopRemoveObserver(m_runLoop
, m_defaultModeRunLoopObserver
, kCFRunLoopDefaultMode
);
241 CFRunLoopRef
wxCFEventLoop::CFGetCurrentRunLoop() const
243 return CFRunLoopGetCurrent();
246 void wxCFEventLoop::WakeUp()
248 CFRunLoopWakeUp(m_runLoop
);
255 wxEventLoopBase
* const loop
= wxEventLoopBase::GetActive();
263 bool wxCFEventLoop::YieldFor(long eventsToProcess
)
266 // Yielding from a non-gui thread needs to bail out, otherwise we end up
267 // possibly sending events in the thread too.
268 if ( !wxThread::IsMain() )
272 #endif // wxUSE_THREADS
274 m_isInsideYield
= true;
275 m_eventsToProcessInsideYield
= eventsToProcess
;
278 // disable log flushing from here because a call to wxYield() shouldn't
279 // normally result in message boxes popping up &c
283 // process all pending events:
284 while ( DoProcessEvents() == 1 )
287 // it's necessary to call ProcessIdle() to update the frames sizes which
288 // might have been changed (it also will update other things set from
289 // OnUpdateUI() which is a nice (and desired) side effect)
290 while ( ProcessIdle() ) {}
292 // if there are pending events, we must process them.
294 wxTheApp
->ProcessPendingEvents();
299 m_isInsideYield
= false;
304 // implement/override base class pure virtual
305 bool wxCFEventLoop::Pending() const
310 int wxCFEventLoop::DoProcessEvents()
312 return DispatchTimeout( 0 );
315 bool wxCFEventLoop::Dispatch()
317 return DoProcessEvents() != 0;
320 int wxCFEventLoop::DispatchTimeout(unsigned long timeout
)
325 int status
= DoDispatchTimeout(timeout
);
343 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout
)
345 SInt32 status
= CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
/ 1000.0 , true);
348 case kCFRunLoopRunFinished
:
349 wxFAIL_MSG( "incorrect run loop state" );
351 case kCFRunLoopRunStopped
:
354 case kCFRunLoopRunTimedOut
:
357 case kCFRunLoopRunHandledSource
:
364 void wxCFEventLoop::DoRun()
368 // generate and process idle events for as long as we don't
369 // have anything else to do
372 // if the "should exit" flag is set, the loop should terminate
373 // but not before processing any remaining messages so while
374 // Pending() returns true, do process them
377 while ( DoProcessEvents() == 1 )
385 void wxCFEventLoop::DoStop()
387 CFRunLoopStop(CFGetCurrentRunLoop());
390 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
391 // terminating when Exit() is called
392 int wxCFEventLoop::Run()
394 // event loops are not recursive, you need to create another loop!
395 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
397 // ProcessIdle() and ProcessEvents() below may throw so the code here should
398 // be exception-safe, hence we must use local objects for all actions we
400 wxEventLoopActivator
activate(this);
402 // we must ensure that OnExit() is called even if an exception is thrown
403 // from inside ProcessEvents() but we must call it from Exit() in normal
404 // situations because it is supposed to be called synchronously,
405 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
406 // something similar here)
412 #endif // wxUSE_EXCEPTIONS
417 // exit the outer loop as well
424 if ( !wxTheApp
|| !wxTheApp
->OnExceptionInMainLoop() )
429 //else: continue running the event loop
433 // OnException() throwed, possibly rethrowing the same
434 // exception again: very good, but we still need OnExit() to
441 #endif // wxUSE_EXCEPTIONS
446 // sets the "should exit" flag and wakes up the loop so that it terminates
448 void wxCFEventLoop::Exit(int rc
)
455 // TODO Move to thread_osx.cpp
459 // ----------------------------------------------------------------------------
460 // GUI Serialization copied from MSW implementation
461 // ----------------------------------------------------------------------------
463 // if it's false, some secondary thread is holding the GUI lock
464 static bool gs_bGuiOwnedByMainThread
= true;
466 // critical section which controls access to all GUI functions: any secondary
467 // thread (i.e. except the main one) must enter this crit section before doing
469 static wxCriticalSection
*gs_critsectGui
= NULL
;
471 // critical section which protects gs_nWaitingForGui variable
472 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
474 // number of threads waiting for GUI in wxMutexGuiEnter()
475 static size_t gs_nWaitingForGui
= 0;
477 void wxOSXThreadModuleOnInit()
479 gs_critsectWaitingForGui
= new wxCriticalSection();
480 gs_critsectGui
= new wxCriticalSection();
481 gs_critsectGui
->Enter();
485 void wxOSXThreadModuleOnExit()
487 if ( gs_critsectGui
)
489 if ( !wxGuiOwnedByMainThread() )
491 gs_critsectGui
->Enter();
492 gs_bGuiOwnedByMainThread
= true;
495 gs_critsectGui
->Leave();
496 wxDELETE(gs_critsectGui
);
499 wxDELETE(gs_critsectWaitingForGui
);
503 // wake up the main thread
504 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
509 void wxMutexGuiEnterImpl()
511 // this would dead lock everything...
512 wxASSERT_MSG( !wxThread::IsMain(),
513 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
515 // the order in which we enter the critical sections here is crucial!!
517 // set the flag telling to the main thread that we want to do some GUI
519 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
524 wxWakeUpMainThread();
526 // now we may block here because the main thread will soon let us in
527 // (during the next iteration of OnIdle())
528 gs_critsectGui
->Enter();
531 void wxMutexGuiLeaveImpl()
533 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
535 if ( wxThread::IsMain() )
537 gs_bGuiOwnedByMainThread
= false;
541 // decrement the number of threads waiting for GUI access now
542 wxASSERT_MSG( gs_nWaitingForGui
> 0,
543 wxT("calling wxMutexGuiLeave() without entering it first?") );
547 wxWakeUpMainThread();
550 gs_critsectGui
->Leave();
553 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
555 wxASSERT_MSG( wxThread::IsMain(),
556 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
558 if ( !gs_critsectWaitingForGui
)
561 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
563 if ( gs_nWaitingForGui
== 0 )
565 // no threads are waiting for GUI - so we may acquire the lock without
566 // any danger (but only if we don't already have it)
567 if ( !wxGuiOwnedByMainThread() )
569 gs_critsectGui
->Enter();
571 gs_bGuiOwnedByMainThread
= true;
573 //else: already have it, nothing to do
577 // some threads are waiting, release the GUI lock if we have it
578 if ( wxGuiOwnedByMainThread() )
580 //else: some other worker thread is doing GUI
584 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
586 return gs_bGuiOwnedByMainThread
;