]> git.saurik.com Git - wxWidgets.git/blob - src/osx/core/evtloop_cf.cpp
12ecb2c87292d3e0945739a81bfc141a23a63266
[wxWidgets.git] / src / osx / core / evtloop_cf.cpp
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
6 // RCS-ID: $Id$
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 #ifndef WX_PRECOMP
29 #include "wx/log.h"
30 #include "wx/app.h"
31 #endif
32
33 #include "wx/evtloopsrc.h"
34
35 #include "wx/scopedptr.h"
36
37 #include "wx/osx/private.h"
38 #include "wx/osx/core/cfref.h"
39 #include "wx/thread.h"
40
41 #if wxUSE_GUI
42 #include "wx/nonownedwnd.h"
43 #endif
44
45 // ============================================================================
46 // wxCFEventLoopSource and wxCFEventLoop implementation
47 // ============================================================================
48
49 #if wxUSE_EVENTLOOP_SOURCE
50
51 namespace
52 {
53
54 void 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
62 void
63 wx_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
86 wxEventLoopSource *
87 wxCFEventLoop::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
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
117 // Enable the callbacks initially.
118 EnableDescriptorCallBacks(cffd, source->GetFlags());
119
120 source->SetFileDescriptor(cffd.release());
121
122 return source.release();
123 }
124
125 void wxCFEventLoopSource::SetFileDescriptor(CFFileDescriptorRef cffd)
126 {
127 wxASSERT_MSG( !m_cffd, "shouldn't be called more than once" );
128
129 m_cffd = cffd;
130 }
131
132 wxCFEventLoopSource::~wxCFEventLoopSource()
133 {
134 if ( m_cffd )
135 CFRelease(m_cffd);
136 }
137
138 #endif // wxUSE_EVENTLOOP_SOURCE
139
140 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
141 {
142 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
143 if ( eventloop )
144 eventloop->CommonModeObserverCallBack(observer, activity);
145 }
146
147 void 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
154 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
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 && ShouldProcessIdleEvents() )
167 wxTheApp->ProcessPendingEvents();
168 }
169
170 if ( activity & kCFRunLoopBeforeWaiting )
171 {
172 if ( ShouldProcessIdleEvents() && ProcessIdle() )
173 {
174 WakeUp();
175 }
176 else
177 {
178 #if wxUSE_THREADS
179 wxMutexGuiLeaveOrEnter();
180 #endif
181 }
182 }
183 }
184
185 void
186 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer),
187 int WXUNUSED(activity))
188 {
189 /*
190 if ( activity & kCFRunLoopBeforeTimers )
191 {
192 }
193
194 if ( activity & kCFRunLoopBeforeWaiting )
195 {
196 }
197 */
198 }
199
200
201 wxCFEventLoop::wxCFEventLoop()
202 {
203 m_shouldExit = false;
204 m_processIdleEvents = true;
205
206 #if wxUSE_UIACTIONSIMULATOR
207 m_shouldWaitForEvent = false;
208 #endif
209
210 m_runLoop = CFGetCurrentRunLoop();
211
212 CFRunLoopObserverContext ctxt;
213 bzero( &ctxt, sizeof(ctxt) );
214 ctxt.info = this;
215 m_commonModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
216 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXCommonModeObserverCallBack, &ctxt );
217 CFRunLoopAddObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
218
219 m_defaultModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
220 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXDefaultModeObserverCallBack, &ctxt );
221 CFRunLoopAddObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
222 }
223
224 wxCFEventLoop::~wxCFEventLoop()
225 {
226 CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
227 CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
228
229 CFRelease(m_defaultModeRunLoopObserver);
230 CFRelease(m_commonModeRunLoopObserver);
231 }
232
233
234 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
235 {
236 return CFRunLoopGetCurrent();
237 }
238
239 void wxCFEventLoop::WakeUp()
240 {
241 CFRunLoopWakeUp(m_runLoop);
242 }
243
244 #if wxUSE_BASE
245
246 void wxMacWakeUp()
247 {
248 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
249
250 if ( loop )
251 loop->WakeUp();
252 }
253
254 #endif
255
256 bool wxCFEventLoop::YieldFor(long eventsToProcess)
257 {
258 #if wxUSE_THREADS
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() )
262 {
263 return true;
264 }
265 #endif // wxUSE_THREADS
266
267 m_isInsideYield = true;
268 m_eventsToProcessInsideYield = eventsToProcess;
269
270 #if wxUSE_LOG
271 // disable log flushing from here because a call to wxYield() shouldn't
272 // normally result in message boxes popping up &c
273 wxLog::Suspend();
274 #endif // wxUSE_LOG
275
276 // process all pending events:
277 while ( DoProcessEvents() == 1 )
278 ;
279
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() ) {}
284
285 // if there are pending events, we must process them.
286 if (wxTheApp)
287 wxTheApp->ProcessPendingEvents();
288
289 #if wxUSE_LOG
290 wxLog::Resume();
291 #endif // wxUSE_LOG
292 m_isInsideYield = false;
293
294 return true;
295 }
296
297 // implement/override base class pure virtual
298 bool wxCFEventLoop::Pending() const
299 {
300 return true;
301 }
302
303 int wxCFEventLoop::DoProcessEvents()
304 {
305 #if wxUSE_UIACTIONSIMULATOR
306 if ( m_shouldWaitForEvent )
307 {
308 int handled = DispatchTimeout( 1000 );
309 wxASSERT_MSG( handled == 1, "No Event Available");
310 m_shouldWaitForEvent = false;
311 return handled;
312 }
313 else
314 #endif
315 return DispatchTimeout( 0 );
316 }
317
318 bool wxCFEventLoop::Dispatch()
319 {
320 return DoProcessEvents() != 0;
321 }
322
323 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
324 {
325 if ( !wxTheApp )
326 return 0;
327
328 int status = DoDispatchTimeout(timeout);
329
330 switch( status )
331 {
332 case 0:
333 break;
334 case -1:
335 if ( m_shouldExit )
336 return 0;
337
338 break;
339 case 1:
340 break;
341 }
342
343 return status;
344 }
345
346 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
347 {
348 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
349 switch( status )
350 {
351 case kCFRunLoopRunFinished:
352 wxFAIL_MSG( "incorrect run loop state" );
353 break;
354 case kCFRunLoopRunStopped:
355 return 0;
356 break;
357 case kCFRunLoopRunTimedOut:
358 return -1;
359 break;
360 case kCFRunLoopRunHandledSource:
361 default:
362 break;
363 }
364 return 1;
365 }
366
367 void wxCFEventLoop::OSXDoRun()
368 {
369 for ( ;; )
370 {
371 // generate and process idle events for as long as we don't
372 // have anything else to do
373 DoProcessEvents();
374
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
378 if ( m_shouldExit )
379 {
380 while ( DoProcessEvents() == 1 )
381 ;
382
383 break;
384 }
385 }
386 }
387
388 void wxCFEventLoop::OSXDoStop()
389 {
390 CFRunLoopStop(CFGetCurrentRunLoop());
391 }
392
393 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
394 // terminating when Exit() is called
395 int wxCFEventLoop::DoRun()
396 {
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
408
409 OSXDoRun();
410
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
437
438 return m_exitcode;
439 }
440
441 // sets the "should exit" flag and wakes up the loop so that it terminates
442 // soon
443 void wxCFEventLoop::ScheduleExit(int rc)
444 {
445 m_exitcode = rc;
446 m_shouldExit = true;
447 OSXDoStop();
448 }
449
450 wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
451 {
452 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
453 if ( cfl )
454 {
455 m_formerState = cfl->ShouldProcessIdleEvents();
456 cfl->SetProcessIdleEvents(false);
457 }
458 else
459 m_formerState = true;
460 }
461
462 wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
463 {
464 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
465 if ( cfl )
466 cfl->SetProcessIdleEvents(m_formerState);
467 }
468
469 // TODO Move to thread_osx.cpp
470
471 #if wxUSE_THREADS
472
473 // ----------------------------------------------------------------------------
474 // GUI Serialization copied from MSW implementation
475 // ----------------------------------------------------------------------------
476
477 // if it's false, some secondary thread is holding the GUI lock
478 static bool gs_bGuiOwnedByMainThread = true;
479
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
482 // any GUI calls
483 static wxCriticalSection *gs_critsectGui = NULL;
484
485 // critical section which protects gs_nWaitingForGui variable
486 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
487
488 // number of threads waiting for GUI in wxMutexGuiEnter()
489 static size_t gs_nWaitingForGui = 0;
490
491 void wxOSXThreadModuleOnInit()
492 {
493 gs_critsectWaitingForGui = new wxCriticalSection();
494 gs_critsectGui = new wxCriticalSection();
495 gs_critsectGui->Enter();
496 }
497
498
499 void wxOSXThreadModuleOnExit()
500 {
501 if ( gs_critsectGui )
502 {
503 if ( !wxGuiOwnedByMainThread() )
504 {
505 gs_critsectGui->Enter();
506 gs_bGuiOwnedByMainThread = true;
507 }
508
509 gs_critsectGui->Leave();
510 wxDELETE(gs_critsectGui);
511 }
512
513 wxDELETE(gs_critsectWaitingForGui);
514 }
515
516
517 // wake up the main thread
518 void WXDLLIMPEXP_BASE wxWakeUpMainThread()
519 {
520 wxMacWakeUp();
521 }
522
523 void wxMutexGuiEnterImpl()
524 {
525 // this would dead lock everything...
526 wxASSERT_MSG( !wxThread::IsMain(),
527 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
528
529 // the order in which we enter the critical sections here is crucial!!
530
531 // set the flag telling to the main thread that we want to do some GUI
532 {
533 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
534
535 gs_nWaitingForGui++;
536 }
537
538 wxWakeUpMainThread();
539
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();
543 }
544
545 void wxMutexGuiLeaveImpl()
546 {
547 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
548
549 if ( wxThread::IsMain() )
550 {
551 gs_bGuiOwnedByMainThread = false;
552 }
553 else
554 {
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?") );
558
559 gs_nWaitingForGui--;
560
561 wxWakeUpMainThread();
562 }
563
564 gs_critsectGui->Leave();
565 }
566
567 void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
568 {
569 wxASSERT_MSG( wxThread::IsMain(),
570 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
571
572 if ( !gs_critsectWaitingForGui )
573 return;
574
575 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
576
577 if ( gs_nWaitingForGui == 0 )
578 {
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() )
582 {
583 gs_critsectGui->Enter();
584
585 gs_bGuiOwnedByMainThread = true;
586 }
587 //else: already have it, nothing to do
588 }
589 else
590 {
591 // some threads are waiting, release the GUI lock if we have it
592 if ( wxGuiOwnedByMainThread() )
593 wxMutexGuiLeave();
594 //else: some other worker thread is doing GUI
595 }
596 }
597
598 bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
599 {
600 return gs_bGuiOwnedByMainThread;
601 }
602
603 #endif