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