1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/app.mm
4 // Author: David Elliott
8 // Copyright: (c) David Elliott
9 // Licence: wxWidgets licence
10 /////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
22 #include "wx/module.h"
24 #include "wx/cocoa/ObjcPose.h"
25 #include "wx/cocoa/autorelease.h"
26 #include "wx/cocoa/mbarman.h"
27 #include "wx/cocoa/NSApplication.h"
29 #if wxUSE_WX_RESOURCES
30 # include "wx/resource.h"
33 #import <AppKit/NSApplication.h>
34 #import <Foundation/NSRunLoop.h>
35 #import <Foundation/NSThread.h>
36 #import <AppKit/NSEvent.h>
37 #import <Foundation/NSString.h>
38 #import <Foundation/NSNotification.h>
39 #import <AppKit/NSCell.h>
41 // ========================================================================
42 // wxPoseAsInitializer
43 // ========================================================================
44 wxPoseAsInitializer *wxPoseAsInitializer::sm_first = NULL;
46 static bool sg_needIdle = true;
48 // ========================================================================
49 // wxPoserNSApplication
50 // ========================================================================
51 @interface wxPoserNSApplication : NSApplication
55 - (NSEvent *)nextEventMatchingMask:(unsigned int)mask untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)flag;
56 - (void)sendEvent: (NSEvent*)anEvent;
57 @end // wxPoserNSApplication
59 WX_IMPLEMENT_POSER(wxPoserNSApplication);
61 @implementation wxPoserNSApplication : NSApplication
63 /* NOTE: The old method of idle event handling added the handler using the
64 [NSRunLoop -performSelector:target:argument:order:modes] which caused
65 the invocation to occur at the begining of [NSApplication
66 -nextEventMatchingMask:untilDate:expiration:inMode:dequeue:]. However,
67 the code would be scheduled for invocation with every iteration of
68 the event loop. This new method simply overrides the method. The
69 same caveats apply. In particular, by the time the event loop has
70 called this method, it usually expects to receive an event. If you
71 plan on stopping the event loop, it is wise to send an event through
72 the queue to ensure this method will return.
73 See wxEventLoop::Exit() for more information.
75 This overridden method calls the superclass method with an untilDate
76 parameter that indicates nil should be returned if there are no pending
77 events. That is, nextEventMatchingMask: should not wait for an event.
78 If nil is returned then idle event processing occurs until the user
79 does not request anymore idle events or until a real event comes through.
81 RN: Even though Apple documentation states that nil can be passed in place
82 of [NSDate distantPast] in the untilDate parameter, this causes Jaguar (10.2)
83 to get stuck in some kind of loop deep within nextEventMatchingMask:, thus we
84 need to explicitly pass [NSDate distantPast] instead.
87 - (NSEvent *)nextEventMatchingMask:(unsigned int)mask untilDate:(NSDate *)expiration inMode:(NSString *)mode dequeue:(BOOL)flag
89 // Get the same events except don't block
90 NSEvent *event = [super nextEventMatchingMask:mask untilDate:[NSDate distantPast] inMode:mode dequeue:flag];
91 // If we got one, simply return it
94 // No events, try doing some idle stuff
97 && !wxTheApp->IsInAssert()
99 && ([NSDefaultRunLoopMode isEqualToString:mode] || [NSModalPanelRunLoopMode isEqualToString:mode]))
102 wxLogTrace(wxTRACE_COCOA,wxT("Processing idle events"));
103 while(wxTheApp->ProcessIdle())
105 // Get the same events except don't block
106 NSEvent *event = [super nextEventMatchingMask:mask untilDate:[NSDate distantPast] inMode:mode dequeue:flag];
107 // If we got one, simply return it
110 // we didn't get one, do some idle work
111 wxLogTrace(wxTRACE_COCOA,wxT("Looping idle events"));
113 // No more idle work requested, block
114 wxLogTrace(wxTRACE_COCOA,wxT("Finished idle processing"));
117 wxLogTrace(wxTRACE_COCOA,wxT("Avoiding idle processing sg_needIdle=%d"),sg_needIdle);
118 return [super nextEventMatchingMask:mask untilDate:expiration inMode:mode dequeue:flag];
121 - (void)sendEvent: (NSEvent*)anEvent
123 wxLogTrace(wxTRACE_COCOA,wxT("SendEvent"));
125 [super sendEvent: anEvent];
128 @end // wxPoserNSApplication
130 // ========================================================================
131 // wxNSApplicationDelegate
132 // ========================================================================
133 @implementation wxNSApplicationDelegate : NSObject
135 // NOTE: Terminate means that the event loop does NOT return and thus
136 // cleanup code doesn't properly execute. Furthermore, wxWidgets has its
137 // own exit on frame delete mechanism.
138 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
143 - (void)applicationWillBecomeActive:(NSNotification *)notification
145 wxTheApp->CocoaDelegate_applicationWillBecomeActive();
148 - (void)applicationDidBecomeActive:(NSNotification *)notification
150 wxTheApp->CocoaDelegate_applicationDidBecomeActive();
153 - (void)applicationWillResignActive:(NSNotification *)notification
155 wxTheApp->CocoaDelegate_applicationWillResignActive();
158 - (void)applicationDidResignActive:(NSNotification *)notification
160 wxTheApp->CocoaDelegate_applicationDidResignActive();
163 - (void)controlTintChanged:(NSNotification *)notification
165 wxLogDebug(wxT("TODO: send EVT_SYS_COLOUR_CHANGED as appropriate"));
168 @end // implementation wxNSApplicationDelegate : NSObject
170 // ========================================================================
172 // ========================================================================
174 // ----------------------------------------------------------------------------
175 // wxApp Static member initialization
176 // ----------------------------------------------------------------------------
177 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
178 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
179 EVT_IDLE(wxAppBase::OnIdle)
180 // EVT_END_SESSION(wxApp::OnEndSession)
181 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
184 // ----------------------------------------------------------------------------
185 // wxApp initialization/cleanup
186 // ----------------------------------------------------------------------------
187 bool wxApp::Initialize(int& argc, wxChar **argv)
189 wxAutoNSAutoreleasePool pool;
190 m_cocoaMainThread = [NSThread currentThread];
191 // Mac OS X passes a process serial number command line argument when
192 // the application is launched from the Finder. This argument must be
193 // removed from the command line arguments before being handled by the
194 // application (otherwise applications would need to handle it)
197 static const wxChar *ARG_PSN = _T("-psn_");
198 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
200 // remove this argument
202 memmove(argv + 1, argv + 2, argc * sizeof(wxChar *));
206 // Posing must be completed before any instances of the Objective-C
207 // classes being posed as are created.
208 wxPoseAsInitializer::InitializePosers();
210 return wxAppBase::Initialize(argc, argv);
213 void wxApp::CleanUp()
215 wxAutoNSAutoreleasePool pool;
217 wxDC::CocoaShutdownTextSystem();
218 wxMenuBarManager::DestroyInstance();
220 [m_cocoaApp setDelegate:nil];
221 [[NSNotificationCenter defaultCenter] removeObserver:m_cocoaAppDelegate
222 name:NSControlTintDidChangeNotification object:nil];
223 [m_cocoaAppDelegate release];
224 m_cocoaAppDelegate = NULL;
226 wxAppBase::CleanUp();
229 // ----------------------------------------------------------------------------
231 // ----------------------------------------------------------------------------
237 m_isInAssert = false;
238 #endif // __WXDEBUG__
243 m_cocoaAppDelegate = NULL;
246 void wxApp::CocoaDelegate_applicationWillBecomeActive()
250 void wxApp::CocoaDelegate_applicationDidBecomeActive()
254 void wxApp::CocoaDelegate_applicationWillResignActive()
256 wxTopLevelWindowCocoa::DeactivatePendingWindow();
259 void wxApp::CocoaDelegate_applicationDidResignActive()
263 bool wxApp::OnInitGui()
265 wxAutoNSAutoreleasePool pool;
266 if(!wxAppBase::OnInitGui())
269 // Create the app using the sharedApplication method
270 m_cocoaApp = [NSApplication sharedApplication];
271 m_cocoaAppDelegate = [[wxNSApplicationDelegate alloc] init];
272 [m_cocoaApp setDelegate:m_cocoaAppDelegate];
273 [[NSNotificationCenter defaultCenter] addObserver:m_cocoaAppDelegate
274 selector:@selector(controlTintChanged:)
275 name:NSControlTintDidChangeNotification object:nil];
277 wxMenuBarManager::CreateInstance();
279 wxDC::CocoaInitializeTextSystem();
283 bool wxApp::CallOnInit()
285 // wxAutoNSAutoreleasePool pool;
291 if(!wxAppBase::OnInit())
301 wxAppConsole::Exit();
304 // Yield to other processes
305 bool wxApp::Yield(bool onlyIfNeeded)
308 static bool s_inYield = false;
311 // disable log flushing from here because a call to wxYield() shouldn't
312 // normally result in message boxes popping up &c
320 wxFAIL_MSG( wxT("wxYield called recursively" ) );
328 // Run the event loop until it is out of events
331 wxAutoNSAutoreleasePool pool;
332 NSEvent *event = [GetNSApplication()
333 nextEventMatchingMask:NSAnyEventMask
334 untilDate:[NSDate distantPast]
335 inMode:NSDefaultRunLoopMode
339 [GetNSApplication() sendEvent: event];
343 // let the logs be flashed again
352 void wxApp::WakeUpIdle()
354 [m_cocoaApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
355 location:NSZeroPoint modifierFlags:NSAnyEventMask
356 timestamp:0 windowNumber:0 context:nil
357 subtype:0 data1:0 data2:0] atStart:NO];
361 void wxApp::OnAssert(const wxChar *file, int line, const wxChar* cond, const wxChar *msg)
364 wxAppBase::OnAssert(file, line, cond, msg);
365 m_isInAssert = false;
367 #endif // __WXDEBUG__