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