offer suppression of idle processing (delayed destruction happened too early eg when...
[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 #if wxUSE_EVENTLOOP_SOURCE
29
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #endif
34
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"
41 #include "wx/thread.h"
42
43 #if wxUSE_GUI
44 #include "wx/nonownedwnd.h"
45 #endif
46
47 // ============================================================================
48 // wxCFEventLoopSource and wxCFEventLoop implementation
49 // ============================================================================
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 )
167 wxTheApp->ProcessPendingEvents();
168 }
169
170 if ( activity & kCFRunLoopBeforeWaiting )
171 {
172 if ( m_processIdleEvents && 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 m_runLoop = CFGetCurrentRunLoop();
207
208 CFRunLoopObserverContext ctxt;
209 bzero( &ctxt, sizeof(ctxt) );
210 ctxt.info = this;
211 m_commonModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
212 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXCommonModeObserverCallBack, &ctxt );
213 CFRunLoopAddObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
214
215 m_defaultModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
216 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXDefaultModeObserverCallBack, &ctxt );
217 CFRunLoopAddObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
218 }
219
220 wxCFEventLoop::~wxCFEventLoop()
221 {
222 CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
223 CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
224
225 CFRelease(m_defaultModeRunLoopObserver);
226 CFRelease(m_commonModeRunLoopObserver);
227 }
228
229
230 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
231 {
232 return CFRunLoopGetCurrent();
233 }
234
235 void wxCFEventLoop::WakeUp()
236 {
237 CFRunLoopWakeUp(m_runLoop);
238 }
239
240 #if wxUSE_BASE
241
242 void wxMacWakeUp()
243 {
244 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
245
246 if ( loop )
247 loop->WakeUp();
248 }
249
250 #endif
251
252 bool wxCFEventLoop::YieldFor(long eventsToProcess)
253 {
254 #if wxUSE_THREADS
255 // Yielding from a non-gui thread needs to bail out, otherwise we end up
256 // possibly sending events in the thread too.
257 if ( !wxThread::IsMain() )
258 {
259 return true;
260 }
261 #endif // wxUSE_THREADS
262
263 m_isInsideYield = true;
264 m_eventsToProcessInsideYield = eventsToProcess;
265
266 #if wxUSE_LOG
267 // disable log flushing from here because a call to wxYield() shouldn't
268 // normally result in message boxes popping up &c
269 wxLog::Suspend();
270 #endif // wxUSE_LOG
271
272 // process all pending events:
273 while ( DoProcessEvents() == 1 )
274 ;
275
276 // it's necessary to call ProcessIdle() to update the frames sizes which
277 // might have been changed (it also will update other things set from
278 // OnUpdateUI() which is a nice (and desired) side effect)
279 while ( ProcessIdle() ) {}
280
281 // if there are pending events, we must process them.
282 if (wxTheApp)
283 wxTheApp->ProcessPendingEvents();
284
285 #if wxUSE_LOG
286 wxLog::Resume();
287 #endif // wxUSE_LOG
288 m_isInsideYield = false;
289
290 return true;
291 }
292
293 // implement/override base class pure virtual
294 bool wxCFEventLoop::Pending() const
295 {
296 return true;
297 }
298
299 int wxCFEventLoop::DoProcessEvents()
300 {
301 return DispatchTimeout( 0 );
302 }
303
304 bool wxCFEventLoop::Dispatch()
305 {
306 return DoProcessEvents() != 0;
307 }
308
309 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
310 {
311 if ( !wxTheApp )
312 return 0;
313
314 int status = DoDispatchTimeout(timeout);
315
316 switch( status )
317 {
318 case 0:
319 break;
320 case -1:
321 if ( m_shouldExit )
322 return 0;
323
324 break;
325 case 1:
326 break;
327 }
328
329 return status;
330 }
331
332 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
333 {
334 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
335 switch( status )
336 {
337 case kCFRunLoopRunFinished:
338 wxFAIL_MSG( "incorrect run loop state" );
339 break;
340 case kCFRunLoopRunStopped:
341 return 0;
342 break;
343 case kCFRunLoopRunTimedOut:
344 return -1;
345 break;
346 case kCFRunLoopRunHandledSource:
347 default:
348 break;
349 }
350 return 1;
351 }
352
353 void wxCFEventLoop::DoRun()
354 {
355 for ( ;; )
356 {
357 // generate and process idle events for as long as we don't
358 // have anything else to do
359 DoProcessEvents();
360
361 // if the "should exit" flag is set, the loop should terminate
362 // but not before processing any remaining messages so while
363 // Pending() returns true, do process them
364 if ( m_shouldExit )
365 {
366 while ( DoProcessEvents() == 1 )
367 ;
368
369 break;
370 }
371 }
372 }
373
374 void wxCFEventLoop::DoStop()
375 {
376 CFRunLoopStop(CFGetCurrentRunLoop());
377 }
378
379 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
380 // terminating when Exit() is called
381 int wxCFEventLoop::Run()
382 {
383 // event loops are not recursive, you need to create another loop!
384 wxCHECK_MSG( !IsRunning(), -1, wxT("can't reenter a message loop") );
385
386 // ProcessIdle() and ProcessEvents() below may throw so the code here should
387 // be exception-safe, hence we must use local objects for all actions we
388 // should undo
389 wxEventLoopActivator activate(this);
390
391 // we must ensure that OnExit() is called even if an exception is thrown
392 // from inside ProcessEvents() but we must call it from Exit() in normal
393 // situations because it is supposed to be called synchronously,
394 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
395 // something similar here)
396 #if wxUSE_EXCEPTIONS
397 for ( ;; )
398 {
399 try
400 {
401 #endif // wxUSE_EXCEPTIONS
402
403 DoRun();
404
405 #if wxUSE_EXCEPTIONS
406 // exit the outer loop as well
407 break;
408 }
409 catch ( ... )
410 {
411 try
412 {
413 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
414 {
415 OnExit();
416 break;
417 }
418 //else: continue running the event loop
419 }
420 catch ( ... )
421 {
422 // OnException() throwed, possibly rethrowing the same
423 // exception again: very good, but we still need OnExit() to
424 // be called
425 OnExit();
426 throw;
427 }
428 }
429 }
430 #endif // wxUSE_EXCEPTIONS
431
432 return m_exitcode;
433 }
434
435 // sets the "should exit" flag and wakes up the loop so that it terminates
436 // soon
437 void wxCFEventLoop::Exit(int rc)
438 {
439 m_exitcode = rc;
440 m_shouldExit = true;
441 DoStop();
442 }
443
444 wxCFEventLoopPauseObservers::wxCFEventLoopPauseObservers()
445 {
446 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
447 if ( cfl )
448 cfl->SetProcessIdleEvents(false);
449 }
450
451 wxCFEventLoopPauseObservers::~wxCFEventLoopPauseObservers()
452 {
453 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
454 if ( cfl )
455 cfl->SetProcessIdleEvents(true);
456 }
457
458 // TODO Move to thread_osx.cpp
459
460 #if wxUSE_THREADS
461
462 // ----------------------------------------------------------------------------
463 // GUI Serialization copied from MSW implementation
464 // ----------------------------------------------------------------------------
465
466 // if it's false, some secondary thread is holding the GUI lock
467 static bool gs_bGuiOwnedByMainThread = true;
468
469 // critical section which controls access to all GUI functions: any secondary
470 // thread (i.e. except the main one) must enter this crit section before doing
471 // any GUI calls
472 static wxCriticalSection *gs_critsectGui = NULL;
473
474 // critical section which protects gs_nWaitingForGui variable
475 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
476
477 // number of threads waiting for GUI in wxMutexGuiEnter()
478 static size_t gs_nWaitingForGui = 0;
479
480 void wxOSXThreadModuleOnInit()
481 {
482 gs_critsectWaitingForGui = new wxCriticalSection();
483 gs_critsectGui = new wxCriticalSection();
484 gs_critsectGui->Enter();
485 }
486
487
488 void wxOSXThreadModuleOnExit()
489 {
490 if ( gs_critsectGui )
491 {
492 if ( !wxGuiOwnedByMainThread() )
493 {
494 gs_critsectGui->Enter();
495 gs_bGuiOwnedByMainThread = true;
496 }
497
498 gs_critsectGui->Leave();
499 wxDELETE(gs_critsectGui);
500 }
501
502 wxDELETE(gs_critsectWaitingForGui);
503 }
504
505
506 // wake up the main thread
507 void WXDLLIMPEXP_BASE wxWakeUpMainThread()
508 {
509 wxMacWakeUp();
510 }
511
512 void wxMutexGuiEnterImpl()
513 {
514 // this would dead lock everything...
515 wxASSERT_MSG( !wxThread::IsMain(),
516 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
517
518 // the order in which we enter the critical sections here is crucial!!
519
520 // set the flag telling to the main thread that we want to do some GUI
521 {
522 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
523
524 gs_nWaitingForGui++;
525 }
526
527 wxWakeUpMainThread();
528
529 // now we may block here because the main thread will soon let us in
530 // (during the next iteration of OnIdle())
531 gs_critsectGui->Enter();
532 }
533
534 void wxMutexGuiLeaveImpl()
535 {
536 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
537
538 if ( wxThread::IsMain() )
539 {
540 gs_bGuiOwnedByMainThread = false;
541 }
542 else
543 {
544 // decrement the number of threads waiting for GUI access now
545 wxASSERT_MSG( gs_nWaitingForGui > 0,
546 wxT("calling wxMutexGuiLeave() without entering it first?") );
547
548 gs_nWaitingForGui--;
549
550 wxWakeUpMainThread();
551 }
552
553 gs_critsectGui->Leave();
554 }
555
556 void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
557 {
558 wxASSERT_MSG( wxThread::IsMain(),
559 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
560
561 if ( !gs_critsectWaitingForGui )
562 return;
563
564 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
565
566 if ( gs_nWaitingForGui == 0 )
567 {
568 // no threads are waiting for GUI - so we may acquire the lock without
569 // any danger (but only if we don't already have it)
570 if ( !wxGuiOwnedByMainThread() )
571 {
572 gs_critsectGui->Enter();
573
574 gs_bGuiOwnedByMainThread = true;
575 }
576 //else: already have it, nothing to do
577 }
578 else
579 {
580 // some threads are waiting, release the GUI lock if we have it
581 if ( wxGuiOwnedByMainThread() )
582 wxMutexGuiLeave();
583 //else: some other worker thread is doing GUI
584 }
585 }
586
587 bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
588 {
589 return gs_bGuiOwnedByMainThread;
590 }
591
592 #endif