resource fork not used anymore
[wxWidgets.git] / src / mac / carbon / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose: wxApp
4 // Author: Stefan Csomor
5 // Modified by:
6 // Created: 1998-01-01
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "app.h"
14 #endif
15
16 #include "wx/defs.h"
17
18 #include "wx/window.h"
19 #include "wx/frame.h"
20 #include "wx/button.h"
21 #include "wx/app.h"
22 #include "wx/utils.h"
23 #include "wx/gdicmn.h"
24 #include "wx/pen.h"
25 #include "wx/brush.h"
26 #include "wx/cursor.h"
27 #include "wx/intl.h"
28 #include "wx/icon.h"
29 #include "wx/palette.h"
30 #include "wx/dc.h"
31 #include "wx/dialog.h"
32 #include "wx/msgdlg.h"
33 #include "wx/log.h"
34 #include "wx/module.h"
35 #include "wx/memory.h"
36 #include "wx/tooltip.h"
37 #include "wx/textctrl.h"
38 #include "wx/menu.h"
39 #include "wx/docview.h"
40 #include "wx/filename.h"
41
42 #include <string.h>
43
44 // mac
45
46 #ifndef __DARWIN__
47 #if __option(profile)
48 #include <profiler.h>
49 #endif
50 #endif
51
52 // #include "apprsrc.h"
53
54 #include "wx/mac/uma.h"
55 #include "wx/mac/macnotfy.h"
56
57 #ifdef __DARWIN__
58 # include <CoreServices/CoreServices.h>
59 # if defined(WXMAKINGDLL_CORE)
60 # include <mach-o/dyld.h>
61 # endif
62 #else
63 # include <Sound.h>
64 # include <Threads.h>
65 # include <ToolUtils.h>
66 # include <DiskInit.h>
67 # include <Devices.h>
68 #endif
69
70 extern wxList wxPendingDelete;
71
72 // set wxMAC_USE_RAEL to 1 if RunApplicationEventLoop should be used
73 // if 0 the lower level CarbonEventLoop will be used
74 // on the long run RAEL should replace the low level event loop
75 // we will have to clean up event handling to make sure we don't
76 // miss handling of things like pending events etc
77 // perhaps we will also have to pipe events through an ueber-event-handler
78 // to make sure we have one place to do all these house-keeping functions
79
80 #define wxMAC_USE_RAEL 0
81
82 #if wxUSE_THREADS
83 extern size_t g_numberOfThreads;
84 #endif // wxUSE_THREADS
85
86 // statics for implementation
87
88 static bool s_inYield = FALSE;
89
90 static bool s_inReceiveEvent = FALSE ;
91 static EventTime sleepTime = kEventDurationNoWait ;
92
93 #if !USE_SHARED_LIBRARY
94 IMPLEMENT_DYNAMIC_CLASS(wxApp, wxEvtHandler)
95 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
96 EVT_IDLE(wxApp::OnIdle)
97 EVT_END_SESSION(wxApp::OnEndSession)
98 EVT_QUERY_END_SESSION(wxApp::OnQueryEndSession)
99 END_EVENT_TABLE()
100 #endif
101
102
103 const short kMacMinHeap = (29 * 1024) ;
104 // platform specific static variables
105
106 const short kwxMacMenuBarResource = 1 ;
107 const short kwxMacAppleMenuId = 1 ;
108
109 WXHRGN wxApp::s_macCursorRgn = NULL;
110 wxWindow* wxApp::s_captureWindow = NULL ;
111 int wxApp::s_lastMouseDown = 0 ;
112 long wxApp::sm_lastMessageTime = 0;
113 long wxApp::s_lastModifiers = 0 ;
114
115
116 bool wxApp::s_macSupportPCMenuShortcuts = true ;
117 long wxApp::s_macAboutMenuItemId = wxID_ABOUT ;
118 long wxApp::s_macPreferencesMenuItemId = wxID_PREFERENCES ;
119 long wxApp::s_macExitMenuItemId = wxID_EXIT ;
120 wxString wxApp::s_macHelpMenuTitleName = wxT("&Help") ;
121
122 // Normally we're not a plugin
123 bool wxApp::sm_isEmbedded = false;
124 //----------------------------------------------------------------------
125 // Core Apple Event Support
126 //----------------------------------------------------------------------
127
128 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
129 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
130 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
131 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
132 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long refcon ) ;
133
134 pascal OSErr AEHandleODoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
135 {
136 return wxTheApp->MacHandleAEODoc( (AppleEvent*) event , reply) ;
137 }
138
139 pascal OSErr AEHandleOApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
140 {
141 return wxTheApp->MacHandleAEOApp( (AppleEvent*) event , reply ) ;
142 }
143
144 pascal OSErr AEHandlePDoc( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
145 {
146 return wxTheApp->MacHandleAEPDoc( (AppleEvent*) event , reply ) ;
147 }
148
149 pascal OSErr AEHandleQuit( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
150 {
151 return wxTheApp->MacHandleAEQuit( (AppleEvent*) event , reply) ;
152 }
153
154 pascal OSErr AEHandleRApp( const AppleEvent *event , AppleEvent *reply , long WXUNUSED(refcon) )
155 {
156 return wxTheApp->MacHandleAERApp( (AppleEvent*) event , reply) ;
157 }
158
159 // AEODoc Calls MacOpenFile on each of the files passed
160
161 short wxApp::MacHandleAEODoc(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply))
162 {
163 AEDescList docList;
164 AEKeyword keywd;
165 DescType returnedType;
166 Size actualSize;
167 long itemsInList;
168 FSSpec theSpec;
169 OSErr err;
170 short i;
171 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
172 if (err != noErr)
173 return err;
174
175 err = AECountItems(&docList, &itemsInList);
176 if (err != noErr)
177 return err;
178
179 ProcessSerialNumber PSN ;
180 PSN.highLongOfPSN = 0 ;
181 PSN.lowLongOfPSN = kCurrentProcess ;
182 SetFrontProcess( &PSN ) ;
183
184 for (i = 1; i <= itemsInList; i++) {
185 AEGetNthPtr(&docList, i, typeFSS, &keywd, &returnedType,
186 (Ptr) & theSpec, sizeof(theSpec), &actualSize);
187 wxString fName = wxMacFSSpec2MacFilename(&theSpec);
188 MacOpenFile(fName);
189 }
190 return noErr;
191 }
192
193 // AEPDoc Calls MacPrintFile on each of the files passed
194
195 short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply))
196 {
197 AEDescList docList;
198 AEKeyword keywd;
199 DescType returnedType;
200 Size actualSize;
201 long itemsInList;
202 FSSpec theSpec;
203 OSErr err;
204 short i;
205 err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList);
206 if (err != noErr)
207 return err;
208
209 err = AECountItems(&docList, &itemsInList);
210 if (err != noErr)
211 return err;
212
213 ProcessSerialNumber PSN ;
214 PSN.highLongOfPSN = 0 ;
215 PSN.lowLongOfPSN = kCurrentProcess ;
216 SetFrontProcess( &PSN ) ;
217
218 for (i = 1; i <= itemsInList; i++) {
219 AEGetNthPtr(&docList, i, typeFSS, &keywd, &returnedType,
220 (Ptr) & theSpec, sizeof(theSpec), &actualSize);
221 wxString fName = wxMacFSSpec2MacFilename(&theSpec);
222 MacPrintFile(fName);
223 }
224 return noErr;
225 }
226
227 // AEOApp calls MacNewFile
228
229 short wxApp::MacHandleAEOApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
230 {
231 MacNewFile() ;
232 return noErr ;
233 }
234
235 // AEQuit attempts to quit the application
236
237 short wxApp::MacHandleAEQuit(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
238 {
239 wxWindow* win = GetTopWindow() ;
240 if ( win )
241 {
242 wxCommandEvent exitEvent(wxEVT_COMMAND_MENU_SELECTED, s_macExitMenuItemId);
243 if (!win->ProcessEvent(exitEvent))
244 win->Close(TRUE ) ;
245 }
246 else
247 {
248 ExitMainLoop() ;
249 }
250 return noErr ;
251 }
252
253 // AEROApp calls MacReopenApp
254
255 short wxApp::MacHandleAERApp(const WXEVENTREF WXUNUSED(event) , WXEVENTREF WXUNUSED(reply))
256 {
257 MacReopenApp() ;
258 return noErr ;
259 }
260
261
262 //----------------------------------------------------------------------
263 // Support Routines linking the Mac...File Calls to the Document Manager
264 //----------------------------------------------------------------------
265
266 void wxApp::MacOpenFile(const wxString & fileName )
267 {
268 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
269 if ( dm )
270 dm->CreateDocument(fileName , wxDOC_SILENT ) ;
271 }
272
273 void wxApp::MacPrintFile(const wxString & fileName )
274 {
275 wxDocManager* dm = wxDocManager::GetDocumentManager() ;
276 if ( dm )
277 {
278 wxDocument *doc = dm->CreateDocument(fileName , wxDOC_SILENT ) ;
279 if ( doc )
280 {
281 wxView* view = doc->GetFirstView() ;
282 if( view )
283 {
284 wxPrintout *printout = view->OnCreatePrintout();
285 if (printout)
286 {
287 wxPrinter printer;
288 printer.Print(view->GetFrame(), printout, TRUE);
289 delete printout;
290 }
291 }
292 if (doc->Close())
293 {
294 doc->DeleteAllViews();
295 dm->RemoveDocument(doc) ;
296 }
297 }
298 }
299 }
300
301 void wxApp::MacNewFile()
302 {
303 }
304
305 void wxApp::MacReopenApp()
306 {
307 // HIG says :
308 // if there is no open window -> create a new one
309 // if all windows are hidden -> show the first
310 // if some windows are not hidden -> do nothing
311
312 wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
313 if ( node == NULL )
314 {
315 MacNewFile() ;
316 }
317 else
318 {
319 wxTopLevelWindow* firstIconized = NULL ;
320 while (node)
321 {
322 wxTopLevelWindow* win = (wxTopLevelWindow*) node->GetData();
323 if ( win->IsIconized() == false )
324 {
325 firstIconized = NULL ;
326 break ;
327 }
328 else
329 {
330 if ( firstIconized == NULL )
331 firstIconized = win ;
332 }
333 node = node->GetNext();
334 }
335 if ( firstIconized )
336 firstIconized->Iconize( false ) ;
337 }
338 }
339
340 //----------------------------------------------------------------------
341 // Carbon Event Handler
342 //----------------------------------------------------------------------
343
344 static const EventTypeSpec eventList[] =
345 {
346 { kEventClassCommand, kEventProcessCommand } ,
347 { kEventClassCommand, kEventCommandUpdateStatus } ,
348
349 { kEventClassMenu, kEventMenuOpening },
350 { kEventClassMenu, kEventMenuClosed },
351 { kEventClassMenu, kEventMenuTargetItem },
352
353 { kEventClassApplication , kEventAppActivated } ,
354 { kEventClassApplication , kEventAppDeactivated } ,
355 // handling the quit event is not recommended by apple
356 // rather using the quit apple event - which we do
357
358 { kEventClassAppleEvent , kEventAppleEvent } ,
359
360 { kEventClassMouse , kEventMouseDown } ,
361 { kEventClassMouse , kEventMouseMoved } ,
362 { kEventClassMouse , kEventMouseUp } ,
363 { kEventClassMouse , kEventMouseDragged } ,
364 { 'WXMC' , 'WXMC' }
365 } ;
366
367 static pascal OSStatus
368 wxMacAppMenuEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
369 {
370 wxMacCarbonEvent cEvent( event ) ;
371 MenuRef menuRef = cEvent.GetParameter<MenuRef>(kEventParamDirectObject) ;
372 wxMenu* menu = wxFindMenuFromMacMenu( menuRef ) ;
373
374 if ( menu )
375 {
376 wxEventType type=0;
377 MenuCommand cmd=0;
378 switch (GetEventKind(event))
379 {
380 case kEventMenuOpening:
381 type = wxEVT_MENU_OPEN;
382 break;
383 case kEventMenuClosed:
384 type = wxEVT_MENU_CLOSE;
385 break;
386 case kEventMenuTargetItem:
387 cmd = cEvent.GetParameter<MenuCommand>(kEventParamMenuCommand,typeMenuCommand) ;
388 if (cmd != 0)
389 type = wxEVT_MENU_HIGHLIGHT;
390 break;
391 default:
392 wxFAIL_MSG(wxT("Unexpected menu event kind"));
393 break;
394 }
395
396 if ( type )
397 {
398 wxMenuEvent wxevent(type, cmd);
399 wxevent.SetEventObject(menu);
400
401 wxEvtHandler* handler = menu->GetEventHandler();
402 if (handler && handler->ProcessEvent(wxevent))
403 {
404 // handled
405 }
406 else
407 {
408 wxWindow *win = menu->GetInvokingWindow();
409 if (win)
410 win->GetEventHandler()->ProcessEvent(wxevent);
411 }
412 }
413 }
414
415 return eventNotHandledErr;
416 }
417
418 static pascal OSStatus wxMacAppCommandEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
419 {
420 OSStatus result = eventNotHandledErr ;
421
422 HICommand command ;
423
424 wxMacCarbonEvent cEvent( event ) ;
425 cEvent.GetParameter<HICommand>(kEventParamDirectObject,typeHICommand,&command) ;
426
427 wxMenuItem* item = NULL ;
428 MenuCommand id = command.commandID ;
429 // for items we don't really control
430 if ( id == kHICommandPreferences )
431 {
432 id = wxApp::s_macPreferencesMenuItemId ;
433
434 wxMenuBar* mbar = wxMenuBar::MacGetInstalledMenuBar() ;
435 if ( mbar )
436 {
437 wxMenu* menu = NULL ;
438 item = mbar->FindItem( id , &menu ) ;
439 }
440 }
441 else if ( id != 0 && command.menu.menuRef != 0 && command.menu.menuItemIndex != 0 )
442 {
443 GetMenuItemRefCon( command.menu.menuRef , command.menu.menuItemIndex , (UInt32*) &item ) ;
444 }
445
446 if ( item )
447 {
448 switch( cEvent.GetKind() )
449 {
450 case kEventProcessCommand :
451 {
452 if (item->IsCheckable())
453 {
454 item->Check( !item->IsChecked() ) ;
455 }
456
457 item->GetMenu()->SendEvent( id , item->IsCheckable() ? item->IsChecked() : -1 ) ;
458 result = noErr ;
459 }
460 break ;
461 case kEventCommandUpdateStatus:
462 // eventually trigger an updateui round
463 result = noErr ;
464 break ;
465 default :
466 break ;
467 }
468 }
469 return result ;
470 }
471
472 static pascal OSStatus wxMacAppApplicationEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
473 {
474 OSStatus result = eventNotHandledErr ;
475 switch ( GetEventKind( event ) )
476 {
477 case kEventAppActivated :
478 {
479 if ( wxTheApp )
480 wxTheApp->SetActive( true , NULL ) ;
481 result = noErr ;
482 }
483 break ;
484 case kEventAppDeactivated :
485 {
486 if ( wxTheApp )
487 wxTheApp->SetActive( false , NULL ) ;
488 result = noErr ;
489 }
490 break ;
491 default :
492 break ;
493 }
494 return result ;
495 }
496
497 pascal OSStatus wxMacAppEventHandler( EventHandlerCallRef handler , EventRef event , void *data )
498 {
499 EventRef formerEvent = (EventRef) wxTheApp->MacGetCurrentEvent() ;
500 EventHandlerCallRef formerEventHandlerCallRef = (EventHandlerCallRef) wxTheApp->MacGetCurrentEventHandlerCallRef() ;
501 wxTheApp->MacSetCurrentEvent( event , handler ) ;
502
503 OSStatus result = eventNotHandledErr ;
504 switch( GetEventClass( event ) )
505 {
506 case kEventClassCommand :
507 result = wxMacAppCommandEventHandler( handler , event , data ) ;
508 break ;
509 case kEventClassApplication :
510 result = wxMacAppApplicationEventHandler( handler , event , data ) ;
511 break ;
512 case kEventClassMenu :
513 result = wxMacAppMenuEventHandler( handler , event , data ) ;
514 break ;
515 case kEventClassMouse :
516 result = wxMacTopLevelMouseEventHandler( handler , event , NULL ) ;
517 break ;
518 case kEventClassAppleEvent :
519 {
520 EventRecord rec ;
521 wxMacConvertEventToRecord( event , &rec ) ;
522 result = AEProcessAppleEvent( &rec ) ;
523 }
524 break ;
525 default :
526 break ;
527 }
528
529 wxTheApp->MacSetCurrentEvent( formerEvent, formerEventHandlerCallRef ) ;
530
531 return result ;
532 }
533
534 DEFINE_ONE_SHOT_HANDLER_GETTER( wxMacAppEventHandler )
535
536 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
537 // we know it's there ;-)
538 WXIMPORT char std::__throws_bad_alloc ;
539 #endif
540
541 pascal static void wxMacAssertOutputHandler(OSType componentSignature, UInt32 options,
542 const char *assertionString, const char *exceptionLabelString,
543 const char *errorString, const char *fileName, long lineNumber, void *value, ConstStr255Param outputMsg)
544 {
545 // flow into assert handling
546 wxString fileNameStr ;
547 wxString assertionStr ;
548 wxString exceptionStr ;
549 wxString errorStr ;
550 #if wxUSE_UNICODE
551 fileNameStr = wxString(fileName, wxConvLocal);
552 assertionStr = wxString(assertionString, wxConvLocal);
553 exceptionStr = wxString((exceptionLabelString!=0) ? exceptionLabelString : "", wxConvLocal) ;
554 errorStr = wxString((errorString!=0) ? errorString : "", wxConvLocal) ;
555 #else
556 fileNameStr = fileName;
557 assertionStr = assertionString;
558 exceptionStr = (exceptionLabelString!=0) ? exceptionLabelString : "" ;
559 errorStr = (errorString!=0) ? errorString : "" ;
560 #endif
561
562 #if 1
563 // flow into log
564 wxLogDebug( wxT("AssertMacros: %s %s %s file: %s, line: %ld (value %p)\n"),
565 assertionStr.c_str() ,
566 exceptionStr.c_str() ,
567 errorStr.c_str(),
568 fileNameStr.c_str(), lineNumber ,
569 value ) ;
570 #else
571
572 wxOnAssert(fileNameStr, lineNumber , assertionStr ,
573 wxString::Format( wxT("%s %s value (%p)") ,exceptionStr, errorStr , value ) ) ;
574 #endif
575 }
576
577 bool wxApp::Initialize(int& argc, wxChar **argv)
578 {
579 // Mac-specific
580
581 #if __WXDEBUG__
582 InstallDebugAssertOutputHandler ( NewDebugAssertOutputHandlerUPP( wxMacAssertOutputHandler ) );
583 #endif
584 UMAInitToolbox( 4, sm_isEmbedded ) ;
585 SetEventMask( everyEvent ) ;
586 UMAShowWatchCursor() ;
587
588 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
589 // open shared library resources from here since we don't have
590 // __wxinitialize in Mach-O shared libraries
591 wxStAppResource::OpenSharedLibraryResource(NULL);
592 #endif
593
594 #ifndef __DARWIN__
595 # if __option(profile)
596 ProfilerInit( collectDetailed, bestTimeBase , 40000 , 50 ) ;
597 # endif
598 #endif
599
600 #ifndef __DARWIN__
601 // now avoid exceptions thrown for new (bad_alloc)
602 // FIXME CS for some changes outside wxMac does not compile anymore
603 #if 0
604 std::__throws_bad_alloc = 0 ;
605 #endif
606
607 #endif
608
609 s_macCursorRgn = ::NewRgn() ;
610
611 // Mac OS X passes a process serial number command line argument when
612 // the application is launched from the Finder. This argument must be
613 // removed from the command line arguments before being handled by the
614 // application (otherwise applications would need to handle it)
615 if ( argc > 1 )
616 {
617 static const wxChar *ARG_PSN = _T("-psn_");
618 if ( wxStrncmp(argv[1], ARG_PSN, wxStrlen(ARG_PSN)) == 0 )
619 {
620 // remove this argument
621 --argc;
622 memmove(argv + 1, argv + 2, argc * sizeof(char *));
623 }
624 }
625
626 if ( !wxAppBase::Initialize(argc, argv) )
627 return false;
628
629 #if wxUSE_INTL
630 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
631 #endif
632
633 #if TARGET_API_MAC_OSX
634 // these might be the startup dirs, set them to the 'usual' dir containing the app bundle
635 wxString startupCwd = wxGetCwd() ;
636 if ( startupCwd == wxT("/") || startupCwd.Right(15) == wxT("/Contents/MacOS") )
637 {
638 CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle() ) ;
639 CFURLRef urlParent = CFURLCreateCopyDeletingLastPathComponent( kCFAllocatorDefault , url ) ;
640 CFRelease( url ) ;
641 CFStringRef path = CFURLCopyFileSystemPath ( urlParent , kCFURLPOSIXPathStyle ) ;
642 CFRelease( urlParent ) ;
643 wxString cwd = wxMacCFStringHolder(path).AsString(wxLocale::GetSystemEncoding());
644 wxSetWorkingDirectory( cwd ) ;
645 }
646 #endif
647
648 wxMacCreateNotifierTable() ;
649
650 UMAShowArrowCursor() ;
651
652 return true;
653 }
654
655 bool wxApp::OnInitGui()
656 {
657 if( !wxAppBase::OnInitGui() )
658 return false ;
659
660 InstallStandardEventHandler( GetApplicationEventTarget() ) ;
661
662 if (!sm_isEmbedded)
663 {
664 InstallApplicationEventHandler(
665 GetwxMacAppEventHandlerUPP(),
666 GetEventTypeCount(eventList), eventList, wxTheApp, (EventHandlerRef *)&(wxTheApp->m_macEventHandler));
667 }
668
669 if (!sm_isEmbedded)
670 {
671 AEInstallEventHandler( kCoreEventClass , kAEOpenDocuments ,
672 NewAEEventHandlerUPP(AEHandleODoc) ,
673 0 , FALSE ) ;
674 AEInstallEventHandler( kCoreEventClass , kAEOpenApplication ,
675 NewAEEventHandlerUPP(AEHandleOApp) ,
676 0 , FALSE ) ;
677 AEInstallEventHandler( kCoreEventClass , kAEPrintDocuments ,
678 NewAEEventHandlerUPP(AEHandlePDoc) ,
679 0 , FALSE ) ;
680 AEInstallEventHandler( kCoreEventClass , kAEReopenApplication ,
681 NewAEEventHandlerUPP(AEHandleRApp) ,
682 0 , FALSE ) ;
683 AEInstallEventHandler( kCoreEventClass , kAEQuitApplication ,
684 NewAEEventHandlerUPP(AEHandleQuit) ,
685 0 , FALSE ) ;
686 }
687
688 return TRUE ;
689 }
690
691 void wxApp::CleanUp()
692 {
693 wxToolTip::RemoveToolTips() ;
694
695 // One last chance for pending objects to be cleaned up
696 wxTheApp->DeletePendingObjects();
697
698 wxMacDestroyNotifierTable() ;
699
700 #ifndef __DARWIN__
701 # if __option(profile)
702 ProfilerDump( (StringPtr)"\papp.prof" ) ;
703 ProfilerTerm() ;
704 # endif
705 #endif
706
707 #if defined(WXMAKINGDLL_CORE) && defined(__DARWIN__)
708 // close shared library resources from here since we don't have
709 // __wxterminate in Mach-O shared libraries
710 wxStAppResource::CloseSharedLibraryResource();
711 #endif
712
713 UMACleanupToolbox() ;
714 if (s_macCursorRgn) {
715 ::DisposeRgn((RgnHandle)s_macCursorRgn);
716 }
717
718 #if 0
719 TerminateAE() ;
720 #endif
721
722 wxAppBase::CleanUp();
723 }
724
725 //----------------------------------------------------------------------
726 // misc initialization stuff
727 //----------------------------------------------------------------------
728
729 #if defined(WXMAKINGDLL_CORE) && !defined(__DARWIN__)
730
731 // for shared libraries we have to manually get the correct resource
732 // ref num upon initializing and releasing when terminating, therefore
733 // the __wxinitialize and __wxterminate must be used
734
735 extern "C" {
736 void __sinit(void); /* (generated by linker) */
737 pascal OSErr __initialize(const CFragInitBlock *theInitBlock);
738 pascal void __terminate(void);
739 }
740
741 pascal OSErr __wxinitialize(const CFragInitBlock *theInitBlock)
742 {
743 return __initialize( theInitBlock ) ;
744 }
745
746 pascal void __wxterminate(void)
747 {
748 __terminate() ;
749 }
750
751 #endif /* WXMAKINGDLL_CORE && !__DARWIN__ */
752
753 bool wxMacConvertEventToRecord( EventRef event , EventRecord *rec)
754 {
755 bool converted = ConvertEventRefToEventRecord( event,rec) ;
756 OSStatus err = noErr ;
757 if ( !converted )
758 {
759 switch( GetEventClass( event ) )
760 {
761 case kEventClassKeyboard :
762 {
763 converted = true ;
764 switch( GetEventKind(event) )
765 {
766 case kEventRawKeyDown :
767 rec->what = keyDown ;
768 break ;
769 case kEventRawKeyRepeat :
770 rec->what = autoKey ;
771 break ;
772 case kEventRawKeyUp :
773 rec->what = keyUp ;
774 break ;
775 case kEventRawKeyModifiersChanged :
776 rec->what = nullEvent ;
777 break ;
778 default :
779 converted = false ;
780 break ;
781 }
782 if ( converted )
783 {
784 UInt32 keyCode ;
785 unsigned char charCode ;
786 UInt32 modifiers ;
787 GetMouse( &rec->where) ;
788
789 err = GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
790 err = GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
791 err = GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
792 rec->modifiers = modifiers ;
793 rec->message = (keyCode << 8 ) + charCode ;
794 }
795 }
796 break ;
797 case kEventClassTextInput :
798 {
799 switch( GetEventKind( event ) )
800 {
801 case kEventTextInputUnicodeForKeyEvent :
802 {
803 EventRef rawEvent ;
804 err = GetEventParameter( event , kEventParamTextInputSendKeyboardEvent ,typeEventRef,NULL,sizeof(rawEvent),NULL,&rawEvent ) ;
805 converted = true ;
806 {
807 UInt32 keyCode ;
808 unsigned char charCode ;
809 UInt32 modifiers ;
810 GetMouse( &rec->where) ;
811 rec->what = keyDown ;
812 err = GetEventParameter(rawEvent, kEventParamKeyModifiers, typeUInt32, NULL, 4, NULL, &modifiers);
813 err = GetEventParameter(rawEvent, kEventParamKeyCode, typeUInt32, NULL, 4, NULL, &keyCode);
814 err = GetEventParameter(rawEvent, kEventParamKeyMacCharCodes, typeChar, NULL, 1, NULL, &charCode);
815 rec->modifiers = modifiers ;
816 rec->message = (keyCode << 8 ) + charCode ;
817 }
818 }
819 break ;
820 default :
821 break ;
822 }
823 }
824 break ;
825 }
826 }
827
828 return converted ;
829 }
830
831 wxApp::wxApp()
832 {
833 m_printMode = wxPRINT_WINDOWS;
834
835 m_macCurrentEvent = NULL ;
836 m_macCurrentEventHandlerCallRef = NULL ;
837 }
838
839 int wxApp::MainLoop()
840 {
841 m_keepGoing = TRUE;
842 #if wxMAC_USE_RAEL
843 RunApplicationEventLoop() ;
844 #else
845 while (m_keepGoing)
846 {
847 MacDoOneEvent() ;
848 }
849 #endif
850 return 0;
851 }
852
853 void wxApp::ExitMainLoop()
854 {
855 m_keepGoing = FALSE;
856 #if wxMAC_USE_RAEL
857 QuitApplicationEventLoop() ;
858 #endif
859 }
860
861 // Is a message/event pending?
862 bool wxApp::Pending()
863 {
864 // without the receive event (with pull param = false ) nothing is ever reported
865 EventRef theEvent;
866 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &theEvent);
867 return GetNumEventsInQueue( GetMainEventQueue() ) > 0 ;
868 }
869
870 // Dispatch a message.
871 bool wxApp::Dispatch()
872 {
873 MacDoOneEvent() ;
874
875 return true;
876 }
877
878 void wxApp::OnIdle(wxIdleEvent& event)
879 {
880 wxAppBase::OnIdle(event);
881
882 // If they are pending events, we must process them: pending events are
883 // either events to the threads other than main or events posted with
884 // wxPostEvent() functions
885 wxMacProcessNotifierAndPendingEvents();
886
887 if(!wxMenuBar::MacGetInstalledMenuBar() && wxMenuBar::MacGetCommonMenuBar())
888 wxMenuBar::MacGetCommonMenuBar()->MacInstallMenuBar();
889 }
890
891 void wxApp::WakeUpIdle()
892 {
893 wxMacWakeUp() ;
894 }
895
896 void wxApp::Exit()
897 {
898 wxApp::CleanUp();
899 ::ExitToShell() ;
900 }
901
902 void wxApp::OnEndSession(wxCloseEvent& WXUNUSED(event))
903 {
904 if (GetTopWindow())
905 GetTopWindow()->Close(TRUE);
906 }
907
908 // Default behaviour: close the application with prompts. The
909 // user can veto the close, and therefore the end session.
910 void wxApp::OnQueryEndSession(wxCloseEvent& event)
911 {
912 if (GetTopWindow())
913 {
914 if (!GetTopWindow()->Close(!event.CanVeto()))
915 event.Veto(TRUE);
916 }
917 }
918
919 extern "C" void wxCYield() ;
920 void wxCYield()
921 {
922 wxYield() ;
923 }
924
925 // Yield to other processes
926
927 bool wxApp::Yield(bool onlyIfNeeded)
928 {
929 if (s_inYield)
930 {
931 if ( !onlyIfNeeded )
932 {
933 wxFAIL_MSG( wxT("wxYield called recursively" ) );
934 }
935
936 return FALSE;
937 }
938
939 s_inYield = TRUE;
940
941 // by definition yield should handle all non-processed events
942
943 EventRef theEvent;
944
945 OSStatus status = noErr ;
946 do
947 {
948 s_inReceiveEvent = true ;
949 status = ReceiveNextEvent(0, NULL,kEventDurationNoWait,true,&theEvent) ;
950 s_inReceiveEvent = false ;
951
952 if ( status == eventLoopTimedOutErr )
953 {
954 // make sure next time the event loop will trigger idle events
955 sleepTime = kEventDurationNoWait ;
956 }
957 else if ( status == eventLoopQuitErr )
958 {
959 // according to QA1061 this may also occur when a WakeUp Process
960 // is executed
961 }
962 else
963 {
964 MacHandleOneEvent( theEvent ) ;
965 ReleaseEvent(theEvent);
966 }
967 } while( status == noErr ) ;
968
969 wxMacProcessNotifierAndPendingEvents() ;
970 s_inYield = FALSE;
971
972 return TRUE;
973 }
974
975 void wxApp::MacDoOneEvent()
976 {
977 EventRef theEvent;
978
979 s_inReceiveEvent = true ;
980 OSStatus status = ReceiveNextEvent(0, NULL,sleepTime,true,&theEvent) ;
981 s_inReceiveEvent = false ;
982 if ( status == eventLoopTimedOutErr )
983 {
984 if ( wxTheApp->ProcessIdle() )
985 sleepTime = kEventDurationNoWait ;
986 else
987 sleepTime = kEventDurationSecond;
988 }
989 else if ( status == eventLoopQuitErr )
990 {
991 // according to QA1061 this may also occur when a WakeUp Process
992 // is executed
993 }
994 else
995 {
996 MacHandleOneEvent( theEvent ) ;
997 ReleaseEvent(theEvent);
998 sleepTime = kEventDurationNoWait ;
999 }
1000 // repeaters
1001
1002 DeletePendingObjects() ;
1003 wxMacProcessNotifierAndPendingEvents() ;
1004 }
1005
1006 /*virtual*/ void wxApp::MacHandleUnhandledEvent( WXEVENTREF evr )
1007 {
1008 // Override to process unhandled events as you please
1009 }
1010
1011 void wxApp::MacHandleOneEvent( WXEVENTREF evr )
1012 {
1013 EventTargetRef theTarget;
1014 theTarget = GetEventDispatcherTarget();
1015 m_macCurrentEvent = evr ;
1016 OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
1017 if(status == eventNotHandledErr)
1018 {
1019 MacHandleUnhandledEvent(evr);
1020 }
1021 wxMacProcessNotifierAndPendingEvents() ;
1022 #if wxUSE_THREADS
1023 wxMutexGuiLeaveOrEnter();
1024 #endif // wxUSE_THREADS
1025 }
1026
1027 long wxMacTranslateKey(unsigned char key, unsigned char code) ;
1028 long wxMacTranslateKey(unsigned char key, unsigned char code)
1029 {
1030 long retval = key ;
1031 switch (key)
1032 {
1033 case kHomeCharCode :
1034 retval = WXK_HOME;
1035 break;
1036 case kEnterCharCode :
1037 retval = WXK_RETURN;
1038 break;
1039 case kEndCharCode :
1040 retval = WXK_END;
1041 break;
1042 case kHelpCharCode :
1043 retval = WXK_HELP;
1044 break;
1045 case kBackspaceCharCode :
1046 retval = WXK_BACK;
1047 break;
1048 case kTabCharCode :
1049 retval = WXK_TAB;
1050 break;
1051 case kPageUpCharCode :
1052 retval = WXK_PAGEUP;
1053 break;
1054 case kPageDownCharCode :
1055 retval = WXK_PAGEDOWN;
1056 break;
1057 case kReturnCharCode :
1058 retval = WXK_RETURN;
1059 break;
1060 case kFunctionKeyCharCode :
1061 {
1062 switch( code )
1063 {
1064 case 0x7a :
1065 retval = WXK_F1 ;
1066 break;
1067 case 0x78 :
1068 retval = WXK_F2 ;
1069 break;
1070 case 0x63 :
1071 retval = WXK_F3 ;
1072 break;
1073 case 0x76 :
1074 retval = WXK_F4 ;
1075 break;
1076 case 0x60 :
1077 retval = WXK_F5 ;
1078 break;
1079 case 0x61 :
1080 retval = WXK_F6 ;
1081 break;
1082 case 0x62:
1083 retval = WXK_F7 ;
1084 break;
1085 case 0x64 :
1086 retval = WXK_F8 ;
1087 break;
1088 case 0x65 :
1089 retval = WXK_F9 ;
1090 break;
1091 case 0x6D :
1092 retval = WXK_F10 ;
1093 break;
1094 case 0x67 :
1095 retval = WXK_F11 ;
1096 break;
1097 case 0x6F :
1098 retval = WXK_F12 ;
1099 break;
1100 case 0x69 :
1101 retval = WXK_F13 ;
1102 break;
1103 case 0x6B :
1104 retval = WXK_F14 ;
1105 break;
1106 case 0x71 :
1107 retval = WXK_F15 ;
1108 break;
1109 }
1110 }
1111 break ;
1112 case kEscapeCharCode :
1113 retval = WXK_ESCAPE ;
1114 break ;
1115 case kLeftArrowCharCode :
1116 retval = WXK_LEFT ;
1117 break ;
1118 case kRightArrowCharCode :
1119 retval = WXK_RIGHT ;
1120 break ;
1121 case kUpArrowCharCode :
1122 retval = WXK_UP ;
1123 break ;
1124 case kDownArrowCharCode :
1125 retval = WXK_DOWN ;
1126 break ;
1127 case kDeleteCharCode :
1128 retval = WXK_DELETE ;
1129 default:
1130 break ;
1131 } // end switch
1132
1133 return retval;
1134 }
1135
1136 int wxMacKeyCodeToModifier(wxKeyCode key)
1137 {
1138 switch (key)
1139 {
1140 case WXK_START:
1141 case WXK_MENU:
1142 return cmdKey;
1143
1144 case WXK_SHIFT:
1145 return shiftKey;
1146
1147 case WXK_CAPITAL:
1148 return alphaLock;
1149
1150 case WXK_ALT:
1151 return optionKey;
1152
1153 case WXK_CONTROL:
1154 return controlKey;
1155
1156 default:
1157 return 0;
1158 }
1159 }
1160
1161 bool wxGetKeyState(wxKeyCode key) //virtual key code if < 10.2.x, else see below
1162 {
1163 //#ifdef __DARWIN__
1164 // wxHIDKeyboard keyboard;
1165 // return keyboard.IsActive(key);
1166 //#else
1167 // TODO: Have it use HID Manager on OSX...
1168 //if OS X > 10.2 (i.e. 10.2.x)
1169 //a known apple bug prevents the system from determining led
1170 //states with GetKeys... can only determine caps lock led
1171 return !!(GetCurrentKeyModifiers() & wxMacKeyCodeToModifier(key));
1172 //else
1173 // KeyMapByteArray keymap;
1174 // GetKeys((BigEndianLong*)keymap);
1175 // return !!(BitTst(keymap, (sizeof(KeyMapByteArray)*8) - iKey));
1176 //#endif
1177 }
1178
1179
1180 bool wxApp::MacSendKeyDownEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1181 {
1182 if ( !focus )
1183 return false ;
1184
1185 short keycode ;
1186 short keychar ;
1187 keychar = short(keymessage & charCodeMask);
1188 keycode = short(keymessage & keyCodeMask) >> 8 ;
1189
1190 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
1191 {
1192 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1193 // and look at the character after
1194 UInt32 state = 0;
1195 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1196 keychar = short(keyInfo & charCodeMask);
1197 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1198 }
1199 long keyval = wxMacTranslateKey(keychar, keycode) ;
1200 long realkeyval = keyval ;
1201 if ( keyval == keychar )
1202 {
1203 // we are not on a special character combo -> pass the real os event-value to EVT_CHAR, but not to EVT_KEY (make upper first)
1204 realkeyval = short(keymessage & charCodeMask) ;
1205 keyval = wxToupper( keyval ) ;
1206 }
1207
1208 wxKeyEvent event(wxEVT_KEY_DOWN);
1209 bool handled = false ;
1210 event.m_shiftDown = modifiers & shiftKey;
1211 event.m_controlDown = modifiers & controlKey;
1212 event.m_altDown = modifiers & optionKey;
1213 event.m_metaDown = modifiers & cmdKey;
1214 event.m_keyCode = keyval ;
1215
1216 event.m_x = wherex;
1217 event.m_y = wherey;
1218 event.m_timeStamp = when;
1219 event.SetEventObject(focus);
1220 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1221 if ( handled && event.GetSkipped() )
1222 handled = false ;
1223 if ( !handled )
1224 {
1225 #if wxUSE_ACCEL
1226 if (!handled)
1227 {
1228 wxWindow *ancestor = focus;
1229 while (ancestor)
1230 {
1231 int command = ancestor->GetAcceleratorTable()->GetCommand( event );
1232 if (command != -1)
1233 {
1234 wxCommandEvent command_event( wxEVT_COMMAND_MENU_SELECTED, command );
1235 handled = ancestor->GetEventHandler()->ProcessEvent( command_event );
1236 break;
1237 }
1238 if (ancestor->IsTopLevel())
1239 break;
1240 ancestor = ancestor->GetParent();
1241 }
1242 }
1243 #endif // wxUSE_ACCEL
1244 }
1245 if (!handled)
1246 {
1247 event.Skip( FALSE ) ;
1248 event.SetEventType( wxEVT_CHAR ) ;
1249 // raw value again
1250 event.m_keyCode = realkeyval ;
1251
1252 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1253 if ( handled && event.GetSkipped() )
1254 handled = false ;
1255 }
1256 if ( !handled && (keyval == WXK_TAB) )
1257 {
1258 wxWindow* iter = focus->GetParent() ;
1259 while( iter && !handled )
1260 {
1261 if ( iter->HasFlag( wxTAB_TRAVERSAL ) )
1262 {
1263 wxNavigationKeyEvent new_event;
1264 new_event.SetEventObject( focus );
1265 new_event.SetDirection( !event.ShiftDown() );
1266 /* CTRL-TAB changes the (parent) window, i.e. switch notebook page */
1267 new_event.SetWindowChange( event.ControlDown() );
1268 new_event.SetCurrentFocus( focus );
1269 handled = focus->GetParent()->GetEventHandler()->ProcessEvent( new_event );
1270 if ( handled && new_event.GetSkipped() )
1271 handled = false ;
1272 }
1273 iter = iter->GetParent() ;
1274 }
1275 }
1276 // backdoor handler for default return and command escape
1277 if ( !handled && (!focus->IsKindOf(CLASSINFO(wxControl) ) || !focus->MacCanFocus() ) )
1278 {
1279 // if window is not having a focus still testing for default enter or cancel
1280 // TODO add the UMA version for ActiveNonFloatingWindow
1281 wxWindow* focus = wxFindWinFromMacWindow( FrontWindow() ) ;
1282 if ( focus )
1283 {
1284 if ( keyval == WXK_RETURN )
1285 {
1286 wxButton *def = wxDynamicCast(focus->GetDefaultItem(),
1287 wxButton);
1288 if ( def && def->IsEnabled() )
1289 {
1290 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
1291 event.SetEventObject(def);
1292 def->Command(event);
1293 return true ;
1294 }
1295 }
1296 /* generate wxID_CANCEL if command-. or <esc> has been pressed (typically in dialogs) */
1297 else if (keyval == WXK_ESCAPE || (keyval == '.' && modifiers & cmdKey ) )
1298 {
1299 wxCommandEvent new_event(wxEVT_COMMAND_BUTTON_CLICKED,wxID_CANCEL);
1300 new_event.SetEventObject( focus );
1301 handled = focus->GetEventHandler()->ProcessEvent( new_event );
1302 }
1303 }
1304 }
1305 return handled ;
1306 }
1307
1308 bool wxApp::MacSendKeyUpEvent( wxWindow* focus , long keymessage , long modifiers , long when , short wherex , short wherey )
1309 {
1310 if ( !focus )
1311 return false ;
1312
1313 short keycode ;
1314 short keychar ;
1315 keychar = short(keymessage & charCodeMask);
1316 keycode = short(keymessage & keyCodeMask) >> 8 ;
1317 if ( modifiers & ( controlKey|shiftKey|optionKey ) )
1318 {
1319 // control interferes with some built-in keys like pgdown, return etc. therefore we remove the controlKey modifier
1320 // and look at the character after
1321 UInt32 state = 0;
1322 UInt32 keyInfo = KeyTranslate((Ptr)GetScriptManagerVariable(smKCHRCache), ( modifiers & (~(controlKey|shiftKey|optionKey))) | keycode, &state);
1323 keychar = short(keyInfo & charCodeMask);
1324 keycode = short(keyInfo & keyCodeMask) >> 8 ;
1325 }
1326 long keyval = wxMacTranslateKey(keychar, keycode) ;
1327
1328 if ( keyval == keychar )
1329 {
1330 keyval = wxToupper( keyval ) ;
1331 }
1332 bool handled = false ;
1333
1334 wxKeyEvent event(wxEVT_KEY_UP);
1335 event.m_shiftDown = modifiers & shiftKey;
1336 event.m_controlDown = modifiers & controlKey;
1337 event.m_altDown = modifiers & optionKey;
1338 event.m_metaDown = modifiers & cmdKey;
1339 event.m_keyCode = keyval ;
1340
1341 event.m_x = wherex;
1342 event.m_y = wherey;
1343 event.m_timeStamp = when;
1344 event.SetEventObject(focus);
1345 handled = focus->GetEventHandler()->ProcessEvent( event ) ;
1346
1347 return handled ;
1348 }