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 wxPoseAsInitializer *wxPoseAsInitializer::sm_first = NULL;
49 @interface wxPoserNSApplication : NSApplication
53 - (void)doIdle: (id)data;
54 - (void)finishLaunching;
55 - (void)sendEvent: (NSEvent*)anEvent;
56 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
57 @end // wxPoserNSApplication
59 @implementation wxPoserNSApplication : NSApplication
61 - (void)doIdle: (id)data
64 wxLogDebug("doIdle called");
65 NSRunLoop *rl = [NSRunLoop currentRunLoop];
66 // runMode: beforeDate returns YES if something was done
67 while(wxTheApp->ProcessIdle()) // FIXME: AND NO EVENTS ARE PENDING
69 wxLogDebug("Looping for idle events");
71 if( [rl runMode:[rl currentMode] beforeDate:[NSDate distantPast]])
73 wxLogDebug("Found actual work to do");
78 wxLogDebug("Idle processing complete, requesting next idle event");
79 // Add ourself back into the run loop (on next event) if necessary
80 wxTheApp->CocoaRequestIdle();
83 - (void)finishLaunching
85 wxLogDebug("finishLaunching");
86 bool initsuccess = wxTheApp->OnInit();
90 [super finishLaunching];
93 - (void)sendEvent: (NSEvent*)anEvent
95 wxLogDebug("SendEvent");
96 wxTheApp->CocoaInstallRequestedIdleHandler();
97 [super sendEvent: anEvent];
100 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
102 BOOL ret = wxTheApp->GetExitOnFrameDelete();
103 wxLogDebug("applicationShouldTermintaeAfterLastWindowClosed=%d",ret);
107 @end // wxPoserNSApplication
108 WX_IMPLEMENT_POSER(wxPoserNSApplication);
110 // ============================================================================
112 // ============================================================================
114 //----------------------------------------------------------------------
116 //----------------------------------------------------------------------
118 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char *WXUNUSED(argv)[] )
120 return wxApp::Initialize();
123 int WXDLLEXPORT wxEntryInitGui()
125 return wxTheApp->OnInitGui();
128 void WXDLLEXPORT wxEntryCleanup()
133 int wxEntry( int argc, char *argv[])
135 if (!wxEntryStart(argc, argv)) {
138 wxLogDebug("Creating application");
139 // create the application object or ensure that one already exists
142 // The app may have declared a global application object, but we recommend
143 // the IMPLEMENT_APP macro is used instead, which sets an initializer
144 // function for delayed, dynamic app object construction.
145 wxCHECK_MSG( wxApp::GetInitializerFunction(), 0,
146 wxT("No initializer - use IMPLEMENT_APP macro.") );
148 wxTheApp = (wxApp*) (*wxApp::GetInitializerFunction()) ();
151 wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
153 // Mac OS X passes a process serial number command line argument when
154 // the application is launched from the Finder. This argument must be
155 // removed from the command line arguments before being handled by the
156 // application (otherwise applications would need to handle it)
160 strncpy(theArg, argv[1], 5);
162 if (strcmp(theArg, "-psn_") == 0) {
163 // assume the argument is always the only one and remove it
168 wxTheApp->argc = argc;
169 wxTheApp->argv = argv;
171 wxLogDebug("initializing gui");
172 // GUI-specific initialization, such as creating an app context.
175 // Here frames insert themselves automatically
176 // into wxTopLevelWindows by getting created
181 wxLogDebug("Time to run");
182 retValue = wxTheApp->OnRun();
184 wxWindow *topWindow = wxTheApp->GetTopWindow();
187 // Forcibly delete the window.
188 if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
189 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
191 topWindow->Close(TRUE);
196 wxTheApp->SetTopWindow(NULL);
211 wxAppConsole::Exit();
214 // ============================================================================
215 // wxApp implementation
216 // ============================================================================
218 // ----------------------------------------------------------------------------
219 // wxApp Static member initialization
220 // ----------------------------------------------------------------------------
222 #if !USE_SHARED_LIBRARY
223 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
224 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
225 EVT_IDLE(wxApp::OnIdle)
226 // EVT_END_SESSION(wxApp::OnEndSession)
227 // EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
231 // ----------------------------------------------------------------------------
232 // wxApp static functions
233 // ----------------------------------------------------------------------------
234 /*static*/ bool wxApp::Initialize()
236 wxPoseAsInitializer::InitializePosers();
237 wxClassInfo::InitializeClasses();
240 wxPendingEventsLocker = new wxCriticalSection;
243 wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
244 wxTheColourDatabase->Initialize();
246 wxInitializeStockLists();
247 wxInitializeStockObjects();
249 #if wxUSE_WX_RESOURCES
250 wxInitializeResourceSystem();
253 wxBitmap::InitStandardHandlers();
255 wxModule::RegisterModules();
256 if (!wxModule::InitializeModules()) {
262 /*static*/ void wxApp::CleanUp()
264 wxModule::CleanUpModules();
266 #if wxUSE_WX_RESOURCES
267 wxCleanUpResourceSystem();
270 wxDeleteStockObjects() ;
272 // Destroy all GDI lists, etc.
273 wxDeleteStockLists();
275 delete wxTheColourDatabase;
276 wxTheColourDatabase = NULL;
278 wxBitmap::CleanUpHandlers();
280 delete wxPendingEvents;
283 delete wxPendingEventsLocker;
284 // If we don't do the following, we get an apparent memory leak.
285 ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
288 wxClassInfo::CleanUpClasses();
293 #if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
294 // At this point we want to check if there are any memory
295 // blocks that aren't part of the wxDebugContext itself,
296 // as a special case. Then when dumping we need to ignore
297 // wxDebugContext, too.
298 if (wxDebugContext::CountObjectsLeft(TRUE) > 0)
300 wxLogDebug(wxT("There were memory leaks."));
301 wxDebugContext::Dump();
302 wxDebugContext::PrintStatistics();
304 // wxDebugContext::SetStream(NULL, NULL);
307 wxDC::CocoaShutdownTextSystem();
309 // do it as the very last thing because everything else can log messages
310 delete wxLog::SetActiveTarget(NULL);
314 // ----------------------------------------------------------------------------
316 // ----------------------------------------------------------------------------
324 #if WXWIN_COMPATIBILITY_2_2
325 m_wantDebugOutput = TRUE;
333 void wxApp::CocoaInstallIdleHandler()
335 wxLogDebug("wxApp::CocoaInstallIdleHandler");
337 // Call doIdle for EVERYTHING dammit
338 // We'd need Foundation/NSConnection.h for this next constant, do we need it?
339 [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode,*/ NSModalPanelRunLoopMode, /**/NSEventTrackingRunLoopMode,/**/ nil] ];
342 bool wxApp::OnInitGui()
344 if(!wxAppBase::OnInitGui())
347 // Create the app using the sharedApplication method
348 m_cocoaApp = [NSApplication sharedApplication];
349 wxDC::CocoaInitializeTextSystem();
350 // [ m_cocoaApp setDelegate:m_cocoaApp ];
352 wxLogDebug("Just for kicks");
353 [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
354 wxLogDebug("okay.. done now");
361 if(!wxAppBase::OnInit())
367 bool wxApp::Initialized()
375 int wxApp::MainLoop()
381 // Returns TRUE if more time is needed.
382 bool wxApp::ProcessIdle()
385 event.SetEventObject(this);
388 return event.MoreRequested();
391 void wxApp::ExitMainLoop()
393 wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
394 // CocoaInstallRequestedIdleHandler();
396 // [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode,*/ nil] ];
397 // actually.. we WANT the idle event
401 [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
403 [m_cocoaApp terminate: m_cocoaApp];
406 // Is a message/event pending?
407 bool wxApp::Pending()
412 // Dispatch a message.
413 void wxApp::Dispatch()
417 void wxApp::OnIdle(wxIdleEvent& event)
419 wxLogDebug("wxApp::OnIdle");
420 static bool s_inOnIdle = FALSE;
422 // Avoid recursion (via ProcessEvent default case)
428 DeletePendingObjects();
430 // flush the logged messages if any
431 wxLog *pLog = wxLog::GetActiveTarget();
432 if ( pLog != NULL && pLog->HasPendingMessages() )
435 // Send OnIdle events to all windows
436 bool needMore = SendIdleEvents();
439 event.RequestMore(TRUE);
444 // Send idle event to all top-level windows
445 bool wxApp::SendIdleEvents()
447 bool needMore = FALSE;
448 wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
451 wxWindow* win = node->GetData();
452 if (SendIdleEvents(win))
455 node = node->GetNext();
460 // Send idle event to window and all subwindows
461 bool wxApp::SendIdleEvents(wxWindow* win)
463 // wxLogDebug("SendIdleEvents win=%p",win);
464 bool needMore = FALSE;
467 event.SetEventObject(win);
468 win->ProcessEvent(event);
470 if (event.MoreRequested())
473 wxWindowList::Node* node = win->GetChildren().GetFirst();
476 // wxLogDebug("child=%p",node->Data());
477 wxWindow* win = node->GetData();
478 if (SendIdleEvents(win))
481 node = node->GetNext();
486 // Yield to other processes
488 bool wxApp::Yield(bool onlyIfNeeded)
491 static bool s_inYield = false;
494 // disable log flushing from here because a call to wxYield() shouldn't
495 // normally result in message boxes popping up &c
503 wxFAIL_MSG( wxT("wxYield called recursively" ) );
511 wxLogDebug("WARNING: SUPPOSED to have yielded!");
512 // FIXME: Do something!
515 // let the logs be flashed again
524 void wxApp::DeletePendingObjects()
526 wxNode *node = wxPendingDelete.GetFirst();
529 wxObject *obj = (wxObject *)node->GetData();
533 if (wxPendingDelete.Find(obj))
536 node = wxPendingDelete.GetFirst();
540 // platform specifics