]> git.saurik.com Git - wxWidgets.git/blob - src/osx/core/evtloop_cf.cpp
Compilation fix for wxMSW with wxUSE_MSGBOX_HOOK==0.
[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 // Copyright: (c) 2009 Vadim Zeitlin <vadim@wxwidgets.org>
7 // (c) 2013 Rob Bresalier
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 #include <CoreFoundation/CFSocket.h>
46
47 // ============================================================================
48 // wxCFEventLoopSource and wxCFEventLoop implementation
49 // ============================================================================
50
51 #if wxUSE_EVENTLOOP_SOURCE
52
53 void wxCFEventLoopSource::InitSourceSocket(CFSocketRef cfSocket)
54 {
55 wxASSERT_MSG( !m_cfSocket, "shouldn't be called more than once" );
56
57 m_cfSocket = cfSocket;
58 }
59
60 wxCFEventLoopSource::~wxCFEventLoopSource()
61 {
62 if ( m_cfSocket )
63 {
64 CFSocketInvalidate(m_cfSocket);
65 CFRelease(m_cfSocket);
66 }
67 }
68
69 #endif // wxUSE_EVENTLOOP_SOURCE
70
71 void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
72 {
73 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
74 if ( eventloop )
75 eventloop->CommonModeObserverCallBack(observer, activity);
76 }
77
78 void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
79 {
80 wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
81 if ( eventloop )
82 eventloop->DefaultModeObserverCallBack(observer, activity);
83 }
84
85 void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
86 {
87 if ( activity & kCFRunLoopBeforeTimers )
88 {
89 // process pending wx events first as they correspond to low-level events
90 // which happened before, i.e. typically pending events were queued by a
91 // previous call to Dispatch() and if we didn't process them now the next
92 // call to it might enqueue them again (as happens with e.g. socket events
93 // which would be generated as long as there is input available on socket
94 // and this input is only removed from it when pending event handlers are
95 // executed)
96
97 if ( wxTheApp && ShouldProcessIdleEvents() )
98 wxTheApp->ProcessPendingEvents();
99 }
100
101 if ( activity & kCFRunLoopBeforeWaiting )
102 {
103 if ( ShouldProcessIdleEvents() && ProcessIdle() )
104 {
105 WakeUp();
106 }
107 else
108 {
109 #if wxUSE_THREADS
110 wxMutexGuiLeaveOrEnter();
111 #endif
112 }
113 }
114 }
115
116 void
117 wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer),
118 int WXUNUSED(activity))
119 {
120 /*
121 if ( activity & kCFRunLoopBeforeTimers )
122 {
123 }
124
125 if ( activity & kCFRunLoopBeforeWaiting )
126 {
127 }
128 */
129 }
130
131
132 wxCFEventLoop::wxCFEventLoop()
133 {
134 m_shouldExit = false;
135 m_processIdleEvents = true;
136
137 #if wxUSE_UIACTIONSIMULATOR
138 m_shouldWaitForEvent = false;
139 #endif
140
141 m_runLoop = CFGetCurrentRunLoop();
142
143 CFRunLoopObserverContext ctxt;
144 bzero( &ctxt, sizeof(ctxt) );
145 ctxt.info = this;
146 m_commonModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
147 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXCommonModeObserverCallBack, &ctxt );
148 CFRunLoopAddObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
149
150 m_defaultModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
151 (CFRunLoopObserverCallBack) wxCFEventLoop::OSXDefaultModeObserverCallBack, &ctxt );
152 CFRunLoopAddObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
153 }
154
155 wxCFEventLoop::~wxCFEventLoop()
156 {
157 CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
158 CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
159
160 CFRelease(m_defaultModeRunLoopObserver);
161 CFRelease(m_commonModeRunLoopObserver);
162 }
163
164
165 CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
166 {
167 return CFRunLoopGetCurrent();
168 }
169
170 void wxCFEventLoop::WakeUp()
171 {
172 CFRunLoopWakeUp(m_runLoop);
173 }
174
175 #if wxUSE_BASE
176
177 void wxMacWakeUp()
178 {
179 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
180
181 if ( loop )
182 loop->WakeUp();
183 }
184
185 #endif
186
187 bool wxCFEventLoop::YieldFor(long eventsToProcess)
188 {
189 #if wxUSE_THREADS
190 // Yielding from a non-gui thread needs to bail out, otherwise we end up
191 // possibly sending events in the thread too.
192 if ( !wxThread::IsMain() )
193 {
194 return true;
195 }
196 #endif // wxUSE_THREADS
197
198 m_isInsideYield = true;
199 m_eventsToProcessInsideYield = eventsToProcess;
200
201 #if wxUSE_LOG
202 // disable log flushing from here because a call to wxYield() shouldn't
203 // normally result in message boxes popping up &c
204 wxLog::Suspend();
205 #endif // wxUSE_LOG
206
207 // process all pending events:
208 while ( DoProcessEvents() == 1 )
209 ;
210
211 // it's necessary to call ProcessIdle() to update the frames sizes which
212 // might have been changed (it also will update other things set from
213 // OnUpdateUI() which is a nice (and desired) side effect)
214 while ( ProcessIdle() ) {}
215
216 // if there are pending events, we must process them.
217 if (wxTheApp)
218 wxTheApp->ProcessPendingEvents();
219
220 #if wxUSE_LOG
221 wxLog::Resume();
222 #endif // wxUSE_LOG
223 m_isInsideYield = false;
224
225 return true;
226 }
227
228 // implement/override base class pure virtual
229 bool wxCFEventLoop::Pending() const
230 {
231 return true;
232 }
233
234 int wxCFEventLoop::DoProcessEvents()
235 {
236 #if wxUSE_UIACTIONSIMULATOR
237 if ( m_shouldWaitForEvent )
238 {
239 int handled = DispatchTimeout( 1000 );
240 wxASSERT_MSG( handled == 1, "No Event Available");
241 m_shouldWaitForEvent = false;
242 return handled;
243 }
244 else
245 #endif
246 return DispatchTimeout( 0 );
247 }
248
249 bool wxCFEventLoop::Dispatch()
250 {
251 return DoProcessEvents() != 0;
252 }
253
254 int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
255 {
256 if ( !wxTheApp )
257 return 0;
258
259 int status = DoDispatchTimeout(timeout);
260
261 switch( status )
262 {
263 case 0:
264 break;
265 case -1:
266 if ( m_shouldExit )
267 return 0;
268
269 break;
270 case 1:
271 break;
272 }
273
274 return status;
275 }
276
277 int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
278 {
279 SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
280 switch( status )
281 {
282 case kCFRunLoopRunFinished:
283 wxFAIL_MSG( "incorrect run loop state" );
284 break;
285 case kCFRunLoopRunStopped:
286 return 0;
287 break;
288 case kCFRunLoopRunTimedOut:
289 return -1;
290 break;
291 case kCFRunLoopRunHandledSource:
292 default:
293 break;
294 }
295 return 1;
296 }
297
298 void wxCFEventLoop::OSXDoRun()
299 {
300 for ( ;; )
301 {
302 // generate and process idle events for as long as we don't
303 // have anything else to do
304 DoProcessEvents();
305
306 // if the "should exit" flag is set, the loop should terminate
307 // but not before processing any remaining messages so while
308 // Pending() returns true, do process them
309 if ( m_shouldExit )
310 {
311 while ( DoProcessEvents() == 1 )
312 ;
313
314 break;
315 }
316 }
317 }
318
319 void wxCFEventLoop::OSXDoStop()
320 {
321 CFRunLoopStop(CFGetCurrentRunLoop());
322 }
323
324 // enters a loop calling OnNextIteration(), Pending() and Dispatch() and
325 // terminating when Exit() is called
326 int wxCFEventLoop::DoRun()
327 {
328 // we must ensure that OnExit() is called even if an exception is thrown
329 // from inside ProcessEvents() but we must call it from Exit() in normal
330 // situations because it is supposed to be called synchronously,
331 // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
332 // something similar here)
333 #if wxUSE_EXCEPTIONS
334 for ( ;; )
335 {
336 try
337 {
338 #endif // wxUSE_EXCEPTIONS
339
340 OSXDoRun();
341
342 #if wxUSE_EXCEPTIONS
343 // exit the outer loop as well
344 break;
345 }
346 catch ( ... )
347 {
348 try
349 {
350 if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
351 {
352 OnExit();
353 break;
354 }
355 //else: continue running the event loop
356 }
357 catch ( ... )
358 {
359 // OnException() throwed, possibly rethrowing the same
360 // exception again: very good, but we still need OnExit() to
361 // be called
362 OnExit();
363 throw;
364 }
365 }
366 }
367 #endif // wxUSE_EXCEPTIONS
368
369 return m_exitcode;
370 }
371
372 // sets the "should exit" flag and wakes up the loop so that it terminates
373 // soon
374 void wxCFEventLoop::ScheduleExit(int rc)
375 {
376 m_exitcode = rc;
377 m_shouldExit = true;
378 OSXDoStop();
379 }
380
381 wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
382 {
383 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
384 if ( cfl )
385 {
386 m_formerState = cfl->ShouldProcessIdleEvents();
387 cfl->SetProcessIdleEvents(false);
388 }
389 else
390 m_formerState = true;
391 }
392
393 wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
394 {
395 wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
396 if ( cfl )
397 cfl->SetProcessIdleEvents(m_formerState);
398 }
399
400 // TODO Move to thread_osx.cpp
401
402 #if wxUSE_THREADS
403
404 // ----------------------------------------------------------------------------
405 // GUI Serialization copied from MSW implementation
406 // ----------------------------------------------------------------------------
407
408 // if it's false, some secondary thread is holding the GUI lock
409 static bool gs_bGuiOwnedByMainThread = true;
410
411 // critical section which controls access to all GUI functions: any secondary
412 // thread (i.e. except the main one) must enter this crit section before doing
413 // any GUI calls
414 static wxCriticalSection *gs_critsectGui = NULL;
415
416 // critical section which protects gs_nWaitingForGui variable
417 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
418
419 // number of threads waiting for GUI in wxMutexGuiEnter()
420 static size_t gs_nWaitingForGui = 0;
421
422 void wxOSXThreadModuleOnInit()
423 {
424 gs_critsectWaitingForGui = new wxCriticalSection();
425 gs_critsectGui = new wxCriticalSection();
426 gs_critsectGui->Enter();
427 }
428
429
430 void wxOSXThreadModuleOnExit()
431 {
432 if ( gs_critsectGui )
433 {
434 if ( !wxGuiOwnedByMainThread() )
435 {
436 gs_critsectGui->Enter();
437 gs_bGuiOwnedByMainThread = true;
438 }
439
440 gs_critsectGui->Leave();
441 wxDELETE(gs_critsectGui);
442 }
443
444 wxDELETE(gs_critsectWaitingForGui);
445 }
446
447
448 // wake up the main thread
449 void WXDLLIMPEXP_BASE wxWakeUpMainThread()
450 {
451 wxMacWakeUp();
452 }
453
454 void wxMutexGuiEnterImpl()
455 {
456 // this would dead lock everything...
457 wxASSERT_MSG( !wxThread::IsMain(),
458 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
459
460 // the order in which we enter the critical sections here is crucial!!
461
462 // set the flag telling to the main thread that we want to do some GUI
463 {
464 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
465
466 gs_nWaitingForGui++;
467 }
468
469 wxWakeUpMainThread();
470
471 // now we may block here because the main thread will soon let us in
472 // (during the next iteration of OnIdle())
473 gs_critsectGui->Enter();
474 }
475
476 void wxMutexGuiLeaveImpl()
477 {
478 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
479
480 if ( wxThread::IsMain() )
481 {
482 gs_bGuiOwnedByMainThread = false;
483 }
484 else
485 {
486 // decrement the number of threads waiting for GUI access now
487 wxASSERT_MSG( gs_nWaitingForGui > 0,
488 wxT("calling wxMutexGuiLeave() without entering it first?") );
489
490 gs_nWaitingForGui--;
491
492 wxWakeUpMainThread();
493 }
494
495 gs_critsectGui->Leave();
496 }
497
498 void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
499 {
500 wxASSERT_MSG( wxThread::IsMain(),
501 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
502
503 if ( !gs_critsectWaitingForGui )
504 return;
505
506 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
507
508 if ( gs_nWaitingForGui == 0 )
509 {
510 // no threads are waiting for GUI - so we may acquire the lock without
511 // any danger (but only if we don't already have it)
512 if ( !wxGuiOwnedByMainThread() )
513 {
514 gs_critsectGui->Enter();
515
516 gs_bGuiOwnedByMainThread = true;
517 }
518 //else: already have it, nothing to do
519 }
520 else
521 {
522 // some threads are waiting, release the GUI lock if we have it
523 if ( wxGuiOwnedByMainThread() )
524 wxMutexGuiLeave();
525 //else: some other worker thread is doing GUI
526 }
527 }
528
529 bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
530 {
531 return gs_bGuiOwnedByMainThread;
532 }
533
534 #endif