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