adding a app-defined event seems to quit inner eventloops like eg the popup of the...
[wxWidgets.git] / src / osx / cocoa / evtloop.mm
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/cocoa/evtloop.mm
3 // Purpose:     implementation of wxEventLoop for OS X
4 // Author:      Vadim Zeitlin, Stefan Csomor
5 // Modified by:
6 // Created:     2006-01-12
7 // RCS-ID:      $Id$
8 // Copyright:   (c) 2006 Vadim Zeitlin <vadim@wxwindows.org>
9 // Licence:     wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24     #pragma hdrstop
25 #endif
26
27 #include "wx/evtloop.h"
28
29 #ifndef WX_PRECOMP
30     #include "wx/app.h"
31     #include "wx/nonownedwnd.h"
32 #endif // WX_PRECOMP
33
34 #include "wx/log.h"
35
36 #include "wx/osx/private.h"
37
38 // ============================================================================
39 // wxEventLoop implementation
40 // ============================================================================
41
42 #if 0
43
44 // in case we want to integrate this
45
46 static NSUInteger CalculateNSEventMaskFromEventCategory(wxEventCategory cat)
47 {
48     // the masking system doesn't really help, as only the lowlevel UI events
49     // are split in a useful way, all others are way to broad
50         
51     if ( (cat | wxEVT_CATEGORY_USER_INPUT) && (cat | (~wxEVT_CATEGORY_USER_INPUT) ) )
52         return NSAnyEventMask;
53     
54     NSUInteger mask = 0;
55
56     if ( cat | wxEVT_CATEGORY_USER_INPUT )
57     {
58         mask |=
59             NSLeftMouseDownMask |
60             NSLeftMouseUpMask |
61             NSRightMouseDownMask |
62             NSRightMouseUpMask |
63             NSMouseMovedMask |
64             NSLeftMouseDraggedMask |
65             NSRightMouseDraggedMask |
66             NSMouseEnteredMask |
67             NSMouseExitedMask |
68             NSScrollWheelMask |
69 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
70             NSTabletPointMask |
71             NSTabletProximityMask |
72 #endif
73             NSOtherMouseDownMask |
74             NSOtherMouseUpMask |
75             NSOtherMouseDraggedMask |
76
77             NSKeyDownMask |
78             NSKeyUpMask |
79             NSFlagsChangedMask |
80 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
81             NSEventMaskGesture |
82             NSEventMaskMagnify |
83             NSEventMaskSwipe |
84             NSEventMaskRotate |
85             NSEventMaskBeginGesture |
86             NSEventMaskEndGesture |
87 #endif
88             0;
89     }
90     
91     if ( cat | (~wxEVT_CATEGORY_USER_INPUT) )
92     {
93         mask |= 
94             NSAppKitDefinedMask |
95             NSSystemDefinedMask |
96             NSApplicationDefinedMask |
97             NSPeriodicMask |
98             NSCursorUpdateMask;
99     }
100     
101     return mask;
102 }
103
104 #endif
105
106 wxGUIEventLoop::wxGUIEventLoop()
107 {
108     m_modalSession = nil;
109     m_dummyWindow = nil;
110     m_modalNestedLevel = 0;
111     m_modalWindow = NULL;
112 }
113
114 wxGUIEventLoop::~wxGUIEventLoop()
115 {
116     wxASSERT( m_modalSession == nil );
117     wxASSERT( m_dummyWindow == nil );
118     wxASSERT( m_modalNestedLevel == 0 );
119 }
120
121 //-----------------------------------------------------------------------------
122 // events dispatch and loop handling
123 //-----------------------------------------------------------------------------
124
125 #if 0
126
127 bool wxGUIEventLoop::Pending() const
128 {
129 #if 0
130     // this code doesn't reliably detect pending events
131     // so better return true and have the dispatch deal with it
132     // as otherwise we end up in a tight loop when idle events are responded
133     // to by RequestMore(true)
134     wxMacAutoreleasePool autoreleasepool;
135   
136     return [[NSApplication sharedApplication]
137             nextEventMatchingMask: NSAnyEventMask
138             untilDate: nil
139             inMode: NSDefaultRunLoopMode
140             dequeue: NO] != nil;
141 #else
142     return true;
143 #endif
144 }
145
146
147 bool wxGUIEventLoop::Dispatch()
148 {
149     if ( !wxTheApp )
150         return false;
151
152     wxMacAutoreleasePool autoreleasepool;
153
154     if(NSEvent *event = [NSApp
155                 nextEventMatchingMask:NSAnyEventMask
156                 untilDate:[NSDate dateWithTimeIntervalSinceNow: m_sleepTime]
157                 inMode:NSDefaultRunLoopMode
158                 dequeue: YES])
159     {
160         WXEVENTREF formerEvent = wxTheApp == NULL ? NULL : wxTheApp->MacGetCurrentEvent();
161         WXEVENTHANDLERCALLREF formerHandler = wxTheApp == NULL ? NULL : wxTheApp->MacGetCurrentEventHandlerCallRef();
162
163         if (wxTheApp)
164             wxTheApp->MacSetCurrentEvent(event, NULL);
165         m_sleepTime = 0.0;
166         [NSApp sendEvent: event];
167
168         if (wxTheApp)
169             wxTheApp->MacSetCurrentEvent(formerEvent , formerHandler);
170     }
171     else
172     {
173         if (wxTheApp)
174             wxTheApp->ProcessPendingEvents();
175         
176         if ( wxTheApp->ProcessIdle() )
177             m_sleepTime = 0.0 ;
178         else
179         {
180             m_sleepTime = 1.0;
181 #if wxUSE_THREADS
182             wxMutexGuiLeave();
183             wxMilliSleep(20);
184             wxMutexGuiEnter();
185 #endif
186         }
187     }
188
189     return true;
190 }
191
192 #endif
193
194 int wxGUIEventLoop::DoDispatchTimeout(unsigned long timeout)
195 {
196     wxMacAutoreleasePool autoreleasepool;
197
198     if ( m_modalSession )
199     {
200         NSInteger response = [NSApp runModalSession:(NSModalSession)m_modalSession];
201         
202         switch (response) 
203         {
204             case NSRunContinuesResponse:
205             {
206                 if ( [[NSApplication sharedApplication]
207                         nextEventMatchingMask: NSAnyEventMask
208                         untilDate: nil
209                         inMode: NSDefaultRunLoopMode
210                         dequeue: NO] != nil )
211                     return 1;
212                 
213                 return -1;
214             }
215                 
216             case NSRunStoppedResponse:
217             case NSRunAbortedResponse:
218                 return -1;
219             default:
220                 wxFAIL_MSG("unknown response code");
221                 break;
222         }
223         return -1;
224     }
225     else 
226     {        
227         NSEvent *event = [NSApp
228                     nextEventMatchingMask:NSAnyEventMask
229                     untilDate:[NSDate dateWithTimeIntervalSinceNow: timeout/1000]
230                     inMode:NSDefaultRunLoopMode
231                     dequeue: YES];
232         
233         if ( event == nil )
234             return -1;
235
236         [NSApp sendEvent: event];
237
238         return 1;
239     }
240 }
241
242 void wxGUIEventLoop::DoRun()
243 {
244     wxMacAutoreleasePool autoreleasepool;
245     [NSApp run];
246 }
247
248 void wxGUIEventLoop::DoStop()
249 {
250     // only calling stop: is not enough when called from a runloop-observer,
251     // therefore add a dummy event, to make sure the runloop gets another round
252     [NSApp stop:0];
253     WakeUp();
254 }
255
256 void wxGUIEventLoop::WakeUp()
257 {
258     NSEvent* cevent = [NSApp currentEvent];
259     
260     // when already in a mouse event handler, don't add higher level event
261     if ( cevent != nil && [cevent type] < NSKeyDown )
262     {
263         wxCFEventLoop::WakeUp();        
264     }
265     else
266     {
267         wxMacAutoreleasePool autoreleasepool;
268         NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined 
269                                         location:NSMakePoint(0.0, 0.0) 
270                                    modifierFlags:0 
271                                        timestamp:0 
272                                     windowNumber:0 
273                                          context:nil
274                                          subtype:0 data1:0 data2:0]; 
275         [NSApp postEvent:event atStart:FALSE];
276     }
277 }
278
279 CFRunLoopRef wxGUIEventLoop::CFGetCurrentRunLoop() const
280 {
281     NSRunLoop* nsloop = [NSRunLoop currentRunLoop];
282     return [nsloop getCFRunLoop];
283 }
284
285
286 // TODO move into a evtloop_osx.cpp
287
288 wxModalEventLoop::wxModalEventLoop(wxWindow *modalWindow)
289 {
290     m_modalWindow = dynamic_cast<wxNonOwnedWindow*> (modalWindow);
291     wxASSERT_MSG( m_modalWindow != NULL, "must pass in a toplevel window for modal event loop" );
292     m_modalNativeWindow = m_modalWindow->GetWXWindow();
293 }
294
295 wxModalEventLoop::wxModalEventLoop(WXWindow modalNativeWindow)
296 {
297     m_modalWindow = NULL;
298     wxASSERT_MSG( modalNativeWindow != NULL, "must pass in a toplevel window for modal event loop" );
299     m_modalNativeWindow = modalNativeWindow;
300 }
301
302 // END move into a evtloop_osx.cpp
303
304 void wxModalEventLoop::DoRun()
305 {
306     wxMacAutoreleasePool pool;
307
308     // If the app hasn't started, flush the event queue
309     // If we don't do this, the Dock doesn't get the message that
310     // the app has started so will refuse to activate it.
311     [NSApplication sharedApplication];
312     if (![NSApp isRunning])
313     {
314         while(NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES])
315         {
316             [NSApp sendEvent:event];
317         }
318     }
319     
320     [NSApp runModalForWindow:m_modalNativeWindow];
321 }
322
323 void wxModalEventLoop::DoStop()
324 {
325     [NSApp abortModal];
326 }
327
328 void wxGUIEventLoop::BeginModalSession( wxWindow* modalWindow )
329 {
330     WXWindow nsnow = nil;
331
332     if ( m_modalNestedLevel > 0 )
333     {
334         wxASSERT_MSG( m_modalWindow == modalWindow, "Nested Modal Sessions must be based on same window");
335         m_modalNestedLevel++;
336         return;
337     }
338     
339     m_modalWindow = modalWindow;
340     m_modalNestedLevel = 1;
341     
342     if ( modalWindow )
343     {
344         // we must show now, otherwise beginModalSessionForWindow does it but it
345         // also would do a centering of the window before overriding all our position
346         if ( !modalWindow->IsShownOnScreen() )
347             modalWindow->Show();
348         
349         wxNonOwnedWindow* now = dynamic_cast<wxNonOwnedWindow*> (modalWindow);
350         wxASSERT_MSG( now != NULL, "must pass in a toplevel window for modal event loop" );
351         nsnow = now ? now->GetWXWindow() : nil;
352     }
353     else
354     {
355         NSRect r = NSMakeRect(10, 10, 0, 0);
356         nsnow = [NSPanel alloc];
357         [nsnow initWithContentRect:r
358                                styleMask:NSBorderlessWindowMask
359                                  backing:NSBackingStoreBuffered
360                                    defer:YES
361          ];
362         [nsnow orderOut:nil];
363         m_dummyWindow = nsnow;
364     }
365     m_modalSession = [NSApp beginModalSessionForWindow:nsnow];
366     wxASSERT_MSG(m_modalSession != NULL, "modal session couldn't be started");
367 }
368
369 void wxGUIEventLoop::EndModalSession()
370 {
371     wxASSERT_MSG(m_modalSession != NULL, "no modal session active");
372     
373     wxASSERT_MSG(m_modalNestedLevel > 0, "incorrect modal nesting level");
374     
375     if ( --m_modalNestedLevel == 0 )
376     {
377         [NSApp endModalSession:(NSModalSession)m_modalSession];
378         m_modalSession = nil;
379         if ( m_dummyWindow )
380         {
381             [m_dummyWindow release];
382             m_dummyWindow = nil;
383         }
384     }
385 }
386
387 //
388 // 
389 //
390
391 wxWindowDisabler::wxWindowDisabler(bool disable)
392 {
393     m_modalEventLoop = NULL;
394     m_disabled = disable;
395     if ( disable )
396         DoDisable();
397 }
398
399 wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip)
400 {
401     m_disabled = true;
402     DoDisable(winToSkip);
403 }
404
405 void wxWindowDisabler::DoDisable(wxWindow *winToSkip)
406 {    
407     // remember the top level windows which were already disabled, so that we
408     // don't reenable them later
409     m_winDisabled = NULL;
410     
411     wxWindowList::compatibility_iterator node;
412     for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
413     {
414         wxWindow *winTop = node->GetData();
415         if ( winTop == winToSkip )
416             continue;
417         
418         // we don't need to disable the hidden or already disabled windows
419         if ( winTop->IsEnabled() && winTop->IsShown() )
420         {
421             winTop->Disable();
422         }
423         else
424         {
425             if ( !m_winDisabled )
426             {
427                 m_winDisabled = new wxWindowList;
428             }
429             
430             m_winDisabled->Append(winTop);
431         }
432     }
433     
434     m_modalEventLoop = (wxEventLoop*)wxEventLoopBase::GetActive();
435     if (m_modalEventLoop)
436         m_modalEventLoop->BeginModalSession(winToSkip);
437 }
438
439 wxWindowDisabler::~wxWindowDisabler()
440 {
441     if ( !m_disabled )
442         return;
443     
444     if (m_modalEventLoop)
445         m_modalEventLoop->EndModalSession();
446     
447     wxWindowList::compatibility_iterator node;
448     for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() )
449     {
450         wxWindow *winTop = node->GetData();
451         if ( !m_winDisabled || !m_winDisabled->Find(winTop) )
452         {
453             winTop->Enable();
454         }
455         //else: had been already disabled, don't reenable
456     }
457     
458     delete m_winDisabled;
459 }
460