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);
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
213 wxTheApp->CocoaRequestIdle();
218 wxLogError(_("Fatal error: exiting"));
224 // ============================================================================
225 // wxApp implementation
226 // ============================================================================
228 // ----------------------------------------------------------------------------
229 // wxApp Static member initialization
230 // ----------------------------------------------------------------------------
231 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
233 #if !USE_SHARED_LIBRARY
234 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
235 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
236 EVT_IDLE(wxApp::OnIdle)
237 // EVT_END_SESSION(wxApp::OnEndSession)
238 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
242 // ----------------------------------------------------------------------------
243 // wxApp static functions
244 // ----------------------------------------------------------------------------
245 /*static*/ bool wxApp::Initialize()
247 wxPoseAsInitializer::InitializePosers();
248 wxClassInfo::InitializeClasses();
251 wxPendingEventsLocker = new wxCriticalSection;
254 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
255 wxTheColourDatabase->Initialize();
257 wxInitializeStockLists();
258 wxInitializeStockObjects();
260 #if wxUSE_WX_RESOURCES
261 wxInitializeResourceSystem();
264 wxBitmap::InitStandardHandlers();
266 wxModule::RegisterModules();
267 if (!wxModule::InitializeModules()) {
273 /*static*/ void wxApp::CleanUp()
275 wxModule::CleanUpModules();
277 #if wxUSE_WX_RESOURCES
278 wxCleanUpResourceSystem();
281 wxDeleteStockObjects() ;
283 // Destroy all GDI lists, etc.
284 wxDeleteStockLists();
286 delete wxTheColourDatabase;
287 wxTheColourDatabase = NULL;
289 wxBitmap::CleanUpHandlers();
291 delete wxPendingEvents;
294 delete wxPendingEventsLocker;
295 // If we don't do the following, we get an apparent memory leak.
296 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
299 wxClassInfo::CleanUpClasses();
304 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
305 // At this point we want to check if there are any memory
306 // blocks that aren't part of the wxDebugContext itself,
307 // as a special case. Then when dumping we need to ignore
308 // wxDebugContext, too.
309 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
311 wxLogDebug(wxT("There were memory leaks."));
312 wxDebugContext::Dump();
313 wxDebugContext::PrintStatistics();
315 // wxDebugContext::SetStream(NULL, NULL);
318 wxDC::CocoaShutdownTextSystem();
320 // do it as the very last thing because everything else can log messages
321 delete wxLog::SetActiveTarget(NULL);
325 // ----------------------------------------------------------------------------
327 // ----------------------------------------------------------------------------
335 #if WXWIN_COMPATIBILITY_2_2
336 m_wantDebugOutput = TRUE;
344 void wxApp::CocoaInstallIdleHandler()
346 wxLogDebug("wxApp::CocoaInstallIdleHandler");
348 // Call doIdle for EVERYTHING dammit
349 // We'd need Foundation/NSConnection.h for this next constant, do we need it?
350 [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode,*/ NSModalPanelRunLoopMode, /**/NSEventTrackingRunLoopMode,/**/ nil] ];
353 bool wxApp::OnInitGui()
355 if(!wxAppBase::OnInitGui())
358 // Create the app using the sharedApplication method
359 m_cocoaApp = [NSApplication sharedApplication];
360 wxDC::CocoaInitializeTextSystem();
361 // [ m_cocoaApp setDelegate:m_cocoaApp ];
363 wxLogDebug("Just for kicks");
364 [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
365 wxLogDebug("okay.. done now");
372 if(!wxAppBase::OnInit())
378 bool wxApp::Initialized()
386 int wxApp::MainLoop()
392 // Returns TRUE if more time is needed.
393 bool wxApp::ProcessIdle()
396 event.SetEventObject(this);
399 return event.MoreRequested();
402 void wxApp::ExitMainLoop()
404 wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
405 // CocoaInstallRequestedIdleHandler();
407 // [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode,*/ nil] ];
408 // actually.. we WANT the idle event
412 [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
414 [m_cocoaApp terminate: m_cocoaApp];
417 // Is a message/event pending?
418 bool wxApp::Pending()
423 // Dispatch a message.
424 void wxApp::Dispatch()
428 void wxApp::OnIdle(wxIdleEvent& event)
430 wxLogDebug("wxApp::OnIdle");
431 static bool s_inOnIdle = FALSE;
433 // Avoid recursion (via ProcessEvent default case)
439 DeletePendingObjects();
441 // flush the logged messages if any
442 wxLog *pLog = wxLog::GetActiveTarget();
443 if ( pLog != NULL && pLog->HasPendingMessages() )
446 // Send OnIdle events to all windows
447 bool needMore = SendIdleEvents();
450 event.RequestMore(TRUE);
455 // Send idle event to all top-level windows
456 bool wxApp::SendIdleEvents()
458 bool needMore = FALSE;
459 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
462 wxWindow* win = node->GetData();
463 if (SendIdleEvents(win))
466 node = node->GetNext();
471 // Send idle event to window and all subwindows
472 bool wxApp::SendIdleEvents(wxWindow* win)
474 // wxLogDebug("SendIdleEvents win=%p",win);
475 bool needMore = FALSE;
478 event.SetEventObject(win);
479 win->ProcessEvent(event);
481 if (event.MoreRequested())
484 wxWindowList::Node* node = win->GetChildren().GetFirst();
487 // wxLogDebug("child=%p",node->Data());
488 wxWindow* win = node->GetData();
489 if (SendIdleEvents(win))
492 node = node->GetNext();
497 // Yield to other processes
499 bool wxApp::Yield(bool onlyIfNeeded)
502 static bool s_inYield = false;
505 // disable log flushing from here because a call to wxYield() shouldn't
506 // normally result in message boxes popping up &c
514 wxFAIL_MSG( wxT("wxYield called recursively" ) );
522 wxLogDebug("WARNING: SUPPOSED to have yielded!");
523 // FIXME: Do something!
526 // let the logs be flashed again
535 void wxApp::DeletePendingObjects()
537 wxNode *node = wxPendingDelete.GetFirst();
540 wxObject *obj = (wxObject *)node->GetData();
544 if (wxPendingDelete.Find(obj))
547 node = wxPendingDelete.GetFirst();
551 // platform specifics