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