]> git.saurik.com Git - wxWidgets.git/blame - src/osx/core/evtloop_cf.cpp
setting debug level explicitly
[wxWidgets.git] / src / osx / core / evtloop_cf.cpp
CommitLineData
5cd99866
VZ
1///////////////////////////////////////////////////////////////////////////////
2// Name: src/osx/core/evtloop_cf.cpp
3// Purpose: wxEventLoop implementation common to both Carbon and Cocoa
4// Author: Vadim Zeitlin
5// Created: 2009-10-18
0056673c 6// RCS-ID: $Id$
5cd99866
VZ
7// Copyright: (c) 2009 Vadim Zeitlin <vadim@wxwidgets.org>
8// Licence: wxWindows licence
9///////////////////////////////////////////////////////////////////////////////
10
11// ============================================================================
12// declarations
13// ============================================================================
14
15// ----------------------------------------------------------------------------
16// headers
17// ----------------------------------------------------------------------------
18
19// for compilers that support precompilation, includes "wx.h".
20#include "wx/wxprec.h"
21
22#ifdef __BORLANDC__
23 #pragma hdrstop
24#endif
25
26#include "wx/evtloop.h"
27
28#if wxUSE_EVENTLOOP_SOURCE
29
fe5816f0
VZ
30#ifndef WX_PRECOMP
31 #include "wx/log.h"
0056673c 32 #include "wx/app.h"
fe5816f0
VZ
33#endif
34
5cd99866
VZ
35#include "wx/evtloopsrc.h"
36
37#include "wx/scopedptr.h"
38
39#include "wx/osx/private.h"
40#include "wx/osx/core/cfref.h"
a94c4b85 41#include "wx/thread.h"
5cd99866 42
976e63a7
VZ
43#if wxUSE_GUI
44 #include "wx/nonownedwnd.h"
45#endif
46
5cd99866
VZ
47// ============================================================================
48// wxCFEventLoopSource and wxCFEventLoop implementation
49// ============================================================================
50
5cd99866
VZ
51namespace
52{
53
54void EnableDescriptorCallBacks(CFFileDescriptorRef cffd, int flags)
55{
56 if ( flags & wxEVENT_SOURCE_INPUT )
57 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorReadCallBack);
58 if ( flags & wxEVENT_SOURCE_OUTPUT )
59 CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorWriteCallBack);
60}
61
62void
63wx_cffiledescriptor_callback(CFFileDescriptorRef cffd,
64 CFOptionFlags flags,
65 void *ctxData)
66{
67 wxLogTrace(wxTRACE_EVT_SOURCE,
68 "CFFileDescriptor callback, flags=%d", flags);
69
70 wxCFEventLoopSource * const
71 source = static_cast<wxCFEventLoopSource *>(ctxData);
72
73 wxEventLoopSourceHandler * const
74 handler = source->GetHandler();
75 if ( flags & kCFFileDescriptorReadCallBack )
76 handler->OnReadWaiting();
77 if ( flags & kCFFileDescriptorWriteCallBack )
78 handler->OnWriteWaiting();
79
80 // we need to re-enable callbacks to be called again
81 EnableDescriptorCallBacks(cffd, source->GetFlags());
82}
83
84} // anonymous namespace
85
86wxEventLoopSource *
87wxCFEventLoop::AddSourceForFD(int fd,
88 wxEventLoopSourceHandler *handler,
89 int flags)
90{
91 wxCHECK_MSG( fd != -1, NULL, "can't monitor invalid fd" );
92
93 wxScopedPtr<wxCFEventLoopSource>
94 source(new wxCFEventLoopSource(handler, flags));
95
96 CFFileDescriptorContext ctx = { 0, source.get(), NULL, NULL, NULL };
97 wxCFRef<CFFileDescriptorRef>
98 cffd(CFFileDescriptorCreate
99 (
100 kCFAllocatorDefault,
101 fd,
102 true, // close on invalidate
103 wx_cffiledescriptor_callback,
104 &ctx
105 ));
106 if ( !cffd )
107 return NULL;
108
5cd99866
VZ
109 wxCFRef<CFRunLoopSourceRef>
110 cfsrc(CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, cffd, 0));
111 if ( !cfsrc )
112 return NULL;
113
114 CFRunLoopRef cfloop = CFGetCurrentRunLoop();
115 CFRunLoopAddSource(cfloop, cfsrc, kCFRunLoopDefaultMode);
116
1dcca9b5
VZ
117 // Enable the callbacks initially.
118 EnableDescriptorCallBacks(cffd, source->GetFlags());
119
bbacbe39
VZ
120 source->SetFileDescriptor(cffd.release());
121
5cd99866
VZ
122 return source.release();
123}
124
125void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd)
126{
127 wxASSERT_MSG( !m_cffd, "shouldn't be called more than once" );
128
129 m_cffd = cffd;
130}
131
132wxCFEventLoopSource::~wxCFEventLoopSource()
133{
134 if ( m_cffd )
135 CFRelease(m_cffd);
136}
137
5cd99866 138#endif // wxUSE_EVENTLOOP_SOURCE
0056673c 139
3cac3654 140void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
293a13ba
SC
141{
142 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
143 if ( eventloop )
3cac3654 144 eventloop->CommonModeObserverCallBack(observer, activity);
976e63a7 145}
293a13ba 146
3cac3654
SC
147void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
148{
149 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
150 if ( eventloop )
151 eventloop->DefaultModeObserverCallBack(observer, activity);
152}
153
154void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
293a13ba
SC
155{
156 if ( activity & kCFRunLoopBeforeTimers )
157 {
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
164 // executed)
165
166 if ( wxTheApp )
167 wxTheApp->ProcessPendingEvents();
168 }
976e63a7 169
3cac3654
SC
170 if ( activity & kCFRunLoopBeforeWaiting )
171 {
592a3c6e
SC
172 if ( ProcessIdle() )
173 {
174 WakeUp();
175 }
176 else
177 {
3cac3654 178#if wxUSE_THREADS
592a3c6e 179 wxMutexGuiLeaveOrEnter();
3cac3654 180#endif
592a3c6e 181 }
3cac3654
SC
182 }
183}
184
6a06eecf
VZ
185void
186wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer),
187 int WXUNUSED(activity))
3cac3654 188{
592a3c6e 189 /*
3cac3654
SC
190 if ( activity & kCFRunLoopBeforeTimers )
191 {
192 }
193
293a13ba
SC
194 if ( activity & kCFRunLoopBeforeWaiting )
195 {
293a13ba 196 }
592a3c6e 197 */
293a13ba
SC
198}
199
3cac3654 200
0056673c
SC
201wxCFEventLoop::wxCFEventLoop()
202{
203 m_shouldExit = false;
976e63a7 204
9aee1212 205 m_runLoop = CFGetCurrentRunLoop();
976e63a7 206
293a13ba
SC
207 CFRunLoopObserverContext ctxt;
208 bzero( &ctxt, sizeof(ctxt) );
209 ctxt.info = this;
3cac3654
SC
210 m_commonModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
211 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXCommonModeObserverCallBack, &ctxt );
212 CFRunLoopAddObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
213 CFRelease(m_commonModeRunLoopObserver);
214
215 m_defaultModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
216 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXDefaultModeObserverCallBack, &ctxt );
217 CFRunLoopAddObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
218 CFRelease(m_defaultModeRunLoopObserver);
0056673c
SC
219}
220
221wxCFEventLoop::~wxCFEventLoop()
222{
3cac3654
SC
223 CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
224 CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
0056673c 225}
976e63a7 226
0056673c
SC
227
228CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
229{
293a13ba 230 return CFRunLoopGetCurrent();
0056673c
SC
231}
232
233void wxCFEventLoop::WakeUp()
234{
58e74b83 235 CFRunLoopWakeUp(m_runLoop);
0056673c
SC
236}
237
3bfba421
SC
238#if wxUSE_BASE
239
240void wxMacWakeUp()
241{
242 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
ce00f59b 243
3bfba421
SC
244 if ( loop )
245 loop->WakeUp();
246}
247
248#endif
249
0056673c
SC
250bool wxCFEventLoop::YieldFor(long eventsToProcess)
251{
252#if wxUSE_THREADS
253 // Yielding from a non-gui thread needs to bail out, otherwise we end up
254 // possibly sending events in the thread too.
255 if ( !wxThread::IsMain() )
256 {
257 return true;
258 }
259#endif // wxUSE_THREADS
976e63a7 260
0056673c
SC
261 m_isInsideYield = true;
262 m_eventsToProcessInsideYield = eventsToProcess;
976e63a7 263
0056673c
SC
264#if wxUSE_LOG
265 // disable log flushing from here because a call to wxYield() shouldn't
266 // normally result in message boxes popping up &c
267 wxLog::Suspend();
268#endif // wxUSE_LOG
976e63a7 269
0056673c
SC
270 // process all pending events:
271 while ( DoProcessEvents() == 1 )
272 ;
976e63a7 273
0056673c
SC
274 // it's necessary to call ProcessIdle() to update the frames sizes which
275 // might have been changed (it also will update other things set from
276 // OnUpdateUI() which is a nice (and desired) side effect)
277 while ( ProcessIdle() ) {}
976e63a7 278
0056673c
SC
279 // if there are pending events, we must process them.
280 if (wxTheApp)
281 wxTheApp->ProcessPendingEvents();
976e63a7 282
0056673c
SC
283#if wxUSE_LOG
284 wxLog::Resume();
285#endif // wxUSE_LOG
286 m_isInsideYield = false;
976e63a7 287
0056673c
SC
288 return true;
289}
290
291// implement/override base class pure virtual
292bool wxCFEventLoop::Pending() const
293{
294 return true;
295}
296
297int wxCFEventLoop::DoProcessEvents()
298{
76435717 299 return DispatchTimeout( 0 );
0056673c
SC
300}
301
302bool wxCFEventLoop::Dispatch()
303{
293a13ba 304 return DoProcessEvents() != 0;
0056673c
SC
305}
306
307int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
308{
309 if ( !wxTheApp )
310 return 0;
311
0056673c 312 int status = DoDispatchTimeout(timeout);
976e63a7 313
0056673c
SC
314 switch( status )
315 {
316 case 0:
317 break;
318 case -1:
319 if ( m_shouldExit )
320 return 0;
976e63a7 321
0056673c
SC
322 break;
323 case 1:
0056673c
SC
324 break;
325 }
976e63a7 326
0056673c
SC
327 return status;
328}
329
330int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
976e63a7 331{
0056673c
SC
332 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
333 switch( status )
334 {
335 case kCFRunLoopRunFinished:
336 wxFAIL_MSG( "incorrect run loop state" );
337 break;
338 case kCFRunLoopRunStopped:
339 return 0;
340 break;
341 case kCFRunLoopRunTimedOut:
342 return -1;
343 break;
344 case kCFRunLoopRunHandledSource:
345 default:
346 break;
347 }
348 return 1;
349}
350
80eee837
SC
351void wxCFEventLoop::DoRun()
352{
353 for ( ;; )
354 {
355 // generate and process idle events for as long as we don't
356 // have anything else to do
357 DoProcessEvents();
976e63a7 358
80eee837
SC
359 // if the "should exit" flag is set, the loop should terminate
360 // but not before processing any remaining messages so while
361 // Pending() returns true, do process them
362 if ( m_shouldExit )
363 {
364 while ( DoProcessEvents() == 1 )
365 ;
976e63a7 366
80eee837
SC
367 break;
368 }
369 }
370}
371
372void wxCFEventLoop::DoStop()
373{
374 CFRunLoopStop(CFGetCurrentRunLoop());
375}
376
0056673c
SC
377// enters a loop calling OnNextIteration(), Pending() and Dispatch() and
378// terminating when Exit() is called
379int wxCFEventLoop::Run()
380{
381 // event loops are not recursive, you need to create another loop!
382 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
976e63a7 383
0056673c
SC
384 // ProcessIdle() and ProcessEvents() below may throw so the code here should
385 // be exception-safe, hence we must use local objects for all actions we
386 // should undo
387 wxEventLoopActivator activate(this);
976e63a7 388
0056673c
SC
389 // we must ensure that OnExit() is called even if an exception is thrown
390 // from inside ProcessEvents() but we must call it from Exit() in normal
391 // situations because it is supposed to be called synchronously,
392 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
393 // something similar here)
394#if wxUSE_EXCEPTIONS
395 for ( ;; )
396 {
397 try
398 {
399#endif // wxUSE_EXCEPTIONS
976e63a7 400
80eee837 401 DoRun();
976e63a7 402
0056673c
SC
403#if wxUSE_EXCEPTIONS
404 // exit the outer loop as well
405 break;
406 }
407 catch ( ... )
408 {
409 try
410 {
411 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
412 {
413 OnExit();
414 break;
415 }
416 //else: continue running the event loop
417 }
418 catch ( ... )
419 {
420 // OnException() throwed, possibly rethrowing the same
421 // exception again: very good, but we still need OnExit() to
422 // be called
423 OnExit();
424 throw;
425 }
426 }
427 }
428#endif // wxUSE_EXCEPTIONS
976e63a7 429
0056673c
SC
430 return m_exitcode;
431}
432
433// sets the "should exit" flag and wakes up the loop so that it terminates
434// soon
435void wxCFEventLoop::Exit(int rc)
436{
437 m_exitcode = rc;
438 m_shouldExit = true;
80eee837
SC
439 DoStop();
440}
a94c4b85
SC
441
442// TODO Move to thread_osx.cpp
443
444#if wxUSE_THREADS
445
446// ----------------------------------------------------------------------------
447// GUI Serialization copied from MSW implementation
448// ----------------------------------------------------------------------------
449
450// if it's false, some secondary thread is holding the GUI lock
451static bool gs_bGuiOwnedByMainThread = true;
452
453// critical section which controls access to all GUI functions: any secondary
454// thread (i.e. except the main one) must enter this crit section before doing
455// any GUI calls
456static wxCriticalSection *gs_critsectGui = NULL;
457
458// critical section which protects gs_nWaitingForGui variable
459static wxCriticalSection *gs_critsectWaitingForGui = NULL;
460
461// number of threads waiting for GUI in wxMutexGuiEnter()
462static size_t gs_nWaitingForGui = 0;
463
464void wxOSXThreadModuleOnInit()
465{
ce00f59b 466 gs_critsectWaitingForGui = new wxCriticalSection();
a94c4b85
SC
467 gs_critsectGui = new wxCriticalSection();
468 gs_critsectGui->Enter();
469}
470
471
472void wxOSXThreadModuleOnExit()
473{
474 if ( gs_critsectGui )
475 {
476 if ( !wxGuiOwnedByMainThread() )
477 {
478 gs_critsectGui->Enter();
479 gs_bGuiOwnedByMainThread = true;
480 }
ce00f59b 481
a94c4b85
SC
482 gs_critsectGui->Leave();
483 wxDELETE(gs_critsectGui);
484 }
ce00f59b 485
a94c4b85
SC
486 wxDELETE(gs_critsectWaitingForGui);
487}
488
489
490// wake up the main thread
491void WXDLLIMPEXP_BASE wxWakeUpMainThread()
492{
493 wxMacWakeUp();
494}
495
496void wxMutexGuiEnterImpl()
497{
498 // this would dead lock everything...
499 wxASSERT_MSG( !wxThread::IsMain(),
500 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
ce00f59b 501
a94c4b85 502 // the order in which we enter the critical sections here is crucial!!
ce00f59b 503
a94c4b85
SC
504 // set the flag telling to the main thread that we want to do some GUI
505 {
506 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 507
a94c4b85
SC
508 gs_nWaitingForGui++;
509 }
ce00f59b 510
a94c4b85 511 wxWakeUpMainThread();
ce00f59b 512
a94c4b85
SC
513 // now we may block here because the main thread will soon let us in
514 // (during the next iteration of OnIdle())
515 gs_critsectGui->Enter();
516}
517
518void wxMutexGuiLeaveImpl()
519{
520 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 521
a94c4b85
SC
522 if ( wxThread::IsMain() )
523 {
524 gs_bGuiOwnedByMainThread = false;
525 }
526 else
527 {
528 // decrement the number of threads waiting for GUI access now
529 wxASSERT_MSG( gs_nWaitingForGui > 0,
530 wxT("calling wxMutexGuiLeave() without entering it first?") );
ce00f59b 531
a94c4b85 532 gs_nWaitingForGui--;
ce00f59b 533
a94c4b85
SC
534 wxWakeUpMainThread();
535 }
ce00f59b 536
a94c4b85
SC
537 gs_critsectGui->Leave();
538}
539
540void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
541{
542 wxASSERT_MSG( wxThread::IsMain(),
543 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
ce00f59b 544
a94c4b85
SC
545 if ( !gs_critsectWaitingForGui )
546 return;
ce00f59b 547
a94c4b85 548 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 549
a94c4b85
SC
550 if ( gs_nWaitingForGui == 0 )
551 {
552 // no threads are waiting for GUI - so we may acquire the lock without
553 // any danger (but only if we don't already have it)
554 if ( !wxGuiOwnedByMainThread() )
555 {
556 gs_critsectGui->Enter();
ce00f59b 557
a94c4b85
SC
558 gs_bGuiOwnedByMainThread = true;
559 }
560 //else: already have it, nothing to do
561 }
562 else
563 {
564 // some threads are waiting, release the GUI lock if we have it
565 if ( wxGuiOwnedByMainThread() )
566 wxMutexGuiLeave();
567 //else: some other worker thread is doing GUI
568 }
569}
570
571bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
572{
573 return gs_bGuiOwnedByMainThread;
574}
575
576#endif