1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/cocoa/app.mm
4 // Author: David Elliott
8 // Copyright: (c) David Elliott
10 // Licence: wxWidgets licence
11 /////////////////////////////////////////////////////////////////////////////
13 #include "wx/wxprec.h"
21 #include "wx/module.h"
24 #include "wx/cocoa/ObjcRef.h"
25 #include "wx/cocoa/autorelease.h"
26 #include "wx/cocoa/mbarman.h"
27 #include "wx/cocoa/NSApplication.h"
29 #import <AppKit/NSApplication.h>
30 #import <Foundation/NSRunLoop.h>
31 #import <Foundation/NSThread.h>
32 #import <AppKit/NSEvent.h>
33 #import <Foundation/NSString.h>
34 #import <Foundation/NSNotification.h>
35 #import <AppKit/NSCell.h>
37 bool wxApp::sm_isEmbedded = false; // Normally we're not a plugin
39 // wxNSApplicationObserver singleton.
40 static wxObjcAutoRefFromAlloc<wxNSApplicationObserver*> sg_cocoaAppObserver = [[WX_GET_OBJC_CLASS(wxNSApplicationObserver) alloc] init];
42 // ========================================================================
43 // wxNSApplicationDelegate
44 // ========================================================================
45 @implementation wxNSApplicationDelegate : NSObject
47 // NOTE: Terminate means that the event loop does NOT return and thus
48 // cleanup code doesn't properly execute. Furthermore, wxWidgets has its
49 // own exit on frame delete mechanism.
50 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
55 @end // implementation wxNSApplicationDelegate : NSObject
56 WX_IMPLEMENT_GET_OBJC_CLASS(wxNSApplicationDelegate,NSObject)
58 // ========================================================================
59 // wxNSApplicationObserver
60 // ========================================================================
61 @implementation wxNSApplicationObserver : NSObject
63 - (void)applicationWillBecomeActive:(NSNotification *)notification
65 wxTheApp->CocoaDelegate_applicationWillBecomeActive();
68 - (void)applicationDidBecomeActive:(NSNotification *)notification
70 wxTheApp->CocoaDelegate_applicationDidBecomeActive();
73 - (void)applicationWillResignActive:(NSNotification *)notification
75 wxTheApp->CocoaDelegate_applicationWillResignActive();
78 - (void)applicationDidResignActive:(NSNotification *)notification
80 wxTheApp->CocoaDelegate_applicationDidResignActive();
83 - (void)applicationWillUpdate:(NSNotification *)notification;
85 wxTheApp->CocoaDelegate_applicationWillUpdate();
88 - (void)controlTintChanged:(NSNotification *)notification
90 wxLogDebug(wxT("TODO: send EVT_SYS_COLOUR_CHANGED as appropriate"));
93 @end // implementation wxNSApplicationObserver : NSObject
94 WX_IMPLEMENT_GET_OBJC_CLASS(wxNSApplicationObserver,NSObject)
96 // ========================================================================
98 // ========================================================================
100 // ----------------------------------------------------------------------------
101 // wxApp Static member initialization
102 // ----------------------------------------------------------------------------
103 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
104 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
105 EVT_IDLE(wxAppBase::OnIdle)
106 // EVT_END_SESSION(wxApp::OnEndSession)
107 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
110 // ----------------------------------------------------------------------------
111 // wxApp initialization/cleanup
112 // ----------------------------------------------------------------------------
113 bool wxApp::Initialize(int& argc, wxChar **argv)
115 wxAutoNSAutoreleasePool pool;
116 m_cocoaMainThread = [NSThread currentThread];
117 // Mac OS X passes a process serial number command line argument when
118 // the application is launched from the Finder. This argument must be
119 // removed from the command line arguments before being handled by the
120 // application (otherwise applications would need to handle it)
123 static const wxChar *ARG_PSN = _T("-psn_");
124 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
126 // remove this argument
128 memmove(argv + 1, argv + 2, argc * sizeof(wxChar *));
132 return wxAppBase::Initialize(argc, argv);
135 void wxApp::CleanUp()
137 wxAutoNSAutoreleasePool pool;
139 wxDC::CocoaShutdownTextSystem();
140 wxMenuBarManager::DestroyInstance();
142 [[NSNotificationCenter defaultCenter] removeObserver:sg_cocoaAppObserver];
145 [m_cocoaApp setDelegate:nil];
146 [m_cocoaAppDelegate release];
147 m_cocoaAppDelegate = NULL;
150 wxAppBase::CleanUp();
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
161 m_isInAssert = false;
162 #endif // __WXDEBUG__
167 m_cocoaAppDelegate = NULL;
170 void wxApp::CocoaDelegate_applicationWillBecomeActive()
174 void wxApp::CocoaDelegate_applicationDidBecomeActive()
178 void wxApp::CocoaDelegate_applicationWillResignActive()
180 wxTopLevelWindowCocoa::DeactivatePendingWindow();
183 void wxApp::CocoaDelegate_applicationDidResignActive()
187 bool wxApp::OnInitGui()
189 wxAutoNSAutoreleasePool pool;
190 if(!wxAppBase::OnInitGui())
193 // Create the app using the sharedApplication method
194 m_cocoaApp = [NSApplication sharedApplication];
198 // Enable response to application delegate messages
199 m_cocoaAppDelegate = [[WX_GET_OBJC_CLASS(wxNSApplicationDelegate) alloc] init];
200 [m_cocoaApp setDelegate:m_cocoaAppDelegate];
203 // Enable response to "delegate" messages on the notification observer
204 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
205 selector:@selector(applicationWillBecomeActive:)
206 name:NSApplicationWillBecomeActiveNotification object:nil];
208 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
209 selector:@selector(applicationDidBecomeActive:)
210 name:NSApplicationDidBecomeActiveNotification object:nil];
212 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
213 selector:@selector(applicationWillResignActive:)
214 name:NSApplicationWillResignActiveNotification object:nil];
216 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
217 selector:@selector(applicationDidResignActive:)
218 name:NSApplicationDidResignActiveNotification object:nil];
220 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
221 selector:@selector(applicationWillUpdate:)
222 name:NSApplicationWillUpdateNotification object:nil];
224 // Enable response to system notifications
225 [[NSNotificationCenter defaultCenter] addObserver:sg_cocoaAppObserver
226 selector:@selector(controlTintChanged:)
227 name:NSControlTintDidChangeNotification object:nil];
230 wxMenuBarManager::CreateInstance();
232 wxDC::CocoaInitializeTextSystem();
238 if(m_cfRunLoopIdleObserver != NULL)
240 // Invalidate the observer which also removes it from the run loop.
241 CFRunLoopObserverInvalidate(m_cfRunLoopIdleObserver);
242 // Release the ref as we don't need it anymore.
243 m_cfRunLoopIdleObserver.reset();
247 bool wxApp::CallOnInit()
249 // wxAutoNSAutoreleasePool pool;
255 if(!wxAppBase::OnInit())
265 wxAppConsole::Exit();
268 // Yield to other processes
269 bool wxApp::Yield(bool onlyIfNeeded)
272 static bool s_inYield = false;
275 // disable log flushing from here because a call to wxYield() shouldn't
276 // normally result in message boxes popping up &c
284 wxFAIL_MSG( wxT("wxYield called recursively" ) );
292 // Run the event loop until it is out of events
295 wxAutoNSAutoreleasePool pool;
296 NSEvent *event = [GetNSApplication()
297 nextEventMatchingMask:NSAnyEventMask
298 untilDate:[NSDate distantPast]
299 inMode:NSDefaultRunLoopMode
303 [GetNSApplication() sendEvent: event];
307 // let the logs be flashed again
316 void wxApp::WakeUpIdle()
318 [m_cocoaApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
319 location:NSZeroPoint modifierFlags:NSAnyEventMask
320 timestamp:0 windowNumber:0 context:nil
321 subtype:0 data1:0 data2:0] atStart:NO];
324 extern "C" static void ObserveMainRunLoopBeforeWaiting(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info);
325 extern "C" static void ObserveMainRunLoopBeforeWaiting(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info)
327 static_cast<wxApp*>(info)->CF_ObserveMainRunLoopBeforeWaiting(observer, activity);
331 static int sg_cApplicationWillUpdate = 0;
334 void wxApp::CocoaDelegate_applicationWillUpdate()
336 wxLogTrace(wxTRACE_COCOA,wxT("applicationWillUpdate"));
338 // CFRunLoopRef cfRunLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
339 CFRunLoopRef cfRunLoop = CFRunLoopGetCurrent();
340 wxCFRef<CFStringRef> cfRunLoopMode(CFRunLoopCopyCurrentMode(cfRunLoop));
342 if(m_cfRunLoopIdleObserver != NULL && m_cfObservedRunLoopMode != cfRunLoopMode)
344 CFRunLoopObserverInvalidate(m_cfRunLoopIdleObserver);
345 m_cfRunLoopIdleObserver.reset();
348 ++sg_cApplicationWillUpdate;
350 if(m_cfRunLoopIdleObserver == NULL)
352 // Enable idle event handling
353 CFRunLoopObserverContext observerContext =
360 m_cfRunLoopIdleObserver.reset(CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, /*repeats*/FALSE, /*priority*/0, ObserveMainRunLoopBeforeWaiting, &observerContext));
361 m_cfObservedRunLoopMode = cfRunLoopMode;
362 CFRunLoopAddObserver(cfRunLoop, m_cfRunLoopIdleObserver, m_cfObservedRunLoopMode);
366 static inline bool FakeNeedMoreIdle()
369 // Return true on every 10th call.
370 static int idleCount = 0;
371 return ++idleCount % 10;
377 void wxApp::CF_ObserveMainRunLoopBeforeWaiting(CFRunLoopObserverRef observer, int activity)
379 // Ensure that the app knows we've been invalidated
380 m_cfRunLoopIdleObserver.reset();
382 wxLogTrace(wxTRACE_COCOA,wxT("Idle BEGIN (%d)"), sg_cApplicationWillUpdate);
383 sg_cApplicationWillUpdate = 0;
385 wxLogTrace(wxTRACE_COCOA,wxT("Idle BEGIN"));
387 if( ProcessIdle() || FakeNeedMoreIdle() )
389 wxLogTrace(wxTRACE_COCOA, wxT("Idle REQUEST MORE"));
390 [NSApp setWindowsNeedUpdate:YES];
394 wxLogTrace(wxTRACE_COCOA, wxT("Idle END"));
399 void wxApp::OnAssert(const wxChar *file, int line, const wxChar* cond, const wxChar *msg)
402 wxAppBase::OnAssert(file, line, cond, msg);
403 m_isInAssert = false;
405 #endif // __WXDEBUG__