1 /////////////////////////////////////////////////////////////////////////////
4 // Author: David Elliott
8 // Copyright: (c) David Elliott
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #include "wx/wxprec.h"
25 #include "wx/dialog.h"
31 #include "wx/module.h"
33 #include "wx/cocoa/ObjcPose.h"
35 #if wxUSE_WX_RESOURCES
36 # include "wx/resource.h"
39 #import <AppKit/NSApplication.h>
40 #import <Foundation/NSRunLoop.h>
41 #import <Foundation/NSArray.h>
43 // ----------------------------------------------------------------------------
45 // ----------------------------------------------------------------------------
47 wxApp *wxTheApp = NULL;
48 wxPoseAsInitializer *wxPoseAsInitializer::sm_first = NULL;
50 @interface wxPoserNSApplication : NSApplication
54 - (void)doIdle: (id)data;
55 - (void)finishLaunching;
56 - (void)sendEvent: (NSEvent*)anEvent;
57 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
58 @end // wxPoserNSApplication
60 @implementation wxPoserNSApplication : NSApplication
62 - (void)doIdle: (id)data
65 wxLogDebug("doIdle called");
66 NSRunLoop *rl = [NSRunLoop currentRunLoop];
67 // runMode: beforeDate returns YES if something was done
68 while(wxTheApp->ProcessIdle()) // FIXME: AND NO EVENTS ARE PENDING
70 wxLogDebug("Looping for idle events");
72 if( [rl runMode:[rl currentMode] beforeDate:[NSDate distantPast]])
74 wxLogDebug("Found actual work to do");
79 wxLogDebug("Idle processing complete, requesting next idle event");
80 // Add ourself back into the run loop (on next event) if necessary
81 wxTheApp->CocoaRequestIdle();
84 - (void)finishLaunching
86 wxLogDebug("finishLaunching");
87 bool initsuccess = wxTheApp->OnInit();
91 [super finishLaunching];
94 - (void)sendEvent: (NSEvent*)anEvent
96 wxLogDebug("SendEvent");
97 wxTheApp->CocoaInstallRequestedIdleHandler();
98 [super sendEvent: anEvent];
101 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
103 BOOL ret = wxTheApp->GetExitOnFrameDelete();
104 wxLogDebug("applicationShouldTermintaeAfterLastWindowClosed=%d",ret);
108 @end // wxPoserNSApplication
109 WX_IMPLEMENT_POSER(wxPoserNSApplication);
111 // ============================================================================
113 // ============================================================================
115 //----------------------------------------------------------------------
117 //----------------------------------------------------------------------
119 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char *WXUNUSED(argv)[] )
121 return wxApp::Initialize();
124 int WXDLLEXPORT wxEntryInitGui()
126 return wxTheApp->OnInitGui();
129 void WXDLLEXPORT wxEntryCleanup()
134 int wxEntry( int argc, char *argv[])
136 if (!wxEntryStart(argc, argv)) {
139 wxLogDebug("Creating application");
140 // create the application object or ensure that one already exists
143 // The app may have declared a global application object, but we recommend
144 // the IMPLEMENT_APP macro is used instead, which sets an initializer
145 // function for delayed, dynamic app object construction.
146 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
147 wxT("No initializer - use IMPLEMENT_APP macro.") );
149 wxTheApp = (wxApp*) (*wxApp::GetInitializerFunction()) ();
152 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
154 // Mac OS X passes a process serial number command line argument when
155 // the application is launched from the Finder. This argument must be
156 // removed from the command line arguments before being handled by the
157 // application (otherwise applications would need to handle it)
161 strncpy(theArg, argv[1], 5);
163 if (strcmp(theArg, "-psn_") == 0) {
164 // assume the argument is always the only one and remove it
169 wxTheApp->argc = argc;
170 wxTheApp->argv = argv;
172 wxLogDebug("initializing gui");
173 // GUI-specific initialization, such as creating an app context.
176 // Here frames insert themselves automatically
177 // into wxTopLevelWindows by getting created
182 wxLogDebug("Time to run");
183 retValue = wxTheApp->OnRun();
185 wxWindow *topWindow = wxTheApp->GetTopWindow();
188 // Forcibly delete the window.
189 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
190 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
192 topWindow->Close(TRUE);
197 wxTheApp->SetTopWindow(NULL);
212 wxAppConsole::Exit();
215 // ============================================================================
216 // wxApp implementation
217 // ============================================================================
219 // ----------------------------------------------------------------------------
220 // wxApp Static member initialization
221 // ----------------------------------------------------------------------------
222 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
224 #if !USE_SHARED_LIBRARY
225 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
226 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
227 EVT_IDLE(wxApp::OnIdle)
228 // EVT_END_SESSION(wxApp::OnEndSession)
229 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
233 // ----------------------------------------------------------------------------
234 // wxApp static functions
235 // ----------------------------------------------------------------------------
236 /*static*/ bool wxApp::Initialize()
238 wxPoseAsInitializer::InitializePosers();
239 wxClassInfo::InitializeClasses();
242 wxPendingEventsLocker = new wxCriticalSection;
245 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
246 wxTheColourDatabase->Initialize();
248 wxInitializeStockLists();
249 wxInitializeStockObjects();
251 #if wxUSE_WX_RESOURCES
252 wxInitializeResourceSystem();
255 wxBitmap::InitStandardHandlers();
257 wxModule::RegisterModules();
258 if (!wxModule::InitializeModules()) {
264 /*static*/ void wxApp::CleanUp()
266 wxModule::CleanUpModules();
268 #if wxUSE_WX_RESOURCES
269 wxCleanUpResourceSystem();
272 wxDeleteStockObjects() ;
274 // Destroy all GDI lists, etc.
275 wxDeleteStockLists();
277 delete wxTheColourDatabase;
278 wxTheColourDatabase = NULL;
280 wxBitmap::CleanUpHandlers();
282 delete wxPendingEvents;
285 delete wxPendingEventsLocker;
286 // If we don't do the following, we get an apparent memory leak.
287 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
290 wxClassInfo::CleanUpClasses();
295 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
296 // At this point we want to check if there are any memory
297 // blocks that aren't part of the wxDebugContext itself,
298 // as a special case. Then when dumping we need to ignore
299 // wxDebugContext, too.
300 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
302 wxLogDebug(wxT("There were memory leaks."));
303 wxDebugContext::Dump();
304 wxDebugContext::PrintStatistics();
306 // wxDebugContext::SetStream(NULL, NULL);
309 wxDC::CocoaShutdownTextSystem();
311 // do it as the very last thing because everything else can log messages
312 delete wxLog::SetActiveTarget(NULL);
316 // ----------------------------------------------------------------------------
318 // ----------------------------------------------------------------------------
326 #if WXWIN_COMPATIBILITY_2_2
327 m_wantDebugOutput = TRUE;
335 void wxApp::CocoaInstallIdleHandler()
337 wxLogDebug("wxApp::CocoaInstallIdleHandler");
339 // Call doIdle for EVERYTHING dammit
340 // We'd need Foundation/NSConnection.h for this next constant, do we need it?
341 [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode,*/ NSModalPanelRunLoopMode, /**/NSEventTrackingRunLoopMode,/**/ nil] ];
344 bool wxApp::OnInitGui()
346 if(!wxAppBase::OnInitGui())
349 // Create the app using the sharedApplication method
350 m_cocoaApp = [NSApplication sharedApplication];
351 wxDC::CocoaInitializeTextSystem();
352 // [ m_cocoaApp setDelegate:m_cocoaApp ];
354 wxLogDebug("Just for kicks");
355 [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
356 wxLogDebug("okay.. done now");
363 if(!wxAppBase::OnInit())
369 bool wxApp::Initialized()
377 int wxApp::MainLoop()
383 // Returns TRUE if more time is needed.
384 bool wxApp::ProcessIdle()
387 event.SetEventObject(this);
390 return event.MoreRequested();
393 void wxApp::ExitMainLoop()
395 wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
396 // CocoaInstallRequestedIdleHandler();
398 // [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode,*/ nil] ];
399 // actually.. we WANT the idle event
403 [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
405 [m_cocoaApp terminate: m_cocoaApp];
408 // Is a message/event pending?
409 bool wxApp::Pending()
414 // Dispatch a message.
415 void wxApp::Dispatch()
419 void wxApp::OnIdle(wxIdleEvent& event)
421 wxLogDebug("wxApp::OnIdle");
422 static bool s_inOnIdle = FALSE;
424 // Avoid recursion (via ProcessEvent default case)
430 DeletePendingObjects();
432 // flush the logged messages if any
433 wxLog *pLog = wxLog::GetActiveTarget();
434 if ( pLog != NULL && pLog->HasPendingMessages() )
437 // Send OnIdle events to all windows
438 bool needMore = SendIdleEvents();
441 event.RequestMore(TRUE);
446 // Send idle event to all top-level windows
447 bool wxApp::SendIdleEvents()
449 bool needMore = FALSE;
450 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
453 wxWindow* win = node->GetData();
454 if (SendIdleEvents(win))
457 node = node->GetNext();
462 // Send idle event to window and all subwindows
463 bool wxApp::SendIdleEvents(wxWindow* win)
465 // wxLogDebug("SendIdleEvents win=%p",win);
466 bool needMore = FALSE;
469 event.SetEventObject(win);
470 win->ProcessEvent(event);
472 if (event.MoreRequested())
475 wxWindowList::Node* node = win->GetChildren().GetFirst();
478 // wxLogDebug("child=%p",node->Data());
479 wxWindow* win = node->GetData();
480 if (SendIdleEvents(win))
483 node = node->GetNext();
488 // Yield to other processes
490 bool wxApp::Yield(bool onlyIfNeeded)
493 static bool s_inYield = false;
496 // disable log flushing from here because a call to wxYield() shouldn't
497 // normally result in message boxes popping up &c
505 wxFAIL_MSG( wxT("wxYield called recursively" ) );
513 wxLogDebug("WARNING: SUPPOSED to have yielded!");
514 // FIXME: Do something!
517 // let the logs be flashed again
526 void wxApp::DeletePendingObjects()
528 wxNode *node = wxPendingDelete.GetFirst();
531 wxObject *obj = (wxObject *)node->GetData();
535 if (wxPendingDelete.Find(obj))
538 node = wxPendingDelete.GetFirst();
542 // platform specifics