removed duplicate wxTheApp and m_appInitFn definitions from all ports, not just MSW
[wxWidgets.git] / src / cocoa / app.mm
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        cocoa/app.mm
3 // Purpose:     wxApp
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2002/11/27
7 // RCS-ID:      $Id:
8 // Copyright:   (c) David Elliott
9 // Licence:     wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21 #ifndef WX_PRECOMP
22     #include "wx/defs.h"
23     #include "wx/app.h"
24     #include "wx/frame.h"
25     #include "wx/dialog.h"
26     #include "wx/dc.h"
27     #include "wx/intl.h"
28     #include "wx/log.h"
29 #endif
30
31 #include "wx/module.h"
32
33 #include "wx/cocoa/ObjcPose.h"
34
35 #if wxUSE_WX_RESOURCES
36 #  include "wx/resource.h"
37 #endif
38
39 #import <AppKit/NSApplication.h>
40 #import <Foundation/NSRunLoop.h>
41 #import <Foundation/NSArray.h>
42
43 // ----------------------------------------------------------------------------
44 // globals
45 // ----------------------------------------------------------------------------
46
47 wxPoseAsInitializer *wxPoseAsInitializer::sm_first = NULL;
48
49 @interface wxPoserNSApplication : NSApplication
50 {
51 }
52
53 - (void)doIdle: (id)data;
54 - (void)finishLaunching;
55 - (void)sendEvent: (NSEvent*)anEvent;
56 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
57 @end // wxPoserNSApplication
58
59 @implementation wxPoserNSApplication : NSApplication
60
61 - (void)doIdle: (id)data
62 {
63     wxASSERT(wxTheApp);
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
68     {
69         wxLogDebug("Looping for idle events");
70         #if 1
71         if( [rl runMode:[rl currentMode] beforeDate:[NSDate distantPast]])
72         {
73             wxLogDebug("Found actual work to do");
74             break;
75         }
76         #endif
77     }
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();
81 }
82
83 - (void)finishLaunching
84 {
85     wxLogDebug("finishLaunching");
86     bool initsuccess = wxTheApp->OnInit();
87     if(!initsuccess)
88         [super stop: NULL];
89
90     [super finishLaunching];
91 }
92
93 - (void)sendEvent: (NSEvent*)anEvent
94 {
95     wxLogDebug("SendEvent");
96     wxTheApp->CocoaInstallRequestedIdleHandler();
97     [super sendEvent: anEvent];
98 }
99
100 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
101 {
102     BOOL ret = wxTheApp->GetExitOnFrameDelete();
103     wxLogDebug("applicationShouldTermintaeAfterLastWindowClosed=%d",ret);
104     return ret;
105 }
106
107 @end // wxPoserNSApplication
108 WX_IMPLEMENT_POSER(wxPoserNSApplication);
109
110 // ============================================================================
111 // functions
112 // ============================================================================
113
114 //----------------------------------------------------------------------
115 // wxEntry
116 //----------------------------------------------------------------------
117
118 int WXDLLEXPORT wxEntryStart( int WXUNUSED(argc), char *WXUNUSED(argv)[] )
119 {
120     return wxApp::Initialize();
121 }
122
123 int WXDLLEXPORT wxEntryInitGui()
124 {
125     return wxTheApp->OnInitGui();
126 }
127
128 void WXDLLEXPORT wxEntryCleanup()
129 {
130     wxApp::CleanUp();
131 }
132
133 int wxEntry( int argc, char *argv[])
134 {
135     if (!wxEntryStart(argc, argv)) {
136         return 0;
137     }
138     wxLogDebug("Creating application");
139    // create the application object or ensure that one already exists
140     if (!wxTheApp)
141     {
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.") );
147
148         wxTheApp = (wxApp*) (*wxApp::GetInitializerFunction()) ();
149     }
150
151     wxCHECK_MSG( wxTheApp, 0, wxT("You have to define an instance of wxApp!") );
152
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)
157
158     if (argc > 1) {
159         char theArg[6] = "";
160         strncpy(theArg, argv[1], 5);
161
162         if (strcmp(theArg, "-psn_") == 0) {
163             // assume the argument is always the only one and remove it
164             --argc;
165         }
166     }
167
168     wxTheApp->argc = argc;
169     wxTheApp->argv = argv;
170
171     wxLogDebug("initializing gui");
172     // GUI-specific initialization, such as creating an app context.
173     wxEntryInitGui();
174
175     // Here frames insert themselves automatically
176     // into wxTopLevelWindows by getting created
177     // in OnInit().
178
179     int retValue = 0;
180
181     wxLogDebug("Time to run");
182     retValue = wxTheApp->OnRun();
183
184     wxWindow *topWindow = wxTheApp->GetTopWindow();
185     if ( topWindow )
186     {
187         // Forcibly delete the window.
188         if ( topWindow->IsKindOf(CLASSINFO(wxFrame)) ||
189                 topWindow->IsKindOf(CLASSINFO(wxDialog)) )
190         {
191             topWindow->Close(TRUE);
192         }
193         else
194         {
195             delete topWindow;
196             wxTheApp->SetTopWindow(NULL);
197         }
198     }
199
200     wxTheApp->OnExit();
201
202     wxEntryCleanup();
203
204     return retValue;
205 }
206
207 void wxApp::Exit()
208 {
209     wxApp::CleanUp();
210
211     wxAppConsole::Exit();
212 }
213
214 // ============================================================================
215 // wxApp implementation
216 // ============================================================================
217
218 // ----------------------------------------------------------------------------
219 // wxApp Static member initialization
220 // ----------------------------------------------------------------------------
221
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)
228 END_EVENT_TABLE()
229 #endif
230
231 // ----------------------------------------------------------------------------
232 // wxApp static functions
233 // ----------------------------------------------------------------------------
234 /*static*/ bool wxApp::Initialize()
235 {
236     wxPoseAsInitializer::InitializePosers();
237     wxClassInfo::InitializeClasses();
238
239 #if wxUSE_THREADS
240     wxPendingEventsLocker = new wxCriticalSection;
241 #endif
242
243     wxTheColourDatabase = new wxColourDatabase(wxKEY_STRING);
244     wxTheColourDatabase->Initialize();
245
246     wxInitializeStockLists();
247     wxInitializeStockObjects();
248
249 #if wxUSE_WX_RESOURCES
250     wxInitializeResourceSystem();
251 #endif
252
253     wxBitmap::InitStandardHandlers();
254
255     wxModule::RegisterModules();
256     if (!wxModule::InitializeModules()) {
257         return FALSE;
258     }
259     return TRUE;
260 }
261
262 /*static*/ void wxApp::CleanUp()
263 {
264     wxModule::CleanUpModules();
265
266 #if wxUSE_WX_RESOURCES
267     wxCleanUpResourceSystem();
268 #endif
269
270     wxDeleteStockObjects() ;
271
272     // Destroy all GDI lists, etc.
273     wxDeleteStockLists();
274
275     delete wxTheColourDatabase;
276     wxTheColourDatabase = NULL;
277
278     wxBitmap::CleanUpHandlers();
279
280     delete wxPendingEvents;
281
282 #if wxUSE_THREADS
283     delete wxPendingEventsLocker;
284     // If we don't do the following, we get an apparent memory leak.
285     ((wxEvtHandler&) wxDefaultValidator).ClearEventLocker();
286 #endif
287
288     wxClassInfo::CleanUpClasses();
289
290     delete wxTheApp;
291     wxTheApp = NULL;
292
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)
299     {
300         wxLogDebug(wxT("There were memory leaks."));
301         wxDebugContext::Dump();
302         wxDebugContext::PrintStatistics();
303     }
304     //  wxDebugContext::SetStream(NULL, NULL);
305 #endif
306
307     wxDC::CocoaShutdownTextSystem();
308 #if wxUSE_LOG
309     // do it as the very last thing because everything else can log messages
310     delete wxLog::SetActiveTarget(NULL);
311 #endif // wxUSE_LOG
312 }
313
314 // ----------------------------------------------------------------------------
315 // wxApp creation
316 // ----------------------------------------------------------------------------
317
318 wxApp::wxApp()
319 {
320     m_topWindow = NULL;
321     wxTheApp = this;
322
323     m_isIdle = true;
324 #if WXWIN_COMPATIBILITY_2_2
325     m_wantDebugOutput = TRUE;
326 #endif
327
328     argc = 0;
329     argv = NULL;
330     m_cocoaApp = NULL;
331 }
332
333 void wxApp::CocoaInstallIdleHandler()
334 {
335     wxLogDebug("wxApp::CocoaInstallIdleHandler");
336     m_isIdle = false;
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] ];
340 }
341
342 bool wxApp::OnInitGui()
343 {
344     if(!wxAppBase::OnInitGui())
345         return FALSE;
346
347     // Create the app using the sharedApplication method
348     m_cocoaApp = [NSApplication sharedApplication];
349     wxDC::CocoaInitializeTextSystem();
350 //    [ m_cocoaApp setDelegate:m_cocoaApp ];
351     #if 0
352     wxLogDebug("Just for kicks");
353     [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
354     wxLogDebug("okay.. done now");
355     #endif
356     return TRUE;
357 }
358
359 bool wxApp::OnInit()
360 {
361     if(!wxAppBase::OnInit())
362         return FALSE;
363
364     return TRUE;
365 }
366
367 bool wxApp::Initialized()
368 {
369   if (GetTopWindow())
370     return TRUE;
371   else
372     return FALSE;
373 }
374
375 int wxApp::MainLoop()
376 {
377     [m_cocoaApp run];
378     return 0;
379 }
380
381 // Returns TRUE if more time is needed.
382 bool wxApp::ProcessIdle()
383 {
384     wxIdleEvent event;
385     event.SetEventObject(this);
386     ProcessEvent(event);
387
388     return event.MoreRequested();
389 }
390
391 void wxApp::ExitMainLoop()
392 {
393     wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
394 //    CocoaInstallRequestedIdleHandler();
395 //    if(m_isIdle)
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
398 // or not
399 #if 0
400     if(!m_isIdle)
401         [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
402 #endif
403     [m_cocoaApp terminate: m_cocoaApp];
404 }
405
406 // Is a message/event pending?
407 bool wxApp::Pending()
408 {
409     return 0;
410 }
411
412 // Dispatch a message.
413 void wxApp::Dispatch()
414 {
415 }
416
417 void wxApp::OnIdle(wxIdleEvent& event)
418 {
419     wxLogDebug("wxApp::OnIdle");
420    static bool s_inOnIdle = FALSE;
421
422     // Avoid recursion (via ProcessEvent default case)
423     if ( s_inOnIdle )
424         return;
425     s_inOnIdle = TRUE;
426
427
428     DeletePendingObjects();
429
430     // flush the logged messages if any
431     wxLog *pLog = wxLog::GetActiveTarget();
432     if ( pLog != NULL && pLog->HasPendingMessages() )
433         pLog->Flush();
434
435     // Send OnIdle events to all windows
436     bool needMore = SendIdleEvents();
437
438     if (needMore)
439       event.RequestMore(TRUE);
440
441     s_inOnIdle = FALSE;
442 }
443
444 // Send idle event to all top-level windows
445 bool wxApp::SendIdleEvents()
446 {
447     bool needMore = FALSE;
448     wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
449     while (node)
450     {
451         wxWindow* win = node->GetData();
452         if (SendIdleEvents(win))
453             needMore = TRUE;
454
455         node = node->GetNext();
456     }
457     return needMore;
458 }
459
460 // Send idle event to window and all subwindows
461 bool wxApp::SendIdleEvents(wxWindow* win)
462 {
463 //    wxLogDebug("SendIdleEvents win=%p",win);
464     bool needMore = FALSE;
465
466     wxIdleEvent event;
467     event.SetEventObject(win);
468     win->ProcessEvent(event);
469
470     if (event.MoreRequested())
471         needMore = TRUE;
472
473     wxWindowList::Node* node = win->GetChildren().GetFirst();
474     while (node)
475     {
476 //        wxLogDebug("child=%p",node->Data());
477         wxWindow* win = node->GetData();
478         if (SendIdleEvents(win))
479             needMore = TRUE;
480
481         node = node->GetNext();
482     }
483     return needMore;
484 }
485
486 // Yield to other processes
487
488 bool wxApp::Yield(bool onlyIfNeeded)
489 {
490     // MT-FIXME
491     static bool s_inYield = false;
492
493 #if wxUSE_LOG
494     // disable log flushing from here because a call to wxYield() shouldn't
495     // normally result in message boxes popping up &c
496     wxLog::Suspend();
497 #endif // wxUSE_LOG
498
499     if (s_inYield)
500     {
501         if ( !onlyIfNeeded )
502         {
503             wxFAIL_MSG( wxT("wxYield called recursively" ) );
504         }
505
506         return false;
507     }
508
509     s_inYield = true;
510
511     wxLogDebug("WARNING: SUPPOSED to have yielded!");
512     // FIXME: Do something!
513
514 #if wxUSE_LOG
515     // let the logs be flashed again
516     wxLog::Resume();
517 #endif // wxUSE_LOG
518
519     s_inYield = false;
520
521     return true;
522 }
523
524 void wxApp::DeletePendingObjects()
525 {
526     wxNode *node = wxPendingDelete.GetFirst();
527     while (node)
528     {
529         wxObject *obj = (wxObject *)node->GetData();
530
531         delete obj;
532
533         if (wxPendingDelete.Find(obj))
534             delete node;
535
536         node = wxPendingDelete.GetFirst();
537     }
538 }
539
540 // platform specifics
541