]> git.saurik.com Git - wxWidgets.git/blame - src/osx/core/evtloop_cf.cpp
avoiding potential mismatch between true and expected state of wxGraphicsContext...
[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
1dcca9b5
VZ
118 // Enable the callbacks initially.
119 EnableDescriptorCallBacks(cffd, source->GetFlags());
120
bbacbe39
VZ
121 source->SetFileDescriptor(cffd.release());
122
5cd99866
VZ
123 return source.release();
124}
125
126void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd)
127{
128 wxASSERT_MSG( !m_cffd, "shouldn't be called more than once" );
129
130 m_cffd = cffd;
131}
132
133wxCFEventLoopSource::~wxCFEventLoopSource()
134{
135 if ( m_cffd )
136 CFRelease(m_cffd);
137}
138
139#else // OS X < 10.5
140
141wxEventLoopSource *
142wxCFEventLoop::AddSourceForFD(int WXUNUSED(fd),
143 wxEventLoopSourceHandler * WXUNUSED(handler),
144 int WXUNUSED(flags))
145{
146 return NULL;
147}
148
149#endif // MAC_OS_X_VERSION_MAX_ALLOWED
150
151#endif // wxUSE_EVENTLOOP_SOURCE
0056673c 152
3cac3654 153void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
293a13ba
SC
154{
155 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
156 if ( eventloop )
3cac3654 157 eventloop->CommonModeObserverCallBack(observer, activity);
976e63a7 158}
293a13ba 159
3cac3654
SC
160void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
161{
162 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
163 if ( eventloop )
164 eventloop->DefaultModeObserverCallBack(observer, activity);
165}
166
167void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
293a13ba
SC
168{
169 if ( activity & kCFRunLoopBeforeTimers )
170 {
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
177 // executed)
178
179 if ( wxTheApp )
180 wxTheApp->ProcessPendingEvents();
181 }
976e63a7 182
3cac3654
SC
183 if ( activity & kCFRunLoopBeforeWaiting )
184 {
592a3c6e
SC
185 if ( ProcessIdle() )
186 {
187 WakeUp();
188 }
189 else
190 {
3cac3654 191#if wxUSE_THREADS
592a3c6e 192 wxMutexGuiLeaveOrEnter();
3cac3654 193#endif
592a3c6e 194 }
3cac3654
SC
195 }
196}
197
6a06eecf
VZ
198void
199wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer),
200 int WXUNUSED(activity))
3cac3654 201{
592a3c6e 202 /*
3cac3654
SC
203 if ( activity & kCFRunLoopBeforeTimers )
204 {
205 }
206
293a13ba
SC
207 if ( activity & kCFRunLoopBeforeWaiting )
208 {
293a13ba 209 }
592a3c6e 210 */
293a13ba
SC
211}
212
3cac3654 213
0056673c
SC
214wxCFEventLoop::wxCFEventLoop()
215{
216 m_shouldExit = false;
976e63a7 217
9aee1212 218 m_runLoop = CFGetCurrentRunLoop();
976e63a7 219
293a13ba
SC
220 CFRunLoopObserverContext ctxt;
221 bzero( &ctxt, sizeof(ctxt) );
222 ctxt.info = this;
3cac3654
SC
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);
227
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);
0056673c
SC
232}
233
234wxCFEventLoop::~wxCFEventLoop()
235{
3cac3654
SC
236 CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
237 CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
0056673c 238}
976e63a7 239
0056673c
SC
240
241CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
242{
293a13ba 243 return CFRunLoopGetCurrent();
0056673c
SC
244}
245
246void wxCFEventLoop::WakeUp()
247{
58e74b83 248 CFRunLoopWakeUp(m_runLoop);
0056673c
SC
249}
250
3bfba421
SC
251#if wxUSE_BASE
252
253void wxMacWakeUp()
254{
255 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
ce00f59b 256
3bfba421
SC
257 if ( loop )
258 loop->WakeUp();
259}
260
261#endif
262
0056673c
SC
263bool wxCFEventLoop::YieldFor(long eventsToProcess)
264{
265#if wxUSE_THREADS
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() )
269 {
270 return true;
271 }
272#endif // wxUSE_THREADS
976e63a7 273
0056673c
SC
274 m_isInsideYield = true;
275 m_eventsToProcessInsideYield = eventsToProcess;
976e63a7 276
0056673c
SC
277#if wxUSE_LOG
278 // disable log flushing from here because a call to wxYield() shouldn't
279 // normally result in message boxes popping up &c
280 wxLog::Suspend();
281#endif // wxUSE_LOG
976e63a7 282
0056673c
SC
283 // process all pending events:
284 while ( DoProcessEvents() == 1 )
285 ;
976e63a7 286
0056673c
SC
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() ) {}
976e63a7 291
0056673c
SC
292 // if there are pending events, we must process them.
293 if (wxTheApp)
294 wxTheApp->ProcessPendingEvents();
976e63a7 295
0056673c
SC
296#if wxUSE_LOG
297 wxLog::Resume();
298#endif // wxUSE_LOG
299 m_isInsideYield = false;
976e63a7 300
0056673c
SC
301 return true;
302}
303
304// implement/override base class pure virtual
305bool wxCFEventLoop::Pending() const
306{
307 return true;
308}
309
310int wxCFEventLoop::DoProcessEvents()
311{
76435717 312 return DispatchTimeout( 0 );
0056673c
SC
313}
314
315bool wxCFEventLoop::Dispatch()
316{
293a13ba 317 return DoProcessEvents() != 0;
0056673c
SC
318}
319
320int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
321{
322 if ( !wxTheApp )
323 return 0;
324
0056673c 325 int status = DoDispatchTimeout(timeout);
976e63a7 326
0056673c
SC
327 switch( status )
328 {
329 case 0:
330 break;
331 case -1:
332 if ( m_shouldExit )
333 return 0;
976e63a7 334
0056673c
SC
335 break;
336 case 1:
0056673c
SC
337 break;
338 }
976e63a7 339
0056673c
SC
340 return status;
341}
342
343int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
976e63a7 344{
0056673c
SC
345 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
346 switch( status )
347 {
348 case kCFRunLoopRunFinished:
349 wxFAIL_MSG( "incorrect run loop state" );
350 break;
351 case kCFRunLoopRunStopped:
352 return 0;
353 break;
354 case kCFRunLoopRunTimedOut:
355 return -1;
356 break;
357 case kCFRunLoopRunHandledSource:
358 default:
359 break;
360 }
361 return 1;
362}
363
80eee837
SC
364void wxCFEventLoop::DoRun()
365{
366 for ( ;; )
367 {
368 // generate and process idle events for as long as we don't
369 // have anything else to do
370 DoProcessEvents();
976e63a7 371
80eee837
SC
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
375 if ( m_shouldExit )
376 {
377 while ( DoProcessEvents() == 1 )
378 ;
976e63a7 379
80eee837
SC
380 break;
381 }
382 }
383}
384
385void wxCFEventLoop::DoStop()
386{
387 CFRunLoopStop(CFGetCurrentRunLoop());
388}
389
0056673c
SC
390// enters a loop calling OnNextIteration(), Pending() and Dispatch() and
391// terminating when Exit() is called
392int wxCFEventLoop::Run()
393{
394 // event loops are not recursive, you need to create another loop!
395 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
976e63a7 396
0056673c
SC
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
399 // should undo
400 wxEventLoopActivator activate(this);
976e63a7 401
0056673c
SC
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)
407#if wxUSE_EXCEPTIONS
408 for ( ;; )
409 {
410 try
411 {
412#endif // wxUSE_EXCEPTIONS
976e63a7 413
80eee837 414 DoRun();
976e63a7 415
0056673c
SC
416#if wxUSE_EXCEPTIONS
417 // exit the outer loop as well
418 break;
419 }
420 catch ( ... )
421 {
422 try
423 {
424 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
425 {
426 OnExit();
427 break;
428 }
429 //else: continue running the event loop
430 }
431 catch ( ... )
432 {
433 // OnException() throwed, possibly rethrowing the same
434 // exception again: very good, but we still need OnExit() to
435 // be called
436 OnExit();
437 throw;
438 }
439 }
440 }
441#endif // wxUSE_EXCEPTIONS
976e63a7 442
0056673c
SC
443 return m_exitcode;
444}
445
446// sets the "should exit" flag and wakes up the loop so that it terminates
447// soon
448void wxCFEventLoop::Exit(int rc)
449{
450 m_exitcode = rc;
451 m_shouldExit = true;
80eee837
SC
452 DoStop();
453}
a94c4b85
SC
454
455// TODO Move to thread_osx.cpp
456
457#if wxUSE_THREADS
458
459// ----------------------------------------------------------------------------
460// GUI Serialization copied from MSW implementation
461// ----------------------------------------------------------------------------
462
463// if it's false, some secondary thread is holding the GUI lock
464static bool gs_bGuiOwnedByMainThread = true;
465
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
468// any GUI calls
469static wxCriticalSection *gs_critsectGui = NULL;
470
471// critical section which protects gs_nWaitingForGui variable
472static wxCriticalSection *gs_critsectWaitingForGui = NULL;
473
474// number of threads waiting for GUI in wxMutexGuiEnter()
475static size_t gs_nWaitingForGui = 0;
476
477void wxOSXThreadModuleOnInit()
478{
ce00f59b 479 gs_critsectWaitingForGui = new wxCriticalSection();
a94c4b85
SC
480 gs_critsectGui = new wxCriticalSection();
481 gs_critsectGui->Enter();
482}
483
484
485void wxOSXThreadModuleOnExit()
486{
487 if ( gs_critsectGui )
488 {
489 if ( !wxGuiOwnedByMainThread() )
490 {
491 gs_critsectGui->Enter();
492 gs_bGuiOwnedByMainThread = true;
493 }
ce00f59b 494
a94c4b85
SC
495 gs_critsectGui->Leave();
496 wxDELETE(gs_critsectGui);
497 }
ce00f59b 498
a94c4b85
SC
499 wxDELETE(gs_critsectWaitingForGui);
500}
501
502
503// wake up the main thread
504void WXDLLIMPEXP_BASE wxWakeUpMainThread()
505{
506 wxMacWakeUp();
507}
508
509void wxMutexGuiEnterImpl()
510{
511 // this would dead lock everything...
512 wxASSERT_MSG( !wxThread::IsMain(),
513 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
ce00f59b 514
a94c4b85 515 // the order in which we enter the critical sections here is crucial!!
ce00f59b 516
a94c4b85
SC
517 // set the flag telling to the main thread that we want to do some GUI
518 {
519 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 520
a94c4b85
SC
521 gs_nWaitingForGui++;
522 }
ce00f59b 523
a94c4b85 524 wxWakeUpMainThread();
ce00f59b 525
a94c4b85
SC
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();
529}
530
531void wxMutexGuiLeaveImpl()
532{
533 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 534
a94c4b85
SC
535 if ( wxThread::IsMain() )
536 {
537 gs_bGuiOwnedByMainThread = false;
538 }
539 else
540 {
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?") );
ce00f59b 544
a94c4b85 545 gs_nWaitingForGui--;
ce00f59b 546
a94c4b85
SC
547 wxWakeUpMainThread();
548 }
ce00f59b 549
a94c4b85
SC
550 gs_critsectGui->Leave();
551}
552
553void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
554{
555 wxASSERT_MSG( wxThread::IsMain(),
556 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
ce00f59b 557
a94c4b85
SC
558 if ( !gs_critsectWaitingForGui )
559 return;
ce00f59b 560
a94c4b85 561 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
ce00f59b 562
a94c4b85
SC
563 if ( gs_nWaitingForGui == 0 )
564 {
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() )
568 {
569 gs_critsectGui->Enter();
ce00f59b 570
a94c4b85
SC
571 gs_bGuiOwnedByMainThread = true;
572 }
573 //else: already have it, nothing to do
574 }
575 else
576 {
577 // some threads are waiting, release the GUI lock if we have it
578 if ( wxGuiOwnedByMainThread() )
579 wxMutexGuiLeave();
580 //else: some other worker thread is doing GUI
581 }
582}
583
584bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
585{
586 return gs_bGuiOwnedByMainThread;
587}
588
589#endif