Provide NSAutoreleasePool instances during initialization
[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 #import <Foundation/NSAutoreleasePool.h>
43
44 // ----------------------------------------------------------------------------
45 // globals
46 // ----------------------------------------------------------------------------
47
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 class wxAutoNSAutoreleasePool
112 {
113 public:
114     wxAutoNSAutoreleasePool()
115     {
116         m_pool = [[NSAutoreleasePool alloc] init];
117     }
118     ~wxAutoNSAutoreleasePool()
119     {
120         [m_pool release];
121     }
122 protected:
123     NSAutoreleasePool *m_pool;
124 };
125
126 // ============================================================================
127 // functions
128 // ============================================================================
129
130 void wxApp::Exit()
131 {
132     wxApp::CleanUp();
133
134     wxAppConsole::Exit();
135 }
136
137 // ============================================================================
138 // wxApp implementation
139 // ============================================================================
140
141 // ----------------------------------------------------------------------------
142 // wxApp Static member initialization
143 // ----------------------------------------------------------------------------
144
145 #if !USE_SHARED_LIBRARY
146 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
147 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
148     EVT_IDLE(wxApp::OnIdle)
149 //    EVT_END_SESSION(wxApp::OnEndSession)
150 //    EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
151 END_EVENT_TABLE()
152 #endif
153
154 // ----------------------------------------------------------------------------
155 // wxApp initialization/cleanup
156 // ----------------------------------------------------------------------------
157
158 bool wxApp::Initialize(int& argc, wxChar **argv)
159 {
160     wxAutoNSAutoreleasePool pool;
161     // Mac OS X passes a process serial number command line argument when
162     // the application is launched from the Finder. This argument must be
163     // removed from the command line arguments before being handled by the
164     // application (otherwise applications would need to handle it)
165     if ( argc > 1 )
166     {
167         static const wxChar *ARG_PSN = _T("-psn_");
168         if ( wxStrncmp(argv[1], ARG_PSN, sizeof(ARG_PSN) - 1) == 0 )
169         {
170             // remove this argument
171             memmove(argv, argv + 1, argc--);
172         }
173     }
174
175     // Posing must be completed before any instances of the Objective-C
176     // classes being posed as are created.
177     wxPoseAsInitializer::InitializePosers();
178
179     return wxAppBase::Initialize(argc, argv);
180 }
181
182 void wxApp::CleanUp()
183 {
184     wxDC::CocoaShutdownTextSystem();
185
186     wxAppBase::CleanUp();
187 }
188
189 // ----------------------------------------------------------------------------
190 // wxApp creation
191 // ----------------------------------------------------------------------------
192
193 wxApp::wxApp()
194 {
195     m_topWindow = NULL;
196     wxTheApp = this;
197
198     m_isIdle = true;
199 #if WXWIN_COMPATIBILITY_2_2
200     m_wantDebugOutput = TRUE;
201 #endif
202
203     argc = 0;
204     argv = NULL;
205     m_cocoaApp = NULL;
206 }
207
208 void wxApp::CocoaInstallIdleHandler()
209 {
210     wxLogDebug("wxApp::CocoaInstallIdleHandler");
211     m_isIdle = false;
212     // Call doIdle for EVERYTHING dammit
213 // We'd need Foundation/NSConnection.h for this next constant, do we need it?
214     [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode,*/ NSModalPanelRunLoopMode, /**/NSEventTrackingRunLoopMode,/**/ nil] ];
215 }
216
217 bool wxApp::OnInitGui()
218 {
219     wxAutoNSAutoreleasePool pool;
220     if(!wxAppBase::OnInitGui())
221         return FALSE;
222
223     // Create the app using the sharedApplication method
224     m_cocoaApp = [NSApplication sharedApplication];
225     wxDC::CocoaInitializeTextSystem();
226 //    [ m_cocoaApp setDelegate:m_cocoaApp ];
227     #if 0
228     wxLogDebug("Just for kicks");
229     [ m_cocoaApp performSelector:@selector(doIdle:) withObject:NULL ];
230     wxLogDebug("okay.. done now");
231     #endif
232     return TRUE;
233 }
234
235 bool wxApp::CallOnInit()
236 {
237     wxAutoNSAutoreleasePool pool;
238     return OnInit();
239 }
240
241 bool wxApp::OnInit()
242 {
243     if(!wxAppBase::OnInit())
244         return FALSE;
245
246     return TRUE;
247 }
248
249 bool wxApp::Initialized()
250 {
251   if (GetTopWindow())
252     return TRUE;
253   else
254     return FALSE;
255 }
256
257 int wxApp::MainLoop()
258 {
259     [m_cocoaApp run];
260     return 0;
261 }
262
263 // Returns TRUE if more time is needed.
264 bool wxApp::ProcessIdle()
265 {
266     wxIdleEvent event;
267     event.SetEventObject(this);
268     ProcessEvent(event);
269
270     return event.MoreRequested();
271 }
272
273 void wxApp::ExitMainLoop()
274 {
275     wxLogDebug("wxApp::ExitMailLoop m_isIdle=%d, isRunning=%d",(int)m_isIdle,(int)[m_cocoaApp isRunning]);
276 //    CocoaInstallRequestedIdleHandler();
277 //    if(m_isIdle)
278 //        [[ NSRunLoop currentRunLoop ] performSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL order:0 modes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, /* NSConnectionReplyRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode,*/ nil] ];
279 // actually.. we WANT the idle event
280 // or not
281 #if 0
282     if(!m_isIdle)
283         [[ NSRunLoop currentRunLoop ] cancelPerformSelector:@selector(doIdle:) target:m_cocoaApp argument:NULL];
284 #endif
285     [m_cocoaApp terminate: m_cocoaApp];
286 }
287
288 // Is a message/event pending?
289 bool wxApp::Pending()
290 {
291     return 0;
292 }
293
294 // Dispatch a message.
295 void wxApp::Dispatch()
296 {
297 }
298
299 void wxApp::OnIdle(wxIdleEvent& event)
300 {
301     wxLogDebug("wxApp::OnIdle");
302    static bool s_inOnIdle = FALSE;
303
304     // Avoid recursion (via ProcessEvent default case)
305     if ( s_inOnIdle )
306         return;
307     s_inOnIdle = TRUE;
308
309
310     DeletePendingObjects();
311
312     // flush the logged messages if any
313     wxLog *pLog = wxLog::GetActiveTarget();
314     if ( pLog != NULL && pLog->HasPendingMessages() )
315         pLog->Flush();
316
317     // Send OnIdle events to all windows
318     bool needMore = SendIdleEvents();
319
320     if (needMore)
321       event.RequestMore(TRUE);
322
323     s_inOnIdle = FALSE;
324 }
325
326 // Send idle event to all top-level windows
327 bool wxApp::SendIdleEvents()
328 {
329     bool needMore = FALSE;
330     wxWindowList::Node* node = wxTopLevelWindows.GetFirst();
331     while (node)
332     {
333         wxWindow* win = node->GetData();
334         if (SendIdleEvents(win))
335             needMore = TRUE;
336
337         node = node->GetNext();
338     }
339     return needMore;
340 }
341
342 // Send idle event to window and all subwindows
343 bool wxApp::SendIdleEvents(wxWindow* win)
344 {
345 //    wxLogDebug("SendIdleEvents win=%p",win);
346     bool needMore = FALSE;
347
348     wxIdleEvent event;
349     event.SetEventObject(win);
350     win->ProcessEvent(event);
351
352     if (event.MoreRequested())
353         needMore = TRUE;
354
355     wxWindowList::Node* node = win->GetChildren().GetFirst();
356     while (node)
357     {
358 //        wxLogDebug("child=%p",node->Data());
359         wxWindow* win = node->GetData();
360         if (SendIdleEvents(win))
361             needMore = TRUE;
362
363         node = node->GetNext();
364     }
365     return needMore;
366 }
367
368 // Yield to other processes
369
370 bool wxApp::Yield(bool onlyIfNeeded)
371 {
372     // MT-FIXME
373     static bool s_inYield = false;
374
375 #if wxUSE_LOG
376     // disable log flushing from here because a call to wxYield() shouldn't
377     // normally result in message boxes popping up &c
378     wxLog::Suspend();
379 #endif // wxUSE_LOG
380
381     if (s_inYield)
382     {
383         if ( !onlyIfNeeded )
384         {
385             wxFAIL_MSG( wxT("wxYield called recursively" ) );
386         }
387
388         return false;
389     }
390
391     s_inYield = true;
392
393     wxLogDebug("WARNING: SUPPOSED to have yielded!");
394     // FIXME: Do something!
395
396 #if wxUSE_LOG
397     // let the logs be flashed again
398     wxLog::Resume();
399 #endif // wxUSE_LOG
400
401     s_inYield = false;
402
403     return true;
404 }
405