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/cocoa/ObjcPose.h"
33 #if wxUSE_WX_RESOURCES
34 # include "wx/resource.h"
37 #import <AppKit/NSApplication.h>
38 #import <Foundation/NSRunLoop.h>
39 #import <Foundation/NSArray.h>
41 // ----------------------------------------------------------------------------
43 // ----------------------------------------------------------------------------
45 wxApp *wxTheApp = NULL;
46 wxPoseAsInitializer *wxPoseAsInitializer::sm_first = NULL;
48 @interface wxPoserNSApplication : NSApplication
52 - (void)doIdle: (id)data;
53 - (void)finishLaunching;
54 - (void)sendEvent: (NSEvent*)anEvent;
55 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
56 @end // wxPoserNSApplication
58 @implementation wxPoserNSApplication : NSApplication
60 - (void)doIdle: (id)data
63 wxLogDebug("doIdle called");
64 NSRunLoop *rl = [NSRunLoop currentRunLoop];
65 // runMode: beforeDate returns YES if something was done
66 while(wxTheApp->ProcessIdle()) // FIXME: AND NO EVENTS ARE PENDING
68 wxLogDebug("Looping for idle events");
70 if( [rl runMode:[rl currentMode] beforeDate:[NSDate distantPast]])
72 wxLogDebug("Found actual work to do");
77 wxLogDebug("Idle processing complete, requesting next idle event");
78 // Add ourself back into the run loop (on next event) if necessary
79 wxTheApp->CocoaRequestIdle();
82 - (void)finishLaunching
84 wxLogDebug("finishLaunching");
85 bool initsuccess = wxTheApp->OnInit();
89 [super finishLaunching];
92 - (void)sendEvent: (NSEvent*)anEvent
94 wxLogDebug("SendEvent");
95 wxTheApp->CocoaInstallRequestedIdleHandler();
96 [super sendEvent: anEvent];
99 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
101 BOOL ret = wxTheApp->GetExitOnFrameDelete();
102 wxLogDebug("applicationShouldTermintaeAfterLastWindowClosed=%d",ret);
106 @end // wxPoserNSApplication
107 WX_IMPLEMENT_POSER(wxPoserNSApplication);
109 // ============================================================================
111 // ============================================================================
113 //----------------------------------------------------------------------
115 //----------------------------------------------------------------------
117 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char *WXUNUSED(argv)[] )
119 return wxApp::Initialize();
122 int WXDLLEXPORT wxEntryInitGui()
124 return wxTheApp->OnInitGui();
127 void WXDLLEXPORT wxEntryCleanup()
132 int wxEntry( int argc, char *argv[])
134 if (!wxEntryStart(argc, argv)) {
137 wxLogDebug("Creating application");
138 // create the application object or ensure that one already exists
141 // The app may have declared a global application object, but we recommend
142 // the IMPLEMENT_APP macro is used instead, which sets an initializer
143 // function for delayed, dynamic app object construction.
144 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
145 wxT("No initializer - use IMPLEMENT_APP macro.") );
147 wxTheApp = (wxApp*) (*wxApp::GetInitializerFunction()) ();
150 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
152 // Mac OS X passes a process serial number command line argument when
153 // the application is launched from the Finder. This argument must be
154 // removed from the command line arguments before being handled by the
155 // application (otherwise applications would need to handle it)
159 strncpy(theArg, argv[1], 5);
161 if (strcmp(theArg, "-psn_") == 0) {
162 // assume the argument is always the only one and remove it
167 wxTheApp->argc = argc;
168 wxTheApp->argv = argv;
170 wxLogDebug("initializing gui");
171 // GUI-specific initialization, such as creating an app context.
174 // Here frames insert themselves automatically
175 // into wxTopLevelWindows by getting created
180 wxLogDebug("Time to run");
181 retValue = wxTheApp->OnRun();
183 wxWindow *topWindow = wxTheApp->GetTopWindow();
186 // Forcibly delete the window.
187 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
188 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
190 topWindow->Close(TRUE);
195 wxTheApp->SetTopWindow(NULL);
206 // ----------------------------------------------------------------------------
208 // ----------------------------------------------------------------------------
211 wxTheApp->CocoaRequestIdle();
216 wxLogError(_("Fatal error: exiting"));
222 // ============================================================================
223 // wxApp implementation
224 // ============================================================================
226 // ----------------------------------------------------------------------------
227 // wxApp Static member initialization
228 // ----------------------------------------------------------------------------
229 wxAppInitializerFunction wxAppBase::m_appInitFn = (wxAppInitializerFunction) NULL;
231 #if !USE_SHARED_LIBRARY
232 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
233 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
234 EVT_IDLE(wxApp::OnIdle)
235 // EVT_END_SESSION(wxApp::OnEndSession)
236 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
240 // ----------------------------------------------------------------------------
241 // wxApp static functions
242 // ----------------------------------------------------------------------------
243 /*static*/ bool wxApp::Initialize()
245 wxPoseAsInitializer::InitializePosers();
246 wxClassInfo::InitializeClasses();
249 wxPendingEventsLocker = new wxCriticalSection;
252 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
253 wxTheColourDatabase->Initialize();
255 wxInitializeStockLists();
256 wxInitializeStockObjects();
258 #if wxUSE_WX_RESOURCES
259 wxInitializeResourceSystem();
262 wxBitmap::InitStandardHandlers();
264 wxModule::RegisterModules();
265 if (!wxModule::InitializeModules()) {
271 /*static*/ void wxApp::CleanUp()
273 wxModule::CleanUpModules();
275 #if wxUSE_WX_RESOURCES
276 wxCleanUpResourceSystem();
279 wxDeleteStockObjects() ;
281 // Destroy all GDI lists, etc.
282 wxDeleteStockLists();
284 delete wxTheColourDatabase;
285 wxTheColourDatabase = NULL;
287 wxBitmap::CleanUpHandlers();
289 delete wxPendingEvents;
292 delete wxPendingEventsLocker;
293 // If we don't do the following, we get an apparent memory leak.
294 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
297 wxClassInfo::CleanUpClasses();
302 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
303 // At this point we want to check if there are any memory
304 // blocks that aren't part of the wxDebugContext itself,
305 // as a special case. Then when dumping we need to ignore
306 // wxDebugContext, too.
307 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
309 wxLogDebug(wxT("There were memory leaks."));
310 wxDebugContext::Dump();
311 wxDebugContext::PrintStatistics();
313 // wxDebugContext::SetStream(NULL, NULL);
316 wxDC::CocoaShutdownTextSystem();
318 // do it as the very last thing because everything else can log messages
319 delete wxLog::SetActiveTarget(NULL);
323 // ----------------------------------------------------------------------------
325 // ----------------------------------------------------------------------------
333 #if WXWIN_COMPATIBILITY_2_2
334 m_wantDebugOutput = TRUE;
342 void wxApp::CocoaInstallIdleHandler()
344 wxLogDebug("wxApp::CocoaInstallIdleHandler");
346 // Call doIdle for EVERYTHING dammit
347 // We'd need Foundation/NSConnection.h for this next constant, do we need it?
348 [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode,*/ NSModalPanelRunLoopMode, /**/NSEventTrackingRunLoopMode,/**/ nil] ];
351 bool wxApp::OnInitGui()
353 if(!wxAppBase::OnInitGui())
356 // Create the app using the sharedApplication method
357 m_cocoaApp = [NSApplication sharedApplication];
358 wxDC::CocoaInitializeTextSystem();
359 // [ m_cocoaApp setDelegate:m_cocoaApp ];
361 wxLogDebug("Just for kicks");
362 [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
363 wxLogDebug("okay.. done now");
370 if(!wxAppBase::OnInit())
376 bool wxApp::Initialized()
384 int wxApp::MainLoop()
390 // Returns TRUE if more time is needed.
391 bool wxApp::ProcessIdle()
394 event.SetEventObject(this);
397 return event.MoreRequested();
400 void wxApp::ExitMainLoop()
402 wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
403 // CocoaInstallRequestedIdleHandler();
405 // [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode,*/ nil] ];
406 // actually.. we WANT the idle event
410 [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
412 [m_cocoaApp terminate: m_cocoaApp];
415 // Is a message/event pending?
416 bool wxApp::Pending()
421 // Dispatch a message.
422 void wxApp::Dispatch()
426 void wxApp::OnIdle(wxIdleEvent& event)
428 wxLogDebug("wxApp::OnIdle");
429 static bool s_inOnIdle = FALSE;
431 // Avoid recursion (via ProcessEvent default case)
437 DeletePendingObjects();
439 // flush the logged messages if any
440 wxLog *pLog = wxLog::GetActiveTarget();
441 if ( pLog != NULL && pLog->HasPendingMessages() )
444 // Send OnIdle events to all windows
445 bool needMore = SendIdleEvents();
448 event.RequestMore(TRUE);
453 // Send idle event to all top-level windows
454 bool wxApp::SendIdleEvents()
456 bool needMore = FALSE;
457 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
460 wxWindow* win = node->GetData();
461 if (SendIdleEvents(win))
464 node = node->GetNext();
469 // Send idle event to window and all subwindows
470 bool wxApp::SendIdleEvents(wxWindow* win)
472 // wxLogDebug("SendIdleEvents win=%p",win);
473 bool needMore = FALSE;
476 event.SetEventObject(win);
477 win->ProcessEvent(event);
479 if (event.MoreRequested())
482 wxWindowList::Node* node = win->GetChildren().GetFirst();
485 // wxLogDebug("child=%p",node->Data());
486 wxWindow* win = node->GetData();
487 if (SendIdleEvents(win))
490 node = node->GetNext();
495 // Yield to other processes
497 bool wxApp::Yield(bool onlyIfNeeded)
500 static bool s_inYield = false;
503 // disable log flushing from here because a call to wxYield() shouldn't
504 // normally result in message boxes popping up &c
512 wxFAIL_MSG( wxT("wxYield called recursively" ) );
520 wxLogDebug("WARNING: SUPPOSED to have yielded!");
521 // FIXME: Do something!
524 // let the logs be flashed again
533 void wxApp::DeletePendingObjects()
535 wxNode *node = wxPendingDelete.GetFirst();
538 wxObject *obj = (wxObject *)node->GetData();
542 if (wxPendingDelete.Find(obj))
545 node = wxPendingDelete.GetFirst();
549 // platform specifics